Home Telegram Bot
Post
Cancel

Telegram Bot (Python).

Building a Telegram bot with Python is a simple task, in this case we will use the python-telegram-bot library that makes thing even simpler. We also need to register our bot in order to get a Telegram API Key for our bot. Once completed, you can have your bot up and running on your local machine, or in a dedicated server for it.

Getting The Telegram Bot API Key


To create a Telegram bot, you need to contact the BotFather, which is essentially a bot used to create other bots.

After starting the conversation with BotFather, the command you need is /newbot which leads to the following steps to create your bot:

Your bot should have two attributes: a name and a username. The name will show up for your bot, while the username will be used for mentions and sharing.

After choosing your bot name and username, which must end with bot, you will get a message containing your token.

Preparing Your Environment


I’m using Python 3, you can use the same, this are the instructions to install in a Linux machine:

1
2
3
$ apt-get update
$ apt-get install -y python3 python3-pip python-dev build-essential python3-venv
$ pip3 install python-telegram-bot

Once completed, it is time to create the bot.

Bot Code


There are three main parts of the bot code,

  1. Initialization of the bot (run_bot() method). * Here we use our Telegram token to register our bot. * We can add handlers for different events/commands, in this case, we are two handlers:
    1. For the /start command.
    2. For when a message is received.
  2. Handling the start of the bot (start_handler(...) method).
  3. Handling the messages (message_handler(...) method).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# bot.py file
import telegram
from telegram import (
    Update
)

from telegram.ext import (
    ApplicationBuilder,
    CallbackContext,
    CommandHandler,
    MessageHandler,
    filters
)

# Replace YOUR_TOKEN_HERE with your own Telegram bot token
TOKEN = '1234567890:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
                    

async def start_handler(update: Update, context: CallbackContext):
    # Handle /start command (When the user starts the bot)
    await context.bot.send_message(chat_id=update.effective_chat.id,
                                   text="Hello! I'm a bot. What can I do for you?")


async def message_handler(update, context):
    # Here you will decide what to do with the received message.
    # For this example, we just reply to the user with the exact same
    # message.
    await context.bot.send_message(
        chat_id=update.effective_chat.id, text=update.message.text)


def run_bot() -> None:
    # Create and configure the bot
    application = (
        ApplicationBuilder()
        .token(TOKEN)
        .concurrent_updates(True)
        .build()
    )

    # Add handlers for /start and messages
    application.add_handler(CommandHandler('start', start_handler))
    application.add_handler(MessageHandler(
        filters.TEXT & (~filters.COMMAND), message_handler))

    # Start the bot
    application.run_polling()


# Entry point
if __name__ == '__main__':
    run_bot()

Finally, we only need to run our code, and that’s it, the bot is up and running, and we can try it on the Telegram app.

To run: $ python3 bot.py

This post is licensed under CC BY 4.0 by the author.