jessicacardoso

bot-telegram

Feb 9th, 2020
1,264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.33 KB | None | 0 0
  1. from telegram import ReplyKeyboardMarkup
  2. from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters,
  3.                           ConversationHandler, PicklePersistence)
  4.  
  5. import logging
  6. import os
  7. import settings
  8.  
  9. # Enable logging
  10. logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  11.                     level=logging.INFO)
  12.  
  13. logger = logging.getLogger(__name__)
  14.  
  15. CHOOSING, TYPING_REPLY, TYPING_CHOICE = range(3)
  16.  
  17. reply_keyboard = [['Age', 'Favourite colour'],
  18.                   ['Done']]
  19.  
  20. markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)
  21.  
  22.  
  23. def facts_to_str(user_data):
  24.     facts = list()
  25.  
  26.     for key, value in user_data.items():
  27.         facts.append('{} - {}'.format(key, value))
  28.  
  29.     return "\n".join(facts).join(['\n', '\n'])
  30.  
  31.  
  32. def start(update, context):
  33.     reply_text = "Hi! My name is Doctor Botter."
  34.     if context.user_data:
  35.         reply_text += " You already told me your {}. Why don't you tell me something more " \
  36.                       "about yourself? Or change anything I " \
  37.                       "already know.".format(", ".join(context.user_data.keys()))
  38.     else:
  39.         reply_text += " I will hold a more complex conversation with you. Why don't you tell me " \
  40.                       "something about yourself?"
  41.     update.message.reply_text(reply_text, reply_markup=markup)
  42.  
  43.     return CHOOSING
  44.  
  45.  
  46. def regular_choice(update, context):
  47.     text = update.message.text.lower()
  48.     context.user_data['choice'] = text
  49.     if context.user_data.get(text):
  50.         reply_text = 'Your {}, I already know the following ' \
  51.                      'about that: {}'.format(text, context.user_data[text])
  52.     else:
  53.         reply_text = 'Your {}? Yes, I would love to hear about that!'.format(text)
  54.     update.message.reply_text(reply_text)
  55.  
  56.     return TYPING_REPLY
  57.  
  58.  
  59. def received_information(update, context):
  60.     text = update.message.text
  61.     category = context.user_data['choice']
  62.     context.user_data[category] = text.lower()
  63.     del context.user_data['choice']
  64.  
  65.     update.message.reply_text("Neat! Just so you know, this is what you already told me:"
  66.                               "{}"
  67.                               "You can tell me more, or change your opinion on "
  68.                               "something.".format(facts_to_str(context.user_data)),
  69.                               reply_markup=markup)
  70.  
  71.     return CHOOSING
  72.  
  73.  
  74. def done(update, context):
  75.     if 'choice' in context.user_data:
  76.         del context.user_data['choice']
  77.  
  78.     update.message.reply_text("I learned these facts about you:"
  79.                               "{}"
  80.                               "Until next time!".format(facts_to_str(context.user_data)))
  81.     return ConversationHandler.END
  82.  
  83.  
  84. def error(update, context):
  85.     """Log Errors caused by Updates."""
  86.     logger.warning('Update "%s" caused error "%s"', update, context.error)
  87.  
  88.  
  89. def main():
  90.     # Create the Updater and pass it your bot's token.
  91.     pp = PicklePersistence(filename='conversationbot')
  92.     updater = Updater(os.getenv("TELEGRAM_TOKEN"), persistence=pp, use_context=True)
  93.  
  94.     # Get the dispatcher to register handlers
  95.     dp = updater.dispatcher
  96.  
  97.     # Add conversation handler with the states CHOOSING, TYPING_CHOICE and TYPING_REPLY
  98.     conv_handler = ConversationHandler(
  99.         entry_points=[CommandHandler('start', start)],
  100.  
  101.         states={
  102.             CHOOSING: [MessageHandler(Filters.regex('^(?!/).*$'),
  103.                                       regular_choice),
  104.  
  105.                        ],
  106.  
  107.             TYPING_REPLY: [MessageHandler(Filters.text,
  108.                                           received_information),
  109.                            ],
  110.         },
  111.  
  112.         fallbacks=[CommandHandler("done", done)],
  113.         name="my_conversation",
  114.         persistent=True
  115.     )
  116.  
  117.     dp.add_handler(conv_handler)
  118.  
  119.     # show_data_handler = CommandHandler('show_data', show_data)
  120.     # dp.add_handler(show_data_handler)
  121.     # log all errors
  122.     dp.add_error_handler(error)
  123.  
  124.     # Start the Bot
  125.     updater.start_polling()
  126.  
  127.     # Run the bot until you press Ctrl-C or the process receives SIGINT,
  128.     # SIGTERM or SIGABRT. This should be used most of the time, since
  129.     # start_polling() is non-blocking and will stop the bot gracefully.
  130.     updater.idle()
  131.  
  132.  
  133. if __name__ == '__main__':
  134.     main()
Add Comment
Please, Sign In to add comment