【发布时间】:2021-02-13 19:19:29
【问题描述】:
我正在构建一个不和谐的机器人来接收来自多个系统和程序的命令。我想将我的不和谐机器人的某些操作公开给 REST 端点,然后在一个地方执行所述操作。
import uvicorn
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional
from discord.ext import commands
app = FastAPI()
TOKEN = 'MY_TOKEN'
bot = commands.Bot(command_prefix='>')
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
@app.get("/")
def hello():
return {"message":"Hello"}
@app.post("/items/")
async def create_item(item: Item):
await send_message()
return item
@bot.event
async def on_ready():
print(f'{bot.user.name} has connected to Discord!')
async def send_message():
user = await bot.fetch_user(USER_ID)
await user.send('????')
if __name__ == "__main__":
bot.run('BOT_TOKEN')
uvicorn.run(app, host='0.0.0.0')
当我尝试运行它时,我只看到机器人处于活动状态。我对python有点新,但我是一名资深程序员。这是由于python“缺乏”多线程吗?还是端口使用情况?
最终目标是调用“/items/”端点并查看发送给我的关于不和谐的消息
编辑
我尝试了所有答案并想出了一些我自己的答案。问题是多线程。我对此感到很沮丧,最后只是将这部分移到了 Node.js。它在技术上并不能解决这个问题,但比导航 python 多线程要容易得多。
server.js:
var express = require('express');
var app = express();
const Discord = require('discord.js');
const client = new Discord.Client();
app.get('/listUsers', function (req, res) {
dm_user();
res.send('hello');
})
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', msg => {
if (msg.content === 'ping') {
msg.reply('pong');
}
});
async function dm_user(id){
var my_user = await client.users.fetch('USER_ID');
console.log(my_user);
}
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
client.login('TOKEN');
})
【问题讨论】:
-
所以,用浏览器导航到
localhost:8000/docs(或您分配给您机器的任何 IP 地址)不会返回任何内容,对吧? -
@isabi 是正确的
-
当你运行
bot.run('BOT_TOKEN')时,它会运行这个函数,直到你停止 bot 并在关闭 bot 后执行uvicorn.run()。所以uvicorn.run()没有被执行,你无法连接到网页。您必须在单独的线程中启动机器人。
标签: python discord.py fastapi