python - 使用日历键盘选择两个日期 Python Telegram Bot

标签 python python-telegram-bot

我需要一个电报机器人,它允许我在选择名称后选择两个日期。这是我的代码,我是新手,希望你能帮助我,我正在使用它 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()

最佳答案

这不是最好的答案,但它对我有用。

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()

关于python - 使用日历键盘选择两个日期 Python Telegram Bot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53748593/

相关文章:

django - Telegram BOT 电子书发送空 POST

python - 在某些消息电报机器人之后保存用户输入

python - 如何在 python-telegram-api 的 ConversationHandler 中管理当前状态

Python 笛卡尔积

GPIO 引脚的 Python 代码正在重新调整错误 NameError : name 'n' is not defined

python - 在Eve中,如何安全地存储用户的密码?

python - 企业社会责任矩阵构建缓慢

对象上的 Python itertools 组合

telegram - 如何在 Telegram/开始时回显消息?

python - Telegram 定时响应