Python + Flask + Discord:如何通过Flask端点通过Disord发送消息? [英] Python + Flask + Discord: How to send a message through discord through a flask endpoint?
本文介绍了Python + Flask + Discord:如何通过Flask端点通过Disord发送消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试发送不和谐的消息,该消息是通过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'.
我有以下(最小)代码
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()
推荐答案
也许您应该考虑使用Webhooks代替机器人.这是一个简单的示例,您应该对其实施烧瓶.
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端点通过Disord发送消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文