Craft your first telegram BOT (2024)

6 min read

·

Jun 2, 2024

--

The power of telegram chat bots

Craft your first telegram BOT (2)

Chatting apps are some of the most used applications in our daily lives, helping us stay in touch with friends and family, and even at work. So, what about creating a chatbot that can do anything you tell it to? You can use it to automate tasks, get the latest updates on various topics, and more. In this article, we’ll create a bot with Telegram. Why Telegram, you ask? For me, it has the best support for tasks like bots and automation. So, without further ado, let’s get started.

Telegram provides us with great documentation on how to use their APIs. However, for simplicity, we will use a package within Python named python-telegram-bot. It offers great support for the majority of the API's features. Let's start by installing this package with the following command:

pip install python-telegram-bot

We are all set now, but before we jump into the code, we need to talk to the BotFather. Who is he? Well, he is the owner of all bots, the one who can give you a bot. Essentially, he’s the admin of bots. So, how can you talk to him? It’s easy! Just open your Telegram app and search for BotFather. You should see a chat with the verified icon on the right and a bot icon on the left.

Craft your first telegram BOT (3)

So let’s start talking to the BotFather by typing /start to activate it. After that, type /newbot. He will ask you to name your bot, so feel free to name it whatever you want. Next, he will ask you for the bot username; you need to choose a unique bot name. Finally, he will give you the bot token. Be careful and keep this token private, as anyone who has access to your token may control your bot.

Enough talking now let’s delve to the real stuff here, the coding I know you are eager to start building your bot so let’s get started.

For our first Bot we will create a bot that uses commands, take arguments and reply to messages. First we start by importing the necessary packages, add some logging for better debugging and write the first command.

Hello world! 👋

import logging
from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler, MessageHandler, filters
from telegram import Update

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

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, please talk to me!")
if __name__ == '__main__':
application = ApplicationBuilder().token('Your secret token goes here!').build()

start_handler = CommandHandler('start', start)
application.add_handler(start_handler)
application.run_polling()

The start function will be our first command, every time we send /start to the bot it will reply to you with the given text. Now go ahead and run your code, now head to telegram and talk to your bot, but wait where is my bot, well you need to invite him first by simply searching by username click on the name you will see a start button when you click it it should reply to you.

The CommandHandler links a specific command to a corresponding function in your code. The command name (the first argument) can be anything you choose; it doesn't have to be the same as the function name. The function is what will be executed when the bot receives the command.

Interesting right! but it’s just the start, next we will send an argument to the bot and he will do something based on our input.

Sum all the numbers 🧮

The next command we will make our bot sum all the given numbers, yeah a calculator bot who thought 😂, Like the previous command but this time we will make use of the context arguments (context.args) as follow

async def sum(update: Update, context: ContextTypes.DEFAULT_TYPE):
sum = 0
for i in context.args:
sum += int(i)
await context.bot.send_message(chat_id=update.effective_chat.id,text=sum)

sum_handler = CommandHandler("sum",sum)
application.add_handler(sum_handler)

What we did is the following we take the context arguments which is a list containing all the argument passed to the command separated by a space, so we loop through all of them and add them together.

Now add the code provided above to the previous code and rerun your bot, so when you type /sum 1 2 3 your bot will respond with 6.

/sum 1 2 3

Magical! The last example we will make our bot respond to any text given or even respond to a certain message without explicitly pass a command.

You are welcome 🤗

What if the bot can actively read all the message and do certain action based on specific message or all message, to do so we follow the same method as before but with a little tweak. So we will make a bot that have some manners and reply when someone thank him, what an idea, right…

async def thanks(update: Update, context: ContextTypes.DEFAULT_TYPE):
if "thanks" in update.message.text:
await context.bot.send_message(chat_id=update.effective_chat.id,text="You're welcome!")

thanks_handler = MessageHandler(filters.TEXT &(~filters.COMMAND),thanks)
application.add_handler(thanks_handler)

As usual rerun your bot and try to say thanks, he will happily reply to the keyword thanks.

What we did differently in this snippet of code is the following: instead of using CommandHandler, we used MessageHandler. We didn’t specify a command name since it is not a command; instead, we provided filters. The first filter indicates to listen to incoming messages of type text, and the second filter is to ignore any commands.

Note: If you provide two message handlers the first one added will be executed first. Example: consider you have two message handlers one to say thank you and one to echo your text

echo_handler = MessageHandler(filters.TEXT &(~filters.COMMAND),echo)
thanks_handler = MessageHandler(filters.TEXT &(~filters.COMMAND),thanks)

application.add_handler(thanks_handler) # <-- this will be executed
application.add_handler(echo_handler) # <-- this will be ignored

The reason behind this is that the package will go through every handler in the order you put them in add_handler, and if it find a match it will execute the handler and exit.

Craft your first telegram BOT (4)

What we achieved 🏁

Your final code should look like this:

import logging
from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler, MessageHandler, filters
from telegram import Update

logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
async def thanks(update: Update, context: ContextTypes.DEFAULT_TYPE):
if "thanks" in update.message.text:
await context.bot.send_message(chat_id=update.effective_chat.id,text="You're welcome!")

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, please talk to me!")

async def sum(update: Update, context: ContextTypes.DEFAULT_TYPE):
sum = 0
for i in context.args:
sum += int(i)
await context.bot.send_message(chat_id=update.effective_chat.id,text=sum)

if __name__ == '__main__':
application = ApplicationBuilder().token('Your secret token goes here!').build()

start_handler = CommandHandler('start', start)
sum_handler = CommandHandler("sum",sum)
thanks_handler = MessageHandler(filters.TEXT &(~filters.COMMAND),thanks)

application.add_handler(start_handler)
application.add_handler(thanks_handler)
application.add_handler(sum_handler)

application.run_polling()

Your bot is perfectly working, Congrats, Oh wait, what if a you provide an unknown command what will happen, to be honest nothing will happen the bot will completely ignore it, but as a programmer you want to treat all the possible cases, to do so we will add a handler for unknown commands as follow:

async def unknown(update: Update, context: ContextTypes.DEFAULT_TYPE):
await context.bot.send_message(chat_id=update.effective_chat.id,text="Sorry, I didn't understand that command.")

unknown_handler = MessageHandler(filters.COMMAND,unknown)
application.add_handler(unknown_handler)

This will tell the bot to listen for all commands and reply with the given message. However, if we place this at the top of all commands, the bot will respond to all commands as unknown and exit. To avoid this, we need to put it at the end. It should be the last handler because if the command doesn’t match any of the previous commands, it should fire the unknown handler.

When you have a lot of commands or you want to publish your bot for others to use, introducing a command suggester will make a significant difference. This way, users won’t have to guess the commands.

Remember the botFather, go to him and type your command name followed with the description you want, for our case we have two commands sum and start so to register them type the following

sum - sum multiple numbers
start - say hello

Now go back to your bot and press “/” you will see the command names followed by the description you gave.

You created your first Telegram bot! Now, you have endless possibilities to create any bot you want. I hope you found this post both interesting and beneficial to your journey toward chatbots and automation with Telegram. Happy botting, and until next time! ❤️.

Craft your first telegram BOT (5)
Craft your first telegram BOT (2024)
Top Articles
Latest Posts
Article information

Author: Errol Quitzon

Last Updated:

Views: 5876

Rating: 4.9 / 5 (79 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Errol Quitzon

Birthday: 1993-04-02

Address: 70604 Haley Lane, Port Weldonside, TN 99233-0942

Phone: +9665282866296

Job: Product Retail Agent

Hobby: Computer programming, Horseback riding, Hooping, Dance, Ice skating, Backpacking, Rafting

Introduction: My name is Errol Quitzon, I am a fair, cute, fancy, clean, attractive, sparkling, kind person who loves writing and wants to share my knowledge and understanding with you.