Learn to Code via Tutorials on Repl.it!

← Back to all posts
Hosting discord.py bots with repl.it
h
TheDrone7 (1890)

Hosting discord.py bots on repl.it

This tutorial shows you how you can host your discord.py bots on repl.it.

For Node.js see this tutorial.

Before you start, you should already have a working bot. Also, this really doesn't matter if you're using discord.py async or discord.py rewrite. Works like a charm for both!

Just to ease things, we'll be using the end product of this tutorial.

Here is the end result: https://repl.it/@TheDrone7/discordpy-rewrite


What we'll be doing?

  1. Creating a web server.

  2. Using uptimerobot to ping our bot every 30 minutes.

    We do this because our repl goes offline after 1 hour of inactivity. So we keep pinging the repl every 30 minutes, to avoid it being idle for one hour.

Step 1: Installing the dependencies.

Using the repl.it package manager, install the following dependencies (assuming you've already made the bot, discord.py would be installed already but is listed just in case): -

  • discord.py
  • flask

In case you don't know about the repl.it package manager, click here to get started with the repl.it editor.

flask is a python module for handling http requests.


Step 2: Setting up a server

Setting up a server using Flask is very easy. But to keep things simple and your bot's file clean, we'll make a server in a new file and name it keep_alive.py since that is what most people like to call the file that helps keep their bot alive.

Open up the keep_alive.py file and import Flask also import Thread you can learn more about Threads here.

from flask import Flask
from threading import Thread

We didn't have to add threading to our requirements since it comes with python.

Next, create the actual server.

app = Flask('')

Easy, isn't it? But it's not over just yet.

Next, we add a route. A route is basically what handles http requests. Without a route the existence of our server does nothing. So add the following code

@app.route('/')
def main():
    return "Your bot is alive!"

@app.route() is a decorator which defines a route. '/' is the default route or the homepage of our server. The main function is called whenever a user makes a request to the '/' route which basically returns whatever has to displayed on the webpage, here we simply send the string Your bot is alive to keep things simple.

Now that our server is ready, we need to make sure that it runs and http requests can be made to it.

def run():
    app.run(host="0.0.0.0", port=8080)

You can basically put any 4 digit number in port which is not already in use. The defaults for python is 8080 and that's what we'll stick to.

Finally, we make a function that we can call to prepare our server and allow it to be pinged.

def keep_alive():
    server = Thread(target=run)
    server.start()

And we're basically done with our keep_alive.py file.


Step 3: Combining the server and bot.

Now that we're done making both the bot and the server, we need to combine the two. That is easy too, open up the main.py file ( or whatever file has the discord_client.run(bot_token) function in it ) and add the following line at the top: -

import keep_alive

This will import the keep_alive file in your bot's main file.

Now just before starting the bot, at the bottom of the same file write the following code: -

keep_alive.keep_alive()

This will run the keep_alive() function that we defined in the keep_alive.py file earlier.

And now your server is ready too! Run the bot, you should see something like this: -

Notice that small window saying Your bot is alive! if you see it, you successfully created the server! Only the last step remains! Before you go into the last step, make sure to copy the repl.co link you see in that small window's address bar. (https://discordpy-rewrite.thedrone7.repl.co in the picture, it will be referred to as the server link in the rest of the tutorial)

And in case you don't see it, go through this tutorial again and make sure you didn't miss something, also if it retains, don't hesitate to comment and tell me.


Step 4: Setting up uptimerobot

First of all visit https://uptimerobot.com/ and register an account just like any other website. (It is free of course)

Next, Once, you're logged in,

  1. Click on the New Monitor button.

  2. Next, choose the HTTP(S) Monitor Type.
    Give it a friendly name of your choice ( naming it after your bot is recommended )
    Paste your server link in the URL/IP field.
    Set the Monitoring Interval to anything between 5 minutes to 45 minutes. ( 30 minutes is recommended)

    Optionally, Select yourself as one of the "Alert Contacts To Notify" so you are notified via e-mail whenever your bot goes offline.
    Finally making it look something like this: -

  3. Click on Create Monitor and you're good to go!


Now you're bot will stay online for as long as it can.

( Repl it being just another host, won't be able to host it 24/7 so it will have a downtime of a few minutes within every 24 hours.)

And you're done! The final product can be found here.

Please upvote if you found this useful!

Also, comment down below if there's something you would like to share or ask.

And finally, thanks for reading it!

Comments
hotnewtop
iMikei (4)

I get the following error:

[SolverProblemError]
Because no versions of replit match >3.0.0,<4.0.0
 and replit (3.0.0) depends on flask (>=1.1.2,<2.0.0), replit (>=3.0.0,<4.0.0) requires flask (>=1.1.2,<2.0.0).
So, because repl-python3-meme-sounds depends on both flask (^2.0.0) and replit (^3.0.0), version solving failed.
exit status 1


Repl.it: Package operation failed.
OrianPax (1)

@iMikei oof bro, same here. dunno what to do. my previous bot is working fine, this one is sucking.

SebastianChris1 (15)

@iMikei Add
flask = "^1.1.4"
under [tool.poetry.dependencies] in the pyproject.toml

muhammadali13 (0)

@SebastianChris1 This works perfectly. Thanks for the comment.

WoefulNebula (9)

The repl says it’s working and Uptime bot says 100% but my bot is not online

Ricky_J_Aquino (6)

Is it just me or did this stop working today?
I am even making a fork of yours and setting my own token and still won't load. (It has been working the past few days).
This is the error...

Repl.it: Updating pack configuration
--> python3 -m poetry install
[RuntimeError]
The Poetry configuration is invalid:
  - 'description' is a required property
Repl.it: Package operation failed.
ShivrajJ (3)

@Ricky_J_Aquino Yeah, I had the same problem. I found a way to make it work after a bit of snooping around. It's failing because there's no description specified in your pyproject.toml file

So, all I did was go to the file pyproject.toml, which might look something like

[tool]
[tool.poetry]
authors = ["Your Name <[email protected]>"]
name = "root"
version = "0.0.0"

and then some stuff below that. I just added a description = "ABC" right below the version key, and it started working.

No clue why it stopped working out of nowhere, but yeah, it says the description bit is mandatory in the Poetry documentation(https://python-poetry.org/docs/pyproject/) now, so maybe something got changed.

Hope it works.

oloskos (4)

I don't get the pop-up saying that 'the bot is alive', here's the cmd:

  • Serving Flask app "" (lazy loading)
  • Environment: production
    WARNING: This is a development server. Do not use it in a production deployment.
    Use a production WSGI server instead.
  • Debug mode: off
  • Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
jojojojo0254 (4)

@oloskos hey i had the same problem and you must run this core directly in repl.it, not in any software you are using.

tdserapio (0)

@oloskos dude thats what supposed to happen

McJet (0)

@oloskos you probably have the window minimized, you have to drag the window open.

JacobH460 (4)

my bot goes down every minute and doesn't come back up for a while
Edit: I got it working, make sure you put the keep_alive.keep_alive() code before the client.run('') code

DK2blue (4)

package operation failed

TheDrone7 (1890)

@DK2blue please report it to the repl.it team at https://repl.it/discord/ I'll mention @enigma_dev cuz he da best.

Warhawk947 (526)

such a great tutorial! How did I not see this sooner?

IronMerkGames (1)

it is currently 2021 is this still a viable way of making a bot?

bottestingg (2)

Can I stop the run after this?

a5rocks (826)

Good job! Now the pressure is on for me to finish my discord bot tutorial... Well, I can just copy and paste this at the bottom :D

viraxor (1)

token env thingy stopped working, here's the error:

Traceback (most recent call last):
  File "tb.py", line 103, in <module>
    bot.run(token, bot=True, reconnect=True)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 678, in run
    return future.result()
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 658, in runner
    await self.start(*args, **kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 621, in start
    await self.login(*args, bot=bot)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 472, in login
    await self.http.static_login(token.strip(), bot=bot)
AttributeError: 'NoneType' object has no attribute 'strip'
JoshuaGottfried (1)

It works, but once I went to test it, since it HOSTS the bot, i closed my IDE and the bot just turned off. I thought it would be hosted,

RealRupert (0)

@JoshuaGottfried Did you get it working because thats happening to me

jojojojo0254 (4)

@RealRupert i got iz working, you must run this code directly in repl.it, notin any software you are using

NORXND (1)

I got OSError: [Errno 98] Address already in use

CalebEevee (0)

I followed the directions; but my bot is usually offline 1 hour after I closed the repl.it tab. Can anyone help?

YxngAnaah (0)

Traceback (most recent call last) Q x
File "main.py", line 1, in <module>
import keep_alive
File "/home/ runner/SFAKMRO/keep_alive.py", line 6
@app.route( "/')
IndentationError : unexpected indent

Help

AestheticGaming (2)



hi, i did this and it's not working. pls help fast, thank you

[deleted]

From flask import Flask @AestheticGaming

[deleted]

keep_alive.py @AestheticGaming

MalakaiShryock (0)

Works great for me! The only thing I am doing differently is I use betteruptime.com, instead of uptimerobot. It is slightly more advanced, but it does the same thing and even has an automatic status-page. Also, with the free plan, it checks a minimum of every 3 minutes, instead of the 5 on uptimerobot. Would def recommend betteruptime.com over uptimerobot if you are looking for a slightly more modern feel, and an automatically updating status page that is also fully controllable.

TheDrone7 (1890)

@MalakaiShryock I actually use the uptimerobot mobile app nowadays (it didn't exist when I originally wrote this tutorial) cuz it has a really epic UI. 💯 Recommend that. Also 5 minutes is actually low enough. Anything below 30 would give maximum uptime and would even keep the workload on replit servers lower.

MalakaiShryock (0)

@TheDrone7 I prefer a higher ping-frequency so I know almost immediately when it is down.

Madbrad200 (0)

@MalakaiShryock you shouldn't ping abuse repl anymore than is absolutely necessary.

[deleted]

works like a charm!

wsx04321 (0)

What to do when this happens

"Repl.it: Updating package configuration

--> python3 -m poetry lock

[RuntimeError]The Poetry configuration is invalid:

'description' is a required property

exit status 1

Repl.it: Package operation failed."

pls help

SamirMishra127 (0)

If I buy and use the real.it hacker plan, (the always on reels feature has been released) do I no longer need to create a web server? can I then let leave my bot and close the window since the real will be always on.

OwenSchafer (0)

@SamirMishra127 I don't think you got a response but I have the same question. I'm trying it out and I'll update you with what happens

SamirMishra127 (0)

@OwenSchafer Awaiting your reply! Thank you.

SamirMishra127 (0)

@OwenSchafer That's amazing to hear. Thank you!:)

Name12 (161)

useful stuff! helped me improve the bot that me, @VulcamWM and @SpaceFire created.

Wonder431 (0)

How do you find your server link?

BqsicCoder (0)

Is this still working as of today?

WilliThePig (0)

Do you also see the little window with the link when you do everything mobile? If you normally see it, then I did sth wrong...

FireDevelopment (0)

OK, so I have a problem, it's running the bot twice, so if I do a command, it responds twice.

AidanMcConachie (1)

I did everything but it goes offline after one hour. I assume this means Flask works but the uptimebot doesn't work. I put the url and 30 minutes interval, please let me know if there is anyway to troubleshoot.

Wonder431 (0)

@AidanMcConachie I am having the same issue, but I think I fixed it. Are you using the correct URL?

AidanMcConachie (1)

@Wonder431 I fixed it. I did not run the project at first, and i set the interval to 5 minutes.

KushalReddy1 (0)

alternatively you can use pythonanywhere.com to do a continous get request to the url of the bot project
others would suggest running the bot directly on pythonaywhere but it does not allow the script to run
so we can set make a script to do a get request to our bot url in a while loop with certain interval of time other in between the get requests

iamcooliguess (17)

My repl works fine when I click run, however, it doesn't work in UptimeRobot. It says "Your bot is alive", so I think the issue is with UptimeRobot.