Skip to content

Instantly share code, notes, and snippets.

@crrapi
Last active December 7, 2023 16:47
Show Gist options
  • Save crrapi/c8465f9ce8b579a8ca3e78845309b832 to your computer and use it in GitHub Desktop.
Save crrapi/c8465f9ce8b579a8ca3e78845309b832 to your computer and use it in GitHub Desktop.
(Don't use if you can) Run a Flask app and a discord.py bot in one program using threads.
# Note: You really should not use this.
# You can easily convert your app
# to use Quart by using async+await
# and then use loop.create_task(bot.start(...))
# before using app.run.
from threading import Thread
from flask import Flask
from functools import partial
from discord.ext import commands
# Initialize our app and the bot itself
app = Flask(__name__)
bot = commands.Bot(command_prefix="!")
# Set up the 'index' route
@app.route("/")
def hello():
return "Hello from {}".format(bot.user.name)
# Make a partial app.run to pass args/kwargs to it
partial_run = partial(app.run, host="0.0.0.0", port=80, debug=True, use_reloader=False)
# Run the Flask app in another thread.
# Unfortunately this means we can't have hot reload
# (We turned it off above)
# Because there's no signal support.
t = Thread(target=partial_run)
t.start()
# Run the bot
bot.run("Your token")
# Now, you can visit your localhost or your VPS' IP in your browser and you should see a message!
@TheRedstoneRadiant
Copy link

Hey @Digbigpig,
Sorry for the late response, but you can use bot.loop.create_task(coro) to run a coroutine (e.g. bot.loop.create_task(channel.send("Hello")))

Awesome!

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