Не работают кнопки в чат-боте Telegram

Рейтинг: 2Ответов: 1Опубликовано: 15.06.2023

Написал чат-бот для telegram с помощью Python. Но столкнулся со следующей проблемой. Код работает только тогда, когда я ввожу команды по типу /start, /show_map и так далее. Но сами кнопки не работают, как это исправить?

import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import pyowm

def start(update, context):
    keyboard = [
        [telegram.KeyboardButton('Прогноз погоди')],
        [telegram.KeyboardButton('Про автора')],
        [telegram.KeyboardButton('Інформація про коледж')]
    ]
    reply_markup = telegram.ReplyKeyboardMarkup(keyboard)
    context.bot.send_message(chat_id=update.effective_chat.id, text='Вітаю! Виберіть опцію:', reply_markup=reply_markup)

def weather(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text='Вкажіть місто:')
    dp.add_handler(MessageHandler(Filters.text, get_weather))

def get_weather(update, context):
    city = update.message.text

    try:
        owm = pyowm.OWM('your-api-key')
        observation = owm.weather_at_place(city)
        w = observation.weather

        temperature = w.temperature('celsius')['temp']
        humidity = w.humidity

        message = f'Погода у місті {city}:\n\n' \
                  f'Температура: {temperature}°C\n' \
                  f'Вологість: {humidity}%'

        context.bot.send_message(chat_id=update.effective_chat.id, text=message)
    except pyowm.exceptions.APIResponseError:
        context.bot.send_message(chat_id=update.effective_chat.id, text='Помилка отримання погоди')

def author(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text='Студент КН-4')

def college_info(update, context):
    keyboard = [
        [telegram.KeyboardButton('Графік роботи')],
        [telegram.KeyboardButton('Показати на карті')],
        [telegram.KeyboardButton('Телефон для зв\'язку')],
        [telegram.KeyboardButton('Перейти на сайт')],
        [telegram.KeyboardButton('Відділення коледжу')]
    ]
    reply_markup = telegram.ReplyKeyboardMarkup(keyboard)
    context.bot.send_message(chat_id=update.effective_chat.id, text='Вас вітає коледж ЛФКХПП НУХТ', reply_markup=reply_markup)

def working_hours(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text='Пн-Пт. з 9:00-17:00')

def show_map(update, context):
    context.bot.send_photo(chat_id=update.effective_chat.id, photo=open('map.jpg', 'rb'))

def contact_phone(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text='Приймальна: +380984949499')

def visit_website(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text='https://example.com')

def college_departments(update, context):
    keyboard = [
        [telegram.KeyboardButton('Економіко-технологічне')],
        [telegram.KeyboardButton('Готельно-ресторанна справа')],
        [telegram.KeyboardButton('Механіко-технологічне')],
        [telegram.KeyboardButton('Заочне')]
    ]
    reply_markup = telegram.ReplyKeyboardMarkup(keyboard)
    context.bot.send_message(chat_id=update.effective_chat.id, text='Виберіть відділення:', reply_markup=reply_markup)

def department_info(update, context):
    department = update.message.text

    if department == 'Економіко-технологічне':
        context.bot.send_message(chat_id=update.effective_chat.id, text='Голова відділення: +380123456789')
    elif department == 'Готельно-ресторанна справа':
        context.bot.send_message(chat_id=update.effective_chat.id, text='Голова відділення: +380987654321')
    elif department == 'Механіко-технологічне':
        context.bot.send_message(chat_id=update.effective_chat.id, text='Голова відділення: +380111111111')
    elif department == 'Заочне':
        context.bot.send_message(chat_id=update.effective_chat.id, text='Голова відділення: +380222222222')

def main_menu(update, context):
    start(update, context)

bot_token = 'YOUR_BOT_TOKEN'
bot = telegram.Bot(token=bot_token)
updater = Updater(token=bot_token, use_context=True)
dp = updater.dispatcher

dp.add_handler(CommandHandler('start', start))
dp.add_handler(CommandHandler('weather', weather))
dp.add_handler(CommandHandler('author', author))
dp.add_handler(CommandHandler('college_info', college_info))
dp.add_handler(CommandHandler('working_hours', working_hours))
dp.add_handler(CommandHandler('show_map', show_map))
dp.add_handler(CommandHandler('contact_phone', contact_phone))
dp.add_handler(CommandHandler('visit_website', visit_website))
dp.add_handler(CommandHandler('college_departments', college_departments))
dp.add_handler(CommandHandler('department_info', department_info))
dp.add_handler(CommandHandler('main_menu', main_menu))

updater.start_polling()
updater.idle()

Для большего понимаю добавляю скрин примера кнопок: Пример кнопок

Ответы

▲ 2Принят

Импортируйте CallbackQueryHandler из модуля telegram.ext:

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler

Измените функцию start так, чтобы она отправляла кнопки с использованием ReplyKeyboardMarkup и добавьте обработчик для кнопок:

    def start(update, context):
        keyboard = [
            [telegram.KeyboardButton('Прогноз погоди')],
            [telegram.KeyboardButton('Про автора')],
            [telegram.KeyboardButton('Інформація про коледж')]
        ]
        reply_markup = telegram.ReplyKeyboardMarkup(keyboard)
        context.bot.send_message(chat_id=update.effective_chat.id, text='Вітаю! Виберіть опцію:', reply_markup=reply_markup)
    
        # Добавляем обработчик для кнопок
        dp.add_handler(CallbackQueryHandler(button_handler))
    
    def button_handler(update, context):
        query = update.callback_query
        data = query.data
    
        if data == 'Прогноз погоди':
            weather(update, context)
        elif data == 'Про автора':
            author(update, context)
        elif data == 'Інформація про коледж':
            college_info(update, context)

Измените функцию college_info так, чтобы она отправляла кнопки с использованием ReplyKeyboardMarkup и добавьте обработчик для кнопок:

def college_info(update, context):
    keyboard = [
        [telegram.KeyboardButton('Графік роботи')],
        [telegram.KeyboardButton('Показати на карті')],
        [telegram.KeyboardButton('Телефон для зв\'язку')],
        [telegram.KeyboardButton('Перейти на сайт')],
        [telegram.KeyboardButton('Відділення коледжу')]
    ]
    reply_markup = telegram.ReplyKeyboardMarkup(keyboard)
    context.bot.send_message(chat_id=update.effective_chat.id, text='Вас вітає коледж ЛФКХПП НУХТ', reply_markup=reply_markup)

    # Добавляем обработчик для кнопок
    dp.add_handler(CallbackQueryHandler(button_handler))

def button_handler(update, context):
    query = update.callback_query
    data = query.data

    if data == 'Графік роботи':
        working_hours(update, context)
    elif data == 'Показати на карті':
        show_map(update, context)
    elif data == 'Телефон для зв\'язку':
        contact_phone(update, context)
    elif data == 'Перейти на сайт':
        visit_website(update, context)
    elif data == 'Відділення коледжу':
        college_departments(update, context)

Удалите функцию main_menu, так как она больше не нужна.