@RoSHkam

Почему не работает код telegram для уведомления о новых видео в python?

Помогите пожалуйста. У меня есть такой код
Код
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()
и вот такая ошибка в консоли у меня
Текст ошибки
Traceback (most recent call last):
File "C:\Users\Game Station\AppData\Roaming\Python\Python312\site-packages\telegram\ext\_jobqueue.py", line 829, in getattr
return getattr(self.job, item)
^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Job' object has no attribute 'context'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:\Users\Game Station\AppData\Roaming\Python\Python312\site-packages\telegram\ext\_jobqueue.py", line 958, in _run
await self.callback(context)
^^^^^^^^^^^^^^^^^^^^^^
File "D:\OSPanel\domains\opentao\youtubeNotifications.py", line 39, in check_new_videos
context.bot.send_message(chat_id=context.job.context, text=message)
^^^^^^^^^^^^^^^^^^^
File "C:\Users\Game Station\AppData\Roaming\Python\Python312\site-packages\telegram\ext\_jobqueue.py", line 831, in getattr
raise AttributeError(
AttributeError: Neither 'telegram.ext.Job' nor 'apscheduler.job.Job' has attribute 'context'

Я не сильно силён в Пайтон и начал его пока только изучать, и поэтому этот код я сделал благодаря ChatGPT.
  • Вопрос задан
  • 119 просмотров
Пригласить эксперта
Ответы на вопрос 1
@Everything_is_bad
PS: И да, этот код я сделал благодаря Chat-GPT 4 Turbo
вот его и проси исправить
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы