In 2026, staying ahead of real-time breaking news, tech blogs, software releases, and industry updates requires automated information filtering. While commercial RSS readers and proprietary Telegram bots exist, many impose strict feed limits, inject intrusive advertisements, or compromise privacy by selling tracking data. Building your own self-hosted Telegram RSS feed and news aggregator bot gives you total control over feed update frequencies, custom message formatting, keyword filtering, and automated publishing directly to your personal Telegram channels or private groups.
This comprehensive tutorial demonstrates how to build an asynchronous Telegram RSS feed aggregator using Python 3.11+, Aiogram 3.x, feedparser, and aiosqlite. Deployable on any Linux VPS or home server via Docker or Systemd, this bot periodically polls RSS/Atom feeds, strips tracking parameters, formats updates into clean HTML Telegram posts, and prevents duplicate deliveries using an embedded SQLite database. Explore verified tech channels on Telekit's Tech & Coding Directory.
Why Self-Host a Telegram RSS News Bot in 2026?
RSS (Really Simple Syndication) remains the open web's standard protocol for content distribution. When paired with Telegram's instant delivery system, RSS feeds become a powerful personal intelligence network. Self-hosting your bot offers distinct operational advantages:
- Zero Artificial Rate Limits: Commercial bots charge expensive monthly subscriptions to monitor more than 3 feeds. A self-hosted bot can poll hundreds of feeds simultaneously with zero subscription fees.
- Privacy & Data Control: Third-party RSS bots log every feed URL, topic interest, and click event. Running your own instance ensures your news gathering habits stay strictly private.
- Custom Filtering & Keyword Rules: Include or exclude posts based on exact regex keywords (e.g., only forward posts containing "Security Alert" or "Python 3.12").
- Clean HTML Formatting: Automatically sanitize HTML tags, strip UTM tracking clutter, and convert long summary blocks into scannable Telegram messages.
System Prerequisites & Architecture Stack
Before proceeding with code setup, ensure your development or hosting environment meets the following requirements:
- Python 3.10+ (Python 3.11 or 3.12 recommended for async performance improvements).
- Telegram Bot Token: Created via Telegram's official @BotFather bot.
- Virtual Private Server (VPS): Linux server (Ubuntu 22.04 LTS or Debian 12) with Docker or systemd for 24/7 background operation.
Step 1: Environment Setup & Project Structure
Open your server terminal and create a dedicated project directory for the RSS bot project:
# Create directory and enter it
mkdir -p ~/telegram-rss-bot
cd ~/telegram-rss-bot
# Set up Python virtual environment
python3 -m venv venv
source venv/bin/activate
# Upgrade pip and install core dependencies
pip install --upgrade pip
pip install aiogram aiohttp feedparser beautifulsoup4 aiosqlite python-dotenv
Create the following project structure:
telegram-rss-bot/
├── .env
├── database.py
├── feed_parser.py
├── main.py
├── requirements.txt
└── Dockerfile
Create a .env configuration file to store secret environment variables safely:
# .env configuration
BOT_TOKEN=123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ_12345678
TARGET_CHAT_ID=-1001234567890
POLL_INTERVAL=600 # Poll feeds every 10 minutes (600 seconds)
Step 2: SQLite Async Database Handler (database.py)
To avoid sending the same article multiple times when an RSS feed refreshes, we implement an SQLite database table that records published article GUIDs or URLs along with active feed subscriptions.
import aiosqlite
import logging
DB_NAME = "rss_bot.db"
async def init_db():
# Initialize SQLite tables for feed channels and sent articles.
async with aiosqlite.connect(DB_NAME) as db:
await db.execute('''
CREATE TABLE IF NOT EXISTS feeds (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
url TEXT UNIQUE NOT NULL,
chat_id INTEGER NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
await db.execute('''
CREATE TABLE IF NOT EXISTS published_entries (
entry_id TEXT PRIMARY KEY,
feed_url TEXT NOT NULL,
published_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
await db.commit()
logging.info("Database initialized successfully.")
async def add_feed(title: str, url: str, chat_id: int) -> bool:
# Add a new RSS feed subscription.
try:
async with aiosqlite.connect(DB_NAME) as db:
await db.execute(
"INSERT INTO feeds (title, url, chat_id) VALUES (?, ?, ?)",
(title, url, chat_id)
)
await db.commit()
return True
except aiosqlite.IntegrityError:
return False
async def get_all_feeds():
# Retrieve all active feed subscriptions.
async with aiosqlite.connect(DB_NAME) as db:
async with db.execute("SELECT id, title, url, chat_id FROM feeds") as cursor:
return await cursor.fetchall()
async def remove_feed(feed_id: int) -> bool:
# Remove a feed subscription by ID.
async with aiosqlite.connect(DB_NAME) as db:
cursor = await db.execute("DELETE FROM feeds WHERE id = ?", (feed_id,))
await db.commit()
return cursor.rowcount > 0
async def is_entry_published(entry_id: str) -> bool:
# Check if an article GUID has already been broadcast.
async with aiosqlite.connect(DB_NAME) as db:
async with db.execute("SELECT 1 FROM published_entries WHERE entry_id = ?", (entry_id,)) as cursor:
row = await cursor.fetchone()
return row is not None
async def mark_entry_published(entry_id: str, feed_url: str):
# Mark an article GUID as published.
async with aiosqlite.connect(DB_NAME) as db:
await db.execute(
"INSERT OR IGNORE INTO published_entries (entry_id, feed_url) VALUES (?, ?)",
(entry_id, feed_url)
)
await db.commit()
Step 3: Async RSS Fetcher & Sanitizer (feed_parser.py)
RSS feeds often contain raw HTML, messy inline scripts, tracking images, and unescaped entities. We use aiohttp to download feed XML asynchronously, feedparser to extract items, and BeautifulSoup to produce clean Telegram HTML formatting.
import aiohttp
import feedparser
from bs4 import BeautifulSoup
import html
import re
def sanitize_html_for_telegram(raw_html: str, max_length: int = 400) -> str:
# Convert raw HTML summaries into clean, safe text for Telegram HTML mode.
if not raw_html:
return ""
# Strip HTML tags using BeautifulSoup
soup = BeautifulSoup(raw_html, "html.parser")
text = soup.get_text(separator=" ", strip=True)
# Unescape HTML entities & clean whitespaces
text = html.unescape(text)
text = re.sub(r'\s+', ' ', text).strip()
if len(text) > max_length:
text = text[:max_length].rstrip() + "..."
return html.escape(text)
async def fetch_rss_entries(feed_url: str):
# Fetch and parse RSS entries asynchronously.
headers = {
"User-Agent": "TelekitRSSBot/2026.1 (Linux VPS; OpenSource Aggregator)"
}
try:
async with aiohttp.ClientSession() as session:
async with session.get(feed_url, headers=headers, timeout=aiohttp.ClientTimeout(total=15)) as response:
if response.status != 200:
return None, []
content = await response.text()
parsed = feedparser.parse(content)
feed_title = parsed.feed.get("title", "RSS Feed")
entries = []
for entry in parsed.entries[:10]: # Limit to 10 latest entries per check
entry_id = entry.get("id") or entry.get("link")
title = entry.get("title", "Untitled Article")
link = entry.get("link", feed_url)
summary_raw = entry.get("summary") or entry.get("description", "")
clean_summary = sanitize_html_for_telegram(summary_raw)
entries.append({
"id": entry_id,
"title": html.escape(title),
"link": link,
"summary": clean_summary
})
return feed_title, entries
except Exception as e:
print(f"Error fetching feed {feed_url}: {e}")
return None, []
Step 4: Bot Main Engine & Background Scheduler (main.py)
The main engine combines Telegram commands (`/add`, `/list`, `/remove`, `/checknow`) with a background asyncio worker task that continuously polls feeds at the defined interval.
import asyncio
import os
import logging
from dotenv import load_dotenv
from aiogram import Bot, Dispatcher, types
from aiogram.filters import Command
from aiogram.enums import ParseMode
import database as db
import feed_parser
load_dotenv()
BOT_TOKEN = os.getenv("BOT_TOKEN")
TARGET_CHAT_ID = os.getenv("TARGET_CHAT_ID")
POLL_INTERVAL = int(os.getenv("POLL_INTERVAL", 600))
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
bot = Bot(token=BOT_TOKEN)
dp = Dispatcher()
@dp.message(Command("start"))
async def cmd_start(message: types.Message):
welcome_text = (
"🤖 Self-Hosted Telegram RSS Bot (2026)
"
"Available Commands:
"
"• /add <feed_url> - Subscribe to an RSS feed
"
"• /list - List all active RSS feeds
"
"• /remove <feed_id> - Unsubscribe from a feed
"
"• /checknow - Trigger an immediate RSS check"
)
await message.answer(welcome_text, parse_mode=ParseMode.HTML)
@dp.message(Command("add"))
async def cmd_add(message: types.Message):
args = message.text.split(maxsplit=1)
if len(args) < 2:
await message.answer("⚠️ Usage: /add https://example.com/feed.xml", parse_mode=ParseMode.HTML)
return
url = args[1].strip()
await message.answer(f"🔍 Testing and validating feed URL: {url}...", parse_mode=ParseMode.HTML)
feed_title, entries = await feed_parser.fetch_rss_entries(url)
if not feed_title:
await message.answer("❌ Failed to fetch or parse RSS feed. Ensure URL is valid.", parse_mode=ParseMode.HTML)
return
target_chat = message.chat.id
success = await db.add_feed(feed_title, url, target_chat)
if success:
await message.answer(f"✅ Subscribed to {feed_title} ({len(entries)} items indexed).", parse_mode=ParseMode.HTML)
else:
await message.answer("⚠️ You are already subscribed to this feed URL.")
@dp.message(Command("list"))
async def cmd_list(message: types.Message):
feeds = await db.get_all_feeds()
if not feeds:
await message.answer("📭 No active RSS feed subscriptions found.")
return
lines = ["📋 Active RSS Subscriptions:
"]
for feed_id, title, url, chat_id in feeds:
lines.append(f"[{feed_id}] {title}
{url}
")
await message.answer("
".join(lines), parse_mode=ParseMode.HTML)
@dp.message(Command("remove"))
async def cmd_remove(message: types.Message):
args = message.text.split(maxsplit=1)
if len(args) < 2 or not args[1].isdigit():
await message.answer("⚠️ Usage: /remove <feed_id>", parse_mode=ParseMode.HTML)
return
feed_id = int(args[1])
removed = await db.remove_feed(feed_id)
if removed:
await message.answer(f"✅ Feed ID {feed_id} successfully removed.", parse_mode=ParseMode.HTML)
else:
await message.answer(f"❌ Feed ID {feed_id} not found.")
async def process_rss_polling():
# Background polling worker.
logging.info("Starting background RSS polling task...")
while True:
try:
feeds = await db.get_all_feeds()
for feed_id, feed_title, feed_url, chat_id in feeds:
title, entries = await feed_parser.fetch_rss_entries(feed_url)
if not entries:
continue
# Process entries in chronological order (oldest to newest)
for entry in reversed(entries):
if await db.is_entry_published(entry["id"]):
continue
# Format Telegram post
msg = (
f"📰 {entry['title']}
"
f"Source: {feed_title}
"
f"{entry['summary']}
"
f"🔗 Read Full Article"
)
try:
target = chat_id or TARGET_CHAT_ID
await bot.send_message(
chat_id=target,
text=msg,
parse_mode=ParseMode.HTML,
disable_web_page_preview=False
)
await db.mark_entry_published(entry["id"], feed_url)
await asyncio.sleep(2) # Telegram rate limit compliance
except Exception as send_err:
logging.error(f"Error sending entry to chat {target}: {send_err}")
except Exception as e:
logging.error(f"Error during RSS polling loop: {e}")
await asyncio.sleep(POLL_INTERVAL)
async def main():
await db.init_db()
asyncio.create_task(process_rss_polling())
logging.info("Bot starting polling mode...")
await dp.start_polling(bot)
if __name__ == "__main__":
asyncio.run(main())
Step 5: 24/7 VPS Deployment (Systemd & Docker)
Option A: Deployment via Systemd Service
To run your bot continuously on Ubuntu/Debian Linux VPS servers with auto-restart on boot, create a systemd service unit file:
# Create service file
sudo nano /etc/systemd/system/telegram-rss.service
# Paste the following configuration:
[Unit]
Description=Telegram RSS News Aggregator Bot
After=network.target
[Service]
Type=simple
User=ubuntu
WorkingDirectory=/home/ubuntu/telegram-rss-bot
ExecStart=/home/ubuntu/telegram-rss-bot/venv/bin/python main.py
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
Enable and start the service with the following terminal commands:
# Reload systemd daemon and enable service
sudo systemctl daemon-reload
sudo systemctl enable telegram-rss
sudo systemctl start telegram-rss
# Check service status and live logs
sudo systemctl status telegram-rss
journalctl -u telegram-rss -f
Option B: Containerized Deployment via Docker Compose
If you prefer Docker containers, create a lightweight Dockerfile in your project root:
# Dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python", "main.py"]
Run the container in detached background mode:
# Build image and run container
docker build -t telegram-rss-bot .
docker run -d --name rss_bot --restart unless-stopped -v $(pwd)/rss_bot.db:/app/rss_bot.db --env-file .env telegram-rss-bot
Frequently Asked Questions (FAQ)
Can I forward RSS updates to a Telegram Channel or Group?
Yes! Add your bot as an Administrator to your Telegram channel or group with "Post Messages" permission. Then, set the TARGET_CHAT_ID in your .env file to the channel's ID (e.g., -1001234567890) or issue the /add command directly within the group.
How do I prevent Telegram from rate-limiting message broadcasts?
Telegram enforces a rate limit of 30 messages per second across all chats and 1 message per second within a single chat. Our implementation includes an explicit await asyncio.sleep(2) delay between broadcasts to keep your bot well within API guidelines.
What happens if an RSS feed provides invalid HTML tags?
Telegram's HTML parse mode rejects unsupported HTML tags (such as <div>, <iframe>, or <script>). Our feed_parser.py uses BeautifulSoup to strip all non-standard elements and escape remaining characters using html.escape().
How much RAM and CPU does this bot consume on a VPS?
Because the stack uses asynchronous Python (aiogram 3 + aiohttp) and SQLite, memory consumption remains under 45 MB of RAM even when monitoring dozens of active RSS feeds, making it ideal for low-cost $3.50/mo VPS instances.
Conclusion
Building a self-hosted Telegram RSS feed bot provides privacy, reliability, and total customization over your daily news streams. By leveraging Python 3, Aiogram 3, and SQLite, you have created a lightweight, production-ready news aggregator that runs 24/7 without subscription fees or data tracking. Explore Telekit's Tech & Coding Catalog to discover verified news channels and tech communities on Telegram!