Hey everyone, Marcus here from ai7bot.com. Man, what a week. My coffee machine decided to stage a protest this morning by refusing to brew anything but lukewarm water. A real crisis, I tell you. But hey, it got me thinking about reliability, about things that just⌠work. And that led me straight to the topic I want to dive into today: Telegram Bots and the Art of the Scheduled Message.
Now, I know what youâre thinking. âMarcus, scheduled messages? Thatâs not exactly groundbreaking stuff.â And youâd be right, to a point. But hereâs the thing: everyone talks about the fancy AI, the natural language processing, the integrations with a dozen different services. And those are all incredibly cool. But sometimes, the most powerful tools are the simplest ones, used smartly. And in the world of bot building, especially on platforms like Telegram, a well-placed, well-timed message can be an absolute goldmine. It’s the silent workhorse, the unsung hero of bot functionality that often gets overlooked.
Think about it. We live in an asynchronous world. People aren’t always online, or in the right headspace, at the exact moment you need to reach them. Maybe you’re running a community, managing a project, or even just trying to remind your D&D group about the next session (a personal pain point, believe me). Sending a message exactly when it’s most impactful, without you having to be glued to your screen, is a superpower. And Telegram bots, with their straightforward API, make this shockingly easy.
Why Telegram for Scheduled Messages?
Iâve dabbled with Discord bots, Slack bots, even some custom webhooks for various internal tools. They all have their strengths. But for raw simplicity and ease of getting a bot up and running with scheduled tasks, Telegram often wins for me. The API is clean, the documentation is decent, and the user base is huge. Plus, Telegram’s channel and group features lend themselves perfectly to broadcasting information at specific times.
My first real “aha!” moment with scheduled messages on Telegram came a few years back. I was part of a small indie game development team. We were all working different hours, different time zones even. Keeping everyone updated on daily progress, bug reports, and meeting times was a nightmare. We tried Slack, but messages would get lost in the noise. Emails were too formal. Then I thought, âWhat if a bot just posted a daily summary every morning?â
It sounds simple, right? But the impact was immediate. Suddenly, everyone woke up, checked the Telegram group, and there was a concise summary of what happened yesterday and what was planned for today. No more digging through threads, no more “did anyone see my message?” It streamlined our communication massively and reduced a lot of friction. That bot, affectionately named “CoffeeBot” (because it delivered updates with your morning coffee), was one of the most beloved tools we ever built, and it was essentially just a glorified cron job sending messages.
The Core Concept: Cron Jobs and Telegram API
At its heart, scheduling messages with a Telegram bot boils down to two main components:
- A way to trigger your code at specific times: This is where cron jobs (on Linux/macOS) or scheduled tasks (on Windows) or even cloud functions with time triggers (AWS Lambda, Google Cloud Functions) come in.
- A way to send messages via the Telegram Bot API: This is a simple HTTP POST request to the
sendMessageendpoint.
Let’s break down a super basic example. For this, I’ll assume you’ve already got a Telegram bot token (if not, talk to BotFather, it’s quick!) and you know your chat ID (you can get this by forwarding a message from the target chat to @userinfobot or by having your bot read messages in a group/channel). Iâll use Python because itâs my go-to for quick bot scripts, but the concept translates to any language.
Example 1: A Daily Reminder Bot (Python & Cron)
Let’s say you want your bot to post a daily reminder in your group at 9 AM every weekday.
First, create a Python script, let’s call it daily_reminder.py:
import requests
import os
from datetime import datetime
# Replace with your bot token and chat ID
BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
CHAT_ID = os.getenv("TELEGRAM_CHAT_ID") # Could be a group ID (negative number) or a user ID
def send_telegram_message(message):
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
payload = {
"chat_id": CHAT_ID,
"text": message,
"parse_mode": "HTML" # Or MarkdownV2, or just plain
}
try:
response = requests.post(url, data=payload)
response.raise_for_status() # Raise an exception for HTTP errors
print(f"Message sent successfully: {response.json()}")
except requests.exceptions.RequestException as e:
print(f"Error sending message: {e}")
if __name__ == "__main__":
today = datetime.now().strftime("%A, %B %d, %Y")
message_text = (
f"Good morning, team! âď¸\n\n"
f"It's {today}. Just a friendly reminder to check our Trello board "
f"and update your tasks for the day. Let's make it a productive one!"
)
if BOT_TOKEN and CHAT_ID:
send_telegram_message(message_text)
else:
print("Error: TELEGRAM_BOT_TOKEN or TELEGRAM_CHAT_ID not set as environment variables.")
A few things to note here:
- Iâm using environment variables for the bot token and chat ID. This is a good practice for security; never hardcode sensitive info directly in your script.
requestslibrary makes HTTP requests easy.parse_mode="HTML"lets you use basic HTML tags for formatting (bold, italics, etc.). Telegram supports MarkdownV2 as well.
To run this automatically, youâd set up a cron job on your server. Open your crontab with crontab -e and add a line like this:
0 9 * * 1-5 /usr/bin/python3 /path/to/your/daily_reminder.py >> /var/log/daily_reminder.log 2>&1
Let’s break down that cron line:
0 9 * * 1-5: This means “at minute 0, hour 9, every day of the month, every month, only on weekdays (1=Monday, 5=Friday)”./usr/bin/python3: The full path to your Python interpreter./path/to/your/daily_reminder.py: The full path to your script.>> /var/log/daily_reminder.log 2>&1: This redirects both standard output and standard error to a log file, which is incredibly helpful for debugging.
And that’s it! Your bot will now send a message every weekday morning. Simple, effective, and hands-off.
Beyond Basic Reminders: Dynamic Content and API Calls
Where this really gets interesting is when you start pulling in dynamic content. That “CoffeeBot” I mentioned for game development? It didn’t just post static text. It pulled data from our Trello board via their API, fetched recent commits from our Git repository, and even checked a shared Google Sheet for upcoming meeting times. The Python script would gather all this info, format it nicely, and then send it.
Imagine a bot that:
- Posts daily weather forecasts for your city using a weather API.
- Sends a summary of new articles from your favorite RSS feed every morning.
- Notifies a team about upcoming deadlines by querying a project management tool’s API.
- Delivers stock market updates or crypto price alerts at specific intervals.
The possibilities are genuinely vast once you combine scheduled execution with external API calls. It’s like having a little personal assistant tirelessly gathering and broadcasting information for you.
Example 2: A Simple RSS Feed Notifier
Let’s quickly sketch out how an RSS feed notifier might work. We’ll use the feedparser library for RSS parsing.
import requests
import os
import feedparser
from datetime import datetime, timezone, timedelta
# Configuration
BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
CHAT_ID = os.getenv("TELEGRAM_CHAT_ID")
RSS_FEED_URL = "https://ai7bot.com/feed/" # Example RSS feed
LAST_CHECKED_FILE = "/tmp/last_checked_ai7bot_feed.txt" # Store timestamp to avoid reposting
def get_last_checked_time():
if os.path.exists(LAST_CHECKED_FILE):
with open(LAST_CHECKED_FILE, 'r') as f:
return datetime.fromisoformat(f.read().strip())
return datetime.now(timezone.utc) - timedelta(days=7) # Go back a week on first run
def set_last_checked_time(dt_obj):
with open(LAST_CHECKED_FILE, 'w') as f:
f.write(dt_obj.isoformat())
def send_telegram_message(message):
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
payload = {
"chat_id": CHAT_ID,
"text": message,
"parse_mode": "HTML",
"disable_web_page_preview": True # Good for clean messages
}
try:
response = requests.post(url, data=payload)
response.raise_for_status()
print(f"Message sent successfully: {response.json()}")
except requests.exceptions.RequestException as e:
print(f"Error sending message: {e}")
if __name__ == "__main__":
if not BOT_TOKEN or not CHAT_ID:
print("Error: TELEGRAM_BOT_TOKEN or TELEGRAM_CHAT_ID not set.")
exit()
last_checked = get_last_checked_time()
feed = feedparser.parse(RSS_FEED_URL)
new_articles = []
current_latest_article_time = last_checked
for entry in feed.entries:
# Convert entry.published_parsed to datetime object in UTC
published_time = datetime(*entry.published_parsed[:6], tzinfo=timezone.utc)
if published_time > last_checked:
new_articles.append(entry)
if published_time > current_latest_article_time:
current_latest_article_time = published_time
if new_articles:
message_parts = [f"New articles from {feed.feed.title}! đ°"]
for article in sorted(new_articles, key=lambda x: datetime(*x.published_parsed[:6])):
message_parts.append(f"⢠{article.title}")
send_telegram_message("\n".join(message_parts))
set_last_checked_time(current_latest_article_time)
else:
print("No new articles found since last check.")
This script does a few extra things:
- It keeps track of the last time it checked the feed to avoid sending duplicate articles using a simple file.
- It uses
feedparserto easily parse the RSS feed. - It formats the output nicely with HTML links.
disable_web_page_preview: Trueis often handy for RSS feeds to keep the message clean and prevent Telegram from generating a large preview for every link.
You’d schedule this script to run every hour or so via cron:
0 * * * * /usr/bin/python3 /path/to/your/rss_notifier.py >> /var/log/rss_notifier.log 2>&1
This cron entry means “at minute 0 of every hour, every day.”
Actionable Takeaways for Your Bot Projects:
- Start Simple: Don’t try to build the next ChatGPT overnight. Identify a repetitive task that could benefit from a simple, scheduled notification. That’s your starting point.
- Use Environment Variables: Seriously, for security and ease of deployment, keep your bot token and sensitive IDs out of your code.
- Log Everything: When dealing with scheduled tasks, things can fail silently. Always redirect output to a log file so you can debug when your bot mysteriously stops sending messages.
- Choose Your Scheduler Wisely: For personal projects, cron is perfectly fine. For more robust, scalable solutions, look into cloud functions (AWS Lambda, Google Cloud Functions) with time-based triggers. They handle the server management for you.
- Error Handling is Your Friend: Add
try-exceptblocks around your API calls. Network issues happen, and you want your bot to gracefully handle them, maybe even send you a private error notification. - Consider Message Frequency: Don’t spam your users! Think about the optimal time and frequency for your messages to be useful, not annoying. Too many messages, and people will mute your bot, defeating its purpose.
- Experiment with Formatting: Telegram’s HTML and MarkdownV2 support allows for clear, readable messages. Use bold, italics, and links to make your information digestible.
Scheduled messages might not be the flashiest bot feature, but they are incredibly practical and often form the backbone of a truly useful bot. They automate routine communication, ensure timely delivery of important information, and free up your time for more complex tasks. So go on, give it a shot. Build that daily stand-up reminder, that weather bot, or even that D&D session reminder. You’ll be surprised how much impact such a simple bot can have.
Until next time, happy bot building!
đ Published: