Discord.py voicecchannel .connect()导致线程挂起



我正在尝试用python编写一个简单的不和bot。我希望机器人能够加入一个语音频道,并不断重复一个mp3文件。我首先尝试在on_ready()函数中使用while循环,这产生了一个可以理解的坏结果。我现在尝试使用一个线程从主线程中单独运行循环,但是discord.py的函数使用async/await,所以我不得不即兴发挥(糟糕)。

import asyncio
import threading
import discord
from discord import app_commands
intents = discord.Intents.all()
client = discord.Client(intents=intents)
discord.Permissions.manage_nicknames = True
tree = app_commands.CommandTree(client)

def targeter():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(play_sounds())
loop.close()
async def play_sounds():
for channel in client.guilds[1].channels:
if str(channel.type) == "voice":
print("started")
player_channel = await channel.connect()
print("done")
@client.event
async def on_ready():
await tree.sync()
threading.Thread(target=targeter).start()
client.run("token")

当我运行该线程时,它到达我引入等待的discord. voicecchannel .connect()函数的行并挂起。其余的命令工作得很好,只是这个线程。正常运行时,connect()命令通常会在几毫秒内返回一个VoiceClient。这是否与我试图跨线程运行函数有关?如果是这样,有没有我没看到的更好的解决方案?

>>> started

为什么使用线程?让我们看看tasks。创建一个每分钟运行一次的任务;让它加入VC,如果它不在里面(也就是第一次运行),然后让它检查歌曲是否仍在运行/播放。

看看这里如何创建player。将播放器对象保存在任务中,然后当任务循环运行时,您可以执行player.is_done()来检查它是否仍在播放-然后再次开始播放歌曲。

最新更新