|
| 1 | +/* |
| 2 | +
|
| 3 | +This Google Script will auto-update the title of your |
| 4 | +YouTube video based on the number of views and comments |
| 5 | +
|
| 6 | +Tutorial: www.labnol.org/update-youtube-title-200818 |
| 7 | +
|
| 8 | +Author: Amit Agarwal https://digitalinspiration.com/ |
| 9 | +
|
| 10 | +Original Idea by Tom Scott youtu.be/BxV14h0kFs0 |
| 11 | +
|
| 12 | +*/ |
| 13 | + |
| 14 | +const updateYouTubeVideo = (e = null) => { |
| 15 | + const id = '<<Video Id>>'; |
| 16 | + const template = 'This video has VIEWCOUNT views and COMMENTCOUNT comments'; |
| 17 | + |
| 18 | + // The cron job is created only when the script is run manually |
| 19 | + if (e === null) { |
| 20 | + const triggerName = 'updateYouTubeVideo'; |
| 21 | + const triggers = ScriptApp.getProjectTriggers().filter((trigger) => { |
| 22 | + return trigger.getHandlerFunction() === triggerName; |
| 23 | + }); |
| 24 | + |
| 25 | + // If time based trigger doesn't exist, create one that runs every 5 minutes |
| 26 | + if (triggers.length === 0) { |
| 27 | + ScriptApp.newTrigger(triggerName).timeBased().everyMinutes(5).create(); |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + // Get the watch statistics of the video |
| 32 | + const { items: [video = {}] = [] } = YouTube.Videos.list('snippet,statistics', { |
| 33 | + id, |
| 34 | + }); |
| 35 | + |
| 36 | + // Parse the YouTube API response to get views and comment count |
| 37 | + const { snippet: { title: oldTitle, categoryId } = {}, statistics: { viewCount, commentCount } = {} } = video; |
| 38 | + |
| 39 | + if (viewCount && commentCount) { |
| 40 | + const newTitle = template.replace('VIEWCOUNT', viewCount).replace('COMMENTCOUNT', commentCount); |
| 41 | + |
| 42 | + // If the video title has not changed, skip this step |
| 43 | + if (oldTitle !== newTitle) { |
| 44 | + YouTube.Videos.update({ id: id, snippet: { title: newTitle, categoryId } }, 'snippet'); |
| 45 | + } |
| 46 | + } |
| 47 | +}; |
0 commit comments