You can set up a custom systemctl service for running your bot on a linux system, this has several benefits because :
- You can do this easily from the command line, it's SSH friendly.
- It can restart your bot on crash.
- It can start on boot.
- Logs are stored by
journalctland can be accessed easily.
Below I've made an example of a service file, this is a template and you can download it and replace it with what's specefic to your bot, here's what each thing means :
Description- More for clarity, describes what the service is in thesystemctlmenu.After- The service to wait for before booting up, leave this asnetwork.targetas the bot will probably crash if it starts when the server has no internet.ExecStart- The full path to the executable, it has to be a full path to the first item, although if it's something like python you don't have to put the full path to the script, see the example (it needs to be in the sameWorkingDirectorythough.WorkingDirectory- The full path to the working directory, should be the one that contains your code.StandardOutput- What to do with the standard output, leave asinheritso it gets captured in thejournalctllogs.StandardError- What to do with the standard error, leave asinheritso it gets captured in thejournalctllogs.Restart- Leave atalwaysto restart on exit ornoto never restart on exit.User- The user to process runs as, don't run it as root.WantedBy- Honestly not sure, but all the examples have this.
Whatever you name your service file will mean what it is referenced as in commands, naming it mybot.service will result in you having to issue commands like systemctl status mybot and so on.
Before you test it, you should cd into the WorkingDirectory and execute the ExecStart command, this will tell you if you have any libraries missing or things that might stop your bot from running.
You'll need sudo for the next steps, once you have done the file, copy it to /etc/systemd/system/ and try it, run systemctl start <service> and then systemctl status <service> to make sure it didn't crash. If it works and you want to make it start at boot, run systemctl enable <service>.
You can access logs by typing journalctl -u <service> -r, you can search for more systemctl and journalctl commands on google.
- Restarting on crash is a great thing and has saved my bot from downtime many times, but if your bot crashes after connecting to discord, the service will restart it, and if your app connects to discord to many times within a short time period discord will regenerate your token.
- In my experience using this with python apps, you must flush the output of the
printcommand for it to log injournalctl, it will still buffer and log in the end when the app stops, but it may be confusing if you get no log lines for ages and then a huge amount at once.
You can use the logger feature with Python to log to journalctl