Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to keep Telegram bot running when closing Python? [duplicate]

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'?

like image 792
Johanna Avatar asked Feb 25 '17 07:02

Johanna


2 Answers

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.

like image 139
Antwane Avatar answered Sep 24 '22 11:09

Antwane


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.

like image 41
rb612 Avatar answered Sep 22 '22 11:09

rb612