0

Я начала изучать создание чат-ботов в телеграме на Python с помощью библиотеки pyTelegramBotAPI. Хочу создать бота, который будет записывать пользователя на приём и сохранять в Google calendar. Пробовала использовать этот код https://github.com/grcanosa/telegram-calendar-keyboard, но ничего не работает.

Вот этот код у меня не работает, потому что здесь используется библиотека python-telegram-bot:

import logging
import telegramcalendar

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)

def calendar_handler(bot,update):
    update.message.reply_text("Please select a date: ",
                        reply_markup=telegramcalendar.create_calendar())


def inline_handler(bot,update):
    selected,date = telegramcalendar.process_calendar_selection(bot, update)
    if selected:
        bot.send_message(chat_id=update.callback_query.from_user.id,
                        text="You selected %s" % (date.strftime("%d/%m/%Y")),
                        reply_markup=ReplyKeyboardRemove())

telegramcalendar.py

import datetime
import calendar

def create_callback_data(action,year,month,day):
    """ Create the callback data associated to each button"""
    return ";".join([action,str(year),str(month),str(day)])

def separate_callback_data(data):
    """ Separate the callback data"""
    return data.split(";")


def create_calendar(year=None,month=None):
    """
    Create an inline keyboard with the provided year and month
    :param int year: Year to use in the calendar, if None the current year is used.
    :param int month: Month to use in the calendar, if None the current month is used.
    :return: Returns the InlineKeyboardMarkup object with the calendar.
    """
    now = datetime.datetime.now()
    if year == None: year = now.year
    if month == None: month = now.month
    data_ignore = create_callback_data("IGNORE", year, month, 0)
    keyboard = []
    #First row - Month and Year
    row=[]
    row.append(InlineKeyboardButton(calendar.month_name[month]+" "+str(year),callback_data=data_ignore))
    keyboard.append(row)
    #Second row - Week Days
    row=[]
    for day in ["Mo","Tu","We","Th","Fr","Sa","Su"]:
        row.append(InlineKeyboardButton(day,callback_data=data_ignore))
    keyboard.append(row)

    my_calendar = calendar.monthcalendar(year, month)
    for week in my_calendar:
        row=[]
        for day in week:
            if(day==0):
                row.append(InlineKeyboardButton(" ",callback_data=data_ignore))
            else:
                row.append(InlineKeyboardButton(str(day),callback_data=create_callback_data("DAY",year,month,day)))
        keyboard.append(row)
    #Last row - Buttons
    row=[]
    row.append(InlineKeyboardButton("<",callback_data=create_callback_data("PREV-MONTH",year,month,day)))
    row.append(InlineKeyboardButton(" ",callback_data=data_ignore))
    row.append(InlineKeyboardButton(">",callback_data=create_callback_data("NEXT-MONTH",year,month,day)))
    keyboard.append(row)

    return InlineKeyboardMarkup(keyboard)


def process_calendar_selection(bot,update):
    """
    Process the callback_query. This method generates a new calendar if forward or
    backward is pressed. This method should be called inside a CallbackQueryHandler.
    :param telegram.Bot bot: The bot, as provided by the CallbackQueryHandler
    :param telegram.Update update: The update, as provided by the CallbackQueryHandler
    :return: Returns a tuple (Boolean,datetime.datetime), indicating if a date is selected
                and returning the date if so.
    """
    ret_data = (False,None)
    query = update.callback_query
    (action,year,month,day) = separate_callback_data(query.data)
    curr = datetime.datetime(int(year), int(month), 1)
    if action == "IGNORE":
        bot.answer_callback_query(callback_query_id= query.id)
    elif action == "DAY":
        bot.edit_message_text(text=query.message.text,
            chat_id=query.message.chat_id,
            message_id=query.message.message_id
            )
        ret_data = True,datetime.datetime(int(year),int(month),int(day))
    elif action == "PREV-MONTH":
        pre = curr - datetime.timedelta(days=1)
        bot.edit_message_text(text=query.message.text,
            chat_id=query.message.chat_id,
            message_id=query.message.message_id,
            reply_markup=create_calendar(int(pre.year),int(pre.month)))
    elif action == "NEXT-MONTH":
        ne = curr + datetime.timedelta(days=31)
        bot.edit_message_text(text=query.message.text,
            chat_id=query.message.chat_id,
            message_id=query.message.message_id,
            reply_markup=create_calendar(int(ne.year),int(ne.month)))
    else:
        bot.answer_callback_query(callback_query_id= query.id,text="Something went wrong!")
        # UNKNOWN
    return ret_data

Выводит такую ошибку: 2020-09-02 13:36:57,852 - requests.packages.urllib3.connectionpool - INFO - Starting new HTTPS connection (1): api.telegram.org

Приведите, пожалуйста, пример кода для библиотеки pyTelegramBotAPI.

6
  • 1
    Приведите код, который "не работает", в текстовом виде, а не по ссылке. И укажите возникающие ошибки
    – dIm0n
    2 сен 2020 в 10:06
  • В 2020-09-02 13:36:57,852 нет ошибки, там даже серьезность лога INFO
    – gil9red
    2 сен 2020 в 10:44
  • А почему тогда бот никак не реагирует на запуск? Извините за столько тупые вопросы, я только учусь
    – Julieta
    2 сен 2020 в 10:52
  • Не извиняйтесь. А вы бота запустили? В коде из вопроса не вижу его запуска
    – gil9red
    2 сен 2020 в 10:53
  • Да, использовала: import telebot from telebot import types TOKEN = ' ' bot = telebot.TeleBot(TOKEN)
    – Julieta
    2 сен 2020 в 10:56

1 ответ 1

0

В вопросе было несколько проблем:

  • Бот не был запущен start_polling() + idle()
  • Код примера библиотеки устарел, в обработчиках вместо (bot, update) теперь используется (update, context)

Переписывание кода с одной библиотеки на другую, мне кажется, неблагодарным делом (тем более, считаю, что библиотеки не сильно отличаются), поэтому предлагаю показать решение для родной библиотеки того модуля.

Пример:

# pip install python-telegram-bot
from telegram import Update, ReplyKeyboardRemove
from telegram.ext import Updater, CommandHandler, CallbackContext, CallbackQueryHandler

import telegramcalendar

import config


def on_calendar(update: Update, context: CallbackContext):
    update.message.reply_text(
        "Please select a date: ",
        reply_markup=telegramcalendar.create_calendar()
    )


def on_callback_query(update: Update, context: CallbackContext):
    query = update.callback_query
    query.answer()

    bot = context.bot

    selected, date = telegramcalendar.process_calendar_selection(bot, update)
    if selected:
        query.message.reply_text(
            text="You selected %s" % (date.strftime("%d/%m/%Y")),
            reply_markup=ReplyKeyboardRemove()
        )


def main():
    updater = Updater(
        config.TOKEN,
        use_context=True
    )

    dp = updater.dispatcher

    dp.add_handler(CommandHandler('calendar', on_calendar))
    dp.add_handler(CallbackQueryHandler(on_callback_query))

    updater.start_polling()

    updater.idle()


if __name__ == '__main__':
    main()

PS.

Пример в ответе очень простой, учебный, а тут пример боевой -- обработка ошибок, логирование запросов, многопоточное выполнение команд.


Скриншот (вызов команды календаря и выбор даты (после нее календарь пропадает)):

введите сюда описание изображения

3
  • Применила ваш код, команда /calendar сработала, пришло смс с календарём, но нажимаю на любую из кнопок и бот молчит, нет ошибок, просто ничего не происходит. В чём может быть проблема?
    – Julieta
    2 сен 2020 в 11:28
  • И ещё вопрос, в примере на github вы используете: from common import get_logger, log_func, я установила common (pip install common), но мне выводит ошибку: ImportError: cannot import name 'get_logger' from 'common'. Нужно установить ещё что-то дополнительно?
    – Julieta
    2 сен 2020 в 12:09
  • Скорее всего вы не добавили обработчик CallbackQueryHandler, именно он ловит нажатия на кнопки. Насчет common.py, не думал, что вы его будете использовать :) Смотрите, common.py и config.py являются моими скриптами и они находятся в папке выше, поэтому в коде есть строка с sys.path.append для добавления папки с теми скриптами. В вашем случае, эти скрипты нужно скопировать в папку с ботом и убрать sys.path.append
    – gil9red
    2 сен 2020 в 12:26

Ваш ответ

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

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