DEV Community

guardlabs_team
guardlabs_team

Posted on Originally published at guardlabs.online

Building a Telegram Bot for Scheduled Channel Messages

Building a Telegram Bot for Scheduled Channel Messages

This article outlines the technical steps to create a Telegram bot that sends scheduled messages to a specified Telegram channel. The solution uses Python and the Telegram Bot API, focusing on a straightforward implementation without external services.

Prerequisites

Python 3.x installed on your system.
requests Python library: pip install requests
schedule Python library (for in-script scheduling): pip install schedule
A Telegram account.
Enter fullscreen mode Exit fullscreen mode

Step 1: Create Your Telegram Bot
Every Telegram bot requires a unique token for API access. This token is obtained through BotFather.

Open Telegram and search for @BotFather.
Start a chat with BotFather and send the command /newbot.
Follow the prompts to choose a name and a username for your bot.
BotFather will provide you with an HTTP API token (e.g., 1234567890:ABCDEFGHIJKLMN_OPQRSTUVWXYZZZ). Keep this token secure; it grants full control over your bot.
Enter fullscreen mode Exit fullscreen mode

Step 2: Add Bot to Channel and Get Channel ID
For your bot to send messages to a channel, it must be an administrator of that channel. You also need the channel's unique ID.

Add Bot to Channel: In your Telegram channel, go to "Manage Channel" > "Administrators" > "Add Administrator". Search for your bot's username and add it. Grant it at least the "Post Messages" permission.
Get Channel ID:

        Send any message to your channel (you can do this manually or via a temporary script using the bot).
        Open your web browser and navigate to: https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates (replace <YOUR_BOT_TOKEN> with your actual bot token).
        Look for a JSON object containing "chat":{"id":-100...}. This negative number is your CHANNEL_ID. It typically appears within a "channel_post" or "message" object.
Enter fullscreen mode Exit fullscreen mode

Step 3: Python Script for Sending Messages
This script defines a function to send a message using the Telegram Bot API.

import requests

BOT_TOKEN = "YOUR_BOT_TOKEN" # Replace with your actual bot token
CHANNEL_ID = "-1001234567890" # Replace with your actual channel ID (negative number)

def send_telegram_message(message_text):
"""Sends a message to the specified Telegram channel."""
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
payload = {
"chat_id": CHANNEL_ID,
"text": message_text,
"parse_mode": "HTML" # Optional: Use HTML for formatting
}
try:
response = requests.post(url, data=payload)
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
print(f"Message sent successfully: {message_text}")
except requests.exceptions.RequestException as e:
print(f"Error sending message: {e}")

Example usage (for testing)

if name == "main":

test_message = "Hello from your bot! This is a test message."

send_telegram_message(test_message)

Step 4: Implement Scheduling Logic
The schedule library allows defining tasks to run at specific times or intervals. Integrate this into your script.

import schedule
import time

Assuming send_telegram_message function from Step 3 is in the same file or imported

--- Configuration (from Step 3, repeated for clarity) ---

BOT_TOKEN = "YOUR_BOT_TOKEN"
CHANNEL_ID = "-1001234567890"

def send_telegram_message(message_text):
# ... (Implementation as in Step 3) ...
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
payload = {
"chat_id": CHANNEL_ID,
"text": message_text,
"parse_mode": "HTML"
}
try:
response = requests.post(url, data=payload)
response.raise_for_status()
print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] Message sent successfully: {message_text}")
except requests.exceptions.RequestException as e:
print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] Error sending message: {e}")

--- Define Scheduled Tasks ---

def daily_report():
message = "Daily Report: All systems operational. No significant events reported."
send_telegram_message(message)

def weekly_summary():
message = "Weekly Summary: Review of the past week's activities is complete."
send_telegram_message(message)

Schedule tasks

schedule.every().day.at("09:00").do(daily_report)
schedule.every().monday.at("17:00").do(weekly_summary)

You can add more complex schedules:

schedule.every(10).minutes.do(lambda: send_telegram_message("10-minute heartbeat check."))

schedule.every().hour.do(lambda: send_telegram_message("Hourly update."))

print("Scheduler started. Waiting for scheduled tasks...")

--- Main Loop to Run Scheduler ---

if name == "main":
while True:
schedule.run_pending()
time.sleep(1) # Wait one second before checking again

Running the Scheduler
Save the combined script (from Step 3 and Step 4) as a .py file (e.g., telegram_scheduler.py). To run it, open a terminal or command prompt, navigate to the directory where you saved the file, and execute:

python telegram_scheduler.py

The script will run continuously, checking for pending tasks every second. For persistent operation on a server, consider running it using tools like nohup, screen, tmux, or configuring it as a systemd service (Linux) or a scheduled task (Windows).
Need this done fast? order it on Kwork.

Top comments (0)