How to create a Telegram bot with Python

Updated: January 2, 2024 By: Guest Contributor Post a comment

Overview

Creating a Telegram bot with Python is a straightforward process that involves writing some Python code, using the Telegram Bot API, and setting up a webhook for interactions. In this guide, we’ll explore how to set up a bot from scratch and extend its functionalities progressively.

Getting Started

Before diving into the code, ensure you have Python installed on your system and a Telegram account to create the bot with.

Step 1: Register Your Bot

  1. Open Telegram and search for the BotFather.
  2. Start a conversation and follow the instructions to create a new bot.
  3. At the end of the setup, you’ll receive your new bot’s token; keep this safe as it’s like a password for your bot.

Step 2: Setting Up Your Python Environment

pip install python-telegram-bot

After setting up your development environment and installing the necessary package, we’re ready to write our first bot.

Example 1: Echo Bot

This basic bot will echo messages sent to it.

from telegram.ext import Updater, MessageHandler, Filters

# Replace 'YOUR_TOKEN' with your bot's API token
updater = Updater('YOUR_TOKEN', use_context=True)
dispatcher = updater.dispatcher

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

echo_handler = MessageHandler(Filters.text & (~Filters.command), echo)
dispatcher.add_handler(echo_handler)

updater.start_polling()

Advanced Features

After setting up a basic bot, it’s time to delve deeper and add advanced features like handling commands, inline queries, and deploying your bot to a server.

Example 2: Command Handler

from telegram.ext import CommandHandler

# Define function to handle the '/start' command
def start(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text='Welcome to your bot!')

# Create a command handler for the '/start' command
start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)

Running the Bot on A Server

When developing a bot, it’s common practice to test it by running the script from your local machine. However, for a production bot, you’ll want to deploy your bot on a server.

updater.start_webhook(listen='0.0.0.0',
                      port=int(os.environ.get('PORT', '5000')),
                      url_path='YOUR_TOKEN')
updater.bot.setWebhook('https://your-web-app.com/' + 'YOUR_TOKEN')

Work with Inline Queries

Beyond just sending messages, Telegram bots can interact with users in-line within any chat. Here’s how to set up a handler for inline queries.

from telegram.ext import InlineQueryHandler
from telegram import InlineQueryResultArticle, InputTextMessageContent

def inline_query(update, context):
    query = update.inline_query.query
    results = [
        InlineQueryResultArticle(
            id=query.upper(),
            title='Caps',
            input_message_content=InputTextMessageContent(query.upper())
        )
    ]
    context.bot.answer_inline_query(update.inline_query.id, results)

inline_query_handler = InlineQueryHandler(inline_query)
dispatcher.add_handler(inline_query_handler)

Database Integration

After you’ve mastered the basics, you can explore more advanced concepts such as database integration, AI chatbots, or handling payments.

Here is a basic example of integrating SQLite with your Telegram bot for persistent data management.

import sqlite3

db = sqlite3.connect('user_data.db')
cursor = db.cursor()

# Create table
cursor.execute('CREATE TABLE IF NOT EXISTS user_data (user_id INT, data TEXT)')

def save_to_db(user_id, data):
    cursor.execute('INSERT INTO user_data (user_id, data) VALUES (?, ?)', (user_id, data))
    db.commit()

db.close()

Conclusion

In this tutorial, you’ve seen how easy it is to create a Telegram bot with Python. Starting from a simple bot echoing messages to delving into more complex features such as command handling and inline queries, there’s a vast potential in what you can develop. Remember to follow security best practices and continually test your bot to ensure it’s working as expected.