Create a Telegram Bot Using Python With Source Code

Create a Telegram Bot Using Python With Source Code

Introduction :

In this article, we will learn how to create a Telegram bot using Python. Recently, Telegram has become one of the most popular apps for messaging and sharing content. Unlike WhatsApp, it doesn’t have a limit on file sharing, and it comes with some built-in bots that can be used in groups (similar to WhatsApp’s channels) to control the chat or filter out spam messages.

A Telegram bot is simply an account on Telegram that is run by software instead of a person. These bots can do many things, like teach, play games, search for information, send broadcasts, remind users about something, connect people, integrate with other services, or even control smart devices (Internet of Things).

To create a new bot, you use a tool in the Telegram app called “BotFather.” BotFather provides a unique token, which we can use in Python to create and manage our Telegram bot.

Required Modules Or Packages:

A Telegram Account: If you don’t already have the Telegram app, you can download it from the Play Store. Once you’ve installed it, create an account using your phone number, just like you would for WhatsApp.

python-telegram-bot module: We’ll need a module called python-telegram-bot. This library gives us a simple way to interact with Telegram’s Bot API using Python. It works with Python versions 3.6.8 and higher. The module includes special classes in the telegram.ext submodule, which make it easy to create and manage bots. If you want to learn more, you can check their official documentation.

How To Run The Code:

Step 1: Once you’ve created a Telegram account, go to the search bar at the top and look for “BotFather.”

Step 2: Click on ‘BotFather’ (it should be the first result), and then type /newbot in the chat.

Step 3: BotFather will ask you to give your bot a name. Pick a unique name for your bot. After that, it will ask for a username. Make sure the username ends with “bot,” like my_bot or hellobot.

Step 4: Once you provide a valid name and username, BotFather will send you a message that looks something like this –

Here, the token value you get will be unique for you. We’ll use this token in our Python code to customize the bot and add commands.

Step 5: Download and install Visual Studio Code (VS Code) on your computer from the official website.

Step 6: Open Visual Studio Code.

Step 7: Create a new file and name it main.py.

Step 8: Copy and paste the code from the link provided.

Step 9: After pasting the code, save the file and click the “Run” button.

Step 10: When asked, enter the token you received from BotFather.

Step 11: Now, open your Telegram bot – it’s working!

Code Explaination :-

This Python code creates the Telegram bot. Just make sure you have a Telegram account and the token that BotFather gave you.

Imports :

  • Updater: This holds the API key we got from BotFather. It helps connect our Python code to the bot so we can add features to it.
  • Update: This triggers whenever the bot gets a new message or command, and it sends a response back to the user.
  • CallbackContext: We won’t use this directly in our code, but it’s needed when we add the dispatcher (which handles tasks in the background).
  • CommandHandler: This is used to manage commands that start with “/”, like “/start” or “/help”, when sent by a user to the bot.
  • MessageHandler: This handles regular messages (not commands) sent by the user to the bot.
  • Filters: This helps filter out different types of messages like normal text, commands, images, etc., from what the user sends.

Define functions for operation :-

Start function: This function shows the first message when the user starts chatting with the bot. You can call it something else if you want, but the message inside will be sent to the user when they type “/start” at the beginning of the conversation.

updater = Updater ("your_own_API_Token got from BotFather",
use_context=True)
def start(update: Update, context: CallbackContext):
update.message.reply_text(
"Enter the text you want to show to the user whenever they start the bot")

In the start message, you should include a welcome message, like “Hello, welcome to the bot!” to greet the user.

Help function: This function is where you provide information about how to use the bot. You can list all the commands the bot understands and give any other details the user might need, like what the bot can do or how to interact with it.

Adding some more functionalities to the Bot :-

def gmail_url(update: Update, context: CallbackContext): update.message.reply_text("gmail link here")

def youtube_url(update: Update, context: CallbackContext):
update.message.reply_text("youtube link")

def linkedin_url(update: Update, context: CallbackContext): update.message.reply_text("Your linkedin profile url")

def geeks_url(update: Update, context: CallbackContext): update.message.reply_text("GeeksforGeeks url here")

def unknown_text(update: Update, context: CallbackContext): update.message.reply_text(
"Sorry I can't recognize you, you said '%s'" % update.message.text)

def unknown (update: Update, context: CallbackContext):
update.message.reply_text(
"Sorry '%s' is not a valid command" % update.message.text)

In this example, we’ve added 4 functions to open Gmail, YouTube, LinkedIn, and GeeksforGeeks. These functions are just for demonstration—you don’t have to use them. You can create your own functions and set them to send any message you want.

The unknown_text function sends a message when the bot gets a text it doesn’t understand. Similarly, the unknown function filters out any unknown commands sent by the user and replies with a message saying it didn’t recognize the command.

Adding the Handlers to handle our messages and commands :-

Each line means that when a user sends a command (the first part of the CommandHandler), the bot will reply with the message from the function listed in the second part of the CommandHandler.

updater.dispatcher.add_handler(CommandHandler('start', start))
updater.dispatcher.add_handler(CommandHandler('youtube', youtube_url)) updater.dispatcher.add_handler(CommandHandler('help', help)) updater.dispatcher.add_handler(CommandHandler('linkedin', linkedIn_url)) updater.dispatcher.add_handler(CommandHandler('gmail', gmail_url)) updater.dispatcher.add_handler(CommandHandler('geeks', geeks_url)) updater.dispatcher.add_handler (MessageHandler(Filters.text, unknown))
updater.dispatcher.add_handler(MessageHandler(
# Filters out unknown commands
Filters.command, unknown))
#Filters out unknown messages.
updater.dispatcher.add_handler (MessageHandler(Filters.text, unknown_text))

Running the bot :-

updater.start_polling()

When we start polling, the bot becomes active and keeps checking for new messages from users. If a message matches one of the commands we’ve set up, the bot will reply with the appropriate response.

Source Code :

main.py

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

# Replace "your_own_API_Token got from BotFather" with your actual bot token
TOKEN = "your_own_API_Token"

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text(
        "Hello sir, Welcome to the Bot. Please write /help to see the commands available."
    )

async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("""Available Commands:
    /youtube - To get the YouTube URL
    /linkedin - To get the LinkedIn profile URL
    /gmail - To get the Gmail URL
    /geeks - To get the GeeksforGeeks URL
    """)

async def gmail_url(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text(
        "Your Gmail link here (I am not giving mine one for security reasons)"
    )

async def youtube_url(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("YouTube Link => https://www.youtube.com/")

async def linkedin_url(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("LinkedIn URL => https://www.linkedin.com/")

async def geeks_url(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("GeeksforGeeks URL => https://www.geeksforgeeks.org/")

async def unknown(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text(
        f"Sorry, '{update.message.text}' is not a valid command."
    )

async def unknown_text(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text(
        f"Sorry, I can't recognize you, you said '{update.message.text}'."
    )

if __name__ == "__main__":
    # Initialize the application
    app = ApplicationBuilder().token(TOKEN).build()

    # Registering the command handlers
    app.add_handler(CommandHandler('start', start))
    app.add_handler(CommandHandler('help', help_command))
    app.add_handler(CommandHandler('youtube', youtube_url))
    app.add_handler(CommandHandler('linkedin', linkedin_url))
    app.add_handler(CommandHandler('gmail', gmail_url))
    app.add_handler(CommandHandler('geeks', geeks_url))

    # Registering the message handlers
    app.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), unknown_text))
    app.add_handler(MessageHandler(filters.COMMAND, unknown))

    # Start the bot
    app.run_polling()

Output :

After running the code, open your Telegram bot, and you should see it working with the responses you set up. Make sure you have a Telegram account and the token from BotFather. The code will ask you to enter your token ID to get everything set up.

Posts You Might Like

9 amazing online courses released by Google to Master AI in 2024:-

Microsoft released 6 free courses on ai that you can’t miss

Leave a Comment