I've built a very simple Telegram bot by following this tutorial. So I have a file containing Python code, and when I run that code, the bot will echo what I say.
Is it true that the bot will only work when I have Python on and the code running? Would this mean that I cannot run any other script in Python at the same time, and neither can close Python down if I want my bot to keep working?
Is there any way to get around this, so that the bot will always be 'on'?
A Telegram bot is a Python program. When you run it, it do what it is supposed to do, then, if you stop the program, the bot stop to work. The problematic is common to all programs, particularily on a server. Think about Nginx, Apache, ssh, etc. Thay are all programs, and they all stop to do their job when they are closed.
If you want to make sure your bot will run always, you have to daemonize it. There is a lot of solutions.
You could transform your script to be a daemon, so when you launch it, it go directly to the background and continue to run until the server is shut down (or the program crash). But in that case, do your bot will re-run if you (or somebody else) restart the computer (server) ? There is some python libraries for this purpose, like daemonize.
Another common solution is to run your bot in a process manager. You can check supervisorctl for example, or you could decide to create a script to run your program from System V, UpStart or Systemd... This suppose you want to deploy your bot on a dedicated server or a VPS. This will be covered by the part 3 of the tutoriel you followed:
The next and final part of this series will [...] be demonstrating how to deploy the Bot to a VPS.
You could also consider encapsulating your bot into an image or a container (Docker, etc.) to run it on a compatible platform.
You should not have a problem running two consoles in Python, on your computer, at least. Your code should only run when Python is open on your computer, correct. As Eli correctly pointed out, a daemon would be suitable if you wanted to host locally.
However, what gets difficult is if you want to have it continuously running online. For example, with Reddit bots that search and post comments on posts, you need to host these through some cloud based service. I suggest using Amazon Web Services, which has a free trial giving you more than enough for basic Python needs. Some people will also use Heroku. Pretty much you're able to save the state of your current Python window, and it will run constantly.
I'd check out this post to see how to set up "screen" in AWS.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With