Telegram Bot with Python Using the Telegram API

Telegram Bot with Python

Bots are sophisticated software programs that are made to carry out certain activities on their own. These automated devices replicate or replace human behavior by following preprogrammed instructions. They are extensively employed in many different applications, including task automation, alerts, and customer service. This post will explain how to use Python and the Telegram API to build a basic Telegram bot.

image Telegram Bot with Python Using the Telegram API

Getting

Before starting with Python, we need to follow a few steps to get the Telegram Bot API key. Here’s how you can do it:

  1. Create a Telegram Account: Download the app and create an account if you don’t already have one for Telegram.
  2. Search for BotFather: BotFather is an official bot that helps create other bots. Look it up on the Telegram application.
  3. Start a Chat with BotFather: Open the chat with BotFather and type /start. You’ll be given a set of instructions.
  4. Build a New Bot: After typing /newbot, submit it. You are going to be asked to give your bot a name. Select a name that embodies the goal of your bot.
  5. Set a Username: Next, you’ll be asked to provide a username for your bot. The username, such as my_awesome_bot, must be unique and finish in “bot.”
  6. Get the API Key: Once you’ve successfully named your bot, BotFather will send you a unique API key. This key will be essential for connecting your Python code to the Telegram bot.
See also  Scientific Calculator in Python with Source Code

Now that you have the API key, let’s move on to building the bot.

New Project :-https://www.youtube.com/@Decodeit2

Setting Up the Environment for Python

To start building the bot in Python, we need the python-telegram-bot package, which can be installed using pip:

pip install python-telegram-bot

After installing the package, let’s move on to coding.

PHP PROJECT:- CLICK HERE

Writing the Telegram Bot in Python

Now, we will create a simple Telegram bot that responds to commands using Python. The first thing we need is to import the necessary modules and initialize the bot using the API key provided by BotFather.

import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

# Replace 'TOKEN' with your actual bot token
bot = telegram.Bot(token='YOUR_API_KEY')

# Set up the updater and dispatcher
updater = Updater(token='YOUR_API_KEY', use_context=True)
dispatcher = updater.dispatcher

Creating a Simple “Hello World” Command

Let’s follow the tradition and create a simple “Hello, World!” command. We will define a function that sends a message in response to the /hello command.

def hello(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text="Hello, World!")

# Add the command handler to the dispatcher
hello_handler = CommandHandler('hello', hello)
dispatcher.add_handler(hello_handler)

Starting the Bot

Now, we need to start polling, which allows the bot to continuously check for new updates (such as messages and commands) from Telegram.

# Start the bot
updater.start_polling()

With this code, once you type /hello in the chat with your bot, it will respond with “Hello, World!”.

See also  Python Code Snippets for Data Science Projects

Creating a COVID-19 Summary Bot

Now that we’ve covered a simple bot, let’s enhance its functionality by building a bot that provides real-time COVID-19 updates using an API. This will demonstrate how to make your bot more interactive and useful.

First, install the requests library, which will allow us to fetch data from an API:

pip install requests

Next, import the necessary modules and set up a function to retrieve COVID-19 data:

import requests
import json

def summary(update, context):
    # Fetching data from the COVID-19 API
    response = requests.get('https://api.covid19api.com/summary')

    if response.status_code == 200:
        data = response.json()
        global_data = data['Global']

        # Sending the global COVID-19 stats to the user
        message = f"COVID-19 Global Summary:\nNew Confirmed: {global_data['NewConfirmed']}\nTotal Confirmed: {global_data['TotalConfirmed']}\nNew Deaths: {global_data['NewDeaths']}\nTotal Deaths: {global_data['TotalDeaths']}\nNew Recovered: {global_data['NewRecovered']}\nTotal Recovered: {global_data['TotalRecovered']}"
        context.bot.send_message(chat_id=update.effective_chat.id, text=message)
    else:
        context.bot.send_message(chat_id=update.effective_chat.id, text="Error retrieving data.")

Now, add this functionality to the dispatcher so users can get COVID-19 updates by typing /summary:

corona_summary_handler = CommandHandler('summary', summary)
dispatcher.add_handler(corona_summary_handler)

Running the COVID-19 Bot

To run the bot, simply use the same updater.start_polling() command as before:

# Start the COVID-19 bot
updater.start_polling()

Now, when you type /summary in your Telegram chat, your bot will fetch and display the latest global COVID-19 statistics.

Screenshot-2024-10-07-191305 Telegram Bot with Python Using the Telegram API
Telegram Bot with Python Using the Telegram API
  • Telegram Bot with Python Using the Telegram API
  • Telegram Bot with Python
  • Telegram Bot with Python Using the Telegram API

2 comments

Post Comment