Building Powerful Telegram Bots with Telethon in Python

Last Updated : 19 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Creating a Telegram bot can significantly enhance how you interact with users, automate tasks, and provide information quickly. Here, we’ll use the Telethon library in Python to build a powerful Telegram bot.

Creating Telegram Bot in Python

Prerequisites

  • Telegram Account: We need a Telegram account to create and manage our bot.
  • Telethon Library: We’ll use Telethon, a Python library for interacting with Telegram’s API.

Step 1: Install Telethon

pip install telethon

Step 2: Set Up the Telegram Bot

  • Open Telegram and search for @BotFather.
  • Start a chat and send the /newbot command.
  • Follow the instructions to create a new bot. Then we’ll receive a bot token, which we need for authentication.

Step 3: Create a New Application

  • Visit my.telegram.org and log in with our Telegram account.
  • Go to the API Development Tools and create a new application.
  • Note down the api_id and api_hash.
Screenshot-2024-06-04-115831

Note down the API Id & Hash key

Step 4: Write the Bot Script

  • Logging Setup: Configures logging to help debug the bot.
  • Telegram Client Initialization: Uses api_id, api_hash, and bot_token to create and start the Telegram client.
  • Command Handlers:
    • /start: Greets the user and offers assistance.
    • /help: Provides a list of commands the bot can respond to.
    • /info: Gives information about the bot.
    • /echo <message>: Echoes back the message sent by the user.
  • Keyword-based Responses: Responds to specific keywords and phrases with predefined messages.
  • Default Response: Provides help information if the user’s message doesn’t match any known commands or keywords.
Python
import logging
from telethon import TelegramClient, events

# Setup logging
logging.basicConfig(level=logging.INFO)

# Your API ID and hash from my.telegram.org
api_id = "your_api_id"
api_hash = 'Your_hash_key'
bot_token = 'Your_bot_token'  # Replace with your actual bot token

# Create the client and connect
client = TelegramClient('bot', api_id, api_hash).start(bot_token=bot_token)

# Handler for the /start command
@client.on(events.NewMessage(pattern='/start'))
async def start(event):
    await event.respond('Hello! I am a Telethon bot. How can I assist you today?')
    logging.info(f'Start command received from {event.sender_id}')

# Handler for the /help command
@client.on(events.NewMessage(pattern='/help'))
async def help(event):
    help_text = (
        "Here are the commands you can use:\n"
        "/start - Start the bot\n"
        "/help - Get help information\n"
        "/info - Get information about the bot\n"
        "/echo <message> - Echo back the message\n"
    )
    await event.respond(help_text)
    logging.info(f'Help command received from {event.sender_id}')

# Handler for the /info command
@client.on(events.NewMessage(pattern='/info'))
async def info(event):
    await event.respond('This bot is created using Telethon in Python. It can respond to various commands and messages.')
    logging.info(f'Info command received from {event.sender_id}')

# Handler for the /echo command
@client.on(events.NewMessage(pattern='/echo (.+)'))
async def echo(event):
    message = event.pattern_match.group(1)
    await event.respond(f'Echo: {message}')
    logging.info(f'Echo command received from {event.sender_id} with message: {message}')

# Keyword-based response handler
@client.on(events.NewMessage)
async def keyword_responder(event):
    message = event.text.lower()

    responses = {
        'hello': 'Hi there! How can I help you today?',
        'how are you': 'I am just a bot, but I am here to assist you!',
        'what is your name': 'I am MyAwesomeBot, your friendly Telegram assistant.',
        'bye': 'Goodbye! Have a great day!',
        'time': 'I cannot tell the current time, but you can check your device!',
        'date': 'I cannot provide the current date, but your device surely can!',
        'weather': 'I cannot check the weather, but there are many apps that can help you with that!',
        'thank you': 'You are welcome!',
        'help me': 'Sure! What do you need help with?',
        'good morning': 'Good morning! I hope you have a great day!',
        'good night': 'Good night! Sweet dreams!',
        'who created you': 'I was created by a developer using the Telethon library in Python.',
    }

    response = responses.get(message, None)

    if response:
        await event.respond(response)
    else:
        # Default response
        default_response = (
            "I didn't understand that command. Here are some commands you can try:\n"
            "/start - Start the bot\n"
            "/help - Get help information\n"
            "/info - Get information about the bot\n"
            "/echo <message> - Echo back the message\n"
        )
        await event.respond(default_response)
    logging.info(f'Message received from {event.sender_id}: {event.text}')

# Start the client
client.start()
client.run_until_disconnected()

Step 5: Run the Bot

python telegram_bot.py

Output:

Conclusion

Building a Telegram bot with Telethon in Python is both rewarding and educational. This guide covers setting up the bot, handling various commands, and responding intelligently to user inputs. Using the Telethon library, the bot can efficiently manage interactions, provide information, and automate tasks. This foundation allows for further expansion of the bot’s features, integration with other services, and improved user engagement. Creating and customizing a Telegram bot offers valuable skills in API usage, Python programming, and real-time interaction management, paving the way for more advanced projects in the future.



Previous Article
Next Article

Similar Reads

Send message to Telegram user using Python
Have you ever wondered how people do automation on Telegram? You may know that Telegram has a big user base and so it is one of the preferred social media to read people. What good thing about Telegram is that it provides a bunch of API's methods, unlike Whatsapp which restricts such things. So in this post, we will be sharing how to send messages
3 min read
Create a Telegram Bot using Python
In this article, we are going to see how to create a telegram bot using Python. In recent times Telegram has become one of the most used messaging and content sharing platforms, it has no file sharing limit like Whatsapp and it comes with some preinstalled bots one can use in any channels (groups in case of whatsapp) to control the behavior or filt
6 min read
Keyboard buttons in Telegram bot Using Python
One common way that we interact with the Telegram bot is through the use of keyboard buttons. These buttons give a convenient and intuitive way to input data and perform specific actions within the bot. Without keyboard buttons, we would have to manually type in commands or responses, which could be time-consuming and may lead to errors. Keyboard b
9 min read
Powerful One-Liner Python codes
Python is a widely-used general-purpose, high-level programming language. Python programs generally are smaller than other programming languages like Java. Programmers have to type relatively less and indentation requirements of the language makes them readable all the time. However, Python programs can be made more concise using some one-liner cod
6 min read
Class Factories: A powerful pattern in Python
A Class Factory is a function that creates and returns a class. It is one of the powerful patterns in Python. In this section, we will cover how to design class factories and the use cases of it. Designing a Class Factory As mentioned, class factories are functions that create and return a class. It can create a class at the coding time (using clas
5 min read
Building Calculator using PyQt5 in Python
In this article we will see how we can create a calculator using PyQt5,A calculator is something used for making mathematical calculations, in particular a small electronic device with a keyboard and a visual display. below is the how the calculator will looks like GUI implementation steps Create a label to show the numbers and the output and set i
5 min read
Building an undirected graph and finding shortest path using Dictionaries in Python
Prerequisites: BFS for a GraphDictionaries in Python In this article, we will be looking at how to build an undirected graph and then find the shortest path between two nodes/vertex of that graph easily using dictionaries in Python Language. Building a Graph using Dictionaries Approach: The idea is to store the adjacency list into the dictionaries,
3 min read
Building a basic HTTP Server from scratch in Python
In this article, we are going to learn how to set up a simple and local HTTP server using Python. An HTTP server can be very useful for testing Android, PC, or Web apps locally during development. It can also be used to share files between two devices connected over the same LAN or WLAN network. Installation: On the terminal run the following state
2 min read
Building a Simple Application using KivyMD in Python
KivyMD is an extension of the Kivy framework. KivyMD is a collection of Material Design widgets for use with Kivy, a GUI framework for making mobile applications. It is similar to the Kivy framework but provides a more attractive GUI. In this article, we will see how to make a simple application in KivyMD using Screen, Label, TextFieldInput, and Bu
3 min read
Building CLI to check status of URL using Python
In this article, we will build a CLI(command-line interface) program to verify the status of a URL using Python. The python CLI takes one or more URLs as arguments and checks whether the URL is accessible (or)not. Stepwise ImplementationStep 1: Setting up files and Installing requirements First, create a directory named "urlcheck" and create a new
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg