from telegram.ext import Application, CommandHandler, CallbackContext
from telegram import Update
import requests
from bs4 import BeautifulSoup
import time
import logging
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
# Telegram Bot Token
TELEGRAM_BOT_TOKEN = '777'
# List of YouTube channel IDs to monitor
CHANNEL_IDS = ['777', 'CHANNEL_ID_2', 'CHANNEL_ID_3']
# Dictionary to keep track of the latest video ID per channel
latest_videos = {}
async def start(update: Update, context: CallbackContext):
await update.message.reply_text('Привет! Я буду оповещать тебя о новых видео с выбранных тобой каналов.')
def check_new_videos(context: CallbackContext):
for channel_id in CHANNEL_IDS:
url = f'https://www.youtube.com/feeds/videos.xml?channel_id={channel_id}'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'xml')
entry = soup.find('entry')
if entry:
video_id = entry.find('yt:videoId').text
# Check if this video is not the latest one we know about
if latest_videos.get(channel_id) != video_id:
latest_videos[channel_id] = video_id
video_title = entry.find('title').text
message = f'Новое видео: {video_title}nСсылка: https://www.youtube.com/watch?v={video_id}'
context.bot.send_message(chat_id=context.job.context, text=message)
time.sleep(1) # Sleep for a bit to avoid rate limiting
async def subscribe(update: Update, context: CallbackContext):
chat_id = update.message.chat_id
context.job_queue.run_repeating(check_new_videos, interval=5, first=0, chat_id=chat_id)
await update.message.reply_text('Вы подписались на уведомления о новых видео.')
if __name__ == '__main__':
application = Application.builder().token(TELEGRAM_BOT_TOKEN).build()
# Commands
application.add_handler(CommandHandler('start', start))
application.add_handler(CommandHandler('subscribe', subscribe))
# Run bot
application.run_polling()