persistentconversationbot.pyΒΆ

  1#!/usr/bin/env python
  2# pylint: disable=unused-argument, wrong-import-position
  3# This program is dedicated to the public domain under the CC0 license.
  4
  5"""
  6First, a few callback functions are defined. Then, those functions are passed to
  7the Application and registered at their respective places.
  8Then, the bot is started and runs until we press Ctrl-C on the command line.
  9
 10Usage:
 11Example of a bot-user conversation using ConversationHandler.
 12Send /start to initiate the conversation.
 13Press Ctrl-C on the command line or send a signal to the process to stop the
 14bot.
 15"""
 16
 17import logging
 18from typing import Dict
 19
 20from telegram import __version__ as TG_VER
 21
 22try:
 23    from telegram import __version_info__
 24except ImportError:
 25    __version_info__ = (0, 0, 0, 0, 0)  # type: ignore[assignment]
 26
 27if __version_info__ < (20, 0, 0, "alpha", 1):
 28    raise RuntimeError(
 29        f"This example is not compatible with your current PTB version {TG_VER}. To view the "
 30        f"{TG_VER} version of this example, "
 31        f"visit https://docs.python-telegram-bot.org/en/v{TG_VER}/examples.html"
 32    )
 33from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, Update
 34from telegram.ext import (
 35    Application,
 36    CommandHandler,
 37    ContextTypes,
 38    ConversationHandler,
 39    MessageHandler,
 40    PicklePersistence,
 41    filters,
 42)
 43
 44# Enable logging
 45logging.basicConfig(
 46    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
 47)
 48# set higher logging level for httpx to avoid all GET and POST requests being logged
 49logging.getLogger("httpx").setLevel(logging.WARNING)
 50
 51logger = logging.getLogger(__name__)
 52
 53CHOOSING, TYPING_REPLY, TYPING_CHOICE = range(3)
 54
 55reply_keyboard = [
 56    ["Age", "Favourite colour"],
 57    ["Number of siblings", "Something else..."],
 58    ["Done"],
 59]
 60markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)
 61
 62
 63def facts_to_str(user_data: Dict[str, str]) -> str:
 64    """Helper function for formatting the gathered user info."""
 65    facts = [f"{key} - {value}" for key, value in user_data.items()]
 66    return "\n".join(facts).join(["\n", "\n"])
 67
 68
 69async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
 70    """Start the conversation, display any stored data and ask user for input."""
 71    reply_text = "Hi! My name is Doctor Botter."
 72    if context.user_data:
 73        reply_text += (
 74            f" You already told me your {', '.join(context.user_data.keys())}. Why don't you "
 75            f"tell me something more about yourself? Or change anything I already know."
 76        )
 77    else:
 78        reply_text += (
 79            " I will hold a more complex conversation with you. Why don't you tell me "
 80            "something about yourself?"
 81        )
 82    await update.message.reply_text(reply_text, reply_markup=markup)
 83
 84    return CHOOSING
 85
 86
 87async def regular_choice(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
 88    """Ask the user for info about the selected predefined choice."""
 89    text = update.message.text.lower()
 90    context.user_data["choice"] = text
 91    if context.user_data.get(text):
 92        reply_text = (
 93            f"Your {text}? I already know the following about that: {context.user_data[text]}"
 94        )
 95    else:
 96        reply_text = f"Your {text}? Yes, I would love to hear about that!"
 97    await update.message.reply_text(reply_text)
 98
 99    return TYPING_REPLY
100
101
102async def custom_choice(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
103    """Ask the user for a description of a custom category."""
104    await update.message.reply_text(
105        'Alright, please send me the category first, for example "Most impressive skill"'
106    )
107
108    return TYPING_CHOICE
109
110
111async def received_information(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
112    """Store info provided by user and ask for the next category."""
113    text = update.message.text
114    category = context.user_data["choice"]
115    context.user_data[category] = text.lower()
116    del context.user_data["choice"]
117
118    await update.message.reply_text(
119        "Neat! Just so you know, this is what you already told me:"
120        f"{facts_to_str(context.user_data)}"
121        "You can tell me more, or change your opinion on something.",
122        reply_markup=markup,
123    )
124
125    return CHOOSING
126
127
128async def show_data(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
129    """Display the gathered info."""
130    await update.message.reply_text(
131        f"This is what you already told me: {facts_to_str(context.user_data)}"
132    )
133
134
135async def done(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
136    """Display the gathered info and end the conversation."""
137    if "choice" in context.user_data:
138        del context.user_data["choice"]
139
140    await update.message.reply_text(
141        f"I learned these facts about you: {facts_to_str(context.user_data)}Until next time!",
142        reply_markup=ReplyKeyboardRemove(),
143    )
144    return ConversationHandler.END
145
146
147def main() -> None:
148    """Run the bot."""
149    # Create the Application and pass it your bot's token.
150    persistence = PicklePersistence(filepath="conversationbot")
151    application = Application.builder().token("TOKEN").persistence(persistence).build()
152
153    # Add conversation handler with the states CHOOSING, TYPING_CHOICE and TYPING_REPLY
154    conv_handler = ConversationHandler(
155        entry_points=[CommandHandler("start", start)],
156        states={
157            CHOOSING: [
158                MessageHandler(
159                    filters.Regex("^(Age|Favourite colour|Number of siblings)$"), regular_choice
160                ),
161                MessageHandler(filters.Regex("^Something else...$"), custom_choice),
162            ],
163            TYPING_CHOICE: [
164                MessageHandler(
165                    filters.TEXT & ~(filters.COMMAND | filters.Regex("^Done$")), regular_choice
166                )
167            ],
168            TYPING_REPLY: [
169                MessageHandler(
170                    filters.TEXT & ~(filters.COMMAND | filters.Regex("^Done$")),
171                    received_information,
172                )
173            ],
174        },
175        fallbacks=[MessageHandler(filters.Regex("^Done$"), done)],
176        name="my_conversation",
177        persistent=True,
178    )
179
180    application.add_handler(conv_handler)
181
182    show_data_handler = CommandHandler("show_data", show_data)
183    application.add_handler(show_data_handler)
184
185    # Run the bot until the user presses Ctrl-C
186    application.run_polling(allowed_updates=Update.ALL_TYPES)
187
188
189if __name__ == "__main__":
190    main()