python - 从 Python Discord 机器人中的同步线程发送消息

标签 python multithreading discord python-asyncio discord.py

我正在使用 discord.py 库在 Python 3.6 中开发一个 Discord 机器人,我在尝试从我创建的线程向特定 channel 发送消息时遇到了问题。

基本上,我有一些线程监控网站,我想调用一个函数(我传递给线程),当我注意到网站上发生变化时,它会向一个特定 channel 发送消息。

我最初尝试在没有 async/await 的情况下直接调用 client.send_message() 但它根本不起作用,所以我编写了发送消息的 async/await 函数(测试它并且它有效) 但我再次从线程调用它时遇到问题,所以我最终将 bot 客户端传递到我的线程并调用 self.bot_client.loop.create_task(self.sendmsgfunction(msg))。这行得通,但与机器人用通常的 @ 回复消息所花费的时间相比,它非常慢(发送消息大约需要 15 秒,而且这可能不是正确的发送方式) bot.event 函数。

我已经尝试使用 asyncio 创建一个事件循环然后调用该函数,但我再次遇到错误。

有什么想法吗?

最佳答案

您可以使用 asyncio.run() 来运行异步函数,如下所示:

import asyncio

async def async_func():
    print("Async function run!")

asyncio.run(async_func())

关于python - 从 Python Discord 机器人中的同步线程发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54928824/

相关文章:

c++ - 中断 boost 线程

python - 运行时警告 : coroutine was never awaited self. _target(*self._args, **self._kwargs)

python - 在 Python 中使用 Selenium 查找登录按钮 id

java - 在线程安全单例中,返回是否必须在同步块(synchronized block)内

python - 如何在 discord python bot 中制作 Canvas 个人资料卡?

python - 烦人的生成器错误

python - 如何从本地系统在远程服务器上运行 Flask 应用程序?

python - 具有线条和面积样式的 Matplotlib 图例

python - 将反引号 (`) + 分数的字符串转换为 float

multithreading - clojure 是 "multithread"吗?