Python + Flask + Discord:如何通过flask端点通过discord发送消息?

Python + Flask + Discord: How to send a message through discord through a flask endpoint?(Python + Flask + Discord:如何通过flask端点通过discord发送消息?)
本文介绍了Python + Flask + Discord:如何通过flask端点通过discord发送消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试发送一条不和谐的消息,通过 Flask 端点激活

I'm trying to send a message with discord, activated through a Flask endpoint

我在调用 http://127.0.0.1:5000/send

RuntimeError: There is no current event loop in thread 'Thread-4'.

我有以下(最少的)代码

I have the following (minimal) code

import discord
from flask import Flask, jsonify

async def my_background_task():

  for message in ['a', 'b']:
    await client.wait_until_ready()
    channel = client.get_channel(CHANNEL_ID)
    await channel.send(message)

  await client.close() 

def sendMessages():
  client = discord.Client()
  client.loop.create_task(my_background_task())
  client.run('SECRET')

app = Flask(__name__)


@app.route('/send')
def send():
  sendMessages()

推荐答案

也许您应该考虑使用 webhook 而不是机器人.这是一个简单的示例,您应该对其实现烧瓶.

Maybe you should consider using webhooks instead of a bot. Here is a simple example you should implement flask to it.

import requests #dependency

url = "<your url>" #webhook url, from here: https://i.imgur.com/aT3AThK.png

data = {}
#for all params, see https://discordapp.com/developers/docs/resources/webhook#execute-webhook
data["content"] = "message content"
data["username"] = "custom username"

#leave this out if you dont want an embed
data["embeds"] = []
embed = {}
#for all params, see https://discordapp.com/developers/docs/resources/channel#embed-object
embed["description"] = "text in embed"
embed["title"] = "embed title"
data["embeds"].append(embed)

result = requests.post(url, json=data, headers={"Content-Type": "application/json"})

try:
    result.raise_for_status()
except requests.exceptions.HTTPError as err:
    print(err)
else:
    print("Payload delivered successfully, code {}.".format(result.status_code))

#result: https://i.imgur.com/DRqXQzA.png

这篇关于Python + Flask + Discord:如何通过flask端点通过discord发送消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do I make a list of all members in a discord server using discord.py?(如何使用 discord.py 列出不和谐服务器中的所有成员?)
how to change discord.py bot activity(如何更改 discord.py 机器人活动)
Issues with getting VoiceChannel.members and Guild.members to return a full list(让 VoiceChannel.members 和 Guild.members 返回完整列表的问题)
Add button components to a message (discord.py)(将按钮组件添加到消息(discord.py))
on_message() and @bot.command issue(on_message() 和@bot.command 问题)
How to edit a message in discord.py(如何在 discord.py 中编辑消息)