【问题标题】:Discord.py send message from non-async functionDiscord.py 从非异步函数发送消息
【发布时间】:2020-10-04 20:04:55
【问题描述】:

我有一个如下所示的程序:

import things
import discord


def on_thing_happen (variable):
    get_info()
    do thing()
    # This is where I want to send a message in Discord

由于某些原因,我的其余代码无法在异步函数中运行。

有没有办法做到这一点?我不能使用异步定义。

【问题讨论】:

  • 您的用例是否允许使用 webhook?
  • 可能,但我以前从未使用过 webhook,所以我不知道我在做什么。
  • 经过进一步检查,不,webhook 不起作用。它需要是一个合适的机器人。
  • discord.py 是一个异步库,虽然从同步函数运行 send 事件“有点”可能,但它可能会导致一些奇怪的行为。我不确定您要运行什么阻塞代码,但最好有一个标准异步函数在an asyncio executor 中运行您的阻塞函数,并且您可以正常使用await send
  • 怎么可能?

标签: python asynchronous discord.py


【解决方案1】:

试试这个:

import things
import discord

client = discord.Client()

def on_thing_happen (variable):
    get_info()
    do thing()
    channel = client.get_channel(CHANNEL ID) #replace with channel id of text channel in discord
    client.loop.create_task(channel.send('Message'))

所以不是await channel.send('message'),而是client.loop.create_task(channel.send('message')

我希望这行得通!

【讨论】:

  • 你是救世主!非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-08
  • 2011-04-05
  • 2015-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多