【发布时间】:2021-11-08 20:38:03
【问题描述】:
我只是想使用 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 示例都是基于等待“事件”,这不是我在这里需要的。
【问题讨论】:
-
如果你只需要一个函数来向某人发送消息,那么你根本不应该使用 discord.py。只需使用 discord 的原始 API 并将消息直接发送给该人
标签: python asynchronous discord python-asyncio