2016-07-19 6 views
3

현재 저는 파이썬 API를 사용하여 전보 봇을 연구하고 있습니다. 이 예제는 여기 https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/conversationbot.py을 사용하고 있습니다. 이 예제를 사용하면 봇에게 시간 초과 응답을 보내고 싶습니다.전보 시간 응답

예를 들어 사용자가 30 초 이내에 응답하지 않으면 "아직 메시지가 있습니까?"또는 뭔가를 보내고 1 분 후에 대화를 끝내십시오. 이런 식으로 구현하려는 이유는 응답이 없으면 대화가 닫히지 않기 때문입니다. 내가 그 대본을 끝낼 때까지는 그 상태에 있습니다. 따라서 사용자는 처음부터 명령을 보내거나 시작할 수 없습니다. 나는 이것을 https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/ext/conversationhandler.py allow_reentry를 활성화 할 수있는 곳에서 찾을 수있었습니다. 내가 한 일은 사용자가 명령/시작을 사용하여 계속해서 새로운 컨버전스를 시작할 수있는 문제를 해결합니다. 그러나 나는 여전히 일정한 시간이 지난 후에 대화를 끝내기를 원합니다. 대화를 끝내려면 ConversationHandler를 반환해야합니다 .END

while 루프는 매번 2의 time.sleep를 사용하여 9에서 카운트 다운을 시도했습니다. 그것과 함께 응답을 읽습니다. update.message.text하지만 반환 명령을 사용하여 반환하지 않는 한 그것은 스크립트에서 결코 전진 할 수 없다는 것을 의미하는/start라는 명령 만 읽습니다. 그러나 내가 말할 수있는 방법을 찾을 수는 없습니다. 사용자가 성별을 선택하면 성별을 반환합니다.

그럼 타이머 기반 응답을 어떻게 구현합니까? 당신은

from telegram import (ReplyKeyboardMarkup) from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, RegexHandler, ConversationHandler) import logging # Enable logging logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) GENDER, PHOTO, LOCATION, BIO = range(4) def start(bot, update): reply_keyboard = [['Boy', 'Girl', 'Other']] bot.sendMessage(update.message.chat_id, text='Hi! My name is Professor Bot. I will hold a conversation with you. ' 'Send /cancel to stop talking to me.\n\n' 'Are you a boy or a girl?', reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)) return GENDER def gender(bot, update): user = update.message.from_user logger.info("Gender of %s: %s" % (user.first_name, update.message.text)) bot.sendMessage(update.message.chat_id, text='I see! Please send me a photo of yourself, ' 'so I know what you look like, or send /skip if you don\'t want to.') return PHOTO def photo(bot, update): user = update.message.from_user photo_file = bot.getFile(update.message.photo[-1].file_id) photo_file.download('user_photo.jpg') logger.info("Photo of %s: %s" % (user.first_name, 'user_photo.jpg')) bot.sendMessage(update.message.chat_id, text='Gorgeous! Now, send me your location please, ' 'or send /skip if you don\'t want to.') return LOCATION def skip_photo(bot, update): user = update.message.from_user logger.info("User %s did not send a photo." % user.first_name) bot.sendMessage(update.message.chat_id, text='I bet you look great! Now, send me your ' 'location please, or send /skip.') return LOCATION def location(bot, update): user = update.message.from_user user_location = update.message.location logger.info("Location of %s: %f/%f" % (user.first_name, user_location.latitude, user_location.longitude)) bot.sendMessage(update.message.chat_id, text='Maybe I can visit you sometime! ' 'At last, tell me something about yourself.') return BIO def skip_location(bot, update): user = update.message.from_user logger.info("User %s did not send a location." % user.first_name) bot.sendMessage(update.message.chat_id, text='You seem a bit paranoid! ' 'At last, tell me something about yourself.') return BIO def bio(bot, update): user = update.message.from_user logger.info("Bio of %s: %s" % (user.first_name, update.message.text)) bot.sendMessage(update.message.chat_id, text='Thank you! I hope we can talk again some day.') return ConversationHandler.END def cancel(bot, update): user = update.message.from_user logger.info("User %s canceled the conversation." % user.first_name) bot.sendMessage(update.message.chat_id, text='Bye! I hope we can talk again some day.') return ConversationHandler.END def error(bot, update, error): logger.warn('Update "%s" caused error "%s"' % (update, error)) def main(): # Create the EventHandler and pass it your bot's token. updater = Updater("TOKEN") # Get the dispatcher to register handlers dp = updater.dispatcher # Add conversation handler with the states GENDER, PHOTO, LOCATION and BIO conv_handler = ConversationHandler( entry_points=[CommandHandler('start', start)], states={ GENDER: [RegexHandler('^(Boy|Girl|Other)$', gender)], PHOTO: [MessageHandler([Filters.photo], photo), CommandHandler('skip', skip_photo)], LOCATION: [MessageHandler([Filters.location], location), CommandHandler('skip', skip_location)], BIO: [MessageHandler([Filters.text], bio)] }, fallbacks=[CommandHandler('cancel', cancel)], allow_reentry=True ) dp.add_handler(conv_handler) # log all errors dp.add_error_handler(error) # Start the Bot updater.start_polling() # Run the bot until the you presses Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT. This should be used most of the time, since # start_polling() is non-blocking and will stop the bot gracefully. updater.idle()

답변