1

Всем привет! Я пишу Telegram бота с помощью библиотеки Telebot. Бот должен запрашивать у пользователя команду /report и предлагать на выбор с помощью кнопок два отчета, которые потом будут созданы с помощью уже существующего скрипта. С этой частью кода проблем не возникло:

@bot.message_handler(commands=['report'])  
def exchange_command(message):  
    keyboard = telebot.types.InlineKeyboardMarkup()  
    keyboard.row(  
        telebot.types.InlineKeyboardButton('Отчет ЕДДС',                     callback_data='get-EDDS'),  
        telebot.types.InlineKeyboardButton('Еженедельный отчет',             callback_data='get-daily_report')  
    )  
    bot.send_message(  
        message.chat.id,   
        'Выберите интересующий вас отчет:',  
        reply_markup=keyboard)  

Далее бот должен предложить выбрать дату отчета. Вот здесь у меня возникают проблемы. Проблемы, видимо, из-за слабого понимания работы библиотеки telebot. Я решил использовать, разработанный FlymeDllVa модуль telebot-calendar. К моему сожалению, у него нет примера с созданием клавиатуры календаря через @bot.callback_query_handler(func=lambda call: True). Вот пример, моих мучений:

@bot.callback_query_handler(func=lambda call: True)
def callback_inline(call):
    if call.message:
        if call.data == "get-EDDS":
            global a
            a = 1
            now = datetime.datetime.now()
            users_calendar_dates[message.chat.id] = (now.year,                                                            now.month)

Объясните нубу как после запроса типа отчета вывести клавиатуру с выбором календаря!

1 ответ 1

2

Я обновил библиотеку. Теперь её будет удобнее использовать. Пример кода для вашего случая ниже.

import logging
import datetime

import telebot
import telebot_calendar
from telebot_calendar import CallbackData

from telebot.types import ReplyKeyboardRemove, CallbackQuery

API_TOKEN = "token"
logger = telebot.logger
telebot.logger.setLevel(logging.DEBUG)

bot = telebot.TeleBot(API_TOKEN)

# Creates a unique calendar
calendar_1 = CallbackData("calendar_1", "action", "year", "month", "day")


@bot.message_handler(commands=["report"])
def exchange_command(message):
    keyboard = telebot.types.InlineKeyboardMarkup()
    keyboard.row(
        telebot.types.InlineKeyboardButton("Отчет ЕДДС", callback_data="get-EDDS"),
        telebot.types.InlineKeyboardButton(
            "Еженедельный отчет", callback_data="get-daily_report"
        ),
    )
    bot.send_message(
        message.chat.id, "Выберите интересующий вас отчет:", reply_markup=keyboard
    )


@bot.callback_query_handler(func=lambda call: call.data.startswith(calendar_1.prefix))
def callback_inline(call: CallbackQuery):
    """
    Processing inline callback requests for a calendar

    :param call:
    :return:
    """

    # At this point, we are sure that this calendar is ours. So we cut the line by the separator of our calendar
    name, action, year, month, day = call.data.split(calendar_1.sep)
    # Processing the calendar. Get either the date or None if the buttons are of a different type
    date = telebot_calendar.calendar_query_handler(
        bot=bot, call=call, name=name, action=action, year=year, month=month, day=day
    )
    # There are additional steps. Let's say if the date DAY is selected, you can execute your code. I sent a message.
    if action == "DAY":
        bot.send_message(
            chat_id=call.from_user.id,
            text=f"You have chosen {date.strftime('%d.%m.%Y')}",
            reply_markup=ReplyKeyboardRemove(),
        )
        print(f"{calendar_1}: Day: {date.strftime('%d.%m.%Y')}")
    elif action == "CANCEL":
        bot.send_message(
            chat_id=call.from_user.id,
            text="Cancellation",
            reply_markup=ReplyKeyboardRemove(),
        )
        print(f"{calendar_1}: Cancellation")


@bot.callback_query_handler(func=lambda call: call.data.startswith("get-EDDS"))
def callback_inline(call: CallbackQuery):
    """
    Processing inline callback requests for keyboard response

    :param call:
    :return:
    """

    if call.data == "get-EDDS":
        now = datetime.datetime.now()  # Get the current date
        bot.edit_message_text(
            chat_id=call.message.chat.id,
            message_id=call.message.message_id,
            text="Selected date",
            reply_markup=telebot_calendar.create_calendar(
                name=calendar_1.prefix, # Specify the NAME of your calendar
                year=now.year,
                month=now.month,
            ),
        )


bot.polling(none_stop=True)

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.