-
Notifications
You must be signed in to change notification settings - Fork 0
/
conversation_nested.py
386 lines (308 loc) · 12.8 KB
/
conversation_nested.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
import logging
from typing import Any, Dict, Tuple
from telegram import __version__ as TG_VER
try:
from telegram import __version_info__
except ImportError:
__version_info__ = (0, 0, 0, 0, 0) # type: ignore[assignment]
if __version_info__ < (20, 0, 0, "alpha", 1):
raise RuntimeError(
f"This example is not compatible with your current PTB version {TG_VER}. To view the "
f"{TG_VER} version of this example, "
f"visit https://docs.python-telegram-bot.org/en/v{TG_VER}/examples.html"
)
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import (
Application,
CallbackQueryHandler,
CommandHandler,
ContextTypes,
ConversationHandler,
MessageHandler,
filters,
)
# Enable logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
logger = logging.getLogger(__name__)
# State definitions for top level conversation
SELECTING_ACTION, ADDING_MEMBER, ADDING_SELF, DESCRIBING_SELF = map(chr, range(4))
# State definitions for second level conversation
SELECTING_LEVEL, SELECTING_GENDER = map(chr, range(4, 6))
# State definitions for descriptions conversation
SELECTING_FEATURE, TYPING = map(chr, range(6, 8))
# Meta states
STOPPING, SHOWING = map(chr, range(8, 10))
# Shortcut for ConversationHandler.END
END = ConversationHandler.END
# Different constants for this example
(
PARENTS,
CHILDREN,
SELF,
GENDER,
MALE,
FEMALE,
AGE,
NAME,
START_OVER,
FEATURES,
CURRENT_FEATURE,
CURRENT_LEVEL,
) = map(chr, range(10, 22))
# Helper
def _name_switcher(level: str) -> Tuple[str, str]:
if level == PARENTS:
return "Father", "Mother"
return "Brother", "Sister"
# Top level conversation callbacks
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> str:
"""Select an action: Adding parent/child or show data."""
text = (
"You may choose to add a family member, yourself, show the gathered data, or end the "
"conversation. To abort, simply type /stop."
)
buttons = [
[
InlineKeyboardButton(text="Add family member", callback_data=str(ADDING_MEMBER)),
InlineKeyboardButton(text="Add yourself", callback_data=str(ADDING_SELF)),
],
[
InlineKeyboardButton(text="Show data", callback_data=str(SHOWING)),
InlineKeyboardButton(text="Done", callback_data=str(END)),
],
]
keyboard = InlineKeyboardMarkup(buttons)
# If we're starting over we don't need to send a new message
if context.user_data.get(START_OVER):
await update.callback_query.answer()
await update.callback_query.edit_message_text(text=text, reply_markup=keyboard)
else:
await update.message.reply_text(
"Hi, I'm Family Bot and I'm here to help you gather information about your family."
)
await update.message.reply_text(text=text, reply_markup=keyboard)
context.user_data[START_OVER] = False
return SELECTING_ACTION
async def adding_self(update: Update, context: ContextTypes.DEFAULT_TYPE) -> str:
"""Add information about yourself."""
context.user_data[CURRENT_LEVEL] = SELF
text = "Okay, please tell me about yourself."
button = InlineKeyboardButton(text="Add info", callback_data=str(MALE))
keyboard = InlineKeyboardMarkup.from_button(button)
await update.callback_query.answer()
await update.callback_query.edit_message_text(text=text, reply_markup=keyboard)
return DESCRIBING_SELF
async def show_data(update: Update, context: ContextTypes.DEFAULT_TYPE) -> str:
"""Pretty print gathered data."""
def pretty_print(data: Dict[str, Any], level: str) -> str:
people = data.get(level)
if not people:
return "\nNo information yet."
return_str = ""
if level == SELF:
for person in data[level]:
return_str += f"\nName: {person.get(NAME, '-')}, Age: {person.get(AGE, '-')}"
else:
male, female = _name_switcher(level)
for person in data[level]:
gender = female if person[GENDER] == FEMALE else male
return_str += (
f"\n{gender}: Name: {person.get(NAME, '-')}, Age: {person.get(AGE, '-')}"
)
return return_str
user_data = context.user_data
text = f"Yourself:{pretty_print(user_data, SELF)}"
text += f"\n\nParents:{pretty_print(user_data, PARENTS)}"
text += f"\n\nChildren:{pretty_print(user_data, CHILDREN)}"
buttons = [[InlineKeyboardButton(text="Back", callback_data=str(END))]]
keyboard = InlineKeyboardMarkup(buttons)
await update.callback_query.answer()
await update.callback_query.edit_message_text(text=text, reply_markup=keyboard)
user_data[START_OVER] = True
return SHOWING
async def stop(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
"""End Conversation by command."""
await update.message.reply_text("Okay, bye.")
return END
async def end(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
"""End conversation from InlineKeyboardButton."""
await update.callback_query.answer()
text = "See you around!"
await update.callback_query.edit_message_text(text=text)
return END
# Second level conversation callbacks
async def select_level(update: Update, context: ContextTypes.DEFAULT_TYPE) -> str:
"""Choose to add a parent or a child."""
text = "You may add a parent or a child. Also you can show the gathered data or go back."
buttons = [
[
InlineKeyboardButton(text="Add parent", callback_data=str(PARENTS)),
InlineKeyboardButton(text="Add child", callback_data=str(CHILDREN)),
],
[
InlineKeyboardButton(text="Show data", callback_data=str(SHOWING)),
InlineKeyboardButton(text="Back", callback_data=str(END)),
],
]
keyboard = InlineKeyboardMarkup(buttons)
await update.callback_query.answer()
await update.callback_query.edit_message_text(text=text, reply_markup=keyboard)
return SELECTING_LEVEL
async def select_gender(update: Update, context: ContextTypes.DEFAULT_TYPE) -> str:
"""Choose to add mother or father."""
level = update.callback_query.data
context.user_data[CURRENT_LEVEL] = level
text = "Please choose, whom to add."
male, female = _name_switcher(level)
buttons = [
[
InlineKeyboardButton(text=f"Add {male}", callback_data=str(MALE)),
InlineKeyboardButton(text=f"Add {female}", callback_data=str(FEMALE)),
],
[
InlineKeyboardButton(text="Show data", callback_data=str(SHOWING)),
InlineKeyboardButton(text="Back", callback_data=str(END)),
],
]
keyboard = InlineKeyboardMarkup(buttons)
await update.callback_query.answer()
await update.callback_query.edit_message_text(text=text, reply_markup=keyboard)
return SELECTING_GENDER
async def end_second_level(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
"""Return to top level conversation."""
context.user_data[START_OVER] = True
await start(update, context)
return END
# Third level callbacks
async def select_feature(update: Update, context: ContextTypes.DEFAULT_TYPE) -> str:
"""Select a feature to update for the person."""
buttons = [
[
InlineKeyboardButton(text="Name", callback_data=str(NAME)),
InlineKeyboardButton(text="Age", callback_data=str(AGE)),
InlineKeyboardButton(text="Done", callback_data=str(END)),
]
]
keyboard = InlineKeyboardMarkup(buttons)
# If we collect features for a new person, clear the cache and save the gender
if not context.user_data.get(START_OVER):
context.user_data[FEATURES] = {GENDER: update.callback_query.data}
text = "Please select a feature to update."
await update.callback_query.answer()
await update.callback_query.edit_message_text(text=text, reply_markup=keyboard)
# But after we do that, we need to send a new message
else:
text = "Got it! Please select a feature to update."
await update.message.reply_text(text=text, reply_markup=keyboard)
context.user_data[START_OVER] = False
return SELECTING_FEATURE
async def ask_for_input(update: Update, context: ContextTypes.DEFAULT_TYPE) -> str:
"""Prompt user to input data for selected feature."""
context.user_data[CURRENT_FEATURE] = update.callback_query.data
text = "Okay, tell me."
await update.callback_query.answer()
await update.callback_query.edit_message_text(text=text)
return TYPING
async def save_input(update: Update, context: ContextTypes.DEFAULT_TYPE) -> str:
"""Save input for feature and return to feature selection."""
user_data = context.user_data
user_data[FEATURES][user_data[CURRENT_FEATURE]] = update.message.text
user_data[START_OVER] = True
return await select_feature(update, context)
async def end_describing(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
"""End gathering of features and return to parent conversation."""
user_data = context.user_data
level = user_data[CURRENT_LEVEL]
if not user_data.get(level):
user_data[level] = []
user_data[level].append(user_data[FEATURES])
# Print upper level menu
if level == SELF:
user_data[START_OVER] = True
await start(update, context)
else:
await select_level(update, context)
return END
async def stop_nested(update: Update, context: ContextTypes.DEFAULT_TYPE) -> str:
"""Completely end conversation from within nested conversation."""
await update.message.reply_text("Okay, bye.")
return STOPPING
BOT_TOKEN = ""
def main() -> None:
"""Run the bot."""
# Create the Application and pass it your bot's token.
application = Application.builder().token(BOT_TOKEN).build()
# Set up third level ConversationHandler (collecting features)
description_conv = ConversationHandler(
entry_points=[
CallbackQueryHandler(
select_feature, pattern="^" + str(MALE) + "$|^" + str(FEMALE) + "$"
)
],
states={
SELECTING_FEATURE: [
CallbackQueryHandler(ask_for_input, pattern="^(?!" + str(END) + ").*$")
],
TYPING: [MessageHandler(filters.TEXT & ~filters.COMMAND, save_input)],
},
fallbacks=[
CallbackQueryHandler(end_describing, pattern="^" + str(END) + "$"),
CommandHandler("stop", stop_nested),
],
map_to_parent={
# Return to second level menu
END: SELECTING_LEVEL,
# End conversation altogether
STOPPING: STOPPING,
},
)
# Set up second level ConversationHandler (adding a person)
add_member_conv = ConversationHandler(
entry_points=[CallbackQueryHandler(select_level, pattern="^" + str(ADDING_MEMBER) + "$")],
states={
SELECTING_LEVEL: [
CallbackQueryHandler(select_gender, pattern=f"^{PARENTS}$|^{CHILDREN}$")
],
SELECTING_GENDER: [description_conv],
},
fallbacks=[
CallbackQueryHandler(show_data, pattern="^" + str(SHOWING) + "$"),
CallbackQueryHandler(end_second_level, pattern="^" + str(END) + "$"),
CommandHandler("stop", stop_nested),
],
map_to_parent={
# After showing data return to top level menu
SHOWING: SHOWING,
# Return to top level menu
END: SELECTING_ACTION,
# End conversation altogether
STOPPING: END,
},
)
# Set up top level ConversationHandler (selecting action)
# Because the states of the third level conversation map to the ones of the second level
# conversation, we need to make sure the top level conversation can also handle them
selection_handlers = [
add_member_conv,
CallbackQueryHandler(show_data, pattern="^" + str(SHOWING) + "$"),
CallbackQueryHandler(adding_self, pattern="^" + str(ADDING_SELF) + "$"),
CallbackQueryHandler(end, pattern="^" + str(END) + "$"),
]
conv_handler = ConversationHandler(
entry_points=[CommandHandler("start", start)],
states={
SHOWING: [CallbackQueryHandler(start, pattern="^" + str(END) + "$")],
SELECTING_ACTION: selection_handlers,
SELECTING_LEVEL: selection_handlers,
DESCRIBING_SELF: [description_conv],
STOPPING: [CommandHandler("start", start)],
},
fallbacks=[CommandHandler("stop", stop)],
)
application.add_handler(conv_handler)
# Run the bot until the user presses Ctrl-C
application.run_polling()
if __name__ == "__main__":
main()