When receiving content notifications and updates, email is one of the primary options most common among netizens. But, it's certainly not the best one as the updates you get are not in real time. To solve this problem, we can take advantage of Telegram Bots and API. Through it, we can get real-time updates of our favorite content stream right within the Telegram app. In this tutorial, we'll learn about setting up a fully automated system to get updates from our favorite RSS feeds and YouTube channels into our Telegram account. You can customize this notification setup as per your needs. Let's get started!
Any content syndication stream regardless of the type of service or platform can be added to this method to receive real-time updates through a Telegram bot. All you need is to once know how to set it up.
Advanced and tech-savvy users can go through Telgram's API reference to create custom solutions and tools to power their business processes in no time. It's easy to use and works flawlessly, every time.
Prerequisites for the Setup
Let's quickly check the list of tools, applications, and devices we may need to configure this setup.
- A Telegram account
- Working knowledge of Python programming language
- A local Linux-powered computer, or a VPS, or a Raspberry Pi device
You do not need to be a professional programmer, to pull this off. Basic knowledge of programming is all you need.
Step 1: Get the RSS Feed URLs
Let's start by fetching the RSS feed of the content streams we'd like to get updates on. One is the website's RSS feed and the other one of the YouTube channel's feed.
Fetch the Website's RSS Feed URL
Almost every website offers RSS feeds to enable users to consume their content in 3rd-party apps. Find the RSS icons and text mentioning the RSS feed on the website. A typical RSS feed URL is like:
https://website-domain.com/rss
https://website-domain.com/feed
If you are struggling to find the RSS feed URL of the website, use the RSS.app service to quickly generate one for you.
Get the YouTube Channel's RSS Feed URL
Preparing a YouTube channel's RSS feed URL is a 2-step process. Here's how to do it.
First of all, open any video of the YouTube channel you want the updates from. Right-click on it and click the View Page Source option from the context menu.
Now search for channelId in the page's source code to grab the channel ID.
Now use the following template to build the YouTube channel's RSS feed URL:
https://www.youtube.com/feeds/videos.xml?channel_id=CHANNEL_ID
As you can see, one has to append the channel ID at the end of this URL. Replace CHANNEL_ID with the actual one you've grabbed from the source code page.
Step 2: Create a Telegram Bot
Save the RSS feed URLs in a plain text file and move on to the next step to create a Telegram bot. This bot acts as bridge between Telegram and your code that leverages the platform's API for fetching and delivering updates. Let's see how we can make this bot.
- Open the Telegram application on your device and search for the
@BotFathermaster bot. - Click the START button or send the
/startcommand. - Send the
/newbotcommand and give a name to your bot. - Thereafter, provide a username for your bot. Make sure to append
botat the end of the username. - Copy the bot token and save it in a text file. It's a long and cryptic alphanumeric string as shown in the image above. This token will be used to access and use Telegram's HTTP API.
At this point, your Telegram bot is configured and ready for use.
Step 3: Get Your Telegram Chat ID
Next, you have to extract the chat ID from the interaction with the newly created bot. This chat ID instructs the API call where to push the updates on Telegram.
- Search for your bot by typing its username in the search box and open a chat session by selecting it from the search results.
- Now, either click the START button or send the
/startcommand. - Thereafter, send any test or dummy chat message.
- Now use the following URL:
https://api.telegram.org/bot<BOT_TOKEN>/getUpdatesand open it on your web browser. ReplaceBOT_TOKENwith the actual one you've grabbed in the previous section. - You'll get a JSON response in the browser tab. Search for
chat":{"id":CHAT_ID}in the JSON data and copy the chat ID saving it in a text editor.
Both chat ID and bot token will be used while writing the program to configure the entire setup.
Step 4: Write a Python Script to Monitor Feeds and Send Alerts
Now comes the most important part of writing a program that checks the RSS feeds and pushes the updates to the Telegram bot. I've written a custom script you can use as a template.
First of all, install the required libraries. I'm assuming you're on a Linux machine.
pip install requests feedparser
Thereafter, use the following Python script. Save it in a file and give an appropriate name to it. For example, push_updates_telegram.py is what I'll use as this script's file name.
#!/usr/bin/env python3
"""
Telegram RSS and YouTube Feed Bot
Monitors RSS feeds and YouTube channels, sending updates to Telegram chat every 5 minutes.
"""
import requests
import feedparser
import time
import json
import logging
from datetime import datetime, timezone
from typing import Set, Dict, List, Optional
import hashlib
import os
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('telegram_bot.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
class TelegramFeedBot:
def __init__(self, bot_token: str, chat_id: str):
"""
Initialize the Telegram Feed Bot
Args:
bot_token: Telegram bot token from BotFather
chat_id: Target chat ID where messages will be sent
"""
self.bot_token = bot_token
self.chat_id = chat_id
self.telegram_api_url = f"https://api.telegram.org/bot{bot_token}"
# Storage for tracking sent items
self.sent_items: Set[str] = set()
self.storage_file = "sent_items.json"
# RSS and YouTube feeds to monitor
self.rss_feeds: List[str] = []
self.youtube_channels: List[str] = []
# Load previously sent items
self.load_sent_items()
logger.info("Telegram Feed Bot initialized")
def add_rss_feed(self, feed_url: str):
"""Add an RSS feed to monitor"""
self.rss_feeds.append(feed_url)
logger.info(f"Added RSS feed: {feed_url}")
def add_youtube_channel(self, channel_id: str):
"""Add a YouTube channel to monitor (using RSS feed)"""
youtube_rss_url = f"https://www.youtube.com/feeds/videos.xml?channel_id={channel_id}"
self.youtube_channels.append(youtube_rss_url)
logger.info(f"Added YouTube channel: {channel_id}")
def load_sent_items(self):
"""Load previously sent items from storage"""
try:
if os.path.exists(self.storage_file):
with open(self.storage_file, 'r') as f:
data = json.load(f)
self.sent_items = set(data.get('sent_items', []))
logger.info(f"Loaded {len(self.sent_items)} previously sent items")
except Exception as e:
logger.error(f"Error loading sent items: {e}")
def save_sent_items(self):
"""Save sent items to storage"""
try:
data = {'sent_items': list(self.sent_items)}
with open(self.storage_file, 'w') as f:
json.dump(data, f)
except Exception as e:
logger.error(f"Error saving sent items: {e}")
def generate_item_id(self, item: Dict) -> str:
"""Generate unique ID for feed item"""
# Use link and title to create unique hash
content = f"{item.get('link', '')}{item.get('title', '')}"
return hashlib.md5(content.encode()).hexdigest()
def send_telegram_message(self, message: str, parse_mode: str = "HTML"):
"""Send a message to Telegram chat"""
url = f"{self.telegram_api_url}/sendMessage"
data = {
'chat_id': self.chat_id,
'text': message,
'parse_mode': parse_mode,
'disable_web_page_preview': False
}
try:
response = requests.post(url, data=data, timeout=10)
response.raise_for_status()
result = response.json()
if result.get('ok'):
logger.info("Message sent successfully")
return True
else:
logger.error(f"Telegram API error: {result}")
return False
except requests.exceptions.RequestException as e:
logger.error(f"Error sending message: {e}")
return False
def format_rss_message(self, item: Dict, feed_title: str = "") -> str:
"""Format RSS item as Telegram message"""
title = item.get('title', 'No title')
link = item.get('link', '')
published = item.get('published', '')
summary = item.get('summary', '')
# Clean up summary (remove HTML tags and limit length)
if summary:
import re
summary = re.sub('<[^<]+?>', '', summary) # Remove HTML tags
summary = summary.strip()
if len(summary) > 200:
summary = summary[:200] + "..."
# Format published date
pub_date = ""
if published:
try:
# Parse and format the date
from email.utils import parsedate_to_datetime
dt = parsedate_to_datetime(published)
pub_date = dt.strftime("%Y-%m-%d %H:%M")
except:
pub_date = published
# Create message
message = f"🔔 <b>New RSS Update</b>\n\n"
if feed_title:
message += f"📰 <b>Source:</b> {feed_title}\n"
message += f"📝 <b>Title:</b> {title}\n"
if pub_date:
message += f"📅 <b>Published:</b> {pub_date}\n"
if summary:
message += f"📄 <b>Summary:</b> {summary}\n"
message += f"🔗 <a href='{link}'>Read More</a>"
return message
def format_youtube_message(self, item: Dict) -> str:
"""Format YouTube item as Telegram message"""
title = item.get('title', 'No title')
link = item.get('link', '')
published = item.get('published', '')
author = item.get('author', '')
# Format published date
pub_date = ""
if published:
try:
from email.utils import parsedate_to_datetime
dt = parsedate_to_datetime(published)
pub_date = dt.strftime("%Y-%m-%d %H:%M")
except:
pub_date = published
# Create message
message = f"🎥 <b>New YouTube Video</b>\n\n"
if author:
message += f"👤 <b>Channel:</b> {author}\n"
message += f"📝 <b>Title:</b> {title}\n"
if pub_date:
message += f"📅 <b>Published:</b> {pub_date}\n"
message += f"🔗 <a href='{link}'>Watch Video</a>"
return message
def check_rss_feeds(self):
"""Check all RSS feeds for new items"""
new_items = []
for feed_url in self.rss_feeds:
try:
logger.info(f"Checking RSS feed: {feed_url}")
feed = feedparser.parse(feed_url)
if feed.bozo:
logger.warning(f"Feed parsing warning for {feed_url}: {feed.bozo_exception}")
feed_title = feed.feed.get('title', '')
for entry in feed.entries[:10]: # Check last 10 entries
item_id = self.generate_item_id(entry)
if item_id not in self.sent_items:
message = self.format_rss_message(entry, feed_title)
new_items.append((item_id, message))
except Exception as e:
logger.error(f"Error checking RSS feed {feed_url}: {e}")
return new_items
def check_youtube_feeds(self):
"""Check all YouTube channel feeds for new items"""
new_items = []
for youtube_feed in self.youtube_channels:
try:
logger.info(f"Checking YouTube feed: {youtube_feed}")
feed = feedparser.parse(youtube_feed)
if feed.bozo:
logger.warning(f"Feed parsing warning for {youtube_feed}: {feed.bozo_exception}")
for entry in feed.entries[:5]: # Check last 5 videos
item_id = self.generate_item_id(entry)
if item_id not in self.sent_items:
message = self.format_youtube_message(entry)
new_items.append((item_id, message))
except Exception as e:
logger.error(f"Error checking YouTube feed {youtube_feed}: {e}")
return new_items
def run_check_cycle(self):
"""Run one complete check cycle for all feeds"""
logger.info("Starting feed check cycle")
# Check RSS feeds
rss_items = self.check_rss_feeds()
# Check YouTube feeds
youtube_items = self.check_youtube_feeds()
# Combine all new items
all_new_items = rss_items + youtube_items
# Sort by timestamp if possible (newest first)
# For simplicity, we'll send in the order we found them
# Send messages for new items
sent_count = 0
for item_id, message in all_new_items:
if self.send_telegram_message(message):
self.sent_items.add(item_id)
sent_count += 1
time.sleep(1) # Small delay between messages
else:
logger.error("Failed to send message, stopping this cycle")
break
if sent_count > 0:
logger.info(f"Sent {sent_count} new updates")
self.save_sent_items()
else:
logger.info("No new updates found")
def run(self, check_interval: int = 300):
"""
Main loop - check feeds every specified interval
Args:
check_interval: Time between checks in seconds (default: 300 = 5 minutes)
"""
logger.info(f"Starting bot with {check_interval} second intervals")
logger.info(f"Monitoring {len(self.rss_feeds)} RSS feeds and {len(self.youtube_channels)} YouTube channels")
while True:
try:
self.run_check_cycle()
logger.info(f"Waiting {check_interval} seconds until next check...")
time.sleep(check_interval)
except KeyboardInterrupt:
logger.info("Bot stopped by user")
break
except Exception as e:
logger.error(f"Unexpected error in main loop: {e}")
logger.info("Waiting 60 seconds before retrying...")
time.sleep(60)
def main():
"""Main function to run the bot"""
# Configuration - Replace with your actual values
BOT_TOKEN = "YOUR_BOT_TOKEN_HERE" # Get from @BotFather
CHAT_ID = "YOUR_CHAT_ID_HERE" # Your chat ID or channel ID
if BOT_TOKEN == "YOUR_BOT_TOKEN_HERE" or CHAT_ID == "YOUR_CHAT_ID_HERE":
print("Please set your bot token and chat ID before running!")
print("To do that:")
print("1. Edit the BOT_TOKEN and CHAT_ID variables in this script")
return
# Create a bot instance
bot = TelegramFeedBot(BOT_TOKEN, CHAT_ID)
# Add your RSS feeds here
bot.add_rss_feed("ADD WEBSITE RSS FEED URL HERE")
bot.add_rss_feed("ADD YOUTUBE CHANNEL RSS FEED URL HERE")
# # You can also add YouTube channel ID here (uncomment to activate this function)
# bot.add_youtube_channel("ADD YOUTUBE CHANNEL ID HERE")
# Start the bot (checks every 5 minutes = 300 seconds)
bot.run(check_interval=300)
if __name__ == "__main__":
main()
In this script, assign the bot token and chat ID (saved earlier) to the variables mentioned below.
# Configuration - Replace with your actual values
BOT_TOKEN = "YOUR_BOT_TOKEN_HERE" # Get from @BotFather
CHAT_ID = "YOUR_CHAT_ID_HERE" # Your chat ID or channel ID
For adding RSS feed URLs, find the code shown below and update it with the feed URLs you prepared earlier in the first step.
bot.add_rss_feed("ADD WEBSITE RSS FEED URL HERE")
bot.add_rss_feed("ADD YOUTUBE CHANNEL RSS FEED URL HERE")
A YouTube channel can be added in two different ways. Either through the RSS feed URL as shown above or you can directly use the function given below by passing the channel ID as its argument.
bot.add_youtube_channel("ADD YOUTUBE CHANNEL ID HERE")
In the script, this function is commented out. If you want to use it, uncomment it and provide the channel ID you want to get the updates from.
python3 push_updates_telegram.py
On my Linux machine, to execute this script, I used the command given above. On your system, use the file name you have used for the script.
And here's how the update notifications looked (see above) within my Telegram app. I used my blog's RSS feed URL and BBC News YouTube channel as the source for getting updates notifications.
In this script, you can add multiple RSS feeds and multiple YouTube channels. The program will process all of them without any issues.
Step 5: Run as a Background Service (Optional)
If you want to run this script as a backgorund service that runs continuously on your Linux machine, you can do that too. We'll use the systemd service for the same.
1. Prepare Your Python Script
First of all, make sure your Python script file has the necessary file permissions.
sudo chmod +x /path/to/your/script.py
# In our case, the command will be:
sudo chmod +x ~/push_updates_telegram.py
2. Create a Systemd Service File
Create a service file in the /etc/systemd/system/ directory.
sudo nano /etc/systemd/system/your-service-name.service
# In our example, the command can be:
sudo nano /etc/systemd/system/telegram-rss-updates.service
Now add the following configuration to this file. In your case, make the necessary changes as per your setup and needs.
[Unit]
Description=Your Python Script Description
After=network.target
[Service]
Type=simple
User=your-username
WorkingDirectory=/path/to/your/script/directory
ExecStart=/usr/bin/python3 /path/to/your/script.py
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
In our example, the configuration would look something like this.
[Unit]
Description=Automatic RSS Updates to Telegram
After=network.target
[Service]
Type=simple
User=rajeevedmonds
WorkingDirectory=/home/rajeevedmonds
ExecStart=/usr/bin/python3 /home/rajeevedmonds/push_updates_telegram.py
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
Here's what these options mean:
- After=network.target: Start this service as soon as the network starts on the Linux machine.
- User: The username of the account under which this service will be executed. Do not use the
rootaccount for the same. - WorkingDirectory: Full path to the directory where the Python script resides.
- ExecStart: Full path of the Python executable and the script file.
- Restart: If the service crashes for some reason, automatically restart it.
- RestartSec: The number of seconds the service should wait before attempting a restart.
3. Enable and Start the Service
After saving the configuration file, it's time to activate the service. Here's how to do it.
# Reload systemd to recognize the new service
sudo systemctl daemon-reload
# Enable the service to start on boot
sudo systemctl enable your-service-name.service
# Start the service immediately
sudo systemctl start your-service-name.service
Make sure to make the necessary changes replacing the generic service name with the one you've given to your service.
Conclusion
With this setup, you’ve created your news and YouTube alert system using RSS and a free, fast messaging app called Telegram. It’s private, spam-free, and completely under your control.
This system is perfect for:
- Bloggers monitoring competitors
- Investors tracking financial news
- Fans who never want to miss a new video
- Developers building alert bots for clients
So, what are you waiting for? Go ahead and build your automated notification system, right now!