←back to #AskDushyant

Telegram Bots: Building from Scratch

With over 18 years of experience in building and managing enterprise-level applications, I’ve seen firsthand how crucial it is for tech systems to share accurate information instantly, especially when serving millions of customers. In today’s fast-paced digital world, having the right information at the right time can make all the difference. This is where messaging apps like Telegram and bots come into play. Telegram provide inbuilt bots functionality, a powerful tools that can automate tasks, provide notifications, and enhance user interaction in various applications. In this tech guide, we will walk through the entire process of creating a Telegram bot from scratch, setting it up on Telegram, and configuring it to receive alert messages scheduled on your server.

What is a Telegram Bot?

A Telegram bot is an automated software application that interacts with users on Telegram. Bots can perform various tasks, such as sending notifications, responding to user queries, and integrating with external systems to provide real-time updates.

Prerequisites

Before we dive into creating a Telegram bot, ensure you have:

  • A Telegram account
  • Basic knowledge of programming (Python, Shell will be used in this guide)
  • Access to a server or local machine to run your bot

Creating a New Bot on Telegram

Start a Chat with BotFather
  1. Open Telegram: Launch the Telegram app on your device.
  2. Search for BotFather: In the search bar, type
@BotFather

and select the official BotFather bot.

  1. Start a Chat: Click the “Start” button or type
/start

to initiate a conversation.

Create a New Bot
  1. Create a Bot: Type /newbot
/newbot

and send the message. BotFather will prompt you to choose a name and a username for your bot.

  1. Name Your Bot: Enter a name for your bot (e.g., “My Alert Bot”).
  2. Set a Username: Choose a unique username ending with “bot” (e.g., “my_alert_bot”).
  3. Receive Your Token: After creation, BotFather will provide you with a unique API token. Save this token as it will be used to authenticate your bot.

Setting Up Your Development Environment

Install Required Libraries

You will need the python-telegram-bot library to interact with the Telegram API. Install it using pip:

pip install python-telegram-bot

Writing Your First Bot Script

Create a Python script (bot.py) to define the behavior of your bot. Here’s a basic example:

from telegram import Update
from telegram.ext import Updater, CommandHandler, CallbackContext, CallbackQueryHandler
import logging

# Replace 'YOUR_API_TOKEN' with your actual bot token
API_TOKEN = 'YOUR_API_TOKEN'

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)
logger = logging.getLogger(__name__)

def start(update: Update, context: CallbackContext) -> None:
    update.message.reply_text('Hello! I am your alert bot. How can I help you today?')

def help_command(update: Update, context: CallbackContext) -> None:
    update.message.reply_text('Send /start to receive a welcome message.')

def main() -> None:
    updater = Updater(API_TOKEN, use_context=True)
    dispatcher = updater.dispatcher

    dispatcher.add_handler(CommandHandler('start', start))
    dispatcher.add_handler(CommandHandler('help', help_command))

    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

Deploying Your Bot

Running Locally

To test your bot locally, simply run:

python bot.py

Your bot should now be running and listening for commands.

Deploying on a Server

For continuous operation, deploy your bot on a server. You can use services like Heroku, AWS, or any VPS. Ensure your server environment has Python installed and set up to run your script.

Scheduling Alerts on Your Server

To have your bot receive alert messages from your server, follow these steps:

Set Up a Script to Send Alerts

Create a script (send_alert.py) that will send messages to your bot:

import requests

# Replace 'YOUR_API_TOKEN' and 'CHAT_ID' with actual values
API_TOKEN = 'YOUR_API_TOKEN'
CHAT_ID = 'YOUR_CHAT_ID'
MESSAGE = 'This is a scheduled alert message.'

def send_alert():
    url = f'https://api.telegram.org/bot{API_TOKEN}/sendMessage'
    payload = {
        'chat_id': CHAT_ID,
        'text': MESSAGE
    }
    requests.post(url, data=payload)

if __name__ == '__main__':
    send_alert()

To obtain your CHAT_ID, follow the instructions outlined in Get your Chat_ID: Telegram Bots.

Schedule the Script

Use cron jobs (on Unix-based systems) or Task Scheduler (on Windows) to run the send_alert.py script at regular intervals.

For a cron job, open your crontab with:

crontab -e

Add a line to schedule the script, e.g., to run every hour:

0 * * * * /usr/bin/python3 /path/to/send_alert.py

Testing and Debugging

  1. Test Your Bot: Interact with your bot via Telegram to ensure it responds correctly.
  2. Monitor Alerts: Check if scheduled alerts are being sent as expected.
  3. Debugging: If issues arise, use logging to troubleshoot and ensure your token and chat ID are correct.

Creating a Telegram bot is a straightforward process that can greatly enhance your server’s functionality by providing real-time notifications and automating interactions. With the steps outlined in this guide, you should be well on your way to developing and deploying your own Telegram bot. Happy Bot Building ! 🧑🏻‍💻

#AskDushyant
#Bot #Telegram #Alert #TechTool #ToolKit #CodeSnippet #Messaging
Note: Feel free to extend the functionality of your bot by adding more commands and integrating it with other services.

Leave a Reply

Your email address will not be published. Required fields are marked *