【问题标题】:Sending messages from synchronous thread in a Python Discord bot在 Python Discord 机器人中从同步线程发送消息
【发布时间】:2019-07-22 13:16:50
【问题描述】:

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

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

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

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

有什么想法吗?

【问题讨论】:

  • @AlexanderDmitriev 您介意提供一个使用示例吗?我不知道如何运行我安排的回调
  • 你有没有得到这个?我自己也有类似的问题。
  • @Jachdich 我发现使用 webhook 做这类事情要容易得多
  • 您始终可以直接向 discord API 发送请求,例如通过 webhook,中间不需要像 discord.py 这样繁重的异步库。

标签: python multithreading discord python-asyncio discord.py


【解决方案1】:

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

import asyncio

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

asyncio.run(async_func())

【讨论】:

    【解决方案2】:

    如果你想向特定频道发送消息,首先你应该获取频道对象。

    channel = discord.utils.get(ctx.guild.channels, id=channel_id_here)
    

    那你就可以了

    await channel.send()
    

    【讨论】:

    • 我看不出这是如何回答这个问题的。问题在于同步函数中的await
    猜你喜欢
    • 2023-04-03
    • 2021-08-19
    • 2021-01-08
    • 2019-09-12
    • 2021-08-27
    • 2021-10-29
    • 2021-02-22
    • 2020-11-23
    • 2021-02-20
    相关资源
    最近更新 更多