Create a Telegram Bot Using Python With Source Code

Create a Telegram Bot Using Python With Source Code

Introduction :

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 filter the spam messages sent by users. Telegram Bots are simply Telegram accounts operated by software – not people – and
they’ll often have AI features. They can do anything – teach, play, search, broadcast, remind, connect, integrate with other services, or even pass commands to the Internet of Things. BotFather is a Platform on Telegram App through which new bots were created . It gives us a Token Through which we can create a Telegram bot using python .

Required Modules Or Packages:

A Telegram Account: If you don’t have the Telegram app installed just download it from the play store. After downloading create an account using your mobile number just like WhatsApp.

python-telegram-bot module: Here we will need a module called python- telegram-bot, This library provides a pure Python interface for the Telegram Bot

API. It’s compatible with Python versions 3.6.8+. In addition to the pure API implementation, this library features a number of high-level classes to make the development of bots easy and straightforward. These classes are contained in the “telegram.ext” submodule. For more information, you can check their official

How To Run The Code:

Step 1: After opening an account on Telegram, in the search bar at the top search for “BotFather”.
Step 2: Click on the ‘BotFather’ (first result) and type /newbot .
Step 3: Give a unique name to your bot. After naming it, Botfather will ask for its username.
Then also give a unique name But remember the username of your bot must end with the bot, like my_bot, hellobot etc.
Step 4: After giving a unique name and if it gets accepted you will get a message something
like this –

Here the token value will be different for you, we will use this token in our python code to
make changes in our bot and make it just like we want, and add some commands in it.
Step 5 . Then You Download and Install Visual Studio Code or VS Code In your PC or Laptop by VS Code Official Website .
Step 6 . Now Open Visual Studio Code .
Step 7. Now Make The file named as main.py .
Step 8 . Now Copy And Paste The Code from the Link Given Below
Step 9 . After pasting The code , Save This & Click On Run Button .
Step 10 . Now enter your token provided from BotFather .
Step 11 . Now open your Telegram bot . It’s working !!

Code Explaination :-

This Python code makes the Telegram Bot . Ensures that You Have an account on Telegram and the token Provided from BotFather .

Imports :

• Updater: This will contain the API key we got from BotFather to specify in which bot we are adding functionalities to using our python code.
• Update: This will invoke every time a bot receives an update i.e. message or command and will send the user a message.
CallbackContext: We will not use its functionality directly in our code but when we will be adding the dispatcher it is required (and it will work internally)
• CommandHandler: This Handler class is used to handle any command sent by the user to the bot, a command always starts with “/” i.e “/start”,”/help” etc.
• MessageHandler: This Handler class is used to handle any normal message sent by the user to the bot,
• FIlters: This will filter normal text, commands, images, etc from a sent message.

Define functions for operation :-

Start function : It will display the first conversation, you may name it
something else but the message inside it will be sent to the user whenever they press ‘start’ at the very beginning.

				
					
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")
				
			

Basically, in the start message, you should add something like “Hello Welcome to the Bot” etc. Help function: It is basically in this function you should add any kind of help the user might need, i.e. All the commands your bot understands, The information related to the
bot, etc)

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)
				
			

Here we have added 4 functions one to open Gmail, one for youtube, one for LinkedIn, and the last one for GeeksforGeeks. These are not MANDATORY functions, you can add any kind of functions and their reply_text as you want, these are just for demonstration. Here the unknown_text function will send the message written inside it whenever it gets some unknown messages and the unknown function will Filter out all the unknown commands sent by the user and reply to the message written inside it.

Adding the Handlers to handle our messages and commands :-

Here each line suggests that whenever a user writes a command i.e. the first parameter of the CommandHandler in reply the user gets the message written inside the function mentioned in the next parameter.

				
					
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()
				
			

Here whenever we start polling the bot will be active and it will look for any new message sent by any of the users and if it matches the command specified there it will reply accordingly.

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 . You will see the output like this . Ensure that you have a telegram account And a token provided from BotFather . This code will take your token ID as an input .

Find More Projects

Drawing Ganesha Using Python Turtle Graphics[Drawing Ganapati Using Python] Introduction In this blog post, we will learn how to draw Lord Ganesha …

Contact Management System in Python with a Graphical User Interface (GUI) Introduction: The Contact Management System is a Python-based application designed to …

KBC Game using Python with Source Code Introduction : Welcome to this blog post on building a “Kaun Banega Crorepati” (KBC) game …

Basic Logging System in C++ With Source Code Introduction : It is one of the most important practices in software development. Logging …

Snake Game Using C++ With Source Code Introduction : The Snake Game is one of the most well-known arcade games, having its …

C++ Hotel Management System With Source Code Introduction : It is very important to manage the hotels effectively to avail better customer …

Get Huge Discounts
More Python Projects

Download From Telegram