IntroducingSimple and easy heroku telegram bot in Python - DSPYT

Simple and easy heroku telegram bot in Python - DSPYT

To begin with, the idea for creating a telegram python bot came up during Safety & Security Lab Hackathon. Our team created a sample bot to educate public on computer security and protecting yourself online. The bot was running from our personal notebook and utilized telebot library. However, we experienced difficulties when we put on Heroku. As a result, in this blog post we conduct telegram optimizing. We optimize the python telegram bot template from scratch so we could host heroku telegram bot.

Python Virtual Environment

First, we need to save python dependencies to host telegram python bot on Heroku. In this tutorial related to telegram optimizing, we use python virtual environment library virtualenv. We install the python library:

pip install virtualenv

Next, we start the virtual environment and activate it:

virtualenv project
source project/Scripts/activate

To save the dependencies for server such as Heroku, we run the following python command:

pip freeze > requirements.txt

In case we want to exit python virtual environment:

deactivate

Heroku python telegram optimizing

To create a bot we have to message @BotFather in telegram. The command that creates a bot is /newbot and you have to also name the bot. After that BotFather sends us the HTTP API TOKEN.

python telegram bot creation: Data Science with Python

Python telegram bot

First, we install the key python telegram bot library which is python-telegram-bot:

pip install python-telegram-bot

Next, we create a simple python telegram bot that uses /start and /help commands as well as echos user’s message. The script also uses a web-hook for Heroku hosting:

Do not forget to edit the created TOKEN and APP_NAME that you obtain through Heroku.

Deploying heroku python telegram bot

Besides, we create a Procfile that contains a following line:

web: python3 bot.py

Our folder should contain three files: Procifle, the python script (in this case bot.py) and requirements.txt.

Finally, we deploy python telegram bot on Heroku:

git init
heroku create "app-name" # This is the APP_NAME from the script
git remote -v
git add .
git commit -m "commit"
git push heroku master

The GitHub library for the python telegram bot