@FILMANS

AttributeError: 'Bot' object has no attribute 'dispatcher' Как исправить?

Сам код:
import telegram
from telegram.ext import *
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

# replace with your bot's API token
TOKEN = 'ТОКЕН'

# replace with your Spotify API credentials
SPOTIFY_CLIENT_ID = 'SPOTIFY_CLIENT_ID'
SPOTIFY_CLIENT_SECRET = 'SPOTIFY_CLIENT_SECRET'

# set up the Spotify API client
spotify = spotipy.Spotify(
    client_credentials_manager=SpotifyClientCredentials(
        client_id=SPOTIFY_CLIENT_ID,
        client_secret=SPOTIFY_CLIENT_SECRET
    )
)

# create a Telegram bot object
bot = telegram.Bot(token=TOKEN)

# define a command handler that sends a welcome message to the user
def start(update, context):
    message = 'Hi there! Send me the name of a song, and I\'ll search for it on Spotify and send you an audio file.'
    context.bot.send_message(chat_id=update.effective_chat.id, text=message)

# define a message handler that searches for music and sends an audio file to the user
def search_music(update, context):
    # get the name of the song from the user's message
    query = update.message.text

    # send a "looking for" message to let the user know the bot is searching
    context.bot.send_message(chat_id=update.effective_chat.id, text=f'Looking for "{query}"...')

    # search for the song on Spotify
    results = spotify.search(q=query, type='track', limit=1)

    # get the audio file for the top result and send it to the user
    if len(results['tracks']['items']) > 0:
        track = results['tracks']['items'][0]
        audio_file = track['preview_url']
        context.bot.send_audio(chat_id=update.effective_chat.id, audio=audio_file)
    else:
        context.bot.send_message(chat_id=update.effective_chat.id, text=f'Sorry, I couldn\'t find "{query}".')

# create a command handler and a message handler, and add them to the bot's dispatcher
dispatcher = bot.dispatcher
dispatcher.add_handler(CommandHandler('start', start))
dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, search_music))

# start the bot
bot.polling()


Выходит такая ошибка при запуске:
Traceback (most recent call last):
  File "d:\Видео, проекты\Новая папка\boy.py", line 49, in <module>
    dispatcher = bot.dispatcher
                 ^^^^^^^^^^^^^^
AttributeError: 'Bot' object has no attribute 'dispatcher'


Подскажите, как исправить.
  • Вопрос задан
  • 1073 просмотра
Решения вопроса 1
@5465
Ошибка говорит о том, что у объекта Bot нет атрибута dispatcher. Это происходит потому, что вы используете устаревший способ добавления обработчиков команд и сообщений.

Вместо bot.dispatcher используйте Updater из telegram.ext, чтобы обрабатывать входящие сообщения и команды.

Вот исправленный код:

import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

# replace with your bot's API token
TOKEN = 'ТОКЕН'

# replace with your Spotify API credentials
SPOTIFY_CLIENT_ID = 'SPOTIFY_CLIENT_ID'
SPOTIFY_CLIENT_SECRET = 'SPOTIFY_CLIENT_SECRET'

# set up the Spotify API client
spotify = spotipy.Spotify(
    client_credentials_manager=SpotifyClientCredentials(
        client_id=SPOTIFY_CLIENT_ID,
        client_secret=SPOTIFY_CLIENT_SECRET
    )
)

# define a command handler that sends a welcome message to the user
def start(update, context):
    message = 'Hi there! Send me the name of a song, and I\'ll search for it on Spotify and send you an audio file.'
    context.bot.send_message(chat_id=update.effective_chat.id, text=message)

# define a message handler that searches for music and sends an audio file to the user
def search_music(update, context):
    # get the name of the song from the user's message
    query = update.message.text

    # send a "looking for" message to let the user know the bot is searching
    context.bot.send_message(chat_id=update.effective_chat.id, text=f'Looking for "{query}"...')

    # search for the song on Spotify
    results = spotify.search(q=query, type='track', limit=1)

    # get the audio file for the top result and send it to the user
    if len(results['tracks']['items']) > 0:
        track = results['tracks']['items'][0]
        audio_file = track['preview_url']
        context.bot.send_audio(chat_id=update.effective_chat.id, audio=audio_file)
    else:
        context.bot.send_message(chat_id=update.effective_chat.id, text=f'Sorry, I couldn\'t find "{query}".')

# create an Updater object and add the handlers to it
updater = Updater(token=TOKEN, use_context=True)
dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler('start', start))
dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, search_music))

# start the bot
updater.start_polling()


Этот код должен работать правильно.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

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

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