python - 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 示例都是基于等待“事件”,这不是我在这里需要的。
解决方案
最好的选择是向 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!"})
推荐阅读
- angular - 如何动态更改标题?
- android - 如何在 Android 中获取 TableLayout 单元格值
- graphql - 查询正确,但获取“未定义”数据
- reactjs - 在 React.js 中有条件地渲染不同的元素
- regex - $ 在正则表达式中的行为是什么?
- javascript - 如何使用php和jquery在谷歌地图中动态添加经纬度?
- c# - 如何使用更新的类为 POM QA 自动化框架生成范围报告?
- java - 如何使用流 JAVA 8 合并两个 POJOS 列表,必要时修改一些值
- c - 如果一个线程锁定了一个互斥体并且没有解锁它,那么其余的线程不应该被阻塞吗?
- autohotkey - 我需要关于使用 AHK 设置窗口边框样式的帮助