Skip to content

Instantly share code, notes, and snippets.

@haykkh
Created June 24, 2020 10:09
Show Gist options
  • Save haykkh/49ed16a9c3bbe23491139ee6225d6d09 to your computer and use it in GitHub Desktop.
Save haykkh/49ed16a9c3bbe23491139ee6225d6d09 to your computer and use it in GitHub Desktop.
How to run a discord.py bot with FastAPI
import asyncio
import discord
from fastapi import FastAPI
app = FastAPI()
client = discord.Client()
# where the magic happens
# register an asyncio.create_task(client.start()) on app's startup event
# ^ note not client.run()
@app.on_event("startup")
async def startup_event():
asyncio.create_task(client.start('token'))
@app.get("/")
async def read_root():
return {"Hello": str(client.user)}
@titouanfreville
Copy link

@djalo you can try to setup and initialize the async loop before starting anything so they would most likely run on the same loop. If FastAPI creates its own loop it will not solve any thing though. This helped me to go through the same issue when running FastAPI with a mix between sync and async methods and google Firebase client in async mode.

        loop = new_event_loop()
        set_event_loop(loop)

@alanoitaliano
Copy link

@titouanfreville
Thanks for Your input! Gonna save this for another occasion.
I solved that pretty easily. Switched to discord.py library just because was curious.
No more errors, maybe that will help somebody too

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment