Get Started - Learn How To Make Your Bot!GuidesCode SnippetsGet methodsPost methodsWeb APIUseful linksList of all currently Free ItemsList of EmotesHighrise Bot SDK Changelog
Concept
In this guide we will abroad how to keep your bot always running on Replit. This guide was inpired by
__simo__
who sent this method in the Highrise Discord.
This method is an alternative for running simple bots but itโs restricted to the memory and cpu limitations from Replitโs free plan, one other alternative is to use the Always On tool from Replit for a few dollars.
Required Libraries
- flask
- threading
- time
- traceback
Threading and time are built-in Python libraries so thereโs no need to install it using
pip
, to install flask you can use pip install flask
Code
Hereโs the file structure that we will use for this guide:
run.py
will be the file that we will use to run our bot, to do this we will have to change the .replit configuration file to use the run.py
as the file to be runned when clicking in the Run button. To do that you will need to clock on the three dots and select to show the hidden files, then you will click on .replit and change the entry point to run.py
:ย
ย
After itโs time to code the
run.py
file, open it and import the following libraries:from flask import Flask from threading import Thread from highrise.__main__ import * import time
Now letโs define the two classes used to run, the
WebServer
and the RunBot
classes, here are their full definitions:class WebServer(): def __init__(self): self.app = Flask(__name__) @self.app.route('/') def index() -> str: return "Alive" def run(self) -> None: self.app.run(host='0.0.0.0', port=8080) def keep_alive(self): t = Thread(target=self.run) t.start() class RunBot(): room_id = "room id here" bot_token = "bot token here" bot_file = "bot file name here" bot_class = "bot class name here" def __init__(self) -> None: self.definitions = [ BotDefinition( getattr(import_module(self.bot_file), self.bot_class)(), self.room_id, self.bot_token) ] # More BotDefinition classes can be added to the definitions list def run_loop(self) -> None: while True: try: arun(main(self.definitions)) except Exception as e: # Print the full traceback for the exception import traceback print("Caught an exception:") traceback.print_exc() # This will print the full traceback time.sleep(1) continue
With our classes defined, all that we need to do now is to add the code with the instructions to create the class objects and start their functions when the file is Runned, to do that we will add the following code to the bottom of the file:
if __name__ == "__main__": WebServer().keep_alive() RunBot().run_loop()
Perfect, now all you have to do edit the room, token, class and file name informations with your own and click at the Run button!
After running your code you should see something like this:
This is the link of the WebPage that will keep the bot alive on Replit, but the code will stop running after a few hours if no activity is detected in the website. For that we will use a free tool to ping it every 5 minutes:
Cron-job.orgย is the free service which allows executing any URL regularly and automatically and itโs the tool that we will use to keep our Website alive:
At their website you will need to first setup an account and validate your email, you can do that by clicking on the Start Now button in their main page:
After creating and verifying your account you just need to create a cronjob in their website console:
You can set any title to it, it will be used for you to identify the cronjob only.
At the url field, enter the url given by your code in replit like this one:
Set the the Enable Job and Save responses in job history to on.
Set the Execution schedule to 5 minutes.
You can also set your notification preferences and by the end click on Create:
Now your server should run for as long as your code is running on Replit, note that replit updates or maintaince can stop your code from running.
Full code and explanation
from flask import Flask from threading import Thread from highrise.__main__ import * import time class WebServer(): def __init__(self): self.app = Flask(__name__) @self.app.route('/') def index() -> str: return "Alive" def run(self) -> None: self.app.run(host='0.0.0.0', port=8080) def keep_alive(self): t = Thread(target=self.run) t.start() class RunBot(): room_id = "room id here" bot_token = "bot token here" bot_file = "bot file name here" bot_class = "bot class name here" def __init__(self) -> None: self.definitions = [ BotDefinition( getattr(import_module(self.bot_file), self.bot_class)(), self.room_id, self.bot_token) ] # More BotDefinition classes can be added to the definitions list def run_loop(self) -> None: while True: try: arun(main(self.definitions)) except Exception as e: # Print the full traceback for the exception import traceback print("Caught an exception:") traceback.print_exc() # This will print the full traceback time.sleep(1) continue if __name__ == "__main__": WebServer().keep_alive() RunBot().run_loop()
Here's a step-by-step explanation:
- Import Required Libraries:
- The code starts by importing necessary libraries and modules, such as Flask for creating a web server, threading for managing threads, and other components from the
highrise
library.
- Create a WebServer Class:
- The
WebServer
class is defined. It sets up a Flask web server that listens on all available network interfaces (0.0.0.0
) and port 8080. - It defines a route at the root URL ("/") that returns the string "Alive" when accessed. This route is used to check if the bot is running.
- Run Method in WebServer Class:
- The
run
method starts the Flask web server. This method is used to start the web server when needed.
- keep_alive Method in WebServer Class:
- The
keep_alive
method creates a new thread (t
) and runs therun
method in that thread. This is done so that the web server can run concurrently with the bot.
- Create a RunBot Class:
- The
RunBot
class is defined. It is responsible for running the bot indefinitely. - It defines class variables for the room ID, bot token, bot file name, and bot class name. These should be filled in with the appropriate values.
- init Method in RunBot Class:
- In the constructor (
__init__
), an instance of theBotDefinition
class is created and added to thedefinitions
list. This class appears to be part of thehighrise
library and is used to define bot instances with room IDs and tokens.
- run_loop Method in RunBot Class:
- The
run_loop
method is a loop that runs indefinitely (while True
). - Inside the loop, it tries to execute the
main
function from thehighrise
library with the defined bot definitions. - If an exception occurs during this process, it catches the exception, prints an error message, and then waits for 5 seconds before continuing. This is a way to handle errors and keep the bot running.
- Main Block:
- The code block within
if __name__ == "__main__":
is executed when the script is run directly. - It first creates an instance of the
WebServer
class and calls thekeep_alive
method to start the web server in a separate thread. - Then, it creates an instance of the
RunBot
class and calls therun_loop
method to start the bot, which runs indefinitely.
To run this code:
- Ensure that you have the necessary dependencies installed, including Flask and any required libraries for your bot (possibly the
highrise
library).
- Fill in the placeholders for the room ID, bot token, bot file name, and bot class name in the
RunBot
class with the appropriate values.
- Run the script. The web server will start and can be accessed at
http://<your-replit-app-url>:8080/
to check if it's alive. The bot will run in the background and handle any exceptions gracefully.
ย
ย