python - 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)
解决方案
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())
推荐阅读
- apache-spark - 在 Array 类型的结构中删除一列
- sql - 列 new_value 并显示变量的类型和值
- javascript - 如何从数组中获取坐标?
- c - 为什么我创建的线程没有按顺序打印?
- python - Python脚本将具有多个值的dict列表写入多个文件
- node.js - 在生产服务器上安装节点
- mysql - `WHERE IN` 语句是否优化了重复值?
- mysql - SQL:计算 Q4-to-date 与 Q3-same-period 百分比变化
- angular - Ionic cordova run android --prod 仅在最新版本的打字稿中返回白屏
- java - 正则表达式仅匹配分隔符之间的特定空格