【问题标题】:Sending DM to user in Flask python with discord.py使用 discord.py 在 Flask python 中向用户发送 DM
【发布时间】:2020-10-30 23:38:24
【问题描述】:

所以我正在尝试使用 flask 模块为我的 discord 机器人创建一个投票 webhook,但显然在同一个文件中导入 discord.py 和 flask 并不能很好地结合在一起。当我运行我的代码时,它只显示RuntimeError: Event loop stopped before Future completed.。这是我的代码:

#setup code
@app.route('/webhook', methods=['POST'])
def respond():
    data = request.json
    auth = request.headers
    if auth["Authorization"] == "my_auth":
         user = client.get_user(user_id)
         await user.send('Thank you for voting for me! Make sure you vote again in 12 hours!')
    return Response(status=200)

这不起作用,因为您不能在 async 函数之外执行 await,因此我将 await user.send('Thank you for voting for me! Make sure you vote again in 12 hours!') 替换为 client.loop.create_task(user.send('Thank you for voting for me! Make sure you vote again in 12 hours!')),这就是给我带来错误 RuntimeError: Event loop stopped before Future completed. 的原因。有人告诉我,使用 Flask 不会让 discord.py 运行,我不知道如何解决这个问题。那么你能帮我弄清楚当 webhook 被触发时如何给用户发送消息吗?

关于 webhook 的信息: Click Here to see the request

版本: 蟒蛇:3.8.5 不和谐.py:1.4.1 烧瓶:1.1.2

编辑:当我在终端中输入flask run 时,我意识到这实际上有效,但它不适用于gunicorn app:app。由于输入 flask run 运行的是开发服务器,而不是我应该实际使用的服务器,所以我运行 gunicorn app:app 这就是给我 RuntimeError: Event loop stopped before Future completed.

【问题讨论】:

  • 您的应用程序使用 celery 吗?要在烧瓶中实现异步任务,你应该使用 celery。

标签: python flask discord.py


【解决方案1】:

尝试在函数定义中添加异步。

async def respond():

【讨论】:

  • 很遗憾,这并没有解决错误,它仍然显示RuntimeError: Event loop stopped before Future completed.,但感谢您的回复!您还有其他建议吗?
  • 你在用芹菜吗?
  • 其实 celery 是实现异步任务的最佳方案
猜你喜欢
  • 2021-12-24
  • 2021-04-26
  • 2021-07-15
  • 2020-10-10
  • 1970-01-01
  • 2021-04-16
  • 2021-08-07
  • 2021-01-06
  • 2021-02-24
相关资源
最近更新 更多