X Tutup
Skip to content

Commit 360c307

Browse files
committed
update examples
1 parent f2a92cc commit 360c307

File tree

5 files changed

+65
-67
lines changed

5 files changed

+65
-67
lines changed

examples/clibot.py

Lines changed: 26 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@
1818
Type 'stop' on the command line to stop the bot.
1919
"""
2020

21-
from telegram.ext import Updater
21+
from telegram.ext import Updater, StringCommandHandler, StringRegexHandler, \
22+
MessageHandler, CommandHandler, RegexHandler, filters
2223
from telegram.ext.dispatcher import run_async
2324
from time import sleep
2425
import logging
@@ -34,8 +35,9 @@
3435
last_chat_id = 0
3536

3637

37-
# Define a few (command) handlers. These usually take the two arguments bot and
38-
# update. Error handlers also receive the raised TelegramError object in error.
38+
# Define a few (command) handler callback functions. These usually take the
39+
# two arguments bot and update. Error handlers also receive the raised
40+
# TelegramError object in error.
3941
def start(bot, update):
4042
""" Answer in Telegram """
4143
bot.sendMessage(update.message.chat_id, text='Hi!')
@@ -59,13 +61,8 @@ def any_message(bot, update):
5961
update.message.text))
6062

6163

62-
def unknown_command(bot, update):
63-
""" Answer in Telegram """
64-
bot.sendMessage(update.message.chat_id, text='Command not recognized!')
65-
66-
6764
@run_async
68-
def message(bot, update, **kwargs):
65+
def message(bot, update):
6966
"""
7067
Example for an asynchronous handler. It's not guaranteed that replies will
7168
be in order when using @run_async. Also, you have to include **kwargs in
@@ -95,16 +92,12 @@ def cli_noncommand(bot, update, update_queue):
9592
appending it to the argument list. Be careful with this though.
9693
Here, we put the input string back into the queue, but as a command.
9794
98-
To learn more about those optional handler parameters, read:
99-
http://python-telegram-bot.readthedocs.org/en/latest/telegram.dispatcher.html
95+
To learn more about those optional handler parameters, read the
96+
documentation of the Handler classes.
10097
"""
10198
update_queue.put('/%s' % update)
10299

103100

104-
def unknown_cli_command(bot, update):
105-
logger.warn("Command not found: %s" % update)
106-
107-
108101
def error(bot, update, error):
109102
""" Print error to console """
110103
logger.warn('Update %s caused error %s' % (update, error))
@@ -119,42 +112,43 @@ def main():
119112
dp = updater.dispatcher
120113

121114
# This is how we add handlers for Telegram messages
122-
dp.addTelegramCommandHandler("start", start)
123-
dp.addTelegramCommandHandler("help", help)
124-
dp.addUnknownTelegramCommandHandler(unknown_command)
115+
dp.addHandler(CommandHandler("start", start))
116+
dp.addHandler(CommandHandler("help", help))
125117
# Message handlers only receive updates that don't contain commands
126-
dp.addTelegramMessageHandler(message)
127-
# Regex handlers will receive all updates on which their regex matches
128-
dp.addTelegramRegexHandler('.*', any_message)
129-
130-
# String handlers work pretty much the same
131-
dp.addStringCommandHandler('reply', cli_reply)
132-
dp.addUnknownStringCommandHandler(unknown_cli_command)
133-
dp.addStringRegexHandler('[^/].*', cli_noncommand)
118+
dp.addHandler(MessageHandler([filters.TEXT], message))
119+
# Regex handlers will receive all updates on which their regex matches,
120+
# but we have to add it in a separate group, since in one group,
121+
# only one handler will be executed
122+
dp.addHandler(RegexHandler('.*', any_message), group='log')
123+
124+
# String handlers work pretty much the same. Note that we have to tell
125+
# the handler to pass the args or update_queue parameter
126+
dp.addHandler(StringCommandHandler('reply', cli_reply, pass_args=True))
127+
dp.addHandler(StringRegexHandler('[^/].*', cli_noncommand,
128+
pass_update_queue=True))
134129

135130
# All TelegramErrors are caught for you and delivered to the error
136131
# handler(s). Other types of Errors are not caught.
137132
dp.addErrorHandler(error)
138133

139134
# Start the Bot and store the update Queue, so we can insert updates
140-
update_queue = updater.start_polling(poll_interval=0.1, timeout=10)
135+
update_queue = updater.start_polling(timeout=10)
141136

142137
'''
143138
# Alternatively, run with webhook:
144-
updater.bot.setWebhook(webhook_url='https://example.com/%s' % token,
145-
certificate=open('cert.pem', 'rb'))
146139
147140
update_queue = updater.start_webhook('0.0.0.0',
148141
443,
149142
url_path=token,
150143
cert='cert.pem',
151-
key='key.key')
144+
key='key.key',
145+
webhook_url='https://example.com/%s'
146+
% token)
152147
153148
# Or, if SSL is handled by a reverse proxy, the webhook URL is already set
154149
# and the reverse proxy is configured to deliver directly to port 6000:
155150
156-
update_queue = updater.start_webhook('0.0.0.0',
157-
6000)
151+
update_queue = updater.start_webhook('0.0.0.0', 6000)
158152
'''
159153

160154
# Start CLI-Loop

examples/echobot2.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
bot.
1818
"""
1919

20-
from telegram.ext import Updater
20+
from telegram.ext import Updater, CommandHandler, MessageHandler, filters
2121
import logging
2222

2323
# Enable logging
@@ -54,11 +54,11 @@ def main():
5454
dp = updater.dispatcher
5555

5656
# on different commands - answer in Telegram
57-
dp.addTelegramCommandHandler("start", start)
58-
dp.addTelegramCommandHandler("help", help)
57+
dp.addHandler(CommandHandler("start", start))
58+
dp.addHandler(CommandHandler("help", help))
5959

6060
# on noncommand i.e message - echo the message on Telegram
61-
dp.addTelegramMessageHandler(echo)
61+
dp.addHandler(MessageHandler([filters.TEXT], echo))
6262

6363
# log all errors
6464
dp.addErrorHandler(error)

examples/inlinebot.py

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,13 @@
1616
Press Ctrl-C on the command line or send a signal to the process to stop the
1717
bot.
1818
"""
19-
from random import getrandbits
19+
from uuid import uuid4
2020

2121
import re
2222

23-
from telegram import InlineQueryResultArticle, ParseMode
24-
from telegram.ext import Updater
23+
from telegram import InlineQueryResultArticle, ParseMode, \
24+
InputTextMessageContent
25+
from telegram.ext import Updater, InlineQueryHandler, CommandHandler
2526
import logging
2627

2728
# Enable logging
@@ -54,26 +55,27 @@ def inlinequery(bot, update):
5455
results = list()
5556

5657
results.append(InlineQueryResultArticle(
57-
id=hex(getrandbits(64))[2:],
58+
id=uuid4(),
5859
title="Caps",
59-
message_text=query.upper()))
60+
input_message_content=InputTextMessageContent(query.upper())))
6061

6162
results.append(InlineQueryResultArticle(
62-
id=hex(getrandbits(64))[2:],
63+
id=uuid4(),
6364
title="Bold",
64-
message_text="*%s*" % escape_markdown(query),
65-
parse_mode=ParseMode.MARKDOWN))
65+
input_message_content=InputTextMessageContent(
66+
"*%s*" % escape_markdown(query),
67+
parse_mode=ParseMode.MARKDOWN)))
6668

6769
results.append(InlineQueryResultArticle(
68-
id=hex(getrandbits(64))[2:],
70+
id=uuid4(),
6971
title="Italic",
70-
message_text="_%s_" % escape_markdown(query),
71-
parse_mode=ParseMode.MARKDOWN))
72+
input_message_content=InputTextMessageContent(
73+
"_%s_" % escape_markdown(query),
74+
parse_mode=ParseMode.MARKDOWN)))
7275

7376
bot.answerInlineQuery(update.inline_query.id, results=results)
7477

7578

76-
7779
def error(bot, update, error):
7880
logger.warn('Update "%s" caused error "%s"' % (update, error))
7981

@@ -86,11 +88,11 @@ def main():
8688
dp = updater.dispatcher
8789

8890
# on different commands - answer in Telegram
89-
dp.addTelegramCommandHandler("start", start)
90-
dp.addTelegramCommandHandler("help", help)
91+
dp.addHandler(CommandHandler("start", start))
92+
dp.addHandler(CommandHandler("help", help))
9193

9294
# on noncommand i.e message - echo the message on Telegram
93-
dp.addTelegramInlineHandler(inlinequery)
95+
dp.addHandler(InlineQueryHandler(inlinequery))
9496

9597
# log all errors
9698
dp.addErrorHandler(error)

examples/state_machine_bot.py

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55
# This program is dedicated to the public domain under the CC0 license.
66

77
import logging
8-
from telegram import Emoji, ForceReply, ReplyKeyboardMarkup
9-
from telegram.ext import Updater
8+
from telegram import Emoji, ForceReply, ReplyKeyboardMarkup, KeyboardButton
9+
from telegram.ext import Updater, CommandHandler, MessageHandler, filters
1010

1111
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - '
1212
'%(message)s',
@@ -55,14 +55,16 @@ def set_value(bot, update):
5555

5656
# Save the user id and the answer to context
5757
context[chat_id] = (user_id, update.message.text)
58-
reply_markup = ReplyKeyboardMarkup([[YES, NO]], one_time_keyboard=True)
58+
reply_markup = ReplyKeyboardMarkup(
59+
[[KeyboardButton(YES), KeyboardButton(NO)]],
60+
one_time_keyboard=True)
5961
bot.sendMessage(chat_id, text="Are you sure?",
6062
reply_markup=reply_markup)
6163

6264
# If we are waiting for confirmation and the right user answered
6365
elif chat_state == AWAIT_CONFIRMATION and chat_context[0] == user_id:
64-
state[chat_id] = MENU
65-
context[chat_id] = None
66+
del state[chat_id]
67+
del context[chat_id]
6668
if text == YES:
6769
values[chat_id] = chat_context[1]
6870
bot.sendMessage(chat_id,
@@ -77,8 +79,8 @@ def set_value(bot, update):
7779
# Sets the state back to MENU and clears the context
7880
def cancel(bot, update):
7981
chat_id = update.message.chat_id
80-
state[chat_id] = MENU
81-
context[chat_id] = None
82+
del state[chat_id]
83+
del context[chat_id]
8284

8385

8486
def help(bot, update):
@@ -89,12 +91,12 @@ def help(bot, update):
8991
updater = Updater("TOKEN")
9092

9193
# The command
92-
updater.dispatcher.addTelegramCommandHandler('set', set_value)
94+
updater.dispatcher.addHandler(CommandHandler('set', set_value))
9395
# The answer and confirmation
94-
updater.dispatcher.addTelegramMessageHandler(set_value)
95-
updater.dispatcher.addTelegramCommandHandler('cancel', cancel)
96-
updater.dispatcher.addTelegramCommandHandler('start', help)
97-
updater.dispatcher.addTelegramCommandHandler('help', help)
96+
updater.dispatcher.addHandler(MessageHandler([filters.TEXT], set_value))
97+
updater.dispatcher.addHandler(CommandHandler('cancel', cancel))
98+
updater.dispatcher.addHandler(CommandHandler('start', help))
99+
updater.dispatcher.addHandler(CommandHandler('help', help))
98100

99101
# Start the Bot
100102
updater.start_polling()

examples/timerbot.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
bot.
1919
"""
2020

21-
from telegram.ext import Updater
21+
from telegram.ext import Updater, CommandHandler
2222
import logging
2323

2424
# Enable logging
@@ -73,9 +73,9 @@ def main():
7373
dp = updater.dispatcher
7474

7575
# on different commands - answer in Telegram
76-
dp.addTelegramCommandHandler("start", start)
77-
dp.addTelegramCommandHandler("help", start)
78-
dp.addTelegramCommandHandler("set", set)
76+
dp.addHandler(CommandHandler("start", start))
77+
dp.addHandler(CommandHandler("help", start))
78+
dp.addHandler(CommandHandler("set", set))
7979

8080
# log all errors
8181
dp.addErrorHandler(error)

0 commit comments

Comments
 (0)
X Tutup