要将Discord机器人暴露给API,可以使用Flask或FASTAPI这两个Python框架来实现。下面是一个使用Flask框架的示例代码:
from flask import Flask, request
from discord.ext import commands
app = Flask(__name__)
bot = commands.Bot(command_prefix='!')
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')
@app.route('/api/discord', methods=['POST'])
def discord_api():
data = request.get_json()
message = data['message']
channel_id = data['channel_id']
channel = bot.get_channel(int(channel_id))
if channel:
bot.loop.create_task(channel.send(message))
return 'Message sent to Discord channel!'
else:
return 'Invalid channel ID.'
if __name__ == '__main__':
bot.run('YOUR_DISCORD_BOT_TOKEN')
app.run()
在以上示例中,我们使用Flask创建了一个简单的API端点/api/discord
,它接收一个JSON对象作为请求的主体,其中包含message
和channel_id
字段。然后,我们通过bot.get_channel
方法获取Discord中对应的频道,如果找到了频道就使用channel.send
方法发送消息。
确保将YOUR_DISCORD_BOT_TOKEN
替换为你自己的Discord机器人令牌。
如果你想使用FASTAPI框架,可以使用类似的方法。以下是一个使用FASTAPI的示例代码:
from fastapi import FastAPI, HTTPException
from discord.ext import commands
app = FastAPI()
bot = commands.Bot(command_prefix='!')
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')
@app.post('/api/discord')
async def discord_api(message: str, channel_id: int):
channel = bot.get_channel(channel_id)
if channel:
await channel.send(message)
return {'message': 'Message sent to Discord channel!'}
else:
raise HTTPException(status_code=400, detail='Invalid channel ID.')
if __name__ == '__main__':
bot.run('YOUR_DISCORD_BOT_TOKEN')
import uvicorn
uvicorn.run(app, host='0.0.0.0', port=8000)
在以上示例中,我们使用FASTAPI创建了一个简单的API端点/api/discord
,它接收message
和channel_id
作为请求参数。然后,我们通过bot.get_channel
方法获取Discord中对应的频道,如果找到了频道就使用channel.send
方法发送消息。
同样地,请将YOUR_DISCORD_BOT_TOKEN
替换为你自己的Discord机器人令牌。
以上是将Discord机器人暴露给API的两种解决方法,你可以根据自己的需求选择使用Flask或FASTAPI。