如何直接向我的机器人发出请求?例如,我可以随时向服务器发送任何请求并接收响应。是否可以使用机器人来完成此操作,例如 服务器或其他人向我的机器人发送请求,然后它在某处发送消息
如果可以在Python上实现吗?如果可以的话,该怎么办?
注意: webhooks 中的选项不适合我
假设您的机器人已全部设置完毕并准备就绪,您应该通过运行以下命令来安装 Flask 来创建 HTTP 服务器:
pip install flask
(你显然需要有discord.py)
然后,您需要在不和谐机器人脚本中添加一些内容。
首先,创建一个 Flask 应用程序的实例:
app = Flask(__name__)
。然后,创建一个在单独线程中运行 Flask 应用程序的函数:
def run_flask():
app.run(port=5000)
最后,开始吧:
flask_thread = threading.Thread(target=run_flask)
flask_thread.start()
因此,示例如下所示。我将其实现为向特定频道发送消息:
import discord
from discord.ext import commands
from flask import Flask, request, jsonify
import threading
app = Flask(__name__)
bot = commands.Bot(command_prefix='!')
TOKEN = 'YOUR_BOT_TOKEN'
@bot.event
async def on_ready():
print(f'Bot {bot.user} has connected to Discord')
@bot.command(name='hello')
async def hello(ctx):
await ctx.send('Hello!')
#endpoint to send a message to a specific channel
@app.route('/send_message', methods=['POST'])
def send_message():
data = request.get_json()
channel_id = data.get('channel_id')
message = data.get('message')
channel = bot.get_channel(channel_id)
if channel:
bot.loop.create_task(channel.send(message))
return jsonify({'status': 'Message sent!'}), 200
else:
return jsonify({'error': 'Channel not found!'}), 404
#run flask
def run_flask():
app.run(port=5000)
#start flask
flask_thread = threading.Thread(target=run_flask)
flask_thread.start()
bot.run(TOKEN)
请注意,当您运行脚本时,它将启动 Flask HTTP 服务器和不和谐机器人。您可以使用包含
http://localhost:5000/send_message
和 channel_id
的 JSON 负载向 message
发送 POST 请求。
import requests
url = "http://localhost:5000/send_message"
data = {
"channel_id": put_your_channel_id,
"message": "Hello from the HTTP server!"
}
response = requests.post(url, json=data)
print(response.json())
希望它有效!