我正在尝试制作一个从 YouTube 下载歌曲然后播放的机器人。我已经能够设置搜索和下载功能,但由于某种原因,我的机器人在下载 YouTube 歌曲后崩溃了。据我所知,这与 Asyncio 有关。
编辑:添加了完整的输出以及下面的完整代码,代码的相关部分应该仍然是<播放部分,但我已经附加了其余部分。
The error I get:
C:\Users\Admin\PycharmProjects\BattleBot\venv\Scripts\python.exe C:/Users/Admin/PycharmProjects/BattleBot/main.py
The final bot has started.
[youtube] vOXZkm9p_zY: Downloading webpage
[youtube] vOXZkm9p_zY: Downloading player 68cc98b3
WARNING: Requested formats are incompatible for merge and will be merged into mkv.
[download] Destination: Imagine Dragons - Birds (Animated Video)-vOXZkm9p_zY.f137.mp4
[download] 100% of 66.34MiB in 00:03
[download] Destination: Imagine Dragons - Birds (Animated Video)-vOXZkm9p_zY.f251.webm
[download] 100% of 3.56MiB in 00:00
[ffmpeg] Merging formats into "Imagine Dragons - Birds (Animated Video)-vOXZkm9p_zY.mkv"
Deleting original file Imagine Dragons - Birds (Animated Video)-vOXZkm9p_zY.f137.mp4 (pass -k to keep)
Deleting original file Imagine Dragons - Birds (Animated Video)-vOXZkm9p_zY.f251.webm (pass -k to keep)
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001CBE9576F70>
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 746, in call_soon
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
RuntimeError: Event loop is closed
_ClientEventTask exception was never retrieved
future: <ClientEventTask state=finished event=on_message coro=<function on_message at 0x000001CB83D05AF0> exception=SystemExit(0)>
Traceback (most recent call last):
File "C:\Users\Admin\PycharmProjects\BattleBot\venv\lib\site-packages\discord\client.py", line 713, in run
loop.run_forever()
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\windows_events.py", line 316, in run_forever
super().run_forever()
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 596, in run_forever
self._run_once()
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 1890, in _run_once
handle._run()
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\events.py", line 80, in _run
self._context.run(self._callback, *self._args)
File "C:\Users\Admin\PycharmProjects\BattleBot\venv\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Admin\PycharmProjects\BattleBot\main.py", line 31, in on_message
youtube_dl.main(opts)
File "C:\Users\Admin\PycharmProjects\BattleBot\venv\lib\site-packages\youtube_dl\__init__.py", line 475, in main
_real_main(argv)
File "C:\Users\Admin\PycharmProjects\BattleBot\venv\lib\site-packages\youtube_dl\__init__.py", line 470, in _real_main
sys.exit(retcode)
SystemExit: 0
Process finished with exit code 0
代码:
import os
import discord
import youtube_dl
from youtube_api import YouTubeDataAPI
intents = discord.Intents().all()
activity = discord.Activity(name='Tests', type=discord.ActivityType.watching)
bot = discord.Client(intents=intents, activity=activity)
yt = YouTubeDataAPI("")
link = "https://www.youtube.com/watch?v="
os.chdir('C:/Songs')
searchSong = ""
@bot.event
async def on_ready():
print("The final bot has started.")
@bot.event
async def on_message(message):
search_song = str(message.content)
if search_song.startswith('<play'):
search_song = search_song[6:]
searches = yt.search(q=search_song, max_results=1)
valuesColl = searches[0].values()
valueIter = iter(valuesColl)
songID = next(valueIter)
opts = [(link + songID)]
youtube_dl.main(opts)
files = [x for x in os.listdir('C:\\Songs') if x.endswith(".mp4")]
newest = max(files, key=os.path.getctime)
channel = message.channel
voice_channel = message.author.voice.channel
vc = await voice_channel.connect()
vc.play(discord.FFmpegPCMAudio(newest))
@bot.event
async def on_member_update(before, after):
if before.status != after.status and (str(after.status) == "idle" or str(after.status) == "offline") and str(
before.status) != "offline":
if after.voice is not None:
embed = discord.Embed(title=f"KICKED FOR BEING " + str(after.status))
embed.add_field(name='Test Kick', value=before.mention)
embed.add_field(name='AMM', value="https://www.youtube.com/watch?v=w1PRiHEHJd8")
channel = bot.get_channel(788477061962268693)
await channel.send(embed=embed)
await after.edit(voice_channel=None)
@bot.event
async def on_voice_state_update(member, before, after):
if before.channel is None and after.channel is not None and str(member.status) == "offline":
embed = discord.Embed(title=f"KICKED FOR BEING " + str(member.status))
embed.add_field(name='Test Kick', value=member.mention)
embed.add_field(name='AMM', value="https://www.youtube.com/watch?v=w1PRiHEHJd8")
channel = bot.get_channel(channelid)
await channel.send(embed=embed)
await member.edit(voice_channel=None)