X Tutup
Skip to content

Commit 2a2b679

Browse files
committed
improved and renamed examples
1 parent f75e329 commit 2a2b679

File tree

5 files changed

+64
-53
lines changed

5 files changed

+64
-53
lines changed

README.rst

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -155,9 +155,9 @@ _`Getting started`
155155

156156
View the last release API documentation at: https://core.telegram.org/bots/api
157157

158-
------
158+
--------------------
159159
_`The Updater class`
160-
------
160+
--------------------
161161

162162
The ``Updater`` class is the new way to create bots with ``python-telegram-bot``. It provides an easy-to-use interface to the ``telegram.Bot`` by caring about getting new updates from telegram and forwarding them to the ``Dispatcher`` class. We can register handler functions in the ``Dispatcher`` to make our bot react to Telegram commands, messages and even arbitrary updates.
163163

@@ -298,9 +298,9 @@ There are many more API methods, to read the full API documentation::
298298

299299
$ pydoc telegram.Bot
300300

301-
-----------
301+
----------
302302
_`Logging`
303-
-----------
303+
----------
304304

305305
You can get logs in your main application by calling `logging` and setting the log level you want::
306306

@@ -318,14 +318,24 @@ _`Examples`
318318

319319
Here follows some examples to help you to get your own Bot up to speed:
320320

321-
- `echobot <https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/echobot.py>`_ replies back messages.
321+
- `echobot2 <https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/echobot2.py>`_ replies back messages.
322+
323+
- `clibot <https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/clibot.py>`_ has a command line interface.
322324

323-
- `roboed <https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/roboed.py>`_ talks to `Robô Ed <http://www.ed.conpet.gov.br/br/converse.php>`_.
325+
- `Welcome Bot <https://github.com/jh0ker/welcomebot>`_ greets everyone who joins a group chat.
326+
327+
Legacy examples (pre-3.0):
328+
329+
- `echobot <https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/legacy/echobot.py>`_ replies back messages.
330+
331+
- `roboed <https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/legacy/roboed.py>`_ talks to `Robô Ed <http://www.ed.conpet.gov.br/br/converse.php>`_.
324332

325333
- `Simple-Echo-Telegram-Bot <https://github.com/sooyhwang/Simple-Echo-Telegram-Bot>`_ simple Python Telegram bot that echoes your input with Flask microframework, setWebhook method, and Google App Engine (optional) - by @sooyhwang.
326334

327335
- `DevOps Reaction Bot <https://github.com/leandrotoledo/gae-devops-reaction-telegram-bot>`_ sends latest or random posts from `DevOps Reaction <http://devopsreactions.tumblr.com/>`_. Running on `Google App Engine <https://cloud.google.com/appengine>`_ (billing has to be enabled for fully Socket API support).
328336

337+
Other notable examples:
338+
329339
- `TwitterForwarderBot <https://github.com/franciscod/telegram-twitter-forwarder-bot>`_ forwards you tweets from people that you have subscribed to.
330340

331341
================
Lines changed: 35 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#!/usr/bin/env python
22
# -*- coding: utf-8 -*-
33
#
4-
# Simple Bot to reply to Telegram messages
4+
# Example Bot to show some of the functionality of the library
55
# Copyright (C) 2015 Leandro Toledo de Souza <devs@python-telegram-bot.org>
66
#
77
# This program is free software: you can redistribute it and/or modify
@@ -27,33 +27,29 @@
2727
inserted into the update queue for the bot to handle.
2828
2929
Usage:
30-
Basic Echobot example, repeats messages. Reply to last chat from the command
31-
line by typing "/reply <text>"
30+
Repeats messages with a delay.
31+
Reply to last chat from the command line by typing "/reply <text>"
3232
Type 'stop' on the command line to stop the bot.
3333
"""
3434

3535
from telegram import Updater
3636
from telegram.dispatcher import run_async
3737
from time import sleep
3838
import logging
39-
import sys
4039

41-
root = logging.getLogger()
42-
root.setLevel(logging.INFO)
40+
# Enable Logging
41+
logging.basicConfig(
42+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
43+
level=logging.INFO)
4344

44-
ch = logging.StreamHandler(sys.stdout)
45-
ch.setLevel(logging.INFO)
46-
formatter = \
47-
logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
48-
ch.setFormatter(formatter)
49-
root.addHandler(ch)
45+
logger = logging.getLogger(__name__)
5046

47+
# We use this var to save the last chat id, so we can reply to it
5148
last_chat_id = 0
5249

53-
logger = logging.getLogger(__name__)
54-
5550

56-
# Command Handlers
51+
# Define a few (command) handlers. These usually take the two arguments bot and
52+
# update. Error handlers also receive the raised TelegramError object in error.
5753
def start(bot, update):
5854
""" Answer in Telegram """
5955
bot.sendMessage(update.message.chat_id, text='Hi!')
@@ -87,25 +83,20 @@ def message(bot, update, **kwargs):
8783
"""
8884
Example for an asynchronous handler. It's not guaranteed that replies will
8985
be in order when using @run_async. Also, you have to include **kwargs in
90-
your parameter list.
86+
your parameter list. The kwargs contain all optional parameters that are
9187
"""
9288

93-
print(kwargs)
94-
9589
sleep(2) # IO-heavy operation here
9690
bot.sendMessage(update.message.chat_id, text='Echo: %s' %
9791
update.message.text)
9892

9993

100-
def error(bot, update, error):
101-
""" Print error to console """
102-
logger.warn('Update %s caused error %s' % (update, error))
103-
104-
94+
# These handlers are for updates of type str. We use them to react to inputs
95+
# on the command line interface
10596
def cli_reply(bot, update, args):
10697
"""
107-
For any update of type telegram.Update or str, you can get the argument
108-
list by appending args to the function parameters.
98+
For any update of type telegram.Update or str that contains a command, you
99+
can get the argument list by appending args to the function parameters.
109100
Here, we reply to the last active chat with the text after the command.
110101
"""
111102
if last_chat_id is not 0:
@@ -117,6 +108,9 @@ def cli_noncommand(bot, update, update_queue):
117108
You can also get the update queue as an argument in any handler by
118109
appending it to the argument list. Be careful with this though.
119110
Here, we put the input string back into the queue, but as a command.
111+
112+
To learn more about those optional handler parameters, read:
113+
http://python-telegram-bot.readthedocs.org/en/latest/telegram.dispatcher.html
120114
"""
121115
update_queue.put('/%s' % update)
122116

@@ -125,28 +119,39 @@ def unknown_cli_command(bot, update):
125119
logger.warn("Command not found: %s" % update)
126120

127121

122+
def error(bot, update, error):
123+
""" Print error to console """
124+
logger.warn('Update %s caused error %s' % (update, error))
125+
126+
128127
def main():
129128
# Create the EventHandler and pass it your bot's token.
130-
token = 'token'
131-
updater = Updater(token, workers=2)
129+
token = 'TOKEN'
130+
updater = Updater(token, workers=10)
132131

133132
# Get the dispatcher to register handlers
134133
dp = updater.dispatcher
135134

135+
# This is how we add handlers for Telegram messages
136136
dp.addTelegramCommandHandler("start", start)
137137
dp.addTelegramCommandHandler("help", help)
138138
dp.addUnknownTelegramCommandHandler(unknown_command)
139+
# Message handlers only receive updates that don't contain commands
139140
dp.addTelegramMessageHandler(message)
141+
# Regex handlers will receive all updates on which their regex matches
140142
dp.addTelegramRegexHandler('.*', any_message)
141143

144+
# String handlers work pretty much the same
142145
dp.addStringCommandHandler('reply', cli_reply)
143146
dp.addUnknownStringCommandHandler(unknown_cli_command)
144147
dp.addStringRegexHandler('[^/].*', cli_noncommand)
145148

149+
# All TelegramErrors are caught for you and delivered to the error
150+
# handler(s). Other types of Errors are not caught.
146151
dp.addErrorHandler(error)
147152

148153
# Start the Bot and store the update Queue, so we can insert updates
149-
update_queue = updater.start_polling(poll_interval=0.1, timeout=20)
154+
update_queue = updater.start_polling(poll_interval=0.1, timeout=10)
150155

151156
'''
152157
# Alternatively, run with webhook:
@@ -178,9 +183,9 @@ def main():
178183
updater.stop()
179184
break
180185

181-
# else, put the text into the update queue
186+
# else, put the text into the update queue to be handled by our handlers
182187
elif len(text) > 0:
183-
update_queue.put(text) # Put command into queue
188+
update_queue.put(text)
184189

185190
if __name__ == '__main__':
186191
main()
Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -23,32 +23,27 @@
2323
2424
First, a few handler functions are defined. Then, those functions are passed to
2525
the Dispatcher and registered at their respective places.
26-
Then, the bot is started and the CLI-Loop is entered.
26+
Then, the bot is started and runs until we press Ctrl-C on the command line.
2727
2828
Usage:
2929
Basic Echobot example, repeats messages.
30-
Type 'stop' on the command line to stop the bot.
30+
Press Ctrl-C on the command line or send a signal to the process to stop the
31+
bot.
3132
"""
3233

3334
from telegram import Updater
3435
import logging
35-
import sys
3636

3737
# Enable logging
38-
root = logging.getLogger()
39-
root.setLevel(logging.INFO)
40-
41-
ch = logging.StreamHandler(sys.stdout)
42-
ch.setLevel(logging.DEBUG)
43-
formatter = \
44-
logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
45-
ch.setFormatter(formatter)
46-
root.addHandler(ch)
38+
logging.basicConfig(
39+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
40+
level=logging.INFO)
4741

4842
logger = logging.getLogger(__name__)
4943

5044

51-
# Command Handlers
45+
# Define a few command handlers. These usually take the two arguments bot and
46+
# update. Error handlers also receive the raised TelegramError object in error.
5247
def start(bot, update):
5348
bot.sendMessage(update.message.chat_id, text='Hi!')
5449

@@ -79,14 +74,15 @@ def main():
7974
# on noncommand i.e message - echo the message on Telegram
8075
dp.addTelegramMessageHandler(echo)
8176

82-
# on error - print error to stdout
77+
# log all errors
8378
dp.addErrorHandler(error)
8479

8580
# Start the Bot
86-
updater.start_polling(timeout=5)
81+
updater.start_polling()
8782

88-
# Run the bot until the user presses Ctrl-C or the process receives SIGINT,
89-
# SIGTERM or SIGABRT
83+
# Run the bot until the you presses Ctrl-C or the process receives SIGINT,
84+
# SIGTERM or SIGABRT. This should be used most of the time, since
85+
# start_polling() is non-blocking and will stop the bot gracefully.
9086
updater.idle()
9187

9288
if __name__ == '__main__':

0 commit comments

Comments
 (0)
X Tutup