Выберите две даты с помощью клавиатуры календаря Python Telegram Bot - PullRequest
0 голосов
/ 12 декабря 2018

Мне нужен бот-телеграмма, который позволяет мне выбрать две даты после выбора имени.Это мой код, я новичок в этом, я надеюсь, вы можете помочь мне, я использую его python-telegram-bot

Проблема с кодом заключается в том, что он позволяет тольковыбрать первую дату, а затем календарь исчезнет.

Мой код основан на https://github.com/grcanosa/telegram-calendar-keyboard

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler,ConversationHandler
from telegram.ext import CallbackQueryHandler
from telegram import ReplyKeyboardRemove
import telegramcalendar

FIRST, SECOND = range(2)

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

def calendar_handler(bot,update):
    query = update.callback_query
    reply_markup=telegramcalendar.create_calendar()

    bot.edit_message_text(
        chat_id=query.message.chat_id,
        message_id=query.message.message_id,
        text=u"Choose First date"
    )

    bot.edit_message_reply_markup(
        chat_id=query.message.chat_id,
        message_id=query.message.message_id,
        reply_markup=reply_markup
    )
    selected,date = telegramcalendar.process_calendar_selection(bot, update)
    if selected:
        bot.send_message(chat_id=update.callback_query.from_user.id,
                    text="Date: %s" % (date.strftime("%Y-%m-%d")))
        return SECOND

def calendar_handler1(bot,update):
    query = update.callback_query
    reply_markup=telegramcalendar.create_calendar()

    bot.edit_message_text(
        chat_id=query.message.chat_id,
        message_id=query.message.message_id,
        text=u"Choose second date"
    )
    bot.edit_message_reply_markup(
        chat_id=query.message.chat_id,
        message_id=query.message.message_id,
        reply_markup=reply_markup
    )
    selected1,date = telegramcalendar.process_calendar_selection(bot, update)
    if selected1:
        bot.send_message(chat_id=update.callback_query.from_user.id,
                    text="Other date: %s" % (date.strftime("%Y-%m-%d")))

def start(bot, update):
    keyboard = [[InlineKeyboardButton("Name1", callback_data='1'),
             InlineKeyboardButton("Name2", callback_data='2')]]
    reply_markup = InlineKeyboardMarkup(keyboard)
    update.message.reply_text('Choose:', reply_markup=reply_markup)
    return FIRST

def main():
    updater = Updater("TOKEN")
    conv_handler = ConversationHandler(
        entry_points=[CommandHandler('start', start)],
        states={
            FIRST: [CallbackQueryHandler(calendar_handler)],
            SECOND: [CallbackQueryHandler(calendar_handler1)]
        },
        fallbacks=[CommandHandler('start', start)]
    )
    updater.dispatcher.add_handler(conv_handler)

    # Start the Bot
    updater.start_polling()

    # Run the bot until the user presses Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT
    updater.idle()


if __name__ == '__main__':
   main()

1 Ответ

0 голосов
/ 13 декабря 2018

Это не лучший ответ, но он работает для меня.

import logging
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler,ConversationHandler
from telegram.ext import CallbackQueryHandler
from telegram import ReplyKeyboardRemove
import telegramcalendar

CANTIDAD,FECHA1,FECHA2 = range(3)

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

def calendar_handler(bot,update):
    query = update.callback_query
    reply_markup=telegramcalendar.create_calendar()

    bot.edit_message_text(
        chat_id=query.message.chat_id,
        message_id=query.message.message_id,
        text=u"Escoja una fecha inicial para reporte: "
    )
    bot.edit_message_reply_markup(
        chat_id=query.message.chat_id,
        message_id=query.message.message_id,
        reply_markup=reply_markup
    )
    selected=0
    try:
        selected,date = telegramcalendar.process_calendar_selection(bot, update)
    except:
        pass

    if selected:
        bot.edit_message_text(
            chat_id=query.message.chat_id,
            message_id=query.message.message_id,
            text="Fecha Inicial de reporte: %s \nPor favor escoja la fecha final de reporte: " % (date.strftime("%Y-%m-%d"))
        )
        bot.edit_message_reply_markup(
            chat_id=query.message.chat_id,
            message_id=query.message.message_id,
            reply_markup=reply_markup
        )
    return FECHA2


def calendar_handler1(bot,update):
    query = update.callback_query
    reply_markup=telegramcalendar.create_calendar()

    bot.edit_message_text(
        chat_id=query.message.chat_id,
        message_id=query.message.message_id,
        text=u"Escoja una fecha final para el analisis"
    )
    bot.edit_message_reply_markup(
        chat_id=query.message.chat_id,
        message_id=query.message.message_id,
        reply_markup=reply_markup
    )
    selected,date = telegramcalendar.process_calendar_selection(bot, update)
    if selected:
        bot.send_message(chat_id=update.callback_query.from_user.id,
                    text="Fecha Final de analisis: %s\n Espere mientras le entregamos su reporte..." % (date.strftime("%Y-%m-%d")),
                    reply_markup=ReplyKeyboardRemove())

def cantidad(bot, update):
    query = update.callback_query
    keyboard = [[InlineKeyboardButton("5", callback_data='5'),
             InlineKeyboardButton("10", callback_data='10'),
             InlineKeyboardButton("15", callback_data='15'),
             InlineKeyboardButton("20", callback_data='20'),
             InlineKeyboardButton("25", callback_data='25'),
             InlineKeyboardButton("30", callback_data='30'),]]
    reply_markup = InlineKeyboardMarkup(keyboard)
    bot.edit_message_text(
        chat_id=query.message.chat_id,
        message_id=query.message.message_id,
        text=u"Escoja la cantidad de datos que desea reflejados en el reporte"
    )
    bot.edit_message_reply_markup(
        chat_id=query.message.chat_id,
        message_id=query.message.message_id,
        reply_markup=reply_markup
    )
    return FECHA1

def fecha_final_func(bot, update):
    query = update.callback_query
    bot.edit_message_text(
        chat_id=query.message.chat_id,
        message_id=query.message.message_id,
        text=u"Escoger fecha final"
    )

def start(bot, update):
    keyboard = [[InlineKeyboardButton("Name1", callback_data='1'),
             InlineKeyboardButton("Name2", callback_data='2')]]
    reply_markup = InlineKeyboardMarkup(keyboard)
    update.message.reply_text('Escoja:', reply_markup=reply_markup)
    return CANTIDAD

def help(bot, update):
    update.message.reply_text("Use /start to test this bot.")

def error(bot, update, error):
    """Log Errors caused by Updates."""
    logger.warning('Update "%s" caused error "%s"', update, error)

def main():
    # Create the Updater and pass it your bot's token.
    updater = Updater("TOKEN")
    conv_handler = ConversationHandler(
        entry_points=[CommandHandler('start', start)],
        states={
            CANTIDAD: [CallbackQueryHandler(cantidad)],
            FECHA1: [CallbackQueryHandler(calendar_handler)],
            FECHA2: [CallbackQueryHandler(calendar_handler1)]
        },
        fallbacks=[CommandHandler('start', start)]
    )
    updater.dispatcher.add_handler(conv_handler)

    # Start the Bot
    updater.start_polling()

    # Run the bot until the user presses Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT
    updater.idle()

if __name__ == '__main__':
    main()
...