├── .env.example ├── .github └── FUNDING.yml ├── .gitignore ├── API_Service ├── Analytics-Service.json └── YouTube-Data-API.json ├── Dockerfile ├── LICENSE ├── README.md ├── YouTube_API.py ├── keep_alive.py ├── main.py ├── output-examples ├── README.MD └── media │ ├── !adType.png │ ├── !demographics.png │ ├── !geoReport.png │ ├── !geo_revenue.png │ ├── !getMonth.png │ ├── !lifetime.png │ ├── !os.png │ ├── !playlist.png │ ├── !refresh.png │ ├── !search.png │ ├── !shares.png │ ├── !stats.png │ ├── !switch.png │ ├── !topEarnings.png │ ├── coffee-logo.png │ └── onReady.png └── requirements.txt /.env.example: -------------------------------------------------------------------------------- 1 | # --------------- Required: --------------- 2 | 3 | # Description: Retrieve Discord bot token from https://discord.com/developers/applications 4 | # Type: String 5 | # Example format: B4DSAUIDoJFEHW.Ifs57fdS.nHjfrhgdfHikugGHjhH689V 6 | DISCORD_TOKEN= 7 | 8 | # Description: Create YouTube API key from https://console.cloud.google.com/apis/credentials 9 | # Type: String 10 | # Example format: BADfege-545gfgf_kVTAYVHFHNFKJ-hfnjdgf 11 | YOUTUBE_API_KEY= 12 | 13 | 14 | # --------------- Optional: --------------- 15 | 16 | # Description: Path of YouTube/Google Client Secret JSON file 17 | # Type: String 18 | # Default: 'CLIENT_SECRET.json' in the current directory 19 | CLIENT_PATH=CLIENT_SECRET.json 20 | 21 | # Description: Discord channel ID 22 | # Type: String 23 | # Default: None 24 | DISCORD_CHANNEL=None 25 | 26 | # Description: Whether to use a Flask server for keep alive or not 27 | # Type: Boolean 28 | # Default: False 29 | # Values: True or False 30 | KEEP_ALIVE=False 31 | 32 | # Description: Whether to use experimental features or not 33 | # Type: Boolean 34 | # Default: False 35 | # Values: True or False 36 | DEV_MODE=False 37 | 38 | # Description: A JSON string that contains the client ID, project ID, secret client ID, and refresh token for YouTube API authentication. You MUST add in 'refresh_token' manually. 39 | # Type: JSON String 40 | # IMPORTANT: Must add refresh token manually from downloaded JSON file 41 | # "refresh_token": "YOUR REFRESH TOKEN (MANUALLY ADDED FROM DOWNLOADED JSON)", 42 | 43 | # Formatted Example: 44 | # 45 | # { 46 | # "installed": { 47 | # "client_id": "YOUR-CLIENT-ID-HERE.apps.googleusercontent.com", 48 | # "project_id": "YOUR-PROJECT-ID", 49 | # "auth_uri": "https://accounts.google.com/o/oauth2/auth", 50 | # "token_uri": "https://oauth2.googleapis.com/token", 51 | # "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", 52 | # "client_secret": "YOUR-SECRET-CLIENT-ID", 53 | # "refresh_token": "YOUR REFRESH TOKEN (MANUALLY ADDED INTO THE DOWNLOADED JSON FROM CREDENTIALS.JSON FILE)", 54 | # "redirect_uris": [ 55 | # "http://localhost" 56 | # ] 57 | # } 58 | # } 59 | CLIENT_SECRET={"installed":{"client_id":"YOUR-CLIENT-ID-HERE.apps.googleusercontent.com","project_id":"YOUR-PROJECT-ID","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"YOUR-SECRET-CLIENT-ID","refresh_token": "YOUR REFRESH TOKEN (MANUALLY ADDED FROM DOWNLOADED JSON)","redirect_uris":["http://localhost"]}} 60 | 61 | 62 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [Prem-ium] 2 | custom: https://www.buymeacoffee.com/prem.ium 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .env 2 | *cred*.json 3 | *SECRET*.json 4 | test* 5 | *pycache* 6 | .vscode 7 | .replit 8 | replit* 9 | nenv* -------------------------------------------------------------------------------- /API_Service/Analytics-Service.json: -------------------------------------------------------------------------------- 1 | { 2 | "fullyEncodeReservedExpansion": true, 3 | "auth": { 4 | "oauth2": { 5 | "scopes": { 6 | "https://www.googleapis.com/auth/yt-analytics-monetary.readonly": { 7 | "description": "View monetary and non-monetary YouTube Analytics reports for your YouTube content" 8 | }, 9 | "https://www.googleapis.com/auth/youtubepartner": { 10 | "description": "View and manage your assets and associated content on YouTube" 11 | }, 12 | "https://www.googleapis.com/auth/yt-analytics.readonly": { 13 | "description": "View YouTube Analytics reports for your YouTube content" 14 | }, 15 | "https://www.googleapis.com/auth/youtube": { 16 | "description": "Manage your YouTube account" 17 | }, 18 | "https://www.googleapis.com/auth/youtube.readonly": { 19 | "description": "View your YouTube account" 20 | } 21 | } 22 | } 23 | }, 24 | "ownerName": "Google", 25 | "servicePath": "", 26 | "discoveryVersion": "v1", 27 | "mtlsRootUrl": "https://youtubeanalytics.mtls.googleapis.com/", 28 | "id": "youtubeAnalytics:v2", 29 | "title": "YouTube Analytics API", 30 | "baseUrl": "https://youtubeanalytics.googleapis.com/", 31 | "kind": "discovery#restDescription", 32 | "schemas": { 33 | "ListGroupItemsResponse": { 34 | "description": "Response message for GroupsService.ListGroupItems.", 35 | "properties": { 36 | "errors": { 37 | "description": "Apiary error details", 38 | "$ref": "Errors" 39 | }, 40 | "items": { 41 | "items": { 42 | "$ref": "GroupItem" 43 | }, 44 | "description": "A list of groups that match the API request parameters. Each item in the list represents a `groupItem` resource.", 45 | "type": "array" 46 | }, 47 | "kind": { 48 | "type": "string", 49 | "description": "Identifies the API resource's type. The value will be `youtube#groupItemListResponse`." 50 | }, 51 | "etag": { 52 | "description": "The Etag of this resource.", 53 | "type": "string" 54 | } 55 | }, 56 | "id": "ListGroupItemsResponse", 57 | "type": "object" 58 | }, 59 | "ResultTableColumnHeader": { 60 | "id": "ResultTableColumnHeader", 61 | "properties": { 62 | "dataType": { 63 | "type": "string", 64 | "description": "The type of the data in the column (`STRING`, `INTEGER`, `FLOAT`, etc.)." 65 | }, 66 | "name": { 67 | "description": "The name of the dimension or metric.", 68 | "type": "string" 69 | }, 70 | "columnType": { 71 | "type": "string", 72 | "description": "The type of the column (`DIMENSION` or `METRIC`)." 73 | } 74 | }, 75 | "description": "The description of a column of the result table.", 76 | "type": "object" 77 | }, 78 | "GroupItemResource": { 79 | "id": "GroupItemResource", 80 | "properties": { 81 | "id": { 82 | "description": "The channel, video, playlist, or asset ID that YouTube uses to uniquely identify the item that is being added to the group.", 83 | "type": "string" 84 | }, 85 | "kind": { 86 | "type": "string", 87 | "description": "Identifies the type of resource being added to the group. Valid values for this property are: * `youtube#channel` * `youtube#playlist` * `youtube#video` * `youtubePartner#asset`" 88 | } 89 | }, 90 | "type": "object" 91 | }, 92 | "ErrorProto": { 93 | "properties": { 94 | "locationType": { 95 | "enum": [ 96 | "PATH", 97 | "OTHER", 98 | "PARAMETER" 99 | ], 100 | "enumDescriptions": [ 101 | "location is an xpath-like path pointing to the request field that caused the error.", 102 | "other location type which can safely be shared externally.", 103 | "Location is request parameter. This maps to the {@link PARAMETERS} in {@link MessageLocation}." 104 | ], 105 | "type": "string" 106 | }, 107 | "argument": { 108 | "type": "array", 109 | "items": { 110 | "type": "string" 111 | }, 112 | "description": "Error arguments, to be used when building user-friendly error messages given the error domain and code. Different error codes require different arguments." 113 | }, 114 | "debugInfo": { 115 | "description": "Debugging information, which should not be shared externally.", 116 | "type": "string" 117 | }, 118 | "domain": { 119 | "type": "string", 120 | "description": "Error domain. RoSy services can define their own domain and error codes. This should normally be the name of an enum type, such as: gdata.CoreErrorDomain" 121 | }, 122 | "location": { 123 | "type": "string", 124 | "description": "Location of the error, as specified by the location type. If location_type is PATH, this should be a path to a field that's relative to the request, using FieldPath notation (net/proto2/util/public/field_path.h). Examples: authenticated_user.gaia_id resource.address[2].country" 125 | }, 126 | "externalErrorMessage": { 127 | "type": "string", 128 | "description": "A short explanation for the error, which can be shared outside Google. Please set domain, code and arguments whenever possible instead of this error message so that external APIs can build safe error messages themselves. External messages built in a RoSy interface will most likely refer to information and concepts that are not available externally and should not be exposed. It is safer if external APIs can understand the errors and decide what the error message should look like." 129 | }, 130 | "code": { 131 | "type": "string", 132 | "description": "Error code in the error domain. This should correspond to a value of the enum type whose name is in domain. See the core error domain in error_domain.proto." 133 | } 134 | }, 135 | "id": "ErrorProto", 136 | "description": "Describes one specific error.", 137 | "type": "object" 138 | }, 139 | "Errors": { 140 | "type": "object", 141 | "properties": { 142 | "requestId": { 143 | "type": "string", 144 | "description": "Request identifier generated by the service, which can be used to identify the error in the logs" 145 | }, 146 | "code": { 147 | "description": "Global error code. Deprecated and ignored. Set custom error codes in ErrorProto.domain and ErrorProto.code instead.", 148 | "enumDescriptions": [ 149 | "", 150 | "", 151 | "", 152 | "", 153 | "", 154 | "", 155 | "", 156 | "" 157 | ], 158 | "enum": [ 159 | "BAD_REQUEST", 160 | "FORBIDDEN", 161 | "NOT_FOUND", 162 | "CONFLICT", 163 | "GONE", 164 | "PRECONDITION_FAILED", 165 | "INTERNAL_ERROR", 166 | "SERVICE_UNAVAILABLE" 167 | ], 168 | "type": "string" 169 | }, 170 | "error": { 171 | "description": "Specific error description and codes", 172 | "type": "array", 173 | "items": { 174 | "$ref": "ErrorProto" 175 | } 176 | } 177 | }, 178 | "description": "Request Error information. The presence of an error field signals that the operation has failed.", 179 | "id": "Errors" 180 | }, 181 | "Group": { 182 | "type": "object", 183 | "description": "A group.", 184 | "properties": { 185 | "etag": { 186 | "description": "The Etag of this resource.", 187 | "type": "string" 188 | }, 189 | "snippet": { 190 | "$ref": "GroupSnippet", 191 | "description": "The `snippet` object contains basic information about the group, including its creation date and name." 192 | }, 193 | "contentDetails": { 194 | "$ref": "GroupContentDetails", 195 | "description": "The `contentDetails` object contains additional information about the group, such as the number and type of items that it contains." 196 | }, 197 | "errors": { 198 | "description": "Apiary error details", 199 | "$ref": "Errors" 200 | }, 201 | "id": { 202 | "description": "The ID that YouTube uses to uniquely identify the group.", 203 | "type": "string" 204 | }, 205 | "kind": { 206 | "type": "string", 207 | "description": "Identifies the API resource's type. The value will be `youtube#group`." 208 | } 209 | }, 210 | "id": "Group" 211 | }, 212 | "QueryResponse": { 213 | "properties": { 214 | "kind": { 215 | "description": "This value specifies the type of data included in the API response. For the query method, the kind property value will be `youtubeAnalytics#resultTable`.", 216 | "type": "string" 217 | }, 218 | "rows": { 219 | "items": { 220 | "type": "array", 221 | "items": { 222 | "type": "any" 223 | } 224 | }, 225 | "type": "array", 226 | "description": "The list contains all rows of the result table. Each item in the list is an array that contains comma-delimited data corresponding to a single row of data. The order of the comma-delimited data fields will match the order of the columns listed in the `columnHeaders` field. If no data is available for the given query, the `rows` element will be omitted from the response. The response for a query with the `day` dimension will not contain rows for the most recent days." 227 | }, 228 | "columnHeaders": { 229 | "items": { 230 | "$ref": "ResultTableColumnHeader" 231 | }, 232 | "description": "This value specifies information about the data returned in the `rows` fields. Each item in the `columnHeaders` list identifies a field returned in the `rows` value, which contains a list of comma-delimited data. The `columnHeaders` list will begin with the dimensions specified in the API request, which will be followed by the metrics specified in the API request. The order of both dimensions and metrics will match the ordering in the API request. For example, if the API request contains the parameters `dimensions=ageGroup,gender&metrics=viewerPercentage`, the API response will return columns in this order: `ageGroup`, `gender`, `viewerPercentage`.", 233 | "type": "array" 234 | }, 235 | "errors": { 236 | "$ref": "Errors", 237 | "description": "When set, indicates that the operation failed." 238 | } 239 | }, 240 | "id": "QueryResponse", 241 | "type": "object", 242 | "description": "Response message for TargetedQueriesService.Query." 243 | }, 244 | "GroupContentDetails": { 245 | "type": "object", 246 | "id": "GroupContentDetails", 247 | "properties": { 248 | "itemCount": { 249 | "description": "The number of items in the group.", 250 | "type": "string", 251 | "format": "uint64" 252 | }, 253 | "itemType": { 254 | "description": "The type of resources that the group contains. Valid values for this property are: * `youtube#channel` * `youtube#playlist` * `youtube#video` * `youtubePartner#asset`", 255 | "type": "string" 256 | } 257 | }, 258 | "description": "A group's content details." 259 | }, 260 | "EmptyResponse": { 261 | "properties": { 262 | "errors": { 263 | "$ref": "Errors", 264 | "description": "Apiary error details" 265 | } 266 | }, 267 | "description": "Empty response.", 268 | "id": "EmptyResponse", 269 | "type": "object" 270 | }, 271 | "GroupSnippet": { 272 | "id": "GroupSnippet", 273 | "properties": { 274 | "publishedAt": { 275 | "format": "google-datetime", 276 | "description": "The date and time that the group was created. The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format.", 277 | "type": "string" 278 | }, 279 | "title": { 280 | "type": "string", 281 | "description": "The group name. The value must be a non-empty string." 282 | } 283 | }, 284 | "type": "object", 285 | "description": "A group snippet." 286 | }, 287 | "GroupItem": { 288 | "description": "A group item.", 289 | "id": "GroupItem", 290 | "type": "object", 291 | "properties": { 292 | "kind": { 293 | "description": "Identifies the API resource's type. The value will be `youtube#groupItem`.", 294 | "type": "string" 295 | }, 296 | "resource": { 297 | "$ref": "GroupItemResource", 298 | "description": "The `resource` object contains information that identifies the item being added to the group." 299 | }, 300 | "etag": { 301 | "type": "string", 302 | "description": "The Etag of this resource." 303 | }, 304 | "id": { 305 | "type": "string", 306 | "description": "The ID that YouTube uses to uniquely identify the `channel`, `video`, `playlist`, or `asset` resource that is included in the group. Note that this ID refers specifically to the inclusion of that resource in a particular group and is different than the channel ID, video ID, playlist ID, or asset ID that uniquely identifies the resource itself. The `resource.id` property's value specifies the unique channel, video, playlist, or asset ID." 307 | }, 308 | "errors": { 309 | "description": "Apiary error details", 310 | "$ref": "Errors" 311 | }, 312 | "groupId": { 313 | "description": "The ID that YouTube uses to uniquely identify the group that contains the item.", 314 | "type": "string" 315 | } 316 | } 317 | }, 318 | "ListGroupsResponse": { 319 | "type": "object", 320 | "description": "Response message for GroupsService.ListGroups.", 321 | "properties": { 322 | "errors": { 323 | "$ref": "Errors", 324 | "description": "Apiary error details" 325 | }, 326 | "kind": { 327 | "description": "Identifies the API resource's type. The value will be `youtube#groupListResponse`.", 328 | "type": "string" 329 | }, 330 | "nextPageToken": { 331 | "type": "string", 332 | "description": "The token that can be used as the value of the `pageToken` parameter to retrieve the next page in the result set." 333 | }, 334 | "etag": { 335 | "type": "string", 336 | "description": "The Etag of this resource." 337 | }, 338 | "items": { 339 | "type": "array", 340 | "items": { 341 | "$ref": "Group" 342 | }, 343 | "description": "A list of groups that match the API request parameters. Each item in the list represents a `group` resource." 344 | } 345 | }, 346 | "id": "ListGroupsResponse" 347 | } 348 | }, 349 | "version": "v2", 350 | "version_module": true, 351 | "basePath": "", 352 | "parameters": { 353 | "$.xgafv": { 354 | "enumDescriptions": [ 355 | "v1 error format", 356 | "v2 error format" 357 | ], 358 | "location": "query", 359 | "type": "string", 360 | "enum": [ 361 | "1", 362 | "2" 363 | ], 364 | "description": "V1 error format." 365 | }, 366 | "prettyPrint": { 367 | "type": "boolean", 368 | "location": "query", 369 | "default": "true", 370 | "description": "Returns response with indentations and line breaks." 371 | }, 372 | "access_token": { 373 | "location": "query", 374 | "type": "string", 375 | "description": "OAuth access token." 376 | }, 377 | "key": { 378 | "location": "query", 379 | "type": "string", 380 | "description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token." 381 | }, 382 | "quotaUser": { 383 | "location": "query", 384 | "type": "string", 385 | "description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters." 386 | }, 387 | "upload_protocol": { 388 | "location": "query", 389 | "description": "Upload protocol for media (e.g. \"raw\", \"multipart\").", 390 | "type": "string" 391 | }, 392 | "fields": { 393 | "description": "Selector specifying which fields to include in a partial response.", 394 | "type": "string", 395 | "location": "query" 396 | }, 397 | "callback": { 398 | "description": "JSONP", 399 | "location": "query", 400 | "type": "string" 401 | }, 402 | "uploadType": { 403 | "type": "string", 404 | "location": "query", 405 | "description": "Legacy upload protocol for media (e.g. \"media\", \"multipart\")." 406 | }, 407 | "oauth_token": { 408 | "type": "string", 409 | "location": "query", 410 | "description": "OAuth 2.0 token for the current user." 411 | }, 412 | "alt": { 413 | "location": "query", 414 | "description": "Data format for response.", 415 | "type": "string", 416 | "enumDescriptions": [ 417 | "Responses with Content-Type of application/json", 418 | "Media download with context-dependent Content-Type", 419 | "Responses with Content-Type of application/x-protobuf" 420 | ], 421 | "enum": [ 422 | "json", 423 | "media", 424 | "proto" 425 | ], 426 | "default": "json" 427 | } 428 | }, 429 | "documentationLink": "https://developers.google.com/youtube/analytics", 430 | "name": "youtubeAnalytics", 431 | "resources": { 432 | "reports": { 433 | "methods": { 434 | "query": { 435 | "parameters": { 436 | "endDate": { 437 | "location": "query", 438 | "type": "string", 439 | "description": "The end date for fetching YouTube Analytics data. The value should be in `YYYY-MM-DD` format. required: true, pattern: [0-9]{4}-[0-9]{2}-[0-9]{2}" 440 | }, 441 | "ids": { 442 | "location": "query", 443 | "type": "string", 444 | "description": "Identifies the YouTube channel or content owner for which you are retrieving YouTube Analytics data. - To request data for a YouTube user, set the `ids` parameter value to `channel==CHANNEL_ID`, where `CHANNEL_ID` specifies the unique YouTube channel ID. - To request data for a YouTube CMS content owner, set the `ids` parameter value to `contentOwner==OWNER_NAME`, where `OWNER_NAME` is the CMS name of the content owner. required: true, pattern: [a-zA-Z]+==[a-zA-Z0-9_+-]+" 445 | }, 446 | "metrics": { 447 | "location": "query", 448 | "type": "string", 449 | "description": "A comma-separated list of YouTube Analytics metrics, such as `views` or `likes,dislikes`. See the [Available Reports](/youtube/analytics/v2/available_reports) document for a list of the reports that you can retrieve and the metrics available in each report, and see the [Metrics](/youtube/analytics/v2/dimsmets/mets) document for definitions of those metrics. required: true, pattern: [0-9a-zA-Z,]+" 450 | }, 451 | "dimensions": { 452 | "description": "A comma-separated list of YouTube Analytics dimensions, such as `views` or `ageGroup,gender`. See the [Available Reports](/youtube/analytics/v2/available_reports) document for a list of the reports that you can retrieve and the dimensions used for those reports. Also see the [Dimensions](/youtube/analytics/v2/dimsmets/dims) document for definitions of those dimensions.\" pattern: [0-9a-zA-Z,]+", 453 | "location": "query", 454 | "type": "string" 455 | }, 456 | "sort": { 457 | "type": "string", 458 | "description": "A comma-separated list of dimensions or metrics that determine the sort order for YouTube Analytics data. By default the sort order is ascending. The '`-`' prefix causes descending sort order.\", pattern: [-0-9a-zA-Z,]+", 459 | "location": "query" 460 | }, 461 | "currency": { 462 | "location": "query", 463 | "description": "The currency to which financial metrics should be converted. The default is US Dollar (USD). If the result contains no financial metrics, this flag will be ignored. Responds with an error if the specified currency is not recognized.\", pattern: [A-Z]{3}", 464 | "type": "string" 465 | }, 466 | "filters": { 467 | "description": "A list of filters that should be applied when retrieving YouTube Analytics data. The [Available Reports](/youtube/analytics/v2/available_reports) document identifies the dimensions that can be used to filter each report, and the [Dimensions](/youtube/analytics/v2/dimsmets/dims) document defines those dimensions. If a request uses multiple filters, join them together with a semicolon (`;`), and the returned result table will satisfy both filters. For example, a filters parameter value of `video==dMH0bHeiRNg;country==IT` restricts the result set to include data for the given video in Italy.\",", 468 | "location": "query", 469 | "type": "string" 470 | }, 471 | "startDate": { 472 | "type": "string", 473 | "description": "The start date for fetching YouTube Analytics data. The value should be in `YYYY-MM-DD` format. required: true, pattern: \"[0-9]{4}-[0-9]{2}-[0-9]{2}", 474 | "location": "query" 475 | }, 476 | "includeHistoricalChannelData": { 477 | "type": "boolean", 478 | "description": "If set to true historical data (i.e. channel data from before the linking of the channel to the content owner) will be retrieved.\",", 479 | "location": "query" 480 | }, 481 | "maxResults": { 482 | "location": "query", 483 | "description": "The maximum number of rows to include in the response.\", minValue: 1", 484 | "type": "integer", 485 | "format": "int32" 486 | }, 487 | "startIndex": { 488 | "type": "integer", 489 | "format": "int32", 490 | "description": "An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter (one-based, inclusive).\", minValue: 1", 491 | "location": "query" 492 | } 493 | }, 494 | "httpMethod": "GET", 495 | "path": "v2/reports", 496 | "scopes": [ 497 | "https://www.googleapis.com/auth/youtube", 498 | "https://www.googleapis.com/auth/youtube.readonly", 499 | "https://www.googleapis.com/auth/youtubepartner", 500 | "https://www.googleapis.com/auth/yt-analytics-monetary.readonly", 501 | "https://www.googleapis.com/auth/yt-analytics.readonly" 502 | ], 503 | "response": { 504 | "$ref": "QueryResponse" 505 | }, 506 | "id": "youtubeAnalytics.reports.query", 507 | "flatPath": "v2/reports", 508 | "parameterOrder": [], 509 | "description": "Retrieve your YouTube Analytics reports." 510 | } 511 | } 512 | }, 513 | "groups": { 514 | "methods": { 515 | "update": { 516 | "parameterOrder": [], 517 | "scopes": [ 518 | "https://www.googleapis.com/auth/youtube", 519 | "https://www.googleapis.com/auth/youtube.readonly", 520 | "https://www.googleapis.com/auth/youtubepartner", 521 | "https://www.googleapis.com/auth/yt-analytics-monetary.readonly", 522 | "https://www.googleapis.com/auth/yt-analytics.readonly" 523 | ], 524 | "path": "v2/groups", 525 | "parameters": { 526 | "onBehalfOfContentOwner": { 527 | "type": "string", 528 | "location": "query", 529 | "description": "This parameter can only be used in a properly authorized request. **Note:** This parameter is intended exclusively for YouTube content partners that own and manage many different YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's authorization credentials identify a YouTube user who is acting on behalf of the content owner specified in the parameter value. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The account that the user authenticates with must be linked to the specified YouTube content owner." 530 | } 531 | }, 532 | "description": "Modifies a group. For example, you could change a group's title.", 533 | "response": { 534 | "$ref": "Group" 535 | }, 536 | "flatPath": "v2/groups", 537 | "httpMethod": "PUT", 538 | "id": "youtubeAnalytics.groups.update", 539 | "request": { 540 | "$ref": "Group" 541 | } 542 | }, 543 | "insert": { 544 | "request": { 545 | "$ref": "Group" 546 | }, 547 | "description": "Creates a group.", 548 | "parameters": { 549 | "onBehalfOfContentOwner": { 550 | "type": "string", 551 | "description": "This parameter can only be used in a properly authorized request. **Note:** This parameter is intended exclusively for YouTube content partners that own and manage many different YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's authorization credentials identify a YouTube user who is acting on behalf of the content owner specified in the parameter value. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The account that the user authenticates with must be linked to the specified YouTube content owner.", 552 | "location": "query" 553 | } 554 | }, 555 | "parameterOrder": [], 556 | "path": "v2/groups", 557 | "flatPath": "v2/groups", 558 | "scopes": [ 559 | "https://www.googleapis.com/auth/youtube", 560 | "https://www.googleapis.com/auth/youtube.readonly", 561 | "https://www.googleapis.com/auth/youtubepartner", 562 | "https://www.googleapis.com/auth/yt-analytics-monetary.readonly", 563 | "https://www.googleapis.com/auth/yt-analytics.readonly" 564 | ], 565 | "response": { 566 | "$ref": "Group" 567 | }, 568 | "httpMethod": "POST", 569 | "id": "youtubeAnalytics.groups.insert" 570 | }, 571 | "list": { 572 | "httpMethod": "GET", 573 | "scopes": [ 574 | "https://www.googleapis.com/auth/youtube", 575 | "https://www.googleapis.com/auth/youtube.readonly", 576 | "https://www.googleapis.com/auth/youtubepartner", 577 | "https://www.googleapis.com/auth/yt-analytics-monetary.readonly", 578 | "https://www.googleapis.com/auth/yt-analytics.readonly" 579 | ], 580 | "parameters": { 581 | "onBehalfOfContentOwner": { 582 | "location": "query", 583 | "description": "This parameter can only be used in a properly authorized request. **Note:** This parameter is intended exclusively for YouTube content partners that own and manage many different YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's authorization credentials identify a YouTube user who is acting on behalf of the content owner specified in the parameter value. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The account that the user authenticates with must be linked to the specified YouTube content owner.", 584 | "type": "string" 585 | }, 586 | "mine": { 587 | "type": "boolean", 588 | "location": "query", 589 | "description": "This parameter can only be used in a properly authorized request. Set this parameter's value to true to retrieve all groups owned by the authenticated user." 590 | }, 591 | "id": { 592 | "description": "The `id` parameter specifies a comma-separated list of the YouTube group ID(s) for the resource(s) that are being retrieved. Each group must be owned by the authenticated user. In a `group` resource, the `id` property specifies the group's YouTube group ID. Note that if you do not specify a value for the `id` parameter, then you must set the `mine` parameter to `true`.", 593 | "location": "query", 594 | "type": "string" 595 | }, 596 | "pageToken": { 597 | "location": "query", 598 | "type": "string", 599 | "description": "The `pageToken` parameter identifies a specific page in the result set that should be returned. In an API response, the `nextPageToken` property identifies the next page that can be retrieved." 600 | } 601 | }, 602 | "parameterOrder": [], 603 | "description": "Returns a collection of groups that match the API request parameters. For example, you can retrieve all groups that the authenticated user owns, or you can retrieve one or more groups by their unique IDs.", 604 | "path": "v2/groups", 605 | "flatPath": "v2/groups", 606 | "response": { 607 | "$ref": "ListGroupsResponse" 608 | }, 609 | "id": "youtubeAnalytics.groups.list" 610 | }, 611 | "delete": { 612 | "scopes": [ 613 | "https://www.googleapis.com/auth/youtube", 614 | "https://www.googleapis.com/auth/youtube.readonly", 615 | "https://www.googleapis.com/auth/youtubepartner", 616 | "https://www.googleapis.com/auth/yt-analytics-monetary.readonly", 617 | "https://www.googleapis.com/auth/yt-analytics.readonly" 618 | ], 619 | "path": "v2/groups", 620 | "parameterOrder": [], 621 | "response": { 622 | "$ref": "EmptyResponse" 623 | }, 624 | "httpMethod": "DELETE", 625 | "parameters": { 626 | "id": { 627 | "description": "The `id` parameter specifies the YouTube group ID of the group that is being deleted.", 628 | "type": "string", 629 | "location": "query" 630 | }, 631 | "onBehalfOfContentOwner": { 632 | "location": "query", 633 | "description": "This parameter can only be used in a properly authorized request. **Note:** This parameter is intended exclusively for YouTube content partners that own and manage many different YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's authorization credentials identify a YouTube user who is acting on behalf of the content owner specified in the parameter value. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The account that the user authenticates with must be linked to the specified YouTube content owner.", 634 | "type": "string" 635 | } 636 | }, 637 | "id": "youtubeAnalytics.groups.delete", 638 | "flatPath": "v2/groups", 639 | "description": "Deletes a group." 640 | } 641 | } 642 | }, 643 | "groupItems": { 644 | "methods": { 645 | "delete": { 646 | "flatPath": "v2/groupItems", 647 | "scopes": [ 648 | "https://www.googleapis.com/auth/youtube", 649 | "https://www.googleapis.com/auth/youtube.readonly", 650 | "https://www.googleapis.com/auth/youtubepartner", 651 | "https://www.googleapis.com/auth/yt-analytics-monetary.readonly", 652 | "https://www.googleapis.com/auth/yt-analytics.readonly" 653 | ], 654 | "description": "Removes an item from a group.", 655 | "httpMethod": "DELETE", 656 | "parameters": { 657 | "id": { 658 | "description": "The `id` parameter specifies the YouTube group item ID of the group item that is being deleted.", 659 | "type": "string", 660 | "location": "query" 661 | }, 662 | "onBehalfOfContentOwner": { 663 | "description": "This parameter can only be used in a properly authorized request. **Note:** This parameter is intended exclusively for YouTube content partners that own and manage many different YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's authorization credentials identify a YouTube user who is acting on behalf of the content owner specified in the parameter value. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The account that the user authenticates with must be linked to the specified YouTube content owner.", 664 | "type": "string", 665 | "location": "query" 666 | } 667 | }, 668 | "id": "youtubeAnalytics.groupItems.delete", 669 | "path": "v2/groupItems", 670 | "response": { 671 | "$ref": "EmptyResponse" 672 | }, 673 | "parameterOrder": [] 674 | }, 675 | "list": { 676 | "httpMethod": "GET", 677 | "response": { 678 | "$ref": "ListGroupItemsResponse" 679 | }, 680 | "path": "v2/groupItems", 681 | "parameterOrder": [], 682 | "description": "Returns a collection of group items that match the API request parameters.", 683 | "flatPath": "v2/groupItems", 684 | "parameters": { 685 | "groupId": { 686 | "description": "The `groupId` parameter specifies the unique ID of the group for which you want to retrieve group items.", 687 | "type": "string", 688 | "location": "query" 689 | }, 690 | "onBehalfOfContentOwner": { 691 | "description": "This parameter can only be used in a properly authorized request. **Note:** This parameter is intended exclusively for YouTube content partners that own and manage many different YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's authorization credentials identify a YouTube user who is acting on behalf of the content owner specified in the parameter value. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The account that the user authenticates with must be linked to the specified YouTube content owner.", 692 | "location": "query", 693 | "type": "string" 694 | } 695 | }, 696 | "id": "youtubeAnalytics.groupItems.list", 697 | "scopes": [ 698 | "https://www.googleapis.com/auth/youtube", 699 | "https://www.googleapis.com/auth/youtube.readonly", 700 | "https://www.googleapis.com/auth/youtubepartner", 701 | "https://www.googleapis.com/auth/yt-analytics-monetary.readonly", 702 | "https://www.googleapis.com/auth/yt-analytics.readonly" 703 | ] 704 | }, 705 | "insert": { 706 | "flatPath": "v2/groupItems", 707 | "parameters": { 708 | "onBehalfOfContentOwner": { 709 | "location": "query", 710 | "description": "This parameter can only be used in a properly authorized request. **Note:** This parameter is intended exclusively for YouTube content partners that own and manage many different YouTube channels. The `onBehalfOfContentOwner` parameter indicates that the request's authorization credentials identify a YouTube user who is acting on behalf of the content owner specified in the parameter value. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The account that the user authenticates with must be linked to the specified YouTube content owner.", 711 | "type": "string" 712 | } 713 | }, 714 | "request": { 715 | "$ref": "GroupItem" 716 | }, 717 | "scopes": [ 718 | "https://www.googleapis.com/auth/youtube", 719 | "https://www.googleapis.com/auth/youtube.readonly", 720 | "https://www.googleapis.com/auth/youtubepartner", 721 | "https://www.googleapis.com/auth/yt-analytics-monetary.readonly", 722 | "https://www.googleapis.com/auth/yt-analytics.readonly" 723 | ], 724 | "httpMethod": "POST", 725 | "description": "Creates a group item.", 726 | "id": "youtubeAnalytics.groupItems.insert", 727 | "path": "v2/groupItems", 728 | "response": { 729 | "$ref": "GroupItem" 730 | }, 731 | "parameterOrder": [] 732 | } 733 | } 734 | } 735 | }, 736 | "icons": { 737 | "x32": "http://www.google.com/images/icons/product/search-32.gif", 738 | "x16": "http://www.google.com/images/icons/product/search-16.gif" 739 | }, 740 | "description": "Retrieves your YouTube Analytics data.", 741 | "canonicalName": "YouTube Analytics", 742 | "rootUrl": "https://youtubeanalytics.googleapis.com/", 743 | "batchPath": "batch", 744 | "protocol": "rest", 745 | "ownerDomain": "google.com", 746 | "revision": "20230314" 747 | } -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3 2 | 3 | ADD requirements.txt / 4 | RUN pip install -r requirements.txt 5 | ADD main.py / 6 | ADD YouTube_API.py / 7 | ADD CLIENT_SECRET.json / 8 | ADD credentials.json / 9 | 10 | CMD [ "python", "./main.py"] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | BSD 3-Clause License 2 | 3 | Copyright (c) 2022-Present, Prem Patel 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are met: 7 | 8 | 1. Redistributions of source code must retain the above copyright notice, this 9 | list of conditions and the following disclaimer. 10 | 11 | 2. Redistributions in binary form must reproduce the above copyright notice, 12 | this list of conditions and the following disclaimer in the documentation 13 | and/or other materials provided with the distribution. 14 | 15 | 3. Neither the name of the copyright holder nor the names of its 16 | contributors may be used to endorse or promote products derived from 17 | this software without specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 20 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 22 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 23 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 24 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 25 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 26 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 27 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | YouTube 3 |

4 |

📊 YouTube Analytics Discord Bot 🤖

5 | 6 |

7 | An awesome Discord Bot to fetch your YouTube Channel Analytics. 8 |

9 | 10 |

11 | 12 | 13 | 14 | 15 | GitHub Sponsor 16 | 17 | 18 | Buy Me A Coffee 19 | 20 |

21 | 22 | --- 23 | 24 | ## Features 🔧 25 | - Collects data on various metrics, including views, revenue, subscriber growth, & more. 26 | - Helps analyze channel performance and identify areas for improvement. 27 | - User-friendly Discord Button UI. 28 | - Docker Support. 29 | - Developer Mode. 30 | - Efficient API Service Build Methods & Fail-Safe(s). 31 | - 24/7 Operation with Replit & Flask (Dev Mode + Build from Document). 32 | 33 | ### Input Formatting & Bot Commands 🔠 34 | Start every command with `!`. Optional command inputs are denoted with [brackets]. 35 | 36 | Check [Example Output Folder](https://github.com/Prem-ium/youtube-analytics-bot/blob/main/output-examples/README.MD) for output examples. 37 | 38 | - MM / DD Format (MONTH/DATE, assumes current year) or MM / DD / YYYY: 39 | ```sh 40 | !stats 01/01 12/01 41 | !stats 01/01/2021 12/31/2021 42 | ``` 43 | 44 | ### Text Commands 💬 45 | | Command | Description | 46 | |---------|-------------| 47 | | `!button [startDate] [endDate]` | Open Discord Button UI with all supported commands. | 48 | | `!stats [startDate] [endDate]` | 📅 YouTube Analytics Report Card: Displays views, watch-time, estimated revenue, CPM, ad-impressions, & more. Defaults to current month if no date range is specified. | 49 | | `!getMonth [month/year]` | Return stats for a specific month. 📆 | 50 | | `!lifetime` | Get lifetime stats. 🧮 | 51 | | `!topEarnings [startDate] [endDate] [Length to Return]` | Get a list of the highest revenue-earning videos on your channel. 💰 | 52 | | `!geo_revenue [startDate] [endDate] [Length to Return]` | Get a list of your top revenue-earning countries. 🌎💰 | 53 | | `!geoReport [startDate] [endDate] [Length to Return]` | Detailed report of views, revenue, CPM, etc., by country. 🌎 | 54 | | `!adtype [startDate] [endDate]` | Get highest-performing ad types within specified time range. 💰 | 55 | | `!demographics [startDate] [endDate]` | Get demographics data (age and gender) of viewers. 👨‍👩‍👧‍👧 | 56 | | `!shares [startDate] [endDate] [Length to Return]` | Return list of top sharing methods for your videos. 📤 | 57 | | `!search [startDate] [endDate] [Length to Return]` | Return YouTube search terms resulting in the most views of your video(s). 🔍 | 58 | | `!os [startDate] [endDate] [Length to Return]` | Return top operating systems watching your videos (ranked by views). 📟 | 59 | | `!playlist [startDate] [endDate] [Length to Return]` | Retrieve your Playlist Report. | 60 | | `!everything [startDate] [endDate]` | Return everything. Call every method and output all available data. ♾️ | 61 | | `!refresh [token]` | Refresh API Token! | 62 | | `!switch` | Switch Dev Mode On/Off. | 63 | | `!help` | Send all Discord commands with explanations. 🦮 | 64 | | `!ping` | Check if the bot is running. | 65 | 66 | ### Button Supported Commands 🔘 67 | Upon invoking the `!button` command, these are currently supported with a scene containing interactive buttons: 68 | - Analytics 69 | - Top Revenue Videos 70 | - Top Searched Keywords 71 | - Playlist Stats 72 | - Geographic Data 73 | - OS Statistics 74 | - Traffic Source 75 | - Shares 76 | - Top Geographic-Based Revenue 77 | 78 | --- 79 | 80 | ## Set-Up & Installation 🚀 81 | To use this project, enable Google Cloud Console YouTube Analytics/Data API for your account and create a Discord bot to obtain a Discord token. 82 | 83 | ### Google Cloud Console API Setup 🌐 84 | 85 | 1. **Create a New Project** 86 | - Visit [Google Cloud Console](https://console.cloud.google.com/apis) and create a new project. 87 | 88 | 2. **Enable APIs and Services** 89 | - Go to **API & Services** and select **Enable APIs and Services**. 90 | 91 | 3. **Enable YouTube APIs** 92 | - Search for and enable both **YouTube Data API** and **YouTube Analytics API**. 93 | 94 | 4. **Configure OAuth Consent Screen** 95 | - Return to **API & Services** page and click on **Credentials**. 96 | - Select **User Type (External)**, then configure the **OAuth Consent Screen** with these YouTube Analytics-related scopes: 97 | - `https://www.googleapis.com/auth/youtube.readonly` 98 | - `https://www.googleapis.com/auth/yt-analytics-monetary.readonly` 99 | 100 | 5. **Complete OAuth Configuration** 101 | - Finish the rest of the OAuth configuration. 102 | 103 | 6. **Create OAuth Credentials** 104 | - Click **Create Credentials**, then select **OAuth Credentials**, followed by **Desktop Application**. 105 | 106 | 7. **Download OAuth JSON File** 107 | - Download the JSON file and name it `CLIENT_SECRET.json`. 108 | - Place this file in the same folder as your program. 109 | 110 | 8. **Create API Key** 111 | - Create Credentials → API Key. 112 | - Copy and assign the API key to the `YOUTUBE_API_KEY` environment variable. 113 | 114 | Your Google Cloud Console API is now ready! 115 | 116 | ### Discord Bot Setup 🌐 117 | 118 | 1. **Create a Discord Application** 119 | - Go to [Discord Developers](https://discord.com/developers/) and create a new application. Name it "YouTube Apprise" or something suitable. 120 | 121 | 2. **Configure OAuth2** 122 | - In your new application, go to the **OAuth2** URL Generator section. 123 | 124 | 3. **Select Scopes and Permissions** 125 | - Under **Scopes**, choose **Bot** and enable the required bot permissions, such as **Send Messages** and **Read Message History**. 126 | 127 | 4. **Generate Bot Invite Link** 128 | - Copy the generated link from the **Permissions** section and use it to add the bot to your server. 129 | 130 | 5. *(Optional)* **Customize Profile Picture** 131 | - Upload an appealing image in the **Rich Presence** section. 132 | 133 | 6. **Retrieve Bot Token** 134 | - In the **Bot** section, obtain the bot token and assign it to the `DISCORD_TOKEN` environment variable. 135 | 136 | Your Discord bot is now set up! 137 | 138 | ## Installation 🛠️ 139 | 140 | The bot can be run using Python or Docker. 141 | 142 | ### Python Script 🐍 143 | 144 | 1. Clone this repository, cd into it, and install dependencies: 145 | ```sh 146 | git clone https://github.com/Prem-ium/youtube-analytics-bot 147 | cd youtube-analytics-bot 148 | pip install -r requirements.txt 149 | ``` 150 | 151 | 2. Configure your `.env` file (see below for options). 152 | 3. Run the script: 153 | ```sh 154 | python main.py 155 | ``` 156 | 157 | ### Docker Setup 🐳 158 | 159 | 1. **Generate Credentials JSON File** 160 | - Run the Python script locally to generate the `credentials.json` file. 161 | 162 | 2. **Install Docker** 163 | - Download and install Docker. 164 | 165 | 3. **Configure `.env` File** 166 | - Configure your `.env` file with the necessary settings. 167 | 168 | 4. **Build Docker Image** 169 | ```sh 170 | docker build -t youtube-apprise . 171 | ``` 172 | 173 | 5. **Start Bot in Docker Container** 174 | ```sh 175 | docker run -it --env-file ./.env --restart unless-stopped --name youtube-apprise youtube-apprise 176 | ``` 177 | 178 | 6. **Running the Bot** 179 | - To exit logs without stopping the bot, press `CTRL-p` followed by `CTRL-q`. 180 | 181 | --- 182 | ## Environment Variables 🖥️ 183 | 184 | Refer to the `.env.example` file for options. 185 | 186 | ### Required `.env`: 187 | | Environment Variable | Description | 188 | |----------------------|-------------| 189 | | `DISCORD_TOKEN` | Discord bot token | 190 | | `YOUTUBE_API_KEY` | YouTube Data API key | 191 | 192 | ### Optional `.env`: 193 | | Environment Variable | Description | 194 | |----------------------|-------------| 195 | | `CLIENT_PATH` | Path to YouTube/Google Client Secret JSON file (defaults to current directory). | 196 | | `DEV_MODE` | Enable experimental features (requires CLIENT_SECRET). | 197 | | `CLIENT_SECRET` | Contents of `CLIENT_SECRET.json`. | 198 | | `DISCORD_CHANNEL` | Channel ID for developer mode. | 199 | | `KEEP_ALIVE` | Boolean value to keep the bot running (e.g., True for Replit). | 200 | 201 | --- 202 | ## Experiencing Issues? 🛠️ 203 | As of 9/8/2024, I have disabled the Issues privilege for the general public. For direct support on any bugs or issues, please consider sponsoring me as a GitHub Sponsor under the Silver or Gold tier. 204 | [![Sponsor](https://img.shields.io/badge/sponsor-30363D?style=for-the-badge&logo=GitHub-Sponsors&logoColor=#white)](https://github.com/sponsors/Prem-ium) 205 | 206 | --- 207 | ## Donations ❤️ 208 | If you appreciate my work, you can donate via: 209 | 210 | 1. **GitHub Sponsors** - [Donate via GitHub Sponsors](https://github.com/sponsors/Prem-ium). 211 | 2. **Buy Me A Coffee**: [Donate via Buy Me A Coffee](https://www.buymeacoffee.com/prem.ium). 212 | 213 | --- 214 | ## License 📝 215 | This repository is licensed under the [BSD 3-Clause License](https://choosealicense.com/licenses/bsd-3-clause/#). 216 | 217 | --- 218 | ## Final Remarks ✨ 219 | Please leave a ⭐ if you found this project cool! Made possible by Google's YouTube Analytics/Data APIs. May your analytics skyrocket! 📈 220 | -------------------------------------------------------------------------------- /YouTube_API.py: -------------------------------------------------------------------------------- 1 | # Github Repository: https://github.com/Prem-ium/youtube-analytics-bot 2 | 3 | # BSD 3-Clause License 4 | # 5 | # Copyright (c) 2022-present, Prem Patel 6 | # All rights reserved. 7 | # 8 | # Redistribution and use in source and binary forms, with or without 9 | # modification, are permitted provided that the following conditions are met: 10 | # 11 | # 1. Redistributions of source code must retain the above copyright notice, this 12 | # list of conditions and the following disclaimer. 13 | # 14 | # 2. Redistributions in binary form must reproduce the above copyright notice, 15 | # this list of conditions and the following disclaimer in the documentation 16 | # and/or other materials provided with the distribution. 17 | # 18 | # 3. Neither the name of the copyright holder nor the names of its 19 | # contributors may be used to endorse or promote products derived from 20 | # this software without specific prior written permission. 21 | # 22 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 23 | # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 24 | # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 25 | # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 26 | # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 27 | # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 28 | # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 29 | # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 30 | # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | 33 | 34 | import os, datetime, traceback, requests, json 35 | import discord 36 | 37 | from oauth2client.client import HttpAccessTokenRefreshError 38 | from googleapiclient.discovery import build, build_from_document 39 | from oauth2client.file import Storage 40 | from oauth2client import client, tools 41 | from google.oauth2.credentials import Credentials 42 | 43 | from dotenv import load_dotenv 44 | 45 | # Load the .env file & assign the variables 46 | load_dotenv() 47 | 48 | YOUTUBE_API_KEY = os.environ["YOUTUBE_API_KEY"] 49 | 50 | DEV_MODE = (os.environ.get("DEV_MODE", "False").lower() == "true") 51 | 52 | if DEV_MODE: 53 | print("- " * 25) 54 | print("Attention: Developer mode enabled.") 55 | print("The program will rely on the CLIENT_SECRET JSON Dict assigned to the proper .env variable.") 56 | print("It will not search for or use a CLIENT_SECRET.json file.") 57 | print("- " * 25) 58 | 59 | try: 60 | CLIENT_SECRETS = json.loads(os.environ.get("CLIENT_SECRET", None))['installed'] 61 | except: raise Exception("CLIENT_SECRET is missing within .env file, please add it and try again.") 62 | 63 | else: 64 | CLIENT_SECRETS = os.environ.get("CLIENT_PATH", "CLIENT_SECRET.json") 65 | 66 | # Declare global scope 67 | SCOPES = ["https://www.googleapis.com/auth/youtube.readonly", 68 | "https://www.googleapis.com/auth/yt-analytics-monetary.readonly"] 69 | 70 | def get_service (API_SERVICE_NAME='youtubeAnalytics', API_VERSION='v2', SCOPES=SCOPES): 71 | global DEV_MODE, CLIENT_SECRETS 72 | 73 | # Build the service object if DEV_MODE is enabled, otherwise use the credentials.json file 74 | if DEV_MODE: 75 | try: 76 | credentials = Credentials.from_authorized_user_info(CLIENT_SECRETS) 77 | return build(API_SERVICE_NAME, API_VERSION, credentials=credentials) 78 | except: print(f'Failed to build service:\n{traceback.format_exc()}') 79 | 80 | try: 81 | credential_path = os.path.join('./', 'credentials.json') 82 | store = Storage(credential_path) 83 | credentials = store.get() 84 | if not credentials or credentials.invalid: 85 | flow = client.flow_from_clientsecrets(CLIENT_SECRETS, SCOPES) 86 | credentials = tools.run_flow(flow, store) 87 | return build(API_SERVICE_NAME, API_VERSION, credentials=credentials) 88 | except: print(f'Failed to run client flow service: \n{traceback.format_exc()}') 89 | 90 | try: 91 | credentials = Credentials.from_authorized_user_info(CLIENT_SECRETS) 92 | json_path = 'API_Service/Analytics-Service.json' if API_SERVICE_NAME == 'youtubeAnalytics' else 'API_Service/YouTube-Data-API.json' 93 | print(f'Building failed (This is expected behavior on replit.com), trying to build from document: {json_path}') 94 | with open(json_path) as f: 95 | service = json.load(f) 96 | return build_from_document(service, credentials = credentials) 97 | except Exception as e: 98 | print(f'Failed: Exhaused all get_service methods: \n{traceback.format_exc()}') 99 | raise 100 | 101 | # Swap between dev mode and normal mode 102 | async def dev_mode(): 103 | global DEV_MODE, CLIENT_SECRETS 104 | DEV_MODE = not DEV_MODE 105 | 106 | if DEV_MODE: 107 | # Developer mode is enabled 108 | print("Developer mode is enabled. The program will rely on CLIENT_SECRET JSON Dict assigned to the proper .env variable.") 109 | print("Check .env.example for an example. Remember to add your refresh token in the JSON.\n") 110 | try: 111 | CLIENT_SECRETS = json.loads(os.environ.get("CLIENT_SECRET", "{}")).get("installed") 112 | if CLIENT_SECRETS is None: 113 | raise Exception("CLIENT_SECRET is missing within .env file. Please add it and try again.") 114 | except json.JSONDecodeError: 115 | raise Exception("CLIENT_SECRET in .env is not a valid JSON string.") 116 | else: 117 | CLIENT_SECRETS = os.environ.get("CLIENT_PATH", "CLIENT_SECRET.json") 118 | 119 | def refresh_token (token=None): 120 | print(f'Refreshing Credentials Access Token...') 121 | global DEV_MODE 122 | if DEV_MODE: 123 | global CLIENT_SECRETS 124 | global YOUTUBE_ANALYTICS 125 | global YOUTUBE_DATA 126 | 127 | if token is not None: 128 | try: 129 | refresh_token = {"refresh_token": token} 130 | CLIENT_SECRETS.update(refresh_token) 131 | return f"Dev Mode: Successfully updated refresh token to {token}\nYou will need to update if the bot is restarted.\n" 132 | except Exception as e: return f"Ran into {e.__class__.__name__} Exception: {e}" 133 | 134 | data = { 135 | 'client_id': CLIENT_SECRETS['client_id'], 136 | 'client_secret': CLIENT_SECRETS['client_secret'], 137 | 'refresh_token': CLIENT_SECRETS['refresh_token'], 138 | 'grant_type': 'refresh_token' 139 | } 140 | response = requests.post('https://accounts.google.com/o/oauth2/token', data=data) 141 | if response.status_code == 200: 142 | response_json = response.json() 143 | CLIENT_SECRETS['access_token'] = response_json['access_token'] 144 | CLIENT_SECRETS['expires_in'] = response_json['expires_in'] 145 | 146 | # Calculate and update token expiry time 147 | now = datetime.datetime.now() 148 | CLIENT_SECRETS['token_expiry'] = (now + datetime.timedelta(seconds=response_json['expires_in'])).isoformat() 149 | 150 | message = f"{response.status_code}:\tSuccessfully refreshed token\n{datetime.datetime.now()}\n" 151 | YOUTUBE_ANALYTICS = get_service() 152 | YOUTUBE_DATA = get_service('youtube', 'v3', SCOPES) 153 | else: 154 | message = f"{response.status_code}:\tFalied to refresh token\t{datetime.datetime.now()}\n{response.text}" 155 | else: 156 | message = None 157 | with open('credentials.json') as f: 158 | cred = json.load(f) 159 | data = { 160 | 'client_id': cred['client_id'], 161 | 'client_secret': cred['client_secret'], 162 | 'refresh_token': cred['refresh_token'], 163 | 'grant_type': 'refresh_token' 164 | } 165 | 166 | response = requests.post('https://accounts.google.com/o/oauth2/token', data=data) 167 | if response.status_code == 200: 168 | response_json = response.json() 169 | 170 | # Update token_response with new access token and expiry time 171 | cred['token_response']['access_token'] = response_json['access_token'] 172 | cred['token_response']['expires_in'] = response_json['expires_in'] 173 | 174 | # Calculate and update token expiry time 175 | now = datetime.datetime.now() 176 | cred['token_expiry'] = (now + datetime.timedelta(seconds=response_json['expires_in'])).isoformat() 177 | message = f"{response.status_code}:\tSuccessfully refreshed token\n{datetime.datetime.now()}\n" 178 | # Save updated credentials to file 179 | with open('credentials.json', 'w') as f: 180 | json.dump(cred, f) 181 | else: 182 | message = f"{response.status_code}:\tFalied to refresh token\t{datetime.datetime.now()}\n{response.text}" 183 | return message 184 | 185 | 186 | 187 | # Refresh the token 188 | async def refresh(return_embed=False, token=None): 189 | message = refresh_token(token) 190 | if return_embed: 191 | embed = discord.Embed(title=f"YouTube Analytics Bot Refresh", color=0x00ff00) 192 | embed.add_field(name="Status", value=message, inline=False) 193 | return embed 194 | else: 195 | return message 196 | def execute_api_request(client_library_function, **kwargs): 197 | return client_library_function(**kwargs).execute() 198 | 199 | # Discord bot command methods. 200 | async def get_stats (start=datetime.datetime.now().strftime("%Y-%m-01"), end=datetime.datetime.now().strftime("%Y-%m-%d")): 201 | try: 202 | # Query the YouTube Analytics API 203 | response = execute_api_request( 204 | YOUTUBE_ANALYTICS.reports().query, 205 | ids='channel==MINE', 206 | startDate=start, 207 | endDate=end, 208 | metrics='views,estimatedMinutesWatched,subscribersGained,subscribersLost,estimatedRevenue,cpm,monetizedPlaybacks,playbackBasedCpm,adImpressions,likes,dislikes,averageViewDuration,shares,averageViewPercentage,subscribersGained,subscribersLost', 209 | ) 210 | 211 | # Retrieve the data from the response 212 | views = response['rows'][0][0] 213 | minutes = response['rows'][0][1] 214 | subscribersGained = response['rows'][0][2] - response['rows'][0][3] 215 | revenue = response['rows'][0][4] 216 | cpm = response['rows'][0][5] 217 | monetizedPlaybacks = response['rows'][0][6] 218 | playbackCpm = response['rows'][0][7] 219 | adImpressions = response['rows'][0][8] 220 | likes = response['rows'][0][9] 221 | dislikes = response['rows'][0][10] 222 | averageViewDuration = response['rows'][0][11] 223 | shares = response['rows'][0][12] 224 | averageViewPercentage = response['rows'][0][13] 225 | subscribersGained = response['rows'][0][14] 226 | subscribersLost = response['rows'][0][15] 227 | netSubscribers = subscribersGained - subscribersLost 228 | 229 | # Terminary operator to check if start/end year share a year, and strip/remove if that's the case 230 | start, end = (start[5:] if start[:4] == end[:4] else f'{start[5:]}-{start[:4]}').replace('-', '/'), (end[5:] if start[:4] == end[:4] else f'{end[5:]}-{end[:4]}').replace('-', '/') 231 | 232 | # create a Discord Embed object 233 | embed = discord.Embed(title=f"YouTube Analytics Report ({start} - {end})", color=0x00ff00) 234 | 235 | # add fields to the embed 236 | embed.add_field(name="Views", value=f"{round(views,2):,}", inline=True) 237 | embed.add_field(name="Ratings", value=f"{100*round(likes/(likes + dislikes),2):,}%", inline=True) 238 | embed.add_field(name="Minutes Watched", value=f"{round(minutes,2):,}", inline=True) 239 | embed.add_field(name="Average View Duration", value=f"{round(averageViewDuration,2):,}s ({round(averageViewPercentage,2):,}%)", inline=True) 240 | embed.add_field(name="Net Subscribers", value=f"{round(netSubscribers,2):,}", inline=True) 241 | embed.add_field(name="Shares", value=f"{round(shares,2):,}", inline=True) 242 | 243 | embed.add_field(name="\u200b", value="\u200b", inline=False) 244 | 245 | embed.add_field(name="Estimated Revenue", value=f"${round(revenue,2):,}", inline=True) 246 | embed.add_field(name="CPM", value=f"${round(cpm,2):,}", inline=True) 247 | embed.add_field(name="Monetized Playbacks (±2.0%)", value=f"{round(monetizedPlaybacks,2):,}", inline=True) 248 | embed.add_field(name="Playback CPM", value=f"${round(playbackCpm,2):,}", inline=True) 249 | embed.add_field(name="Ad Impressions", value=f"{round(adImpressions,2):,}", inline=True) 250 | 251 | # Build the response string 252 | response_str = f'YouTube Analytics Report ({start}\t-\t{end})\n\n' 253 | response_str += f'Views:\t{round(views,2):,}\nRatings:\t{100*round(likes/(likes + dislikes),2):,}%\nMinutes Watched:\t{round(minutes,2):,}\nAverage View Duration:\t{round(averageViewDuration,2):,}s ({round(averageViewPercentage,2):,}%)\nNet Subscribers:\t{round(netSubscribers,2):,}\nShares:\t{round(shares,2):,}\n\n' 254 | response_str += f'Estimated Revenue:\t${round(revenue,2):,}\nCPM:\t${round(cpm,2):,}\nMonetized Playbacks (±2.0%):\t{round(monetizedPlaybacks,2):,}\nPlayback CPM:\t${round(playbackCpm,2):,}\nAd Impressions:\t{round(adImpressions,2):,}' 255 | print(response_str + '\nSending to Discord...') 256 | 257 | return embed, response_str 258 | 259 | except HttpAccessTokenRefreshError: return "The credentials have been revoked or expired, please re-run the application to re-authorize." 260 | except Exception as e: 261 | print(traceback.format_exc()) 262 | return f"Ran into {e.__class__.__name__} exception, {traceback.format_exc()}" 263 | 264 | 265 | async def top_revenue (results=10, start=datetime.datetime.now().strftime("%Y-%m-01"), end=datetime.datetime.now().strftime("%Y-%m-%d")): 266 | try: 267 | # Query the YouTube Analytics API 268 | response = execute_api_request( 269 | YOUTUBE_ANALYTICS.reports().query, 270 | ids='channel==MINE', 271 | startDate=start, 272 | endDate=end, 273 | dimensions='video', 274 | metrics='estimatedRevenue', 275 | sort='-estimatedRevenue', 276 | maxResults=results, 277 | ) 278 | 279 | # Retrieve video IDs and earnings from the response 280 | video_ids = [] 281 | earnings = [] 282 | for data in response['rows']: 283 | video_ids.append(data[0]) 284 | earnings.append(data[1]) 285 | 286 | # Query the YouTube Data API 287 | request = YOUTUBE_DATA.videos().list( 288 | part="snippet", 289 | id=','.join(video_ids) 290 | ) 291 | response = request.execute() 292 | 293 | # Format the start and end dates 294 | start, end = (start[5:] if start[:4] == end[:4] else f'{start[5:]}-{start[:4]}').replace('-', '/'), (end[5:] if start[:4] == end[:4] else f'{end[5:]}-{end[:4]}').replace('-', '/') 295 | 296 | # create a Discord Embed object 297 | embed = discord.Embed(title=f"Top {results} Earning Videos ({start} - {end})", color=0x00ff00) 298 | 299 | total = 0 300 | for i in range(len(response['items'])): 301 | embed.add_field(name=f"{i + 1}) {response['items'][i]['snippet']['title']}:\t${round(earnings[i], 2):,}", value=f"------------------------------------------------------------------------------------", inline=False) 302 | total += earnings[i] 303 | embed.add_field(name="\u200b", value="\u200b", inline=False) 304 | embed.add_field(name=f"Top {results} Total Earnings", value=f"${round(total, 2):,}", inline=False) 305 | 306 | # Build the response string 307 | response_str = f'Top {results} Earning Videos ({start}\t-\t{end}):\n\n' 308 | total = 0 309 | for i in range(len(response['items'])): 310 | response_str += f'{i + 1}) {response["items"][i]["snippet"]["title"]} - ${round(earnings[i], 2):,}\n' 311 | total += earnings[i] 312 | response_str += f'\n\nTop {results} Total Earnings: ${round(total, 2):,}' 313 | print(response_str) 314 | 315 | return embed, response_str 316 | 317 | except HttpAccessTokenRefreshError: return "The credentials have been revoked or expired, please re-run the application to re-authorize." 318 | except Exception as e: 319 | print(traceback.format_exc()) 320 | return f"Ran into {e.__class__.__name__} exception, {traceback.format_exc()}" 321 | 322 | 323 | async def top_countries_by_revenue (results=10, startDate=datetime.datetime.now().strftime("%m/01/%y"), endDate=datetime.datetime.now().strftime("%m/%d/%y")): 324 | try: 325 | # Query the YouTube Analytics API 326 | response = execute_api_request( 327 | YOUTUBE_ANALYTICS.reports().query, 328 | ids='channel==MINE', 329 | startDate=startDate, 330 | endDate=endDate, 331 | dimensions='country', 332 | metrics='estimatedRevenue', 333 | sort='-estimatedRevenue', 334 | maxResults=results, 335 | ) 336 | 337 | # Format the start and end dates 338 | startDate, endDate = (startDate[5:] if startDate[:4] == endDate[:4] else f'{startDate[5:]}-{startDate[:4]}').replace( 339 | '-', '/'), (endDate[5:] if startDate[:4] == endDate[:4] else f'{endDate[5:]}-{endDate[:4]}').replace('-', '/') 340 | 341 | # Build the response string 342 | return_str = f'Top {results} Countries by Revenue: ({startDate}\t-\t{endDate})\n' 343 | 344 | embed = discord.Embed(title=f"Top {results} Countries by Revenue: ({startDate} - {endDate})", color=0x00ff00) 345 | for row in response['rows']: 346 | embed.add_field(name=f"{row[0]}:\t\t${round(row[1],2):,}", value=f"${round(row[1],2):,}", inline=False) 347 | return_str += f'{row[0]}:\t\t${round(row[1],2):,}\n' 348 | print(row[0], row[1]) 349 | 350 | embed.add_field(name="\u200b", value="\u200b", inline=False) 351 | 352 | return embed, return_str 353 | 354 | except HttpAccessTokenRefreshError: return "The credentials have been revoked or expired, please re-run the application to re-authorize." 355 | except Exception as e: 356 | print(traceback.format_exc()) 357 | return f"Ran into {e.__class__.__name__} exception, {traceback.format_exc()}" 358 | 359 | 360 | async def get_ad_preformance (start=datetime.datetime.now().strftime("%Y-%m-01"), end=datetime.datetime.now().strftime("%Y-%m-%d")): 361 | try: 362 | response = execute_api_request( 363 | YOUTUBE_ANALYTICS.reports().query, 364 | ids='channel==MINE', 365 | startDate=start, 366 | endDate=end, 367 | dimensions='adType', 368 | metrics='grossRevenue,adImpressions,cpm', 369 | sort='-grossRevenue' 370 | ) 371 | 372 | # Terminary operator to check if start/end year share a year, and strip/remove if that's the case 373 | start_str = (start[5:] if start[:4] == end[:4] else f'{start[5:]}-{start[:4]}').replace('-', '/') 374 | end_str = (end[5:] if start[:4] == end[:4] else f'{end[5:]}-{end[:4]}').replace('-', '/') 375 | 376 | response_str = f'Ad Preformance ({start_str}\t-\t{end_str})\n\n' 377 | embed = discord.Embed(title=f"Ad Preformance ({start_str} - {end_str})", color=0x00ff00) 378 | # Parse the response into nice formatted string 379 | for row in response['rows']: 380 | embed.add_field(name=f"{row[0]}:\t\t${round(row[1],2):,}", value=f"Gross Revenue:\t${round(row[1],2):,}\tCPM:\t${round(row[3],2):,}\tImpressions:\t{round(row[2],2):,}", inline=False) 381 | response_str += f'Ad Type:\t{row[0]}\n\tGross Revenue:\t${round(row[1],2):,}\tCPM:\t${round(row[3],2):,}\tImpressions:\t{round(row[2],2):,}\n\n\n' 382 | 383 | return embed, response_str 384 | 385 | except HttpAccessTokenRefreshError: return "The credentials have been revoked or expired, please re-run the application to re-authorize." 386 | except Exception as e: 387 | print(traceback.format_exc()) 388 | return f"Ran into {e.__class__.__name__} exception, {traceback.format_exc()}" 389 | 390 | # More detailed geo data/report 391 | async def get_detailed_georeport (results=5, startDate=datetime.datetime.now().strftime("%m/01/%y"), endDate=datetime.datetime.now().strftime("%m/%d/%y")): 392 | try: 393 | # Get top preforming countries by revenue 394 | response = execute_api_request( 395 | YOUTUBE_ANALYTICS.reports().query, 396 | ids='channel==MINE', 397 | startDate=startDate, 398 | endDate=endDate, 399 | dimensions='country', 400 | metrics='views,estimatedRevenue,estimatedAdRevenue,estimatedRedPartnerRevenue,grossRevenue,adImpressions,cpm,playbackBasedCpm,monetizedPlaybacks', 401 | sort='-estimatedRevenue', 402 | maxResults=results, 403 | ) 404 | 405 | # Parse the response using rows and columnHeaders 406 | response_str = f'Top {results} Countries by Revenue: ({startDate} - {endDate})\n\n' 407 | embed = discord.Embed(title=f"Top {results} Countries by Revenue: ({startDate} - {endDate})", color=0x00ff00) 408 | for row in response['rows']: 409 | response_str += f'{row[0]}:\n' 410 | for i in range(len(row)): 411 | if "country" in response["columnHeaders"][i]["name"]: 412 | continue 413 | response_str += f'\t{response["columnHeaders"][i]["name"]}:\t{round(row[i],2):,}\n' 414 | embed.add_field(name=f"{response['columnHeaders'][i]['name']}:", value=f"{round(row[i],2):,}", inline=False) 415 | response_str += '\n' 416 | 417 | print(f'Data received:\t{response}\n\nReport Generated:\n{response_str}') 418 | return embed, response_str 419 | 420 | except HttpAccessTokenRefreshError: return "The credentials have been revoked or expired, please re-run the application to re-authorize." 421 | except Exception as e: 422 | print(traceback.format_exc()) 423 | return f"Ran into {e.__class__.__name__} exception, {traceback.format_exc()}" 424 | 425 | async def get_demographics (startDate=datetime.datetime.now().strftime("%m/01/%y"), endDate=datetime.datetime.now().strftime("%m/%d/%y")): 426 | try: 427 | # Get top preforming countries by revenue 428 | response = execute_api_request( 429 | YOUTUBE_ANALYTICS.reports().query, 430 | dimensions="ageGroup,gender", 431 | ids='channel==MINE', 432 | startDate=startDate, 433 | endDate=endDate, 434 | metrics="viewerPercentage", 435 | sort="-viewerPercentage", 436 | ) 437 | startDate, endDate = (startDate[5:] if startDate[:4] == endDate[:4] else f'{startDate[5:]}-{startDate[:4]}').replace('-', '/'), (endDate[5:] if startDate[:4] == endDate[:4] else f'{endDate[5:]}-{endDate[:4]}').replace('-', '/') 438 | response_str = f'Gender Viewership Demographics ({startDate}\t-\t{endDate})\n\n' 439 | embed = discord.Embed(title=f"Gender Viewership Demographics ({startDate}\t-\t{endDate})", color=0x00ff00) 440 | 441 | # Parse the response into nice formatted string 442 | for row in response['rows']: 443 | if round(row[2],2) < 1: break 444 | row[0] = row[0].split('e') 445 | 446 | response_str += f'{round(row[2],2)}% Views come from {row[1]} with age of {row[0][1]}\n' 447 | embed.add_field(name=f"{round(row[2],2)}% Views come from {row[1]} with age of {row[0][1]}", value=f"{round(row[2],2)}%", inline=False) 448 | print(f'Demographics Report Generated & Sent:\n{response_str}') 449 | return embed, response_str 450 | 451 | except HttpAccessTokenRefreshError: return "The credentials have been revoked or expired, please re-run the application to re-authorize." 452 | except Exception as e: 453 | print(traceback.format_exc()) 454 | return f"Ran into {e.__class__.__name__} exception, {traceback.format_exc()}" 455 | 456 | async def get_shares (results = 5, start=datetime.datetime.now().strftime("%Y-%m-01"), end=datetime.datetime.now().strftime("%Y-%m-%d")): 457 | try: 458 | request = YOUTUBE_ANALYTICS.reports().query( 459 | dimensions="sharingService", 460 | startDate=start, 461 | endDate=end, 462 | ids="channel==MINE", 463 | maxResults=results, 464 | metrics="shares", 465 | sort="-shares" 466 | ).execute() 467 | 468 | # Terminary operator to check if start/end year share a year, and strip/remove if that's the case 469 | start_str, end_str = (start[5:] if start[:4] == end[:4] else f'{start[5:]}-{start[:4]}').replace('-', '/'), (end[5:] if start[:4] == end[:4] else f'{end[5:]}-{end[:4]}').replace('-', '/') 470 | 471 | response_str = f'Top Sharing Services ({start_str}\t-\t{end_str})\n\n' 472 | embed = discord.Embed(title=f"Top Sharing Services ({start_str}\t-\t{end_str})", color=0x00ff00) 473 | # Parse the response into nice formatted string 474 | for row in request['rows']: 475 | response_str += f'{row[0].replace("_", " ")}:\t{row[1]:,}\n' 476 | embed.add_field(name=f'{row[0].replace("_", " ")}:', value=f"{row[1]:,}", inline=False) 477 | print(f'Shares Report Generated & Sent:\n{response_str}') 478 | return embed, response_str 479 | 480 | except HttpAccessTokenRefreshError: return "The credentials have been revoked or expired, please re-run the application to re-authorize." 481 | except Exception as e: 482 | print(traceback.format_exc()) 483 | return f"Ran into {e.__class__.__name__} exception, {traceback.format_exc()}" 484 | 485 | async def get_traffic_source (results=10, start=datetime.datetime.now().strftime("%Y-%m-01"), end=datetime.datetime.now().strftime("%Y-%m-%d")): 486 | try: 487 | request = YOUTUBE_ANALYTICS.reports().query( 488 | dimensions="insightTrafficSourceDetail", 489 | endDate=end, 490 | filters="insightTrafficSourceType==YT_SEARCH", 491 | ids="channel==MINE", 492 | maxResults=results, 493 | metrics="views", 494 | sort="-views", 495 | startDate=start 496 | ).execute() 497 | 498 | # Terminary operator to check if start/end year share a year, and strip/remove if that's the case 499 | start_str, end_str = (start[5:] if start[:4] == end[:4] else f'{start[5:]}-{start[:4]}').replace('-', '/'), (end[5:] if start[:4] == end[:4] else f'{end[5:]}-{end[:4]}').replace('-', '/') 500 | 501 | response_str = f'Top Search Traffic Terms ({start_str}\t-\t{end_str})\n\n' 502 | embed = discord.Embed(title=f"Top Search Traffic Terms ({start_str}\t-\t{end_str})", color=0x00ff00) 503 | # Parse the response into nice formatted string 504 | for row in request['rows']: 505 | response_str += f'{row[0].replace("_", " ")}:\t{row[1]:,}\n' 506 | embed.add_field(name=f'{row[0].replace("_", " ")}:', value=f"{row[1]:,}", inline=False) 507 | print(f'Traffic Report Generated:\n{response_str}') 508 | 509 | return embed, response_str 510 | 511 | except HttpAccessTokenRefreshError: return "The credentials have been revoked or expired, please re-run the application to re-authorize." 512 | except Exception as e: 513 | print(traceback.format_exc()) 514 | return f"Ran into {e.__class__.__name__} exception, {traceback.format_exc()}" 515 | 516 | 517 | async def get_operating_stats (results = 10, start=datetime.datetime.now().strftime("%Y-%m-01"), end=datetime.datetime.now().strftime("%Y-%m-%d")): 518 | try: 519 | request = YOUTUBE_ANALYTICS.reports().query( 520 | dimensions="operatingSystem", 521 | endDate=end, 522 | maxResults=results, 523 | ids="channel==MINE", 524 | metrics="views,estimatedMinutesWatched", 525 | sort="-views,estimatedMinutesWatched", 526 | startDate=start 527 | ).execute() 528 | start_str, end_str = (start[5:] if start[:4] == end[:4] else f'{start[5:]}-{start[:4]}').replace('-', '/'), (end[5:] if start[:4] == end[:4] else f'{end[5:]}-{end[:4]}').replace('-', '/') 529 | response_str = f'Top Operating System ({start_str}\t-\t{end_str})\n' 530 | embed = discord.Embed(title=f"Top Operating System ({start_str}\t-\t{end_str})", color=0x00ff00) 531 | for row in request['rows']: 532 | response_str += f'\t{row[0]}:\n\t\tViews:\t\t{round(row[1], 2):,}\n\t\tEstimated Watchtime:\t\t{round(row[2],2):,}\n' 533 | embed.add_field(name=f'{row[0]}:', value=f"Views:\t\t{round(row[1], 2):,}\nEstimated Watchtime:\t\t{round(row[2],2):,}", inline=False) 534 | print(response_str) 535 | return embed, response_str 536 | 537 | except HttpAccessTokenRefreshError: return "The credentials have been revoked or expired, please re-run the application to re-authorize." 538 | except Exception as e: 539 | print(traceback.format_exc()) 540 | return f"Ran into {e.__class__.__name__} exception, {traceback.format_exc()}" 541 | 542 | async def get_playlist_stats (results = 5, start=datetime.datetime.now().strftime("%Y-%m-01"), end=datetime.datetime.now().strftime("%Y-%m-%d")): 543 | try: 544 | request = YOUTUBE_ANALYTICS.reports().query( 545 | dimensions="playlist", 546 | endDate=end, 547 | filters="isCurated==1", 548 | ids="channel==MINE", 549 | maxResults=results, 550 | metrics="estimatedMinutesWatched,views,playlistStarts,averageTimeInPlaylist", 551 | sort="-views", 552 | startDate=start 553 | ) 554 | response = request.execute() 555 | 556 | playlist_ids = ','.join([row[0] for row in response['rows']]) 557 | playlist_ids = [] 558 | views = [] 559 | playlist_starts = [] 560 | average_time_in_playlist = [] 561 | estimated_minutes_watched = [] 562 | for row in response['rows']: 563 | playlist_ids.append(row[0]) 564 | views.append(row[1]) 565 | playlist_starts.append(row[2]) 566 | average_time_in_playlist.append(row[3]) 567 | estimated_minutes_watched.append(row[4]) 568 | 569 | request = YOUTUBE_DATA.playlists().list( 570 | part="snippet", 571 | id=playlist_ids 572 | ) 573 | response = request.execute() 574 | start, end = (start[5:] if start[:4] == end[:4] else f'{start[5:]}-{start[:4]}').replace('-', '/'), (end[5:] if start[:4] == end[:4] else f'{end[5:]}-{end[:4]}').replace('-', '/') 575 | response_str = f'```YouTube Analytics Report ({start}\t-\t{end})\n\n' 576 | embed = discord.Embed(title=f"Top Operating System ({start}\t-\t{end})", color=0x00ff00) 577 | for row in response['items']: 578 | response_str += f"{row['snippet']['title']}:\nViews: {views[playlist_ids.index(row['id'])]}\nPlaylist Starts: {playlist_starts[playlist_ids.index(row['id'])]}\nAverage Time Spent in Playlist: {average_time_in_playlist[playlist_ids.index(row['id'])]}\nEstimated Minutes Watched: {estimated_minutes_watched[playlist_ids.index(row['id'])]}\n\n" 579 | embed.add_field(name=f'{row["snippet"]["title"]}:', value=f"Views: {views[playlist_ids.index(row['id'])]}\nPlaylist Starts: {playlist_starts[playlist_ids.index(row['id'])]}\nAverage Time Spent in Playlist: {average_time_in_playlist[playlist_ids.index(row['id'])]}\nEstimated Minutes Watched: {estimated_minutes_watched[playlist_ids.index(row['id'])]}", inline=False) 580 | response_str += '```' 581 | print('Playlist Report Generated:\n', response_str) 582 | return embed, response_str 583 | 584 | except HttpAccessTokenRefreshError: return "The credentials have been revoked or expired, please re-run the application to re-authorize." 585 | except Exception as e: 586 | print(traceback.format_exc()) 587 | return f"Ran into {e.__class__.__name__} exception, {traceback.format_exc()}" 588 | 589 | YOUTUBE_ANALYTICS = get_service() 590 | YOUTUBE_DATA = get_service("youtube", "v3", YOUTUBE_API_KEY) -------------------------------------------------------------------------------- /keep_alive.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from threading import Thread 3 | 4 | app = Flask('') 5 | 6 | @app.route('/') 7 | def home(): 8 | return "I'm alivvveee! This is a Discord bot made by @Prem-ium on GitHub." 9 | 10 | def run(): 11 | app.run(host = '0.0.0.0', port = 8080) 12 | 13 | def keep_alive(): 14 | t = Thread(target = run) 15 | t.start() -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | # Github Repository: https://github.com/Prem-ium/youtube-analytics-bot 2 | 3 | # BSD 3-Clause License 4 | # 5 | # Copyright (c) 2022-present, Prem Patel 6 | # All rights reserved. 7 | # 8 | # Redistribution and use in source and binary forms, with or without 9 | # modification, are permitted provided that the following conditions are met: 10 | # 11 | # 1. Redistributions of source code must retain the above copyright notice, this 12 | # list of conditions and the following disclaimer. 13 | # 14 | # 2. Redistributions in binary form must reproduce the above copyright notice, 15 | # this list of conditions and the following disclaimer in the documentation 16 | # and/or other materials provided with the distribution. 17 | # 18 | # 3. Neither the name of the copyright holder nor the names of its 19 | # contributors may be used to endorse or promote products derived from 20 | # this software without specific prior written permission. 21 | # 22 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 23 | # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 24 | # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 25 | # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 26 | # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 27 | # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 28 | # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 29 | # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 30 | # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | 33 | import os, datetime, traceback, calendar, asyncio 34 | from calendar import monthrange 35 | from dotenv import load_dotenv 36 | import discord 37 | from discord.ext import commands 38 | 39 | from YouTube_API import * 40 | 41 | # Load the .env file & assign the variables 42 | load_dotenv() 43 | 44 | if not os.environ["DISCORD_TOKEN"]: 45 | raise Exception("ERROR: `DISCORD_TOKEN` is missing in .env, please add it and restart.") 46 | elif not os.environ["YOUTUBE_API_KEY"]: 47 | raise Exception("ERROR: `YOUTUBE_API_KEY` is missing in .env, please add it and restart.") 48 | 49 | DISCORD_TOKEN = os.environ["DISCORD_TOKEN"] 50 | DISCORD_CHANNEL = os.environ.get("DISCORD_CHANNEL", None) 51 | 52 | if DISCORD_CHANNEL: 53 | DISCORD_CHANNEL = int(DISCORD_CHANNEL) 54 | 55 | if (os.environ.get("KEEP_ALIVE", "False").lower() == "true"): 56 | from keep_alive import keep_alive 57 | keep_alive() 58 | 59 | # Change dates to API format 60 | async def update_dates (startDate, endDate): 61 | splitStartDate, splitEndDate = startDate.split('/'), endDate.split('/') 62 | 63 | # If the start and end dates are in the first month of the year & they are the same date 64 | if (splitStartDate[1] == '01' and (splitStartDate[0] == splitEndDate[0] and splitEndDate[1] in ['01', '02', '03'])): 65 | year = startDate.split('/')[2] if (len(startDate.split('/')) > 2) else datetime.datetime.now().strftime("%Y") 66 | year = str(int(year) - 1 if int(splitStartDate[0]) == 1 else year) 67 | year = f'20{year}' if len(year) == 2 else year 68 | 69 | previousMonth = int(splitStartDate[0]) - 1 if int(splitStartDate[0]) > 1 else 12 70 | lastDay = monthrange(int(year), previousMonth)[1] 71 | 72 | # Set the start and end dates to the previous month 73 | startDate = datetime.datetime.strptime(f'{previousMonth}/01', '%m/%d').strftime(f'{year}/%m/%d').replace('/', '-') 74 | endDate = datetime.datetime.strptime(f'{previousMonth}/{lastDay}', '%m/%d').strftime(f'{year}/%m/%d').replace('/', '-') 75 | 76 | # If the start or end date is missing the year 77 | elif len(startDate) != 5 or len(endDate) != 5: 78 | # Set the start and end dates to the full date including the year 79 | startDate = datetime.datetime.strptime(startDate, '%m/%d/%y').strftime('%Y/%m/%d').replace('/', '-') 80 | endDate = datetime.datetime.strptime(endDate, '%m/%d/%y').strftime('%Y/%m/%d').replace('/', '-') 81 | else: 82 | currentYear = datetime.datetime.now().strftime("%Y") 83 | if len(startDate) == 5: 84 | startDate = datetime.datetime.strptime(startDate, '%m/%d').strftime(f'{currentYear}/%m/%d').replace('/', '-') 85 | if len(endDate) == 5: 86 | endDate = datetime.datetime.strptime(endDate, '%m/%d').strftime(f'{currentYear}/%m/%d').replace('/', '-') 87 | return startDate, endDate 88 | 89 | class SimpleView(discord.ui.View): 90 | startDate: datetime = datetime.datetime.now().strftime("%Y-%m-01") 91 | endDate: datetime = datetime.datetime.now().strftime("%Y-%m-%d") 92 | 93 | def __init__(self, startDate=datetime.datetime.now().strftime("%m/01/%y"), endDate=datetime.datetime.now().strftime("%m/%d/%y"), timeout=None): 94 | super().__init__(timeout=timeout) 95 | async def initialize_dates(): 96 | self.startDate, self.endDate = await update_dates(startDate, endDate) 97 | 98 | asyncio.ensure_future(initialize_dates()) 99 | 100 | ##TODO: Add a way to resend buttons without making bot edit the message & destroy old stats 101 | async def update_buttons(self, interaction: discord.Interaction, embed: discord.Embed, response_str: str): 102 | await interaction.response.edit_message(content=response_str, embed=embed, view=self) 103 | 104 | @discord.ui.button(label='Analytics', style=discord.ButtonStyle.blurple) 105 | async def channel_stats(self, interaction: discord.Interaction, button: discord.ui.Button): 106 | embed, response_str = await get_stats(start=self.startDate, end=self.endDate) 107 | await self.update_buttons(interaction, embed, response_str) 108 | 109 | @discord.ui.button(label="Top Revenue Videos", style=discord.ButtonStyle.blurple) 110 | async def top_earners(self, interaction: discord.Interaction, button: discord.ui.Button): 111 | embed, response_str = await top_revenue(results=10, start=self.startDate, end=self.endDate) 112 | await self.update_buttons(interaction, embed, response_str) 113 | 114 | @discord.ui.button(label="Search Keyword Terms", style=discord.ButtonStyle.blurple) 115 | async def search_stats(self, interaction: discord.Interaction, button: discord.ui.Button): 116 | embed, response_str = await get_traffic_source(results=10, start=self.startDate, end=self.endDate) 117 | await self.update_buttons(interaction, embed, response_str) 118 | 119 | @discord.ui.button(label='Playlist Stats', style=discord.ButtonStyle.blurple) 120 | async def playlist_stats(self, interaction: discord.Interaction, button: discord.ui.Button): 121 | embed, response_str = await get_playlist_stats(results=5, start=self.startDate, end=self.endDate) 122 | await self.update_buttons(interaction, embed, response_str) 123 | 124 | @discord.ui.button(label='Geographic', style=discord.ButtonStyle.blurple) 125 | async def geo_stats(self, interaction: discord.Interaction, button: discord.ui.Button): 126 | embed, response_str = await get_detailed_georeport(results=5, startDate=self.startDate, endDate=self.endDate) 127 | await self.update_buttons(interaction, embed, response_str) 128 | embed, response_str = await top_countries_by_revenue(results=5, start=self.startDate, end=self.endDate) 129 | await interaction.response.edit_message(content=response_str, embed=embed, view=self) 130 | 131 | @discord.ui.button(label='OS Stats', style=discord.ButtonStyle.blurple) 132 | async def os_stats(self, interaction: discord.Interaction, button: discord.ui.Button): 133 | embed, response_str = await get_operating_stats(results=5, start=self.startDate, end=self.endDate) 134 | await self.update_buttons(interaction, embed, response_str) 135 | 136 | @discord.ui.button(label='Traffic Source', style=discord.ButtonStyle.blurple) 137 | async def traffic_source(self, interaction: discord.Interaction, button: discord.ui.Button): 138 | embed, response_str = await get_traffic_source(results=5, start=self.startDate, end=self.endDate) 139 | await self.update_buttons(interaction, embed, response_str) 140 | 141 | @discord.ui.button(label='Shares', style=discord.ButtonStyle.blurple) 142 | async def shares(self, interaction: discord.Interaction, button: discord.ui.Button): 143 | embed, response_str = await get_shares(results=5, start=self.startDate, end=self.endDate) 144 | await self.update_buttons(interaction, embed, response_str) 145 | 146 | @discord.ui.button(label='Top Earning Countries', style=discord.ButtonStyle.blurple) 147 | async def highest_earning_countries(self, interaction: discord.Interaction, button: discord.ui.Button): 148 | embed, response_str = await top_countries_by_revenue(results=5, startDate=self.startDate, endDate=self.endDate) 149 | await self.update_buttons(interaction, embed, response_str) 150 | 151 | @discord.ui.button(label='Refresh Token', style=discord.ButtonStyle.success) 152 | async def token_ref(self, interaction: discord.Interaction, button: discord.ui.Button): 153 | status = await refresh(return_embed=False) 154 | print(status) 155 | await interaction.response.send_message(status) 156 | 157 | @discord.ui.button(label="Refresh Dates", style=discord.ButtonStyle.blurple) 158 | async def refresh_dates(self, interaction: discord.Interaction, button: discord.ui.Button): 159 | self.startDate, self.endDate = await update_dates(startDate=datetime.datetime.now().strftime("%m/01/%y"), endDate=datetime.datetime.now().strftime("%m/%d/%y")) 160 | await interaction.response.send_message(f"Dates have been refreshed to {self.startDate} - {self.endDate}") 161 | 162 | @discord.ui.button(label='Ping!', style=discord.ButtonStyle.grey) 163 | async def got_ping(self, interaction: discord.Interaction, button: discord.ui.Button): 164 | await interaction.response.send_message('Pong!') 165 | 166 | if __name__ == "__main__": 167 | # Refresh Token & Retrieve Channel ID at Launch 168 | try: refresh_token() 169 | except FileNotFoundError as e: print(f'{e.__class__.__name__, e}{get_service()}') 170 | 171 | CHANNEL_ID = YOUTUBE_DATA.channels().list(part="id",mine=True).execute()['items'][0]['id'] 172 | discord_intents = discord.Intents.all() 173 | bot = commands.Bot(command_prefix='!', intents=discord_intents) 174 | bot.remove_command('help') 175 | 176 | if DISCORD_CHANNEL: 177 | @bot.event 178 | async def on_ready(): 179 | await bot.get_channel(DISCORD_CHANNEL).send(embed=discord.Embed( 180 | title="YouTube Analytics Bot Online", 181 | description="The bot is ready to provide YouTube analytics at your command!", 182 | color=discord.Color.green() 183 | )) 184 | await bot.get_channel(DISCORD_CHANNEL).send(view=SimpleView()) 185 | 186 | # Help command 187 | @bot.command() 188 | async def help(ctx): 189 | available_commands = [ 190 | {"command": "`!button`", "parameters": "`[startDate] [endDate]`", "description": "Opens a view shortcut for all available commands", "example": "!button -- !button 01/01 12/01\n"}, 191 | {"command": "`!stats`", "parameters": "`[startDate] [endDate]`", "description": "Return stats within a time range (defaults to current month)", "example": "!stats 01/01 12/01 -- !stats 01/01/2021 01/31/2021\n"}, 192 | {"command": "`!getMonth`", "parameters": "`[month/year]`", "description": "Return stats for a specific month", "example": "!getMonth 01/21 -- !getMonth 10/2020\n"}, 193 | {"command": "`!lifetime`", "parameters": "N/A", "description": "Get lifetime stats", "example": "!lifetime\n"}, 194 | {"command": "`!topEarnings`", "parameters": "`[startDate] [endDate] [# of countries]`", "description": "Return top revenue-earning videos", "example": "!topEarnings 01/01 12/1 5\n"}, 195 | {"command": "`!geo_revenue`", "parameters": "`[startDate] [endDate] [# of countries]`", "description": "Top countries by revenue", "example": "!geo_revenue 01/01 12/1 5\n"}, 196 | {"command": "`!geoReport`", "parameters": "`[startDate] [endDate] [# of countries]`", "description": "More detailed revenue report by country", "example": "!geoReport 01/01 12/1 5\n"}, 197 | {"command": "`!adtype`", "parameters": "`[startDate] [endDate]`", "description": "Get highest performing ad types", "example": "!adtype 01/01 12/1\n"}, 198 | {"command": "`!demographics`","parameters": "`[startDate] [endDate]`", "description": "Get viewer demographics data (age and gender)", "example": "!demographics 01/01 12/1\n"}, 199 | {"command": "`!shares`", "parameters": "`[startDate] [endDate] [# of results]`", "description": "Return top videos by shares", "example": "!shares 01/01 12/1 5\n"}, 200 | {"command": "`!search`", "parameters": "`[startDate] [endDate] [# of results]`", "description": "Return top search terms by views", "example": "!search 01/01 12/1 5\n"}, 201 | {"command": "`!os`", "parameters": "`[startDate] [endDate] [# of results]`", "description": "Return top operating systems by views", "example": "!os 01/01 12/1 5\n"}, 202 | {"command": "`!playlist`", "parameters": "`[startDate] [endDate] [# of results]`", "description": "Return playlist stats", "example": "!playlist 01/01 12/1\n"}, 203 | {"command": "`!everything`", "parameters": "`[startDate] [endDate]`", "description": "Return all available data", "example": "!everything 01/01 12/1\n\n"}, 204 | {"command": "`!refresh`", "parameters": "N/A", "description": "Refresh the API token", "example": "!refresh"}, 205 | {"command": "`!switch`", "parameters": "N/A", "description": "Toggle between dev and user mode (temporary)", "example": "!switch"}, 206 | {"command": "`!restart`", "parameters": "N/A", "description": "Restart the bot", "example": "!restart"}, 207 | {"command": "`!help`", "parameters": "N/A", "description": "Show this help message", "example": "!help"}, 208 | {"command": "`!ping`", "parameters": "N/A", "description": "Check bot latency", "example": "!ping"}, 209 | ] 210 | current_field = "Parameters are optional, most commands have default dates, denoted by `[]`.\n\n" 211 | 212 | for cmd_info in available_commands: 213 | field_content = f"**Command:** {cmd_info['command']}\n" 214 | field_content +=f"**Parameters:** {cmd_info['parameters']}\n" if cmd_info['parameters'] != "None" else "" 215 | field_content += f"**Description:** {cmd_info['description']}\n" 216 | field_content+=f"**Example:** {cmd_info['example']}\n\n" if cmd_info['example'] != cmd_info["command"] else "\n" 217 | 218 | current_field += field_content 219 | 220 | embed = discord.Embed(title="Help: Available Commands", color=0x00ff00) 221 | embed.description = current_field 222 | embed.set_footer(text="Bot developed by Prem-ium.\nhttps://github.com/Prem-ium/youtube-analytics-bot\n") 223 | await ctx.send(embed=embed) 224 | 225 | # Button command, opens a View with supported commands 226 | @bot.command() 227 | async def button(ctx, startDate, endDate): 228 | view = SimpleView(startDate, endDate, timeout=None) 229 | await ctx.send(view=view) 230 | 231 | # Retrieve Analytic stats within specified date range, defaults to current month 232 | @bot.command(aliases=['stats', 'thisMonth', 'this_month']) 233 | async def analyze(ctx, startDate=datetime.datetime.now().strftime("%m/01/%y"), endDate=datetime.datetime.now().strftime("%m/%d/%y")): 234 | # Update the start and end dates to be in the correct format 235 | startDate, endDate = await update_dates(startDate, endDate) 236 | try: 237 | # Get the stats for the specified date range 238 | stats = await get_stats(startDate, endDate) 239 | try: await ctx.send(embed=stats[0]) 240 | except: pass 241 | finally: await ctx.send(stats[1]) 242 | 243 | print(f'\n{startDate} - {endDate} stats sent') 244 | except Exception as e: await ctx.send(f'Error:\n {e}\n{traceback.format_exc()}') 245 | 246 | # Lifetime stats 247 | @bot.command(aliases=['lifetime', 'alltime', 'allTime']) 248 | async def lifetime_method(ctx): 249 | try: 250 | stats = await get_stats('2005-02-14', datetime.datetime.now().strftime("%Y-%m-%d")) 251 | try: await ctx.send(embed=stats[0]) 252 | except: pass 253 | finally: await ctx.send(stats[1]) 254 | except Exception as e: await ctx.send(f'Error:\n {e}\n{traceback.format_exc()}') 255 | 256 | # Last month's stats 257 | @bot.command(aliases=['lastMonth']) 258 | async def lastmonthct(ctx): 259 | # Get the last month's start and end dates 260 | startDate = datetime.date.today().replace(day=1) - datetime.timedelta(days=1) 261 | endDate = datetime.date.today().replace(day=1) - datetime.timedelta(days=1) 262 | startDate = startDate.replace(day=1) 263 | endDate = endDate.replace(day=calendar.monthrange(endDate.year, endDate.month)[1]) 264 | try: 265 | stats = await get_stats(startDate.strftime("%Y-%m-%d"), endDate.strftime("%Y-%m-%d")) 266 | try: await ctx.send(embed=stats[0]) 267 | except: pass 268 | finally: await ctx.send(stats[1]) 269 | print(f'\nLast month ({startDate} - {endDate}) stats sent\n') 270 | except Exception as e: await ctx.send(f'Error:\n {e}\n{traceback.format_exc()}') 271 | 272 | # Retrieve top earning videos within specified date range between any month/year, defaults to current month 273 | @bot.command(aliases=['getMonth', 'get_month']) 274 | async def month(ctx, period=datetime.datetime.now().strftime("%m/%Y")): 275 | period = period.split('/') 276 | month, year = period[0], period[1] 277 | year = f'20{year}' if len(year) == 2 else year 278 | lastDate = monthrange(int(year), int(month))[1] 279 | startDate = datetime.datetime.strptime(f'{month}/01', '%m/%d').strftime(f'{year}/%m/%d').replace('/', '-') 280 | endDate = datetime.datetime.strptime(f'{month}/{lastDate}', '%m/%d').strftime(f'{year}/%m/%d').replace('/', '-') 281 | 282 | try: 283 | stats = await get_stats(startDate, endDate) 284 | try: await ctx.send(embed=stats[0]) 285 | except: pass 286 | finally: await ctx.send(stats[1]) 287 | print(f'\nLast month ({startDate} - {endDate}) stats sent\n') 288 | except Exception as e: await ctx.send(f'Error:\n {e}\n{traceback.format_exc()}') 289 | 290 | # Retrieve top earning videos within specified date range, defaults to current month 291 | @bot.command(aliases=['topEarnings', 'topearnings', 'top_earnings']) 292 | async def top(ctx, startDate=datetime.datetime.now().strftime("%m/01/%y"), endDate=datetime.datetime.now().strftime("%m/%d/%y"), results=10): 293 | startDate, endDate = await update_dates(startDate, endDate) 294 | try: 295 | # Get the stats for the specified date range 296 | stats = await top_revenue(results, startDate, endDate) 297 | try: await ctx.send(embed=stats[0]) 298 | except: pass 299 | finally: await ctx.send(stats[1]) 300 | print(f'\n{startDate} - {endDate} top {results} sent') 301 | except Exception as e: await ctx.send(f'Error:\n {e}\n{traceback.format_exc()}') 302 | 303 | # Top revenue by country 304 | @bot.command(aliases=['geo_revenue', 'geoRevenue', 'georevenue']) 305 | async def detailed_georeport(ctx, startDate=datetime.datetime.now().strftime("%m/01/%y"), endDate=datetime.datetime.now().strftime("%m/%d/%y"), results=10): 306 | startDate, endDate = await update_dates(startDate, endDate) 307 | try: 308 | stats = await top_countries_by_revenue(results, startDate, endDate) 309 | try: await ctx.send(embed=stats[0]) 310 | except: pass 311 | finally: await ctx.send(stats[1]) 312 | print(f'\nLast month ({startDate} - {endDate}) geo-revenue report sent\n') 313 | except Exception as e: await ctx.send(f'Error:\n {e}\n{traceback.format_exc()}') 314 | 315 | # Geo Report (views, revenue, cpm, etc) 316 | @bot.command(aliases=['geo_report', 'geoReport', 'georeport']) 317 | async def country(ctx, startDate=datetime.datetime.now().strftime("%m/01/%y"), endDate=datetime.datetime.now().strftime("%m/%d/%y"), results=3): 318 | startDate, endDate = await update_dates(startDate, endDate) 319 | try: 320 | stats = await get_detailed_georeport(results, startDate, endDate) 321 | try: await ctx.send(embed=stats[0]) 322 | except: pass 323 | finally: await ctx.send(stats[1]) 324 | print(f'\n{startDate} - {endDate} earnings by country sent') 325 | except Exception as e: await ctx.send(f'Error:\n {e}\n{traceback.format_exc()}') 326 | 327 | # Ad Type Preformance Data 328 | @bot.command(aliases=['adtype', 'adPreformance', 'adpreformance']) 329 | async def ad(ctx, startDate=datetime.datetime.now().strftime("%m/01/%y"), endDate=datetime.datetime.now().strftime("%m/%d/%y")): 330 | startDate, endDate = await update_dates(startDate, endDate) 331 | try: 332 | stats = await get_ad_preformance(startDate, endDate) 333 | try: await ctx.send(embed=stats[0]) 334 | except: pass 335 | finally: await ctx.send(stats[1]) 336 | print(f'\n{startDate} - {endDate} ad preformance sent') 337 | except Exception as e: await ctx.send(f'Error:\n {e}\n{traceback.format_exc()}') 338 | 339 | # Demographics Report 340 | @bot.command(aliases=['demographics', 'gender', 'age']) 341 | async def demo_graph(ctx, startDate=datetime.datetime.now().strftime("%m/01/%y"), endDate=datetime.datetime.now().strftime("%m/%d/%y")): 342 | startDate, endDate = await update_dates(startDate, endDate) 343 | try: 344 | stats = await get_demographics(startDate, endDate) 345 | try: await ctx.send(embed=stats[0]) 346 | except: pass 347 | finally: await ctx.send(stats[1]) 348 | 349 | print(f'\n{startDate} - {endDate} demographics sent') 350 | except Exception as e: await ctx.send(f'Error:\n {e}\n{traceback.format_exc()}') 351 | # Shares Report 352 | @bot.command(aliases=['shares', 'shares_report', 'sharesReport', 'share_report', 'shareReport']) 353 | async def share_rep(ctx, startDate=datetime.datetime.now().strftime("%m/01/%y"), endDate=datetime.datetime.now().strftime("%m/%d/%y"), results=5): 354 | startDate, endDate = await update_dates(startDate, endDate) 355 | try: 356 | stats = await get_shares(results, startDate, endDate) 357 | try: await ctx.send(embed=stats[0]) 358 | except: pass 359 | finally: await ctx.send(stats[1]) 360 | 361 | print(f'\n{startDate} - {endDate} shares result sent') 362 | except Exception as e: await ctx.send(f'Error:\n {e}\n{traceback.format_exc()}') 363 | 364 | # Search Terms Report 365 | @bot.command(aliases=['search', 'search_terms', 'searchTerms', 'search_report', 'searchReport']) 366 | async def search_rep(ctx, startDate=datetime.datetime.now().strftime("%m/01/%y"), endDate=datetime.datetime.now().strftime("%m/%d/%y"), results=10): 367 | startDate, endDate = await update_dates(startDate, endDate) 368 | try: 369 | stats = await get_traffic_source(results, startDate, endDate) 370 | try: await ctx.send(embed=stats[0]) 371 | except: pass 372 | finally: await ctx.send(stats[1]) 373 | print(f'\n{startDate} - {endDate} search terms result sent') 374 | except Exception as e: await ctx.send(f'Error:\n {e}\n{traceback.format_exc()}') 375 | 376 | # Top Operating Systems 377 | @bot.command(aliases=['os', 'operating_systems', 'operatingSystems', 'topoperatingsystems']) 378 | async def top_os(ctx, startDate=datetime.datetime.now().strftime("%m/01/%y"), endDate=datetime.datetime.now().strftime("%m/%d/%y"), results=10): 379 | startDate, endDate = await update_dates(startDate, endDate) 380 | try: 381 | stats = await get_operating_stats(results, startDate, endDate) 382 | try: await ctx.send(embed=stats[0]) 383 | except: pass 384 | finally: await ctx.send(stats[1]) 385 | print(f'\n{startDate} - {endDate} operating systems result sent') 386 | except Exception as e: await ctx.send(f'Error:\n {e}\n{traceback.format_exc()}') 387 | 388 | # Playlist Report 389 | @bot.command(aliases=['playlist', 'playlist_report', 'playlistReport']) 390 | async def playlist_rep(ctx, startDate=datetime.datetime.now().strftime("%m/01/%y"), endDate=datetime.datetime.now().strftime("%m/%d/%y"), results=5): 391 | startDate, endDate = await update_dates(startDate, endDate) 392 | try: 393 | stats = await get_playlist_stats(results, startDate, endDate) 394 | try: await ctx.send(embed=stats[0]) 395 | except: pass 396 | finally: await ctx.send(stats[1]) 397 | print(f'\n{startDate} - {endDate} playlist stats result sent') 398 | except Exception as e: await ctx.send(f'Error:\n {e}\n{traceback.format_exc()}') 399 | 400 | # Refresh Token 401 | @bot.command(aliases=['refresh', 'refresh_token', 'refreshToken']) 402 | async def refresh_API_token(ctx, token=None): 403 | try: 404 | status = await refresh(return_embed=True, token=token) 405 | await ctx.send(embed=status) 406 | except Exception as e: await ctx.send(f'Error:\n {e}\n{traceback.format_exc()}') 407 | 408 | @bot.command(aliases=['switch', 'devToggle']) 409 | async def sw_dev(ctx): 410 | try: 411 | dev_mode_status = await dev_mode() 412 | message = f"Dev Mode has been {'enabled' if dev_mode_status else 'disabled'}." 413 | await ctx.send(message) 414 | except Exception as e: 415 | await ctx.send(f'Error:\n{e}\n{traceback.format_exc()}') 416 | 417 | # Send all Commands 418 | @bot.command(aliases=['everything', 'all_stats', 'allStats', 'allstats']) 419 | async def all(ctx, startDate=datetime.datetime.now().strftime("%m/01/%y"), endDate=datetime.datetime.now().strftime("%m/%d/%y"), results=10): 420 | startDate, endDate = await update_dates(startDate, endDate) 421 | 422 | stat_functions = [ 423 | (get_stats, (startDate, endDate)), 424 | (top_revenue, (results, startDate, endDate)), 425 | (top_countries_by_revenue, (results, startDate, endDate)), 426 | (get_ad_preformance, (startDate, endDate)), 427 | (get_detailed_georeport, (results, startDate, endDate)), 428 | (get_demographics, (startDate, endDate)), 429 | (get_shares, (results, startDate, endDate)), 430 | (get_traffic_source, (results, startDate, endDate)), 431 | (get_operating_stats, (results, startDate, endDate)), 432 | (get_playlist_stats, (results, startDate, endDate)), 433 | ] 434 | 435 | try: 436 | for stat_function, args in stat_functions: 437 | result = await stat_function(*args) 438 | result = result[0] 439 | await ctx.send(embed=result) 440 | 441 | print(f'\n{startDate} - {endDate} everything sent') 442 | except Exception as e: 443 | await ctx.send(f'Error:\n {e}\n{traceback.format_exc()}') 444 | 445 | # Restart Bot Command 446 | @bot.command(name='restart') 447 | async def restart(ctx): 448 | await ctx.send(f"Restarting...\n") 449 | await bot.close() 450 | os._exit(0) 451 | 452 | # Bot Pong User's Ping 453 | @bot.command(name='ping') 454 | async def ping(ctx): 455 | await ctx.send('pong') 456 | print(f'\n{ctx.author.name} just got ponged!\t{datetime.datetime.now().strftime("%m/%d %H:%M:%S")}\n') 457 | 458 | # Start Discord Bot 459 | print(f"Booting up Discord Bot...\n{'-'*150}") 460 | bot.run(DISCORD_TOKEN) -------------------------------------------------------------------------------- /output-examples/README.MD: -------------------------------------------------------------------------------- 1 | # Example Output 2 |
3 | Image 4 |
5 | 6 |

7 | This section contains example outputs generated by running the command line interface of our application. These outputs demonstrate the variety of visualizations and reports that our application can produce. 8 |

9 | 10 |

11 | Note: These reports are just examples, and the actual outputs generated by our application will depend on the user's data and configuration. Additionally, these examples cannot always represent the most updated version of the script/bot but should give an idea of the example information output & use-cases of this awesome project. More will come soon! 12 |

13 | 14 |
15 |

Statistics Report

16 | 17 | 18 |

Monthly Report

19 | 20 | 21 |

Lifetime Report

22 | 23 | 24 |

Top Earnings Report

25 | 26 | 27 |

Geographic Revenue Report

28 | 29 | 30 |

Geographic Report

31 | 32 | 33 |

Ad Type Report

34 | 35 | 36 |

Demographics Report

37 | 38 | 39 |

Social Shares Report

40 | 41 | 42 |

Search Report

43 | 44 | 45 |

Operating System Report

46 | 47 | 48 |

Playlist Report

49 | 50 | 51 |

Refresh

52 | 53 | 54 |

Switch

55 | 56 |
57 | -------------------------------------------------------------------------------- /output-examples/media/!adType.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Prem-ium/youtube-analytics-bot/84cdd31eb2db5cf5c5ecf8bbdb0f2b56f4c1f1b7/output-examples/media/!adType.png -------------------------------------------------------------------------------- /output-examples/media/!demographics.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Prem-ium/youtube-analytics-bot/84cdd31eb2db5cf5c5ecf8bbdb0f2b56f4c1f1b7/output-examples/media/!demographics.png -------------------------------------------------------------------------------- /output-examples/media/!geoReport.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Prem-ium/youtube-analytics-bot/84cdd31eb2db5cf5c5ecf8bbdb0f2b56f4c1f1b7/output-examples/media/!geoReport.png -------------------------------------------------------------------------------- /output-examples/media/!geo_revenue.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Prem-ium/youtube-analytics-bot/84cdd31eb2db5cf5c5ecf8bbdb0f2b56f4c1f1b7/output-examples/media/!geo_revenue.png -------------------------------------------------------------------------------- /output-examples/media/!getMonth.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Prem-ium/youtube-analytics-bot/84cdd31eb2db5cf5c5ecf8bbdb0f2b56f4c1f1b7/output-examples/media/!getMonth.png -------------------------------------------------------------------------------- /output-examples/media/!lifetime.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Prem-ium/youtube-analytics-bot/84cdd31eb2db5cf5c5ecf8bbdb0f2b56f4c1f1b7/output-examples/media/!lifetime.png -------------------------------------------------------------------------------- /output-examples/media/!os.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Prem-ium/youtube-analytics-bot/84cdd31eb2db5cf5c5ecf8bbdb0f2b56f4c1f1b7/output-examples/media/!os.png -------------------------------------------------------------------------------- /output-examples/media/!playlist.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Prem-ium/youtube-analytics-bot/84cdd31eb2db5cf5c5ecf8bbdb0f2b56f4c1f1b7/output-examples/media/!playlist.png -------------------------------------------------------------------------------- /output-examples/media/!refresh.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Prem-ium/youtube-analytics-bot/84cdd31eb2db5cf5c5ecf8bbdb0f2b56f4c1f1b7/output-examples/media/!refresh.png -------------------------------------------------------------------------------- /output-examples/media/!search.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Prem-ium/youtube-analytics-bot/84cdd31eb2db5cf5c5ecf8bbdb0f2b56f4c1f1b7/output-examples/media/!search.png -------------------------------------------------------------------------------- /output-examples/media/!shares.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Prem-ium/youtube-analytics-bot/84cdd31eb2db5cf5c5ecf8bbdb0f2b56f4c1f1b7/output-examples/media/!shares.png -------------------------------------------------------------------------------- /output-examples/media/!stats.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Prem-ium/youtube-analytics-bot/84cdd31eb2db5cf5c5ecf8bbdb0f2b56f4c1f1b7/output-examples/media/!stats.png -------------------------------------------------------------------------------- /output-examples/media/!switch.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Prem-ium/youtube-analytics-bot/84cdd31eb2db5cf5c5ecf8bbdb0f2b56f4c1f1b7/output-examples/media/!switch.png -------------------------------------------------------------------------------- /output-examples/media/!topEarnings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Prem-ium/youtube-analytics-bot/84cdd31eb2db5cf5c5ecf8bbdb0f2b56f4c1f1b7/output-examples/media/!topEarnings.png -------------------------------------------------------------------------------- /output-examples/media/coffee-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Prem-ium/youtube-analytics-bot/84cdd31eb2db5cf5c5ecf8bbdb0f2b56f4c1f1b7/output-examples/media/coffee-logo.png -------------------------------------------------------------------------------- /output-examples/media/onReady.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Prem-ium/youtube-analytics-bot/84cdd31eb2db5cf5c5ecf8bbdb0f2b56f4c1f1b7/output-examples/media/onReady.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | discord.py 2 | Flask 3 | google_api_python_client 4 | google_auth_oauthlib 5 | oauth2client 6 | protobuf 7 | python-dotenv 8 | Requests 9 | --------------------------------------------------------------------------------