نماذج رموز برمجة التطبيقات
تنظيم صفحاتك في مجموعات
يمكنك حفظ المحتوى وتصنيفه حسب إعداداتك المفضّلة.
تتوفّر نماذج الرموز البرمجية التالية في Apps Script لـ YouTube Data API. يمكنك تنزيل نماذج الرموز البرمجية هذه من مجلد apps-script
في مستودع نماذج الرموز البرمجية لواجهات برمجة تطبيقات YouTube على GitHub.
استرداد فيديوهاتي المحمَّلة
تسترجع هذه الدالة الفيديوهات التي حمّلها مستخدم النص البرمجي الحالي. لتنفيذ هذا الإجراء، يجب الحصول على نطاق القراءة/الكتابة في OAuth لمنصة YouTube بالإضافة إلى تفويض المستخدم. في بيئة التشغيل في Apps Script، في المرة الأولى التي يشغّل فيها المستخدم نصًا برمجيًا، سيطلب منه Apps Script الحصول على إذن للوصول إلى الخدمات التي يستدعيها النص البرمجي. بعد منح الأذونات، يتم تخزينها مؤقتًا لبعض الوقت. سيُطلَب من المستخدم الذي يشغّل النص البرمجي الحصول على الإذن مرة أخرى بعد تغيير الأذونات المطلوبة أو عندما تصبح غير صالحة من خلال الدالة
ScriptApp.invalidateAuth()
.
يتّخذ هذا النص البرمجي الخطوات التالية لاسترداد الفيديوهات التي حمّلها المستخدم النشط:
- جلب قنوات المستخدم
- تُستخدَم هذه السمة لاسترداد قائمة التشغيل "عمليات التحميل" الخاصة بالمستخدم.
- يتحقّق من قائمة التشغيل هذه ويُسجّل معرّفات الفيديوهات وعناوينها.
- تُستخدَم هذه السمة لجلب رمز مميّز للصفحة التالية، إن توفّر. إذا كانت هناك صفحة تالية، يتم جلبها. كرِّر الخطوة 3.
/**
* This function retrieves the current script user's uploaded videos. To execute,
* it requires the OAuth read/write scope for YouTube as well as user authorization.
* In Apps Script's runtime environment, the first time a user runs a script, Apps
* Script will prompt the user for permission to access the services called by the
* script. After permissions are granted, they are cached for some periodF of time.
* The user running the script will be prompted for permission again once the
* permissions required change, or when they are invalidated by the
* ScriptApp.invalidateAuth() function.
*
* This script takes the following steps to retrieve the active user's uploaded videos:
* 1. Fetches the user's channels
* 2. Fetches the user's 'uploads' playlist
* 3. Iterates through this playlist and logs the video IDs and titles
* 4. Fetches a next page token (if any). If there is one, fetches the next page. GOTO Step 3
*/
function retrieveMyUploads() {
var results = YouTube.Channels.list('contentDetails', {mine: true});
for(var i in results.items) {
var item = results.items[i];
// Get the playlist ID, which is nested in contentDetails, as described in the
// Channel resource: https://developers.google.com/youtube/v3/docs/channels
var playlistId = item.contentDetails.relatedPlaylists.uploads;
var nextPageToken = '';
// This loop retrieves a set of playlist items and checks the nextPageToken in the
// response to determine whether the list contains additional items. It repeats that process
// until it has retrieved all of the items in the list.
while (nextPageToken != null) {
var playlistResponse = YouTube.PlaylistItems.list('snippet', {
playlistId: playlistId,
maxResults: 25,
pageToken: nextPageToken
});
for (var j = 0; j < playlistResponse.items.length; j++) {
var playlistItem = playlistResponse.items[j];
Logger.log('[%s] Title: %s',
playlistItem.snippet.resourceId.videoId,
playlistItem.snippet.title);
}
nextPageToken = playlistResponse.nextPageToken;
}
}
}
البحث حسب الكلمة الرئيسية
تبحث هذه الدالة عن الفيديوهات ذات الصلة بالكلمة الرئيسية
'dogs'
. يتم تسجيل أرقام تعريف الفيديوهات والعناوين في نتائج البحث في سجلّ Apps Script.
يُرجى العلم أنّ هذا العيّنة تحدّ من النتائج إلى 25. لعرض المزيد من النتائج، عليك تمرير مَعلمات إضافية كما هو موضّح في
Search:list.
/**
* This function searches for videos related to the keyword 'dogs'. The video IDs and titles
* of the search results are logged to Apps Script's log.
*
* Note that this sample limits the results to 25. To return more results, pass
* additional parameters as documented here:
* https://developers.google.com/youtube/v3/docs/search/list
*/
function searchByKeyword() {
var results = YouTube.Search.list('id,snippet', {q: 'dogs', maxResults: 25});
for(var i in results.items) {
var item = results.items[i];
Logger.log('[%s] Title: %s', item.id.videoId, item.snippet.title);
}
}
البحث حسب الموضوع
تبحث هذه الدالة عن الفيديوهات المرتبطة بموضوع معيّن في Freebase، وتسجِّل أرقام تعريف الفيديوهات وعناوينها في سجلّ Apps Script. يستخدم هذا المثال معرّف الموضوع في Google Apps Script.
يُرجى العلم أنّ هذا العيّنة تحدّ من النتائج إلى 25. لعرض المزيد من النتائج، عليك تمرير مَعلمات إضافية كما هو موضّح في
Search:list.
/**
* This function searches for videos that are associated with a particular Freebase
* topic, logging their video IDs and titles to the Apps Script log. This example uses
* the topic ID for Google Apps Script.
*
* Note that this sample limits the results to 25. To return more results, pass
* additional parameters as documented here:
* https://developers.google.com/youtube/v3/docs/search/list
*/
function searchByTopic() {
var mid = '/m/0gjf126';
var results = YouTube.Search.list('id,snippet', {topicId: mid, maxResults: 25});
for(var i in results.items) {
var item = results.items[i];
Logger.log('[%s] Title: %s', item.id.videoId, item.snippet.title);
}
}
الاشتراك في القناة
يشترك هذا المثال في قناة Google Developers على YouTube المحدّدة من خلال channelId.
/**
* This sample subscribes the active user to the Google Developers
* YouTube channel, specified by the channelId.
*/
function addSubscription() {
// Replace this channel ID with the channel ID you want to subscribe to
var channelId = 'UC_x5XG1OV2P6uZZ5FSM9Ttw';
var resource = {
snippet: {
resourceId: {
kind: 'youtube#channel',
channelId: channelId
}
}
};
try {
var response = YouTube.Subscriptions.insert(resource, 'snippet');
Logger.log(response);
} catch (e) {
if(e.message.match('subscriptionDuplicate')) {
Logger.log('Cannot subscribe; already subscribed to channel: ' + channelId);
} else {
Logger.log('Error adding subscription: ' + e.message);
}
}
}
تحديث الفيديو
يعثر هذا المثال على عمليات تحميل المستخدم النشط، ثمّ يعدّل وصف آخر عملية تحميل من خلال إلحاق سلسلة.
/**
* This sample finds the active user's uploads, then updates the most recent
* upload's description by appending a string.
*/
function updateVideo() {
// 1. Fetch all the channels owned by active user
var myChannels = YouTube.Channels.list('contentDetails', {mine: true});
// 2. Iterate through the channels and get the uploads playlist ID
for (var i = 0; i < myChannels.items.length; i++) {
var item = myChannels.items[i];
var uploadsPlaylistId = item.contentDetails.relatedPlaylists.uploads;
var playlistResponse = YouTube.PlaylistItems.list('snippet', {
playlistId: uploadsPlaylistId,
maxResults: 1
});
// Get the videoID of the first video in the list
var video = playlistResponse.items[0];
var originalDescription = video.snippet.description;
var updatedDescription = originalDescription + ' Description updated via Google Apps Script';
video.snippet.description = updatedDescription;
var resource = {
snippet: {
title: video.snippet.title,
description: updatedDescription,
categoryId: '22'
},
id: video.snippet.resourceId.videoId
};
YouTube.Videos.update(resource, 'id,snippet');
}
}
إنّ محتوى هذه الصفحة مرخّص بموجب ترخيص Creative Commons Attribution 4.0 ما لم يُنصّ على خلاف ذلك، ونماذج الرموز مرخّصة بموجب ترخيص Apache 2.0. للاطّلاع على التفاصيل، يُرجى مراجعة سياسات موقع Google Developers. إنّ Java هي علامة تجارية مسجَّلة لشركة Oracle و/أو شركائها التابعين.
تاريخ التعديل الأخير: 2025-08-21 (حسب التوقيت العالمي المتفَّق عليه)
[[["يسهُل فهم المحتوى.","easyToUnderstand","thumb-up"],["ساعَدني المحتوى في حلّ مشكلتي.","solvedMyProblem","thumb-up"],["غير ذلك","otherUp","thumb-up"]],[["لا يحتوي على المعلومات التي أحتاج إليها.","missingTheInformationINeed","thumb-down"],["الخطوات معقدة للغاية / كثيرة جدًا.","tooComplicatedTooManySteps","thumb-down"],["المحتوى قديم.","outOfDate","thumb-down"],["ثمة مشكلة في الترجمة.","translationIssue","thumb-down"],["مشكلة في العيّنات / التعليمات البرمجية","samplesCodeIssue","thumb-down"],["غير ذلك","otherDown","thumb-down"]],["تاريخ التعديل الأخير: 2025-08-21 (حسب التوقيت العالمي المتفَّق عليه)"],[[["\u003cp\u003eThese code samples, available on GitHub, demonstrate various interactions with the YouTube Data API using Apps Script.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eretrieveMyUploads\u003c/code\u003e function retrieves a user's uploaded videos, requiring OAuth read/write scope and user authorization, iterating through the user's 'uploads' playlist and logging video details.\u003c/p\u003e\n"],["\u003cp\u003e\u003ccode\u003esearchByKeyword\u003c/code\u003e and \u003ccode\u003esearchByTopic\u003c/code\u003e functions demonstrate searching for videos based on keywords or Freebase topics, respectively, both with the option to adjust the number of results.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eaddSubscription\u003c/code\u003e function allows users to subscribe to a specified YouTube channel, providing error handling for duplicate subscription attempts.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eupdateVideo\u003c/code\u003e function illustrates how to modify the description of the most recent video uploaded by the active user.\u003c/p\u003e\n"]]],["Apps Script code samples for the YouTube Data API perform several key actions. `retrieveMyUploads` fetches a user's channels, then their \"uploads\" playlist, logging video IDs and titles iteratively. `searchByKeyword` and `searchByTopic` find videos based on a keyword or Freebase topic, respectively, logging the results. `addSubscription` subscribes the active user to a specified channel. Finally, `updateVideo` retrieves the user's uploads and appends text to the most recent video's description. These samples require OAuth permissions.\n"],null,["# Apps Script Code Samples\n\nThe following Apps Script code samples are available for the YouTube Data API. You can download these code samples from the `apps-script` folder of the [YouTube APIs code sample repository on GitHub](https://github.com/youtube/api-samples).\n\nRetrieve my uploads\n-------------------\n\nThis function retrieves the current script user's uploaded videos. To execute, it requires the OAuth read/write scope for YouTube as well as user authorization. In Apps Script's runtime environment, the first time a user runs a script, Apps Script will prompt the user for permission to access the services called by the script. After permissions are granted, they are cached for some period of time. The user running the script will be prompted for permission again once the permissions required change, or when they are invalidated by the `ScriptApp.invalidateAuth()` function. \n\nThis script takes the following steps to retrieve the active user's uploaded videos:\n\n1. Fetches the user's channels.\n2. Fetches the user's 'uploads' playlist.\n3. Iterates through this playlist and logs the video IDs and titles.\n4. Fetches a next page token, if any. If there is one, fetches the next page. Repeat step 3.\n\n```gdscript\n/**\n * This function retrieves the current script user's uploaded videos. To execute,\n * it requires the OAuth read/write scope for YouTube as well as user authorization.\n * In Apps Script's runtime environment, the first time a user runs a script, Apps\n * Script will prompt the user for permission to access the services called by the\n * script. After permissions are granted, they are cached for some periodF of time.\n * The user running the script will be prompted for permission again once the\n * permissions required change, or when they are invalidated by the\n * ScriptApp.invalidateAuth() function.\n *\n * This script takes the following steps to retrieve the active user's uploaded videos:\n * 1. Fetches the user's channels\n * 2. Fetches the user's 'uploads' playlist\n * 3. Iterates through this playlist and logs the video IDs and titles\n * 4. Fetches a next page token (if any). If there is one, fetches the next page. GOTO Step 3\n */\nfunction retrieveMyUploads() {\n var results = YouTube.Channels.list('contentDetails', {mine: true});\n for(var i in results.items) {\n var item = results.items[i];\n // Get the playlist ID, which is nested in contentDetails, as described in the\n // Channel resource: https://developers.google.com/youtube/v3/docs/channels\n var playlistId = item.contentDetails.relatedPlaylists.uploads;\n\n var nextPageToken = '';\n\n // This loop retrieves a set of playlist items and checks the nextPageToken in the\n // response to determine whether the list contains additional items. It repeats that process\n // until it has retrieved all of the items in the list.\n while (nextPageToken != null) {\n var playlistResponse = YouTube.PlaylistItems.list('snippet', {\n playlistId: playlistId,\n maxResults: 25,\n pageToken: nextPageToken\n });\n\n for (var j = 0; j \u003c playlistResponse.items.length; j++) {\n var playlistItem = playlistResponse.items[j];\n Logger.log('[%s] Title: %s',\n playlistItem.snippet.resourceId.videoId,\n playlistItem.snippet.title);\n\n }\n nextPageToken = playlistResponse.nextPageToken;\n }\n }\n}\n```\n\nSearch by keyword\n-----------------\n\nThis function searches for videos related to the keyword `'dogs'`. The video IDs and titles of the search results are logged to Apps Script's log. \n\nNote that this sample limits the results to 25. To return more results, pass additional parameters as documented in [Search:list](https://developers.google.com/youtube/v3/docs/search/list). \n\n```transact-sql\n/**\n * This function searches for videos related to the keyword 'dogs'. The video IDs and titles\n * of the search results are logged to Apps Script's log.\n *\n * Note that this sample limits the results to 25. To return more results, pass\n * additional parameters as documented here:\n * https://developers.google.com/youtube/v3/docs/search/list\n */\nfunction searchByKeyword() {\n var results = YouTube.Search.list('id,snippet', {q: 'dogs', maxResults: 25});\n for(var i in results.items) {\n var item = results.items[i];\n Logger.log('[%s] Title: %s', item.id.videoId, item.snippet.title);\n }\n}\n```\n\nSearch by topic\n---------------\n\nThis function searches for videos that are associated with a particular Freebase topic, logging their video IDs and titles to the Apps Script log. This example uses the topic ID for Google Apps Script. \n\nNote that this sample limits the results to 25. To return more results, pass additional parameters as documented in [Search:list](https://developers.google.com/youtube/v3/docs/search/list). \n\n```transact-sql\n/**\n * This function searches for videos that are associated with a particular Freebase\n * topic, logging their video IDs and titles to the Apps Script log. This example uses\n * the topic ID for Google Apps Script.\n *\n * Note that this sample limits the results to 25. To return more results, pass\n * additional parameters as documented here:\n * https://developers.google.com/youtube/v3/docs/search/list\n */\nfunction searchByTopic() {\n var mid = '/m/0gjf126';\n var results = YouTube.Search.list('id,snippet', {topicId: mid, maxResults: 25});\n for(var i in results.items) {\n var item = results.items[i];\n Logger.log('[%s] Title: %s', item.id.videoId, item.snippet.title);\n }\n}\n```\n\nSubscribe to channel\n--------------------\n\nThis sample subscribes the active user to the Google Developers YouTube channel, specified by the channelId. \n\n```gdscript\n/**\n * This sample subscribes the active user to the Google Developers\n * YouTube channel, specified by the channelId.\n */\nfunction addSubscription() {\n // Replace this channel ID with the channel ID you want to subscribe to\n var channelId = 'UC_x5XG1OV2P6uZZ5FSM9Ttw';\n var resource = {\n snippet: {\n resourceId: {\n kind: 'youtube#channel',\n channelId: channelId\n }\n }\n };\n\n try {\n var response = YouTube.Subscriptions.insert(resource, 'snippet');\n Logger.log(response);\n } catch (e) {\n if(e.message.match('subscriptionDuplicate')) {\n Logger.log('Cannot subscribe; already subscribed to channel: ' + channelId);\n } else {\n Logger.log('Error adding subscription: ' + e.message);\n }\n }\n}\n```\n\nUpdate video\n------------\n\nThis sample finds the active user's uploads, then updates the most recent upload's description by appending a string. \n\n```gdscript\n/**\n * This sample finds the active user's uploads, then updates the most recent\n * upload's description by appending a string.\n */\nfunction updateVideo() {\n // 1. Fetch all the channels owned by active user\n var myChannels = YouTube.Channels.list('contentDetails', {mine: true});\n // 2. Iterate through the channels and get the uploads playlist ID\n for (var i = 0; i \u003c myChannels.items.length; i++) {\n var item = myChannels.items[i];\n var uploadsPlaylistId = item.contentDetails.relatedPlaylists.uploads;\n\n var playlistResponse = YouTube.PlaylistItems.list('snippet', {\n playlistId: uploadsPlaylistId,\n maxResults: 1\n });\n\n // Get the videoID of the first video in the list\n var video = playlistResponse.items[0];\n var originalDescription = video.snippet.description;\n var updatedDescription = originalDescription + ' Description updated via Google Apps Script';\n\n video.snippet.description = updatedDescription;\n\n var resource = {\n snippet: {\n title: video.snippet.title,\n description: updatedDescription,\n categoryId: '22'\n },\n id: video.snippet.resourceId.videoId\n };\n YouTube.Videos.update(resource, 'id,snippet');\n }\n}\n```"]]