Simple and easy telegram bot in Python on Heroku

To begin with, the idea for creating a telegram 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 notebooks and utilized telebot library. However, we experienced difficulties when we put on Heroku. As a result, I decided to begin optimizing the code from scratch so we could host the bot on Heroku.

The best existing article and tutorial at the moment in time was How to Deploy a Telegram Bot using Heroku for FREE article by Haohui.

Virtual Environment

First, we need to save python dependencies to host the bot on Heroku. Personally, I have already mentioned the platform in the write-up on the Moscow City Hack hackathon. Hence, we can use virtual environment library virtualenv. We install the library:

pip install virtualenv

Start the virtual environment and activate it:

virtualenv project
source project/Scripts/activate

To save the dependencies, for example, for Heroku:

pip freeze > requirements.txt

In case we want to exit the virtual environment:

deactivate

Telegram Bot

Creating the bot

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.

creating the bot

Telegram bot in Python

The key library is python-telegram-bot:

pip install python-telegram-bot

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

import logging
import os
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

# Enables logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)

PORT = int(os.environ.get('PORT', '8443'))

# We define command handlers. Error handlers also receive the raised TelegramError object in error.
def start(update, context):
    """Sends a message when the command /start is issued."""
    update.message.reply_text('Hi!')


def help(update, context):
    """Sends a message when the command /help is issued."""
    update.message.reply_text('Help!')


def echo(update, context):
    """Echos the user message."""
    update.message.reply_text(update.message.text)


def error(update, context):
    """Logs Errors caused by Updates."""
    logger.warning('Update "%s" caused error "%s"', update, context.error)


def main():
    """Starts the bot."""
    # Creates the Updater and pass it your bot's token.
    # Make sure to set use_context=True to use the new context based callbacks
    # Post version 12 this will no longer be necessary
    TOKEN = ' Your Token '#enter your token here
    APP_NAME='https://app-name.herokuapp.com/' #Edit the heroku app-name
    
    updater = Updater(TOKEN, use_context=True)

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("help", help))

    # on noncommand i.e message - echo the message on Telegram
    dp.add_handler(MessageHandler(Filters.text, echo))

    # log all errors
    dp.add_error_handler(error)
    updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=TOKEN, webhook_url=APP_NAME + TOKEN)
    updater.idle()


if __name__ == '__main__':
    main()

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

Deploying on Heroku

Besides, we create a Procfile that contains a line:

web: python3 bot.py

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

Finally, to deploy 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 bot: https://github.com/dspytdao/Telegram_bot_py_heroku


5 thoughts on “Simple and easy telegram bot in Python on Heroku”

  1. Today, I went to the beach with my children. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She placed the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is completely off topic but I had to tell someone!

    Reply

Leave a comment