我试图使用discord.py库将消息发送到使用它的名称的通道。这个库是异步的,我在发送多条消息时遇到了问题。当我试图在send函数已经被调用后发送消息时,我得到以下消息
Task exception was never retrieved
future: <Task finished name='Task-13' coro=<send() done, defined at C:\Users\paula\DiscordBot\Bot.py:65> exception=RuntimeError('cannot reuse already awaited coroutine')>
RuntimeError: cannot reuse already awaited coroutine发送功能:
async def send():
global en_message, en_ChannelName
guild = client.get_guild(some_guild_ID_you_want)
for channel in guild.channels:
if en_ChannelName.get().lower() in channel.name.lower() and type(channel) == discord.channel.TextChannel and en_ChannelName.get() != "":
await channel.send(en_message.get())
break它被以下代码调用的代码:
bt_Send = tk.Button(text="Send", command=partial(client.loop.create_task, send()))我还必须指出,这个不和谐的客户端运行在一个非主线程上(代码:
thread_runBot = t.Thread(target=partial(client.run, botToken))
thread_runBot.start()
TK_dialog.mainloop())
发布于 2022-06-25 20:00:57
由于错误状态,您不能使用协同线两次。
不过有个办法可以绕开这件事。您可以创建一个具有自定义__call__的类,该类在尝试调用时更改行为。
class CoroutineCaller:
def __call__(*args, **kwargs):
# you can also use `asyncio.get_event_loop().create_task` if this doesn't work
client.loop.create_task(send(*args, **kwargs))
sender = CoroutineCaller()当您执行sender()时,它将创建一个新的协同线并将其添加到客户端循环中。
然后你可以这样做:
bt_Send = tk.Button(text="Send", command=sender)这是一个更新的版本,允许您多次调用coroutine。
class CoroutineCaller:
def __call__(coro, *args, **kwargs):
client.loop.create_task(coro(*args, **kwargs))你可以把这叫做caller(ctx.send, 'random message', embed=discord.Embed(title='test'))
https://stackoverflow.com/questions/72752698
复制相似问题