-
FastAPI + discord.py snippet컴퓨터/파이썬 2021. 8. 24. 09:31728x90반응형
FastAPI 서버와 discord.py 서버를 같이 실행시키고 싶었다.
unvicorn.run 한 후에 startUp 함수에서 bot.start를 하는 방법도 있었는데 자꾸 봇이 offline으로 가게 되었다.
Python
import discord from discord.ext import commands from fastapi import FastAPI from uvicorn import Config, Server TOKEN = "토큰" intents = discord.Intents.all() bot = commands.Bot(command_prefix="#", intents=intents) @bot.event async def on_message(message): if message.content.startswith("["): print("yes") @bot.event async def on_ready(): print("Ready)") async def getDiscordUsers(): json = {name: [] for name in names} for i in range(0, 3): channel = bot.get_channel(channels[i]) members = channel.members for member in members: # selfMuted = member.voice.self_mute if member.bot: continue if member.nick == None: json[names[i]].append(member.name) else: json[names[i]].append(member.nick) return json app = FastAPI() @app.get("/discord") async def send_msg(): return await getDiscordUsers() config = Config(app=app, host="0.0.0.0", port=8000, log_level="critical") server = Server(config) bot.loop.create_task(server.serve()) bot.run(TOKEN)
Rust
serenity + actix를 이용하면 futures::future::join을 이용하면 같이 실행된다.
use std::env; use actix_web::{middleware, App, HttpServer}; use serenity::{ async_trait, model::{channel::Message, gateway::Ready}, prelude::{Client, Context, EventHandler}, }; struct Handler; #[async_trait] impl EventHandler for Handler { async fn message(&self, ctx: Context, msg: Message) { if msg.content == "`test" { if let Err(why) = msg.channel_id.say(&ctx.http, "Pong!").await { println!("Error sending message: {:?}", why); } } } async fn ready(&self, _: Context, ready: Ready) { println!("{} is connected!", ready.user.name); } } #[actix_web::main] async fn main() -> std::io::Result<()> { // Configure the client with your Discord bot token in the environment. let token = env::var("DISCORD_TOKEN").expect("Expected a token in the environment"); let mut client = Client::builder(&token) .event_handler(Handler) .await .expect("Err creating client"); let (_, _) = futures::future::join( client.start(), HttpServer::new(|| { App::new() .wrap(middleware::Logger::default()) .service(discordbot::server::hello) }) .bind(discordbot::SERVER) .expect("Error binding") .run(), ) .await; Ok(()) }
728x90'컴퓨터 > 파이썬' 카테고리의 다른 글
Python: 간단한 streamlit 앱 만들면서 배운 점 (0) 2021.09.19 Python Selenium: 여러가지 팁 (0) 2021.06.07 Pyston: Python 3.8.8 최적화 버전 (0) 2021.05.09