首页 > 解决方案 > Discord.py 关闭后运行

问题描述

我只是想使用 Discord.py 编写一个简单的“发送消息”功能,但我正在努力奋斗。

如果您注释掉,send_something('second')那么这将非常有效。但是如果你使用这个函数两次,你就会得到 RuntimeWarning。

def send_something(message):
    client = discord.Client()
    @client.event
    async def on_ready():
        connection = await client.fetch_user(USER_ID)
        await connection.send(message)
        await client.close()

    client.run(TOKEN)

# You can run the first one, but you can't run both
send_something('first') 
send_something('second') # RuntimeWarning: coroutine 'Client.run.<locals>.runner' was never awaited

然后我尝试使其成为异步函数,添加等待,在这种情况下,您现在必须以某种方式“等待”外部函数。所以我这样做了:

async def send_something(message):
    client = discord.Client()
    @client.event
    async def on_ready():
        connection = await client.fetch_user(USER_ID)
        await connection.send(message)
        await client.close()

    await client.run(TOKEN)

# No error but no message gets sent
asyncio.ensure_future(send_something('first'))
asyncio.ensure_future(send_something('second'))

现在没有错误,但消息永远不会发送。我猜脚本在工作完成之前结束并“关闭”?

知道如何编写某种“发送消息”功能吗?因为我发现的所有 discord.py 示例都是基于等待“事件”,这不是我在这里需要的。

标签: pythonasynchronousdiscordpython-asyncio

解决方案


最好的选择是向 discord api 创建一个 post 请求:

代码:

headers = {'Authorization': 'Bot %s' % YOUR_BOT_TOKEN } dm = requests.post(url='https://discord.com/api/v6/users/@me/channels', headers=headers, json={"recipient_id": RECEIVER_ID}).json() requests.post(f"https://discord.com/api/v6/channels/{dm['id']}/messages", headers=headers, json={"content": "Hello!"})


推荐阅读