我有一个 Discord Bot,我想在某个用户上传视频时发送一条消息。我看过 Youtube API ( https://developers.google.com/youtube/v3/docs/videos ),但没有找到如何做我想做的事。
最佳答案
嗯..我每 1 分钟检查一次视频并检查视频链接(或 ID)是否与最后一个视频不相等,然后将视频发布到您要发布到的特定 channel 中。
我用 google-api-python-client
首先pip install google-api-python-client
from from googleapiclient.discovery import build
在你的 on_ready 函数中
@client.event async def on_ready(): youtube=build('youtube','v3',developerKey='Enter your key here') req=youtube.playlistItems().list( playlistId='The Playlist id of the channel you want to post video i.e. the id of video playlist of the channel', part='snippet', maxResults=1 ) res=req.execute() vedioid=res['items'][0]['snippet']['resourceId']['videoId'] link="https://www.youtube.com/watch?v="+vedioid ch=await client.fetch_channel(the channel id from where im checking for the new video) await ch.send(link) yt.start()#Starting tasks loop which is made below for checking every minute if the new video is equal or unequal to old video link
使任务循环以检查视频
@tasks.loop(seconds=60) async def yt(): youtube=build('youtube','v3',developerKey='Enter your key here') req=youtube.playlistItems().list( playlistId='The Playlist id of the channel you want to post video i.e. the id of video playlist of the channel', part='snippet', maxResults=1 ) res=req.execute() vedioid=res['items'][0]['snippet']['resourceId']['videoId'] link="https://www.youtube.com/watch?v="+vedioid ch=await client.fetch_channel(Fetching same channel from which you are checking for the video link) async for message in ch.history(limit=1):#looping through the channel to get the latest message i can do this using last message also but I prefer using channel.history if str(link) != str(message.content): ch2=await client.fetch_channel(the channel you want to post video to) await ch2.send(f'@everyone,**User** just posted a vedio!Go and check it out!\n{link}') await ch.send(link2)#this is important as after posting the video the link must also be posted to the check channel so that the bot do not send other link else: pass
所以基本上我所做的是使用私有(private) channel 在准备好后立即发布机器人的最新视频,因为如果碰巧机器人在两者之间脱机然后上线,它会将链接发布到该 channel 然后我将其作为任务我每分钟检查一次该 youtube channel 的最新视频链接是否与我的私有(private) channel 中的视频链接不相等,这意味着上传者已上传视频,因此将视频发布到我希望发布的 channel 中。如果它等于然后什么都不做,即
pass
如果您使用的是 json 文件或数据库,而不是像我使用 channel 来检查视频那样,您可以使用它。它工作正常。
关于youtube - 当 Youtube 视频上传 API 时通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43118114/