{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "ename": "UnboundLocalError", "evalue": "local variable 'conv_handler' referenced before assignment", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mUnboundLocalError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 167\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 168\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m'__main__'\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 169\u001b[0;31m \u001b[0mmain\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m\u001b[0m in \u001b[0;36mmain\u001b[0;34m()\u001b[0m\n\u001b[1;32m 120\u001b[0m \u001b[0mdp\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mupdater\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdispatcher\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 121\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 122\u001b[0;31m \u001b[0mdp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0madd_handler\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mconv_handler\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 123\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 124\u001b[0m \u001b[0mshow_data_handler\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mCommandHandler\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'show_data'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mshow_data\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mUnboundLocalError\u001b[0m: local variable 'conv_handler' referenced before assignment" ] } ], "source": [ "import logging\n", "\n", "from telegram import ReplyKeyboardMarkup, Update\n", "from telegram.ext import (\n", " Updater,\n", " CommandHandler,\n", " MessageHandler,\n", " Filters,\n", " ConversationHandler,\n", " PicklePersistence,\n", " CallbackContext,\n", ")\n", "\n", "\n", "# Enable logging\n", "logging.basicConfig(\n", " format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO\n", ")\n", "\n", "logger = logging.getLogger(__name__)\n", "\n", "CHOOSING, TYPING_REPLY, TYPING_CHOICE = range(3)\n", "\n", "reply_keyboard = [\n", " ['Submit Translation!'],\n", " ['Want an Explaination?', 'Go to the Project'],\n", " ['Done'],\n", "]\n", "\n", "markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)\n", "\n", "\n", "def facts_to_str(user_data):\n", " facts = list()\n", "\n", " for key, value in user_data.items():\n", " facts.append('{} - {}'.format(key, value))\n", "\n", " return \"\\n\".join(facts).join(['\\n', '\\n'])\n", "\n", "\n", "def start(update: Update, context: CallbackContext) -> None:\n", " reply_text = \"Hi! My name is Doctor Botter.\"\n", " if context.user_data:\n", " reply_text += (\n", " \" You already told me your {}. Why don't you tell me something more \"\n", " \"about yourself? Or change anything I \"\n", " \"already know.\".format(\", \".join(context.user_data.keys()))\n", " )\n", " else:\n", " reply_text += (\n", " \" I will hold a more complex conversation with you. Why don't you tell me \"\n", " \"something about yourself?\"\n", " )\n", " update.message.reply_text(reply_text, reply_markup=markup)\n", "\n", " return CHOOSING\n", "\n", "\n", "def regular_choice(update: Update, context: CallbackContext) -> None:\n", " text = update.message.text.lower()\n", " context.user_data['choice'] = text\n", " if context.user_data.get(text):\n", " reply_text = 'Your {}, I already know the following ' 'about that: {}'.format(\n", " text, context.user_data[text]\n", " )\n", " else:\n", " reply_text = 'Your {}? Yes, I would love to hear about that!'.format(text)\n", " update.message.reply_text(reply_text)\n", "\n", " return TYPING_REPLY\n", "\n", "\n", "def explaination(update: Update, context: CallbackContext) -> None:\n", " update_obj.message.reply_text(f\"This is an explaination\", reply_markup= markup) \n", " \n", "def project(update: Update, context: CallbackContext) -> None:\n", " update_obj.message.reply_text(f\"Here it is! \\n \\n https://issue.xpub.nl/\", reply_markup= markup)\n", "\n", "def received_information(update: Update, context: CallbackContext) -> None:\n", " text = update.message.text\n", " category = context.user_data['choice']\n", " context.user_data[category] = text.lower()\n", " del context.user_data['choice']\n", "\n", " update.message.reply_text(\n", " \"Neat! Just so you know, this is what you already told me:\"\n", " \"{}\"\n", " \"You can tell me more, or change your opinion on \"\n", " \"something.\".format(facts_to_str(context.user_data)),\n", " reply_markup=markup,\n", " )\n", "\n", " return CHOOSING\n", "\n", "\n", "def show_data(update: Update, context: CallbackContext) -> None:\n", " update.message.reply_text(\n", " \"This is what you already told me:\" \"{}\".format(facts_to_str(context.user_data))\n", " )\n", "\n", "\n", "def done(update: Update, context: CallbackContext) -> None:\n", " if 'choice' in context.user_data:\n", " del context.user_data['choice']\n", "\n", " update.message.reply_text(\n", " \"I learned these facts about you:\"\n", " \"{}\"\n", " \"Until next time!\".format(facts_to_str(context.user_data))\n", " )\n", " return ConversationHandler.END\n", "\n", "\n", "def main():\n", " # Create the Updater and pass it your bot's token.\n", " pp = PicklePersistence(filename='conversationbot')\n", " updater = Updater(\"1452534708:AAERTrbN_LUDSLkf0J8sJjvMEEuwfRNka50\", persistence=pp, use_context=True)\n", "\n", " # Get the dispatcher to register handlers\n", " dp = updater.dispatcher\n", "\n", " # Add conversation handler with the states CHOOSING, TYPING_CHOICE and TYPING_REPLY\n", " conv_handler = ConversationHandler(\n", " entry_points=[CommandHandler('/start', start)],\n", " states={\n", " CHOOSING: [\n", " MessageHandler(\n", " Filters.regex('^Explaination?$'), explaination\n", " ),\n", " MessageHandler(Filters.regex('^Project$'), project\n", " ),\n", " MessageHandler(Filters.regex('^Translation!$'), regular_choice,\n", " )\n", " ],\n", " TYPING_CHOICE: [\n", " MessageHandler(\n", " Filters.text & ~(Filters.command | Filters.regex('^Done$')), start\n", " )\n", " ],\n", " TYPING_REPLY: [\n", " MessageHandler(\n", " Filters.text & ~(Filters.command | Filters.regex('^Done$')),\n", " received_information,\n", " )\n", " ],\n", " },\n", " fallbacks=[MessageHandler(Filters.regex('^Done$'), done)],\n", " name=\"my_conversation\",\n", " persistent=True,\n", " )\n", " \n", " dp.add_handler(conv_handler)\n", "\n", " show_data_handler = CommandHandler('show_data', show_data)\n", " dp.add_handler(show_data_handler)\n", "\n", " # Start the Bot\n", " updater.start_polling()\n", "\n", " # Run the bot until you press Ctrl-C or the process receives SIGINT,\n", " # SIGTERM or SIGABRT. This should be used most of the time, since\n", " # start_polling() is non-blocking and will stop the bot gracefully.\n", " updater.idle()\n", "\n", "\n", "#if __name__ == '__main__':\n", "main()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "2020-11-16 13:23:06,337 - apscheduler.scheduler - INFO - Scheduler started\n" ] } ], "source": [ "#!/usr/bin/env python\n", "# -*- coding: utf-8 -*-\n", "# pylint: disable=W0613, C0116, C0103\n", "# type: ignore[union-attr]\n", "# This program is dedicated to the public domain under the CC0 license.\n", "\n", "\"\"\"\n", "First, a few callback functions are defined. Then, those functions are passed to\n", "the Dispatcher and registered at their respective places.\n", "Then, the bot is started and runs until we press Ctrl-C on the command line.\n", "\n", "Usage:\n", "Example of a bot-user conversation using ConversationHandler.\n", "Send /start to initiate the conversation.\n", "Press Ctrl-C on the command line or send a signal to the process to stop the\n", "bot.\n", "\"\"\"\n", "\n", "import logging\n", "\n", "from telegram import ReplyKeyboardMarkup, Update\n", "from telegram.ext import (\n", " Updater,\n", " CommandHandler,\n", " MessageHandler,\n", " Filters,\n", " ConversationHandler,\n", " PicklePersistence,\n", " CallbackContext,\n", ")\n", "\n", "\n", "# Enable logging\n", "logging.basicConfig(\n", " format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO\n", ")\n", "\n", "logger = logging.getLogger(__name__)\n", "\n", "CHOOSING, TYPING_REPLY, TYPING_CHOICE = range(3)\n", "\n", "reply_keyboard = [\n", " ['Age', 'Favourite colour'],\n", " ['Number of siblings', 'Something else...'],\n", " ['Done'],\n", "]\n", "markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)\n", "\n", "\n", "def facts_to_str(user_data):\n", " facts = list()\n", "\n", " for key, value in user_data.items():\n", " facts.append('{} - {}'.format(key, value))\n", "\n", " return \"\\n\".join(facts).join(['\\n', '\\n'])\n", "\n", "\n", "def start(update: Update, context: CallbackContext) -> None:\n", " reply_text = \"Hi! My name is Doctor Botter.\"\n", " if context.user_data:\n", " reply_text += (\n", " \" You already told me your {}. Why don't you tell me something more \"\n", " \"about yourself? Or change anything I \"\n", " \"already know.\".format(\", \".join(context.user_data.keys()))\n", " )\n", " else:\n", " reply_text += (\n", " \" I will hold a more complex conversation with you. Why don't you tell me \"\n", " \"something about yourself?\"\n", " )\n", " update.message.reply_text(reply_text, reply_markup=markup)\n", "\n", " return CHOOSING\n", "\n", "\n", "def regular_choice(update: Update, context: CallbackContext) -> None:\n", " text = update.message.text.lower()\n", " context.user_data['choice'] = text\n", " if context.user_data.get(text):\n", " reply_text = 'Your {}, I already know the following ' 'about that: {}'.format(\n", " text, context.user_data[text]\n", " )\n", " else:\n", " reply_text = 'Your {}? Yes, I would love to hear about that!'.format(text)\n", " update.message.reply_text(reply_text)\n", "\n", " return TYPING_REPLY\n", "\n", "\n", "def custom_choice(update: Update, context: CallbackContext) -> None:\n", " update.message.reply_text(\n", " 'Alright, please send me the category first, ' 'for example \"Most impressive skill\"'\n", " )\n", "\n", " return TYPING_CHOICE\n", "\n", "\n", "def received_information(update: Update, context: CallbackContext) -> None:\n", " text = update.message.text\n", " category = context.user_data['choice']\n", " context.user_data[category] = text.lower()\n", " del context.user_data['choice']\n", "\n", " update.message.reply_text(\n", " \"Neat! Just so you know, this is what you already told me:\"\n", " \"{}\"\n", " \"You can tell me more, or change your opinion on \"\n", " \"something.\".format(facts_to_str(context.user_data)),\n", " reply_markup=markup,\n", " )\n", "\n", " return CHOOSING\n", "\n", "\n", "def show_data(update: Update, context: CallbackContext) -> None:\n", " update.message.reply_text(\n", " \"This is what you already told me:\" \"{}\".format(facts_to_str(context.user_data))\n", " )\n", "\n", "\n", "def done(update: Update, context: CallbackContext) -> None:\n", " if 'choice' in context.user_data:\n", " del context.user_data['choice']\n", "\n", " update.message.reply_text(\n", " \"I learned these facts about you:\"\n", " \"{}\"\n", " \"Until next time!\".format(facts_to_str(context.user_data))\n", " )\n", " return ConversationHandler.END\n", "\n", "\n", "def main():\n", " # Create the Updater and pass it your bot's token.\n", " pp = PicklePersistence(filename='conversationbot')\n", " updater = Updater(\"1452534708:AAERTrbN_LUDSLkf0J8sJjvMEEuwfRNka50\", persistence=pp, use_context=True)\n", "\n", " # Get the dispatcher to register handlers\n", " dp = updater.dispatcher\n", "\n", " # Add conversation handler with the states CHOOSING, TYPING_CHOICE and TYPING_REPLY\n", " conv_handler = ConversationHandler(\n", " entry_points=[CommandHandler('start', start)],\n", " states={\n", " CHOOSING: [\n", " MessageHandler(\n", " Filters.regex('^(Age|Favourite colour|Number of siblings)$'), regular_choice\n", " ),\n", " MessageHandler(Filters.regex('^Something else...$'), custom_choice),\n", " ],\n", " TYPING_CHOICE: [\n", " MessageHandler(\n", " Filters.text & ~(Filters.command | Filters.regex('^Done$')), regular_choice\n", " )\n", " ],\n", " TYPING_REPLY: [\n", " MessageHandler(\n", " Filters.text & ~(Filters.command | Filters.regex('^Done$')),\n", " received_information,\n", " )\n", " ],\n", " },\n", " fallbacks=[MessageHandler(Filters.regex('^Done$'), done)],\n", " name=\"my_conversation\",\n", " persistent=True,\n", " )\n", "\n", " dp.add_handler(conv_handler)\n", "\n", " show_data_handler = CommandHandler('show_data', show_data)\n", " dp.add_handler(show_data_handler)\n", "\n", " # Start the Bot\n", " updater.start_polling()\n", "\n", " # Run the bot until you press Ctrl-C or the process receives SIGINT,\n", " # SIGTERM or SIGABRT. This should be used most of the time, since\n", " # start_polling() is non-blocking and will stop the bot gracefully.\n", " updater.idle()\n", "\n", "\n", "if __name__ == '__main__':\n", " main()\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.6" } }, "nbformat": 4, "nbformat_minor": 4 }