youtube api - 等待视频
我制作了一个机器人,它等待来自多个频道的视频并将新视频发送到电报。代码如下:
from distutils.log import error
from googleapiclient.discovery import build
import config
import time
import telebot
ChannelsAndVideos = []
Channels = config.channels_id
bot_token = config.bot_token
api_key = config.api_key
sleepTime = config.sleepTime
messageText = config.messageText
telegram_channels_id = config.telegram_channels_id
youtube = build('youtube', 'v3', developerKey=api_key)
bot = telebot.TeleBot(bot_token)
sended = []
for ChannelId in Channels:
try:
request = youtube.channels().list(
part='statistics',
id=ChannelId
)
response = request.execute()
if(response['pageInfo']['totalResults'] != 1):
print("Error! Не удалось добавить " + ChannelId)
else:
print(ChannelId + " был добавлен (" + response.get('items')[0].get('statistics').get('videoCount') + " видео)")
ChannelsAndVideos.append((ChannelId, response.get('items')[0].get('statistics').get('videoCount')))
except error:
print(error.message)
while(True):
time.sleep(sleepTime)
for i in range(len(ChannelsAndVideos)):
request = youtube.channels().list(
part='statistics',
id=ChannelsAndVideos[i][0]
)
response = request.execute()
if(response['pageInfo']['totalResults'] != 1):
print("Error!")
else:
if response.get('items')[0].get('statistics').get('videoCount') > ChannelsAndVideos[i][1]:
ChannelsAndVideos[i] = (ChannelsAndVideos[i][0], response.get('items')[0].get('statistics').get('videoCount'))
request = youtube.channels().list(
part='contentDetails',
id=ChannelsAndVideos[i][0]
)
response = request.execute()
request = youtube.playlistItems().list(
part=['contentDetails','snippet','status'],
playlistId=response['items'][0]['contentDetails']['relatedPlaylists']['uploads']
)
response = request.execute()
if not (response['items'][0]['snippet']['resourceId']['videoId'] in sended):
sended.append(response['items'][0]['snippet']['resourceId']['videoId'])
for chat_id in telegram_channels_id:
try:
bot.send_message(chat_id, messageText + "https://www.youtube.com/watch?v=" + response['items'][0]['snippet']['resourceId']['videoId'])
except ...:
print("Не удалось отправить сообщение в " + str(chat_id))
它的实现存在一个问题:每 30 秒它就会请求每个频道的最新视频,所以这会吃掉RAM 和其余可能的请求(它们的数量在 youtube api 中受到限制)。我该如何优化这个系统?
I made a bot that waits for videos from several channels and sends new ones to telegram.. Here is the code:
from distutils.log import error
from googleapiclient.discovery import build
import config
import time
import telebot
ChannelsAndVideos = []
Channels = config.channels_id
bot_token = config.bot_token
api_key = config.api_key
sleepTime = config.sleepTime
messageText = config.messageText
telegram_channels_id = config.telegram_channels_id
youtube = build('youtube', 'v3', developerKey=api_key)
bot = telebot.TeleBot(bot_token)
sended = []
for ChannelId in Channels:
try:
request = youtube.channels().list(
part='statistics',
id=ChannelId
)
response = request.execute()
if(response['pageInfo']['totalResults'] != 1):
print("Error! Не удалось добавить " + ChannelId)
else:
print(ChannelId + " был добавлен (" + response.get('items')[0].get('statistics').get('videoCount') + " видео)")
ChannelsAndVideos.append((ChannelId, response.get('items')[0].get('statistics').get('videoCount')))
except error:
print(error.message)
while(True):
time.sleep(sleepTime)
for i in range(len(ChannelsAndVideos)):
request = youtube.channels().list(
part='statistics',
id=ChannelsAndVideos[i][0]
)
response = request.execute()
if(response['pageInfo']['totalResults'] != 1):
print("Error!")
else:
if response.get('items')[0].get('statistics').get('videoCount') > ChannelsAndVideos[i][1]:
ChannelsAndVideos[i] = (ChannelsAndVideos[i][0], response.get('items')[0].get('statistics').get('videoCount'))
request = youtube.channels().list(
part='contentDetails',
id=ChannelsAndVideos[i][0]
)
response = request.execute()
request = youtube.playlistItems().list(
part=['contentDetails','snippet','status'],
playlistId=response['items'][0]['contentDetails']['relatedPlaylists']['uploads']
)
response = request.execute()
if not (response['items'][0]['snippet']['resourceId']['videoId'] in sended):
sended.append(response['items'][0]['snippet']['resourceId']['videoId'])
for chat_id in telegram_channels_id:
try:
bot.send_message(chat_id, messageText + "https://www.youtube.com/watch?v=" + response['items'][0]['snippet']['resourceId']['videoId'])
except ...:
print("Не удалось отправить сообщение в " + str(chat_id))
There is a problem in its implementation: every 30 seconds it makes a request for the latest videos of each channel, so this eats up RAM and the rest of possible requests (their number is limited in the youtube api). How can I optimize this system?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
减少内存使用
为了避免发送的视频列表不断增长,请使用集合。它还会将发送中的
['videoId']
的运行时复杂度从 O(n) 提高到 O(1)。速率限制
不是在迭代通道之前
sleep
大块,而是在每次向 API 发出请求之前sleep
。为了方便使用,创建一个帮助器request
函数,该函数将确保在下一个请求之前至少有sleepTime
延迟。现在将所有
request.execute()
替换为execute(request)
。根据 YouTube API 使用限制调整sleepTime
值并删除所有time.sleep(sleepTime)
。结果
Reducing memory usage
To avoid the ever growing list of sent videos, use a set. It will also improve the runtime complexity of
['videoId'] in sended
from O(n) to O(1).Rate limiting
Instead of
sleep
ing in big chunk before iterating the channels,sleep
before each request to the api. For easy usage, create a helperrequest
function which will ensure at leastsleepTime
delay before the next request.Now replace all
request.execute()
s withexecute(request)
. AdjustsleepTime
value based on YouTube api usage limits and remove alltime.sleep(sleepTime)
.Result