Building bots — Telegram bot

Technocrat
2 min readSep 13, 2023

--

Telegram bots are automated accounts that can respond to messages, commands and Inline requests. Some useful bots on Telegram are @BotFather (managing bots), @weatherbot, @wikirobot, etc. These bots make Telegram an interactive platform and enhance the user experience.

Setting up a Telegram bot

To build a Telegram bot, first create a bot with @BotFather by sending /newbot command. @BotFather will generate an access token for your bot. Install the python-telegram-bot library using pip.

pip install python-telegram-bot

Create a basic bot that responds to messages:

import telegram

bot = telegram.Bot('YOUR_ACCESS_TOKEN')

# Handle '/start' and '/help'
def start(bot, update):
update.message.reply_text('Hello!')

def help(bot, update):
update.message.reply_text('Help!')

# Handle all other messages
def message(bot, update):
text = update.message.text
update.message.reply_text(f'You said: {text}')

updater = telegram.Updater('YOUR_ACCESS_TOKEN', use_context=True)
updater.dispatcher.add_handler(CommandHandler('start', start))
updater.dispatcher.add_handler(CommandHandler('help', help))
updater.dispatcher.add_handler(MessageHandler(Filters.text, message))

updater.start_polling()

Handling commands

Bot commands start with / and are defined using the CommandHandler. Here's an echo bot that repeats the user's commands:

def echo(bot, update):
bot.send_message(chat_id=update.message.chat_id,
text=update.message.text)

updater.dispatcher.add_handler(CommandHandler('echo', echo))

You can get additional arguments from the Message object passed to your command handler function.

Responding to messages

Create a MessageHandler to respond to generic messages. Here's a bot that replies with a generic response:

def message(bot, update):
bot.send_message(chat_id=update.message.chat_id,
text='I received your message!')

updater.dispatcher.add_handler(MessageHandler(Filters.text, message))

You can get the chat ID and message text from the update.message object.

Sending messages and media

Use bot.send_message() to proactively send messages to users. You can send:

  • Text: bot.send_message(chat_id, text='Hello')
  • Markdown: bot.send_message(chat_id, text='*bold*, _italic_,code', parse_mode='Markdown')
  • Images: bot.send_photo(chat_id, photo=open('image.png', 'rb'))
  • Audio: bot.send_audio(chat_id, audio=open('audio.mp3', 'rb'))
  • Video: bot.send_video(chat_id, video=open('video.mp4', 'rb'))
  • Contacts: bot.send_contact(chat_id, contact='phone_number', first_name='firstname')
  • Location: bot.send_location(chat_id, latitude=0.0, longitude=0.0)

You can use bot.send_chat_action() to restart a conversation with a user. For example, bot.send_chat_action(chat_id, 'typing') will show the user that the bot is typing.

Inline bots

Inline bots can be triggered with an @botname mention in any chat. They respond with results that users can select and share in the chat. Here's a basic example:

@bot.inline_handler  
def inline_echo(bot, update):
query = update.inline_query.query
results = [
telegram.InlineQueryResultArticle(
id=query.upper(),
title=f'Echo: {query.upper()}',
input_message_content=telegram.InputTextMessageContent(f'<b>{query.upper()}</b>')
)
]
update.inline_query.answer(results)

For high traffic bots, you can cache inline query results using the cache_time argument in answer() to improve response times.

Typicaly broadcast to group is useful while sending updates, while sending message instead of user it would be group.

Advanced topics

Some other advanced topics include:

  • Webhooks vs Polling: For production bots, use webhooks to receive messages
  • Threading and concurrency: Handle slow processes concurrently
  • Payments: Implement payments using the Telegram Payments API.
  • Localization: Translate your bot for different languages

These are topics to delve into some other time…

Conclusion

Telegram bots are a great way to build interactive experiences and tools on top of Telegram. With the python-telegram-bot library, building Telegram bots is easy and fun! I hope this article inspired you to create your own creative Telegram bots. Let me know if you have any other questions!

--

--