首页 > 解决方案 > discord.py 在新线程中使用机器人的方法

问题描述

我正在制作我的 discord.py 机器人,并且我想要一种发送自定义消息的方法。我尝试使用on_message但一直有关于线程的错误。

@bot.event
async def on_ready():
        print(f'{bot.user.name} is now on Discord!')
        #Here I want a loop that asks for input, then, if it gets it, the bot sends it.

我试过使用Thread's,但我不能await在一个线程中。

#I want to do somthing like:
channel = bot.get_channel(my_channel_id)
while True:
    msg = input("Bot: ")
    await channel.send(msg)

感谢您的所有回答!


编辑:我无法让您的解决方案发挥作用,我很确定这是我的错。有没有办法让机器人正常运行,但是当它运行时,有一个循环要求输入,并在它得到它时将它作为机器人发送到不和谐。

像这样的工作版本?:

c = bot.get_channel(my_channel_id)
while True:
    message = input("Bot: ")
    await c.send(message)

标签: pythonpython-3.xdiscordpython-multithreadingdiscord.py

解决方案


AFAIK 标准库中没有异步等效项input()。有一些解决方法,这是我认为最干净的建议:

当您的程序启动时启动一个线程,您可以在input()其中运行阻塞调用。我使用了一个 executor,因为 asyncio 有一个方便的功能来与任何类型的 executor 通信。然后从异步代码在 executor 中安排一个新作业并等待它。

import asyncio
from concurrent.futures.thread import ThreadPoolExecutor

async def main():
    loop = asyncio.get_event_loop()
    while True:
        line = await loop.run_in_executor(executor, input)
        print('Got text:', line)


executor = ThreadPoolExecutor(max_workers=1)
asyncio.run(main())

推荐阅读