Skip to content

Commit 2350720

Browse files
committed
Merge branch 'Balduro-boteventhandler'
2 parents e60694a + 185bff7 commit 2350720

File tree

5 files changed

+100
-34
lines changed

5 files changed

+100
-34
lines changed

AUTHORS.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ Contributors
99
The following wonderful people contributed directly or indirectly to this project:
1010

1111
- `Avanatiker <https://github.com/Avanatiker>`_
12+
- `Balduro <https://github.com/Balduro>`_
1213
- `bimmlerd <https://github.com/bimmlerd>`_
1314
- `ErgoZ Riftbit Vaper <https://github.com/ergoz>`_
1415
- `franciscod <https://github.com/franciscod>`_

README.rst

Lines changed: 67 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,11 +54,13 @@ Table of contents
5454

5555
1. `API`_
5656

57-
2. `Logging`_
57+
2. `The Updater class`_
58+
59+
3. `Logging`_
5860

59-
3. `Examples`_
61+
4. `Examples`_
6062

61-
4. `Documentation`_
63+
5. `Documentation`_
6264

6365
- `License`_
6466

@@ -152,10 +154,72 @@ _`Getting started`
152154

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

157+
------
158+
_`The Updater class`
159+
------
160+
161+
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.
162+
163+
As with the old method, we'll need an Access Token. To generate an Access Token, we have to talk to `BotFather <https://telegram.me/botfather>`_ and follow a few simple steps (described `here <https://core.telegram.org/bots#botfather>`_).
164+
165+
First, we create an ``Updater`` object::
166+
167+
>>> from telegram import Updater
168+
>>> updater = Updater(token='token')
169+
170+
For quicker access to the ``Dispatcher`` used by our ``Updater``, we can introduce it locally::
171+
172+
>>> dispatcher = updater.dispatcher
173+
174+
Now, we need to define a function that should process a specific type of update::
175+
176+
>>> def start(bot, update):
177+
... bot.sendMessage(chat_id=update.message.chat_id, text="I'm a bot, please talk to me!")
178+
179+
We want this function to be called on a Telegram message that contains the ``/start`` command, so we need to register it in the dispatcher::
180+
181+
>>> dispatcher.addTelegramCommandHandler('start', start)
182+
183+
The last step is to tell the ``Updater`` to start working::
184+
185+
>>> updater.start_polling()
186+
187+
Our bot is now up and running (go ahead and try it)! It's not doing anything yet, besides answering to the ``/start`` command. Let's add another handler function and register it::
188+
189+
>>> def echo(bot, update):
190+
... bot.sendMessage(chat_id=update.message.chat_id, text=update.message.text)
191+
...
192+
>>> dispatcher.addTelegramMessageHandler(echo)
193+
194+
Our bot should now reply to all messages that are not a command with a message that has the same content.
195+
196+
People might try to send commands to the bot that it doesn't understand, so we should get that covered as well::
197+
198+
>>> def unknown(bot, update):
199+
... bot.sendMessage(chat_id=update.message.chat_id, text="Sorry, I didn't understand that command.")
200+
...
201+
>>> dispatcher.addUnknownTelegramCommandHandler(unknown)
202+
203+
Let's add some functionality to our bot. We want to add the ``/caps`` command, that will take some text as parameter and return it in all caps. We can get the arguments that were passed to the command in the handler function simply by adding it to the parameter list::
204+
205+
>>> def caps(bot, update, args):
206+
... text_caps = ' '.join(args).upper()
207+
... bot.sendMessage(chat_id=update.message.chat_id, text=text_caps)
208+
...
209+
>>> dispatcher.addTelegramCommandHandler('caps', caps)
210+
211+
Now it's time to stop the bot::
212+
213+
>>> updater.stop()
214+
215+
Check out more examples in the `examples folder <https://github.com/leandrotoledo/python-telegram-bot/tree/master/examples>`_!
216+
155217
------
156218
_`API`
157219
------
158220

221+
Note: Using the ``Bot`` class directly is the 'old' method, but some of this is still important information, even if you're using the ``Updater`` class!
222+
159223
The API is exposed via the ``telegram.Bot`` class.
160224

161225
To generate an Access Token you have to talk to `BotFather <https://telegram.me/botfather>`_ and follow a few simple steps (described `here <https://core.telegram.org/bots#botfather>`_).

examples/updater_bot.py

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,8 @@ def unknown_cli_command(bot, update):
106106

107107
def main():
108108
# Create the EventHandler and pass it your bot's token.
109-
updater = Updater("TOKEN", workers=2)
109+
token = 'token'
110+
updater = Updater(token, workers=2)
110111

111112
# Get the dispatcher to register handlers
112113
dp = updater.dispatcher
@@ -125,13 +126,23 @@ def main():
125126

126127
# Start the Bot and store the update Queue, so we can insert updates
127128
update_queue = updater.start_polling(poll_interval=0.1, timeout=20)
129+
128130
'''
129131
# Alternatively, run with webhook:
130-
update_queue = updater.start_webhook('example.com',
132+
updater.bot.setWebhook(webhook_url='https://example.com/%s' % token,
133+
certificate=open('cert.pem', 'wb'))
134+
135+
update_queue = updater.start_webhook('0.0.0.0',
131136
443,
132-
'cert.pem',
133-
'key.key',
134-
listen='0.0.0.0')
137+
url_path=token,
138+
cert='cert.pem',
139+
key='key.key')
140+
141+
# Or, if SSL is handled by a reverse proxy, the webhook URL is already set
142+
# and the reverse proxy is configured to deliver directly to port 6000:
143+
144+
update_queue = updater.start_webhook('0.0.0.0',
145+
6000)
135146
'''
136147

137148
# Start CLI-Loop

telegram/updater.py

Lines changed: 14 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
from time import sleep
1212
import subprocess
1313
from signal import signal, SIGINT, SIGTERM, SIGABRT
14-
1514
from telegram import (Bot, TelegramError, dispatcher, Dispatcher,
1615
NullHandler)
1716
from telegram.utils.webhookhandler import (WebhookServer, WebhookHandler)
@@ -92,17 +91,23 @@ def start_polling(self, poll_interval=1.0, timeout=10, network_delay=2):
9291
# Return the update queue so the main thread can insert updates
9392
return self.update_queue
9493

95-
def start_webhook(self, host, port, listen='0.0.0.0', cert=None, key=None):
94+
def start_webhook(self,
95+
listen='127.0.0.1',
96+
port=80,
97+
url_path='',
98+
cert=None,
99+
key=None):
96100
"""
97101
Starts a small http server to listen for updates via webhook. If cert
98102
and key are not provided, the webhook will be started directly on
99-
http://host:port/, so SSL can be handled by another application. Else,
100-
the webhook will be started on https://host:port/<bot_token>
103+
http://listen:port/url_path, so SSL can be handled by another
104+
application. Else, the webhook will be started on
105+
https://listen:port/url_path
101106
102107
Args:
103-
host (str): Hostname or IP of the bot
104-
port (int): Port the bot should be listening on
105108
listen (Optional[str]): IP-Address to listen on
109+
port (Optional[int]): Port the bot should be listening on
110+
url_path (Optional[str]): Path inside url
106111
cert (Optional[str]): Path to the SSL certificate file
107112
key (Optional[str]): Path to the SSL key file
108113
@@ -115,7 +120,7 @@ def start_webhook(self, host, port, listen='0.0.0.0', cert=None, key=None):
115120
name="dispatcher")
116121
event_handler_thread = Thread(target=self._start_webhook,
117122
name="updater",
118-
args=(host, port, listen, cert, key))
123+
args=(listen, port, url_path, cert, key))
119124

120125
self.running = True
121126

@@ -170,24 +175,10 @@ def _start_polling(self, poll_interval, timeout, network_delay):
170175

171176
self.logger.info('Updater thread stopped')
172177

173-
def _start_webhook(self, host, port, listen, cert, key):
178+
def _start_webhook(self, listen, port, url_path, cert, key):
174179
self.logger.info('Updater thread started')
175180
use_ssl = cert is not None and key is not None
176-
177-
url_base = "https://%s:%d" % (host, port)
178-
if use_ssl:
179-
url_path = "/%s" % self.bot.token
180-
certfile = open(cert, 'rb')
181-
else:
182-
url_path = "/"
183-
certfile = None
184-
185-
# Remove webhook
186-
self.bot.setWebhook(webhook_url=None)
187-
188-
# Set webhook
189-
self.bot.setWebhook(webhook_url=url_base + url_path,
190-
certificate=certfile)
181+
url_path = "/%s" % url_path
191182

192183
# Create and start server
193184
self.httpd = WebhookServer((listen, port), WebhookHandler,

tests/test_updater.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -350,7 +350,7 @@ def test_webhook(self):
350350
# Select random port for travis
351351
port = randrange(1024, 49152)
352352
self.updater.start_webhook('127.0.0.1', port,
353-
listen='127.0.0.1',
353+
url_path='TOKEN',
354354
cert='./tests/test_updater.py',
355355
key='./tests/test_updater.py')
356356
sleep(0.5)
@@ -411,8 +411,7 @@ def test_webhook_no_ssl(self):
411411

412412
# Select random port for travis
413413
port = randrange(1024, 49152)
414-
self.updater.start_webhook('127.0.0.1', port,
415-
listen='127.0.0.1',)
414+
self.updater.start_webhook('127.0.0.1', port)
416415
sleep(0.5)
417416

418417
# Now, we send an update to the server via urlopen

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy