discord.py在新线程中使用漫游器的方式

问题描述 投票:0回答:1

我正在制作我的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,但无法在线程中使用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)
python python-3.x discord python-multithreading discord.py
1个回答
0
投票
AFAIK]标准库中没有input()的异步等效项。有一些解决方法,这是我的建议,我认为这是最干净的:

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

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())

© www.soinside.com 2019 - 2024. All rights reserved.