Dev.to AI πŸ€– Ai πŸ‘ 0 πŸ“– 3 min read

How I Built an Autonomous AI News Aggregator for Telegram in ~100 Lines of Python ($5/mo Setup)

Running a niche tech or AI news channel manually quickly turns into a daily chore: scanning dozens of RSS feeds, filtering out PR fluff, summarizing articles, and formatting posts. Instead of paying for heavy no-code au

Running a niche tech or AI news channel manually quickly turns into a daily chore: scanning dozens of RSS feeds, filtering out PR fluff, summarizing articles, and formatting posts.

Instead of paying for heavy no-code automation platforms or bloated agent frameworks, I built a lightweight, self-hosted Python worker that runs 24/7 on a basic \$4/mo VPS and costs roughly \$1–\$2/mo in LLM API tokens.

Here is the exact architecture, the subtle edge cases that break Telegram bots in production, and how to deploy it cleanly.

The Architecture

The pipeline stays intentionally simple with zero external databases or message brokers:

  1. RSS Ingestion (feedparser + urllib): Polls a configurable list of RSS feeds with custom User-Agent headers to avoid basic bot blocks.
  2. Pre-LLM Keyword Gate (Regex): Filters entries locally before spending a single API token.
  3. Deduplication (SQLite): Tracks every processed URL (including skipped/off-topic ones) in a local posted_news.db file so the bot never re-evaluates old articles.
  4. LLM Editorial Filter & Rewriter (AsyncOpenAI + gpt-4o-mini): Acts as a managing editorβ€”returning SKIP for ads/clickbait or rewriting valid news into a punchy Telegram post.
  5. HTML Sanitizer: Strips unsupported HTML tags and closes dangling tags before calling send_message.

Solving the #1 Production Bug: Broken LLM HTML in Telegram

If you ask an LLM to format output using Telegram's HTML parse mode, it will eventually hallucinate unsupported tags like <p>, <br>, <ul>, or leave an unclosed <b> tag. When that happens, the Telegram Bot API throws a TelegramBadRequest: can't parse entities exception and drops the post.

A lightweight regex sanitizer solves this reliably:

import re

def sanitize_tg_html(text: str) -> str:
    # Keep only tags supported by Telegram HTML parse mode
    text = re.sub(r"</?(?!b>|i>|a\b|code>|pre>)[^>]+>", "", text)
    # Close unclosed bold/italic tags to prevent API parse errors
    if text.count("<b>") > text.count("</b>"):
        text += "</b>"
    if text.count("<i>") > text.count("</i>"):
        text += "</i>"
    return text

Saving 80% on Token Costs with Two-Stage Filtering

Sending every RSS item directly to an LLM wastes tokens on irrelevant posts. Combining a fast regex pre-filter with a strict SKIP system prompt keeps monthly API bills around \$1–\$2:

async def make_post(title: str, summary: str) -> str:
    prompt = (
        f"You are the managing editor of a Telegram channel focused on: '{CHANNEL_TOPIC}'. "
        "If the news item is off-topic, clickbait, or an advertisement, reply strictly with: SKIP\n"
        "Otherwise, write an engaging, concise Telegram post in English (under 850 characters): "
        "<b>Catchy headline with 1 relevant emoji</b>, 2 short punchy paragraphs summarizing the key takeaway, "
        "and 1 thought-provoking question for readers at the end. "
        "Use ONLY <b> and <i> HTML tags. Do NOT use <p>, <br>, or Markdown.\n\n"
        f"Title: {title}\nText: {summary}"
    )
    res = await ai.chat.completions.create(
        model=LLM_MODEL,
        messages=[{"role": "user", "content": prompt}],
        max_tokens=550,
        temperature=0.6
    )
    return sanitize_tg_html(res.choices[0].message.content.strip())

Running 24/7 on Ubuntu with systemd

Rather than running the script inside tmux or screen, wrapping it in a systemd unit ensures automatic restarts on network hiccups or server reboots:

[Unit]
Description=AI Telegram Channel Autoposter
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/root/ai_bot
ExecStart=/root/ai_bot/venv/bin/python /root/ai_bot/poster.py
Restart=always
RestartSec=15

[Install]
WantedBy=multi-user.target

Want the Complete Plug-and-Play Starter Kit?

If you want to skip wiring everything together from scratch, I packaged the complete, production-ready source code (poster.py, .env.example with zero-code configuration, requirements.txt, and the full step-by-step Ubuntu VPS deployment guide) into a ready-to-run kit:

πŸ‘‰ Get the Autonomous AI News Aggregator Starter Kit here

Feel free to drop any questions about aiogram 3, RSS parsing, or prompt tuning in the comments!

πŸ“° Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.