A Telegram channel that repeats a blog, a news site or a shop's new products is one of the simplest things to automate, and one of the easiest to get wrong. The usual first version posts every item in the feed the moment the bot starts, posts some of them again after a restart, wakes the subscribers at three in the morning, loses the end of long captions and stops for a while when Telegram answers "Too Many Requests". This guide builds the pieces that avoid each of those: a polite fetch that remembers what it posted, messages that fit Telegram's limits, a team approval step, quiet hours and an hourly limit. The samples are plain Python 3.12 with no packages and were run as printed.
#The shape of the bot
Create a bot with BotFather and add it to the channel as an administrator with the right to post. The bot then runs a loop: for each feed, fetch it when its interval is due, find the items it has not posted, turn each into a message, send it to a review chat if the feed needs approval, and post it to the channel at the first moment the channel's rules allow. Everything it has to remember goes into one SQLite file, so a restart changes nothing.
#Fetch politely, post once
A feed checked every fifteen minutes is fetched almost a hundred times a day, and it changes a few times. HTTP has a cheap answer for that: send back the ETag and Last-Modified values of the last response as If-None-Match and If-Modified-Since, and an unchanged feed answers 304 Not Modified with no body.
import sqlite3
import urllib.error
import urllib.request
db = sqlite3.connect("razglaska-demo.sqlite")
db.execute("CREATE TABLE IF NOT EXISTS feed (url TEXT PRIMARY KEY, etag TEXT, modified TEXT)")
db.execute("CREATE TABLE IF NOT EXISTS seen (feed TEXT, key TEXT, PRIMARY KEY (feed, key))")
def fetch(url: str) -> bytes | None:
"""The feed body, or None when the server says it has not changed since the last fetch."""
row = db.execute("SELECT etag, modified FROM feed WHERE url = ?", (url,)).fetchone()
req = urllib.request.Request(url, headers={"User-Agent": "feed-to-channel/1.0"})
if row and row[0]:
req.add_header("If-None-Match", row[0])
if row and row[1]:
req.add_header("If-Modified-Since", row[1])
try:
with urllib.request.urlopen(req, timeout=20) as r:
db.execute("INSERT OR REPLACE INTO feed VALUES (?, ?, ?)",
(url, r.headers.get("ETag"), r.headers.get("Last-Modified")))
db.commit()
return r.read()
except urllib.error.HTTPError as e:
if e.code == 304:
return None
raise
def is_new(feed: str, key: str) -> bool:
"""True the first time an item key (its guid or id, else its link) is seen for a feed."""
cur = db.execute("INSERT OR IGNORE INTO seen VALUES (?, ?)", (feed, key))
db.commit()
return cur.rowcount == 1
Against a small local server that sends an ETag, the first call returns the body and the second returns None. Each item needs a key that does not change: the RSS guid, the Atom or JSON Feed id, and only when there is none, the link. is_new() lets SQLite decide in one statement: the insert succeeds only the first time a key is seen for that feed, so the same key in two feeds is two posts, and the same key twice in one feed is one.
The first check of a new feed needs a rule of its own. A feed usually holds the last 10 to 50 items, and posting all of them floods the channel. Mark them all as seen and post none, or only the newest one or two, and post the rest of the feed's life oldest first.
#Fit Telegram's limits
A photo caption can have up to 1024 characters after entities parsing and a text message up to 4096 (Bot API, sendPhoto and sendMessage). "After entities parsing" means the tags of HTML parse mode do not count, but the text they wrap does. Telegram measures message entities in UTF-16 code units, where an emoji takes two, so counting in UTF-16 keeps you on the safe side. In HTML parse mode only &, < and > need escaping in text.
import html
import re
CAPTION_LIMIT = 1024 # photo captions; a text message may have 4096
def visible_length(message_html: str) -> int:
"""Length as Telegram counts it: the text after the HTML tags are parsed, in UTF-16 code units."""
text = html.unescape(re.sub(r"<[^>]+>", "", message_html))
return len(text.encode("utf-16-le")) // 2
def as_post(title: str, summary: str, link: str, photo: str | None) -> tuple[str, dict]:
e = lambda s: html.escape(s, quote=False)
body = f"<b>{e(title)}</b>\n\n{e(summary)}\n\n{e(link)}"
if photo and visible_length(body) <= CAPTION_LIMIT:
return "sendPhoto", {"photo": photo, "caption": body, "parse_mode": "HTML"}
return "sendMessage", {"text": body, "parse_mode": "HTML"}
With a picture and a 900-character summary, the post goes out as a photo with a caption. With a 1000-character summary the whole message is 1037 characters, too long for a caption, so it becomes a text message, where the link preview can still show the picture. That is better than cutting the summary in the middle of a word, and much better than Telegram refusing the request. visible_length("<b>Нов брой</b> & 😀") is 13: the tag is gone, the entity is one character, and the emoji is two.
#An approval step for the team
Some feeds should not go out unread: a press feed with the occasional unrelated item, or a shop feed during a price change. Send those items to a private group of your team instead, as the same message with an inline keyboard: Publish, To queue and Skip. A button press arrives as a callback_query; check that the person who pressed it is one of your admins, answer it with answerCallbackQuery, act on it, and edit the card so the group sees who decided. Keep the item's id in the button's callback_data, which holds at most 64 bytes, and the rest in your database.
#Quiet hours and an hourly limit
A channel that posts at night trains its subscribers to mute it. Hold feed items during quiet hours and space them out with a maximum per hour:
from datetime import datetime, time, timedelta, timezone
from zoneinfo import ZoneInfo
TZ = ZoneInfo("Europe/Sofia")
def in_quiet(moment: datetime, start: time, end: time) -> bool:
t = moment.astimezone(TZ).time()
return start <= t < end if start < end else (t >= start or t < end)
def next_allowed(moment: datetime, start: time, end: time, posted: list[datetime], per_hour: int) -> datetime:
"""The earliest moment from `moment` on that is outside quiet hours and under the hourly limit.
Arithmetic is done in UTC, so an hour is always sixty minutes, also on the night the clocks change."""
t = moment.astimezone(timezone.utc)
posted = [p.astimezone(timezone.utc) for p in posted]
while True:
if in_quiet(t, start, end):
local = t.astimezone(TZ)
day = local.date() if local.time() < end else local.date() + timedelta(days=1)
t = datetime.combine(day, end, TZ).astimezone(timezone.utc)
continue
recent = sorted(p for p in posted if t - timedelta(hours=1) < p <= t)
if len(recent) >= per_hour:
t = recent[-per_hour] + timedelta(hours=1)
continue
return t.astimezone(TZ)
With quiet hours from 22:30 to 07:30, an item found at 23:10 waits until 07:30 the next morning, and one found at 07:29 waits a minute. With a limit of four an hour and posts at 09:00, 09:10, 09:20 and 09:40, an item at 09:45 waits until 10:00, when the 09:00 post leaves the window. The arithmetic runs in UTC because the clocks change: on 28 March 2027 the clocks in Sofia jump from 03:00 to 04:00, so quiet hours that end at 03:30 that night end at 04:30, an hour later on the wall clock but the right moment in real time. For posts that may go out at any hour but should not ring, the Bot API has disable_notification.
#Rate limits and errors
Telegram's bot FAQ asks you to avoid more than one message per second in a single chat, and says bots cannot send more than 20 messages a minute in a group. Above that you get HTTP 429 with parameters.retry_after, the number of seconds to wait: wait that long and try again, rather than retrying at once. Treat 5xx answers and network errors as temporary and retry a few times with a growing pause. Some errors are permanent, for example when the bot is no longer an administrator of the channel; mark the post as failed and tell the admins once, instead of trying again every minute.
Your own posts belong in the same queue. If an admin sends or forwards a message to the bot in a private chat, copyMessage posts it to the channel as it is, with its formatting and media and without the "Forwarded from" line.
#A bot that does all of this
We built Razglaska, a self-hosted Telegram bot for channels in English and Bulgarian. It posts new items from RSS, Atom and JSON feeds with their pictures, oldest first and never twice, with ETag and Last-Modified fetching, a template per feed, filters and a safe first run. Items can wait for approval in a review chat with Publish, To queue and Skip; quiet hours, a limit per hour, silent posts and posting slots keep the channel calm. You can also send it your own posts and choose Post now, Next slot or a typed time such as "tomorrow 9:00" or "утре 9:00". Everything is set in one TOML file, it needs Python 3.11 or newer and no other packages, and it was tested with 45 tests, including full runs against a fake Telegram Bot API and a fake feed server. It was not run against the real Telegram service during testing, and it is listed as Coming soon.
#Frequently asked questions
Why does my bot post the same RSS item twice?
Usually because it remembers posted items only in memory, or keys them by title or date, which can change. Store a key from the item's guid or id in a database and insert it before you post.
How long can a Telegram photo caption be?
Up to 1024 characters after entities parsing, while a text message can have up to 4096. Send a long item as a text message with a link preview instead of cutting it.
What does a 429 error from the Bot API mean?
You sent too many requests. The answer includes retry_after, the seconds to wait before trying again; respect it and keep to about one message per second per chat.
Can I post to a channel without notifying subscribers?
Yes. Send the message with disable_notification set to true, and subscribers receive it without a sound.
Comments
Comments
No comments yet. Ask a question or share what worked for you.
Leave a comment