Skip to content

Commit e5a17ca

Browse files
committed
Updated detailed example to use message handlers
Now using message handlers instead of the listener for almost everything (except console output)
1 parent efdf357 commit e5a17ca

1 file changed

Lines changed: 58 additions & 31 deletions

File tree

‎examples/detailed_example/detailed_example.py‎

Lines changed: 58 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -23,39 +23,29 @@
2323

2424
hideBoard = types.ReplyKeyboardHide() #if sent as reply_markup, will hide the keyboard
2525

26-
def printUser(msg): #debug function (will print every message sent by any user to the console)
27-
print str(msg.chat.first_name) + " [" + str(msg.chat.id) + "]: " + msg.text
26+
#error handling if user isn't known yet
27+
#(obsolete once known users are saved to file, because all users
28+
# had to use the /start command and are therefore known to the bot)
29+
def getUserStep(uid):
30+
if uid in userStep:
31+
return userStep[uid]
32+
else:
33+
knownUsers.append(uid)
34+
userStep[uid] = 0
35+
print "New user detected, who hasn't used \"/start\" yet"
36+
return 0
2837

38+
39+
#only used for console output now
2940
def listener(messages):
3041
"""
3142
When new messages arrive TeleBot will call this function.
3243
"""
3344
for m in messages:
3445
cid = m.chat.id
3546
if m.content_type == 'text':
36-
text = m.text
37-
printUser(m) #print the sent message to the console
38-
39-
if text[0] != '/': #filter out commands
40-
try: #don't quit, when the user hasn't used the "/start" command yet
41-
if userStep[cid]==1: #when the user has issued the "/getImage" command
42-
bot.send_chat_action(cid, 'typing') #for some reason the 'upload_photo' status isn't quite working (doesn't show at all)
43-
if text == "cock": #send the appropriate image based on the reply to the "/getImage" command
44-
bot.send_photo(cid, open('rooster.jpg', 'rb'), reply_markup=hideBoard) #send file and hide keyboard, after image is sent
45-
userStep[cid]=0 #reset the users step back to 0
46-
elif text == "pussy":
47-
bot.send_photo(cid, open('kitten.jpg', 'rb'), reply_markup=hideBoard)
48-
userStep[cid]=0
49-
else:
50-
bot.send_message(cid, "Don't type bullsh*t, if I give you a predefined keyboard!")
51-
bot.send_message(cid, "Please try again")
52-
else:
53-
bot.send_message(cid, "I don't understand \""+text+"\"\nMaybe try the help page at /help") #this is the standard reply to a normal message
54-
55-
except KeyError:
56-
bot.send_message(cid, "I don't know you yet... Please use the \'/start\' command!")
57-
58-
47+
#print the sent message to the console
48+
print str(m.chat.first_name) + " [" + str(m.chat.id) + "]: " + m.text
5949

6050
bot = telebot.TeleBot(TOKEN)
6151
bot.set_update_listener(listener) #register listener
@@ -64,6 +54,8 @@ def listener(messages):
6454
except Exception:
6555
pass
6656

57+
58+
#handle the "/start" command
6759
@bot.message_handler(commands=['start'])
6860
def command_start(m):
6961
cid = m.chat.id
@@ -77,31 +69,66 @@ def command_start(m):
7769
bot.send_message(cid, "I already know you, no need for me to scan you again!")
7870

7971

80-
@bot.message_handler(commands=['help']) #help page
72+
#help page
73+
@bot.message_handler(commands=['help'])
8174
def command_help(m):
8275
cid = m.chat.id
8376
helpText = "The following commands are available: \n"
8477
for key in commands: #generate help text out of the commands dictionary defined at the top
8578
helpText += "/" + key + ": "
8679
helpText += commands[key] + "\n"
8780
bot.send_message(cid, helpText) #send the generated help page
88-
89-
@bot.message_handler(commands=['sendLongText']) #chat_action example (not a good one... sleep is bad, if this bot is used by multiple users)
81+
82+
83+
#chat_action example (not a good one...)
84+
@bot.message_handler(commands=['sendLongText'])
9085
def command_longText(m):
9186
cid = m.chat.id
9287
bot.send_message(cid, "If you think so...")
9388
bot.send_chat_action(cid, 'typing') #show the bot "typing" (max. 5 secs)
9489
time.sleep(3)
9590
bot.send_message(cid,".")
9691

97-
@bot.message_handler(commands=['getImage']) #user can chose an image
92+
93+
#user can chose an image (multi-stage command example)
94+
@bot.message_handler(commands=['getImage'])
9895
def command_image(m):
9996
cid = m.chat.id
10097
bot.send_message(cid, "Please choose your image now", reply_markup=imageSelect) #show the keyboard
10198
userStep[cid] = 1 #set the user to the next step (expecting a reply in the listener now)
10299

100+
101+
#if the user has issued the "/getImage" command, process the answer
102+
@bot.message_handler(func=lambda message: getUserStep(message.chat.id) == 1)
103+
def msg_imageSelect(m):
104+
cid = m.chat.id
105+
text = m.text
106+
bot.send_chat_action(cid, 'typing') #for some reason the 'upload_photo' status isn't quite working (doesn't show at all)
107+
108+
if text == "cock": #send the appropriate image based on the reply to the "/getImage" command
109+
bot.send_photo(cid, open('rooster.jpg', 'rb'), reply_markup=hideBoard) #send file and hide keyboard, after image is sent
110+
userStep[cid]=0 #reset the users step back to 0
111+
elif text == "pussy":
112+
bot.send_photo(cid, open('kitten.jpg', 'rb'), reply_markup=hideBoard)
113+
userStep[cid]=0
114+
else:
115+
bot.send_message(cid, "Don't type bullsh*t, if I give you a predefined keyboard!")
116+
bot.send_message(cid, "Please try again")
117+
118+
119+
#filter on a specific message
120+
@bot.message_handler(func=lambda message: message.text=="hi")
121+
def command_textHi(m):
122+
bot.send_message(m.chat.id, "I love you too!")
123+
124+
#default handler for every other text
125+
@bot.message_handler(func=lambda message: True, content_types=['text'])
126+
def command_default(m):
127+
bot.send_message(m.chat.id, "I don't understand \""+m.text+"\"\nMaybe try the help page at /help") #this is the standard reply to a normal message
128+
129+
103130
while True: # Don't let the main Thread end.
104131
try:
105-
pass
132+
time.sleep(1)
106133
except KeyboardInterrupt:
107-
break
134+
break

0 commit comments

Comments
 (0)