Skip to content

Commit d546a4f

Browse files
committed
Add step handler example.
1 parent 9f6a3bf commit d546a4f

1 file changed

Lines changed: 82 additions & 0 deletions

File tree

‎examples/step_example.py‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
This Example will show you how to use register_next_step handler.
4+
"""
5+
import time
6+
7+
import telebot
8+
from telebot import types
9+
10+
API_TOKEN = '<api_token>'
11+
12+
bot = telebot.TeleBot(API_TOKEN)
13+
14+
user_dict = {}
15+
16+
17+
class User:
18+
def __init__(self, name):
19+
self.name = name
20+
self.age = None
21+
self.sex = None
22+
23+
24+
# Handle '/start' and '/help'
25+
@bot.message_handler(commands=['help', 'start'])
26+
def send_welcome(message):
27+
msg = bot.reply_to(message, """\
28+
Hi there, I am Example bot.
29+
What's your name?
30+
""")
31+
bot.register_next_step_handler(msg, process_name_step)
32+
33+
34+
def process_name_step(message):
35+
try:
36+
chat_id = message.chat.id
37+
name = message.text
38+
user = User(name)
39+
user_dict[chat_id] = user
40+
msg = bot.reply_to(message, 'How old are you?')
41+
bot.register_next_step_handler(msg, process_age_step)
42+
except Exception as e:
43+
bot.reply_to(message, 'oooops')
44+
45+
46+
def process_age_step(message):
47+
try:
48+
chat_id = message.chat.id
49+
age = message.text
50+
if not age.isdigit():
51+
msg = bot.reply_to(message, 'Age should be a number. How old are you?')
52+
bot.register_next_step_handler(msg, process_age_step)
53+
return
54+
user = user_dict[chat_id]
55+
user.age = age
56+
markup = types.ReplyKeyboardMarkup(one_time_keyboard=True)
57+
markup.add('Male', 'Female')
58+
msg = bot.reply_to(message, 'What is your sex', reply_markup=markup)
59+
bot.register_next_step_handler(msg, process_sex_step)
60+
except Exception as e:
61+
bot.reply_to(message, 'oooops')
62+
63+
64+
def process_sex_step(message):
65+
try:
66+
chat_id = message.chat.id
67+
sex = message.text
68+
user = user_dict[chat_id]
69+
if (sex == u'Male') or (sex == u'Female'):
70+
user.sex = sex
71+
else:
72+
raise Exception()
73+
bot.send_message(chat_id, 'Nice to meet you ' + user.name + '\n Age:' + str(user.age) + '\n Sex:' + user.sex)
74+
except Exception as e:
75+
bot.reply_to(message, 'oooops')
76+
77+
78+
bot.polling()
79+
80+
while True:
81+
time.sleep(1)
82+
pass

0 commit comments

Comments
 (0)