Skip to content

Commit 8e9837a

Browse files
committed
Merge branch 'develop'
2 parents 3273aa9 + 361c043 commit 8e9837a

12 files changed

Lines changed: 467 additions & 45 deletions

File tree

‎README.md‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ To start the bot, simply open up a terminal and enter `python echo_bot.py` to ru
118118

119119
All types are defined in types.py. They are all completely in line with the [Telegram API's definition of the types](https://core.telegram.org/bots/api#available-types), except for the Message's `from` field, which is renamed to `from_user` (because `from` is a Python reserved token). Thus, attributes such as `message_id` can be accessed directly with `message.message_id`. Note that `message.chat` can be either an instance of `User` or `GroupChat` (see [How can I distinguish a User and a GroupChat in message.chat?](#how-can-i-distinguish-a-user-and-a-groupchat-in-messagechat)).
120120

121-
The Message object also has a `content_type`attribute, which defines the type of the Message. `content_type` can be one of the following strings:
121+
The Message object also has a `content_type`attribute, which defines the type of the Message. `content_type` can be one of the following strings:
122122
'text', 'audio', 'document', 'photo', 'sticker', 'video', 'location', 'contact', 'new_chat_participant', 'left_chat_participant', 'new_chat_title', 'new_chat_photo', 'delete_chat_photo', 'group_chat_created'.
123123

124124
### Methods
@@ -208,7 +208,7 @@ tb.polling(none_stop=False, interval=0, block=True)
208208
user = tb.get_me()
209209

210210
# setWebhook
211-
tb.set_webhook(url="http://example.com", cert=open('mycert.pem'))
211+
tb.set_webhook(url="http://example.com", certificate=open('mycert.pem'))
212212
# unset webhook
213213
tb.remove_webhook()
214214

@@ -373,8 +373,10 @@ bot.set_update_listener(handle_messages)
373373
bot.polling()
374374
```
375375

376-
### Using web hooks
377-
If you prefer using web hooks to the getUpdates method, you can use the `process_new_messages(messages)` function in TeleBot to make it process the messages that you supply. It takes a list of Message objects. This function is still incubating.
376+
### Using webhooks
377+
When using webhooks telegram sends one Update per call, for processing it you should call process_new_messages([update.message]) when you recieve it.
378+
379+
There are some examples using webhooks in the *examples/webhook_examples* directory.
378380

379381
### Logging
380382

@@ -423,4 +425,4 @@ We now have a Telegram Channel as well! Keep yourself up to date with API change
423425

424426
## Bots using this API
425427
* [SiteAlert bot](https://telegram.me/SiteAlert_bot) ([source](https://github.com/ilteoood/SiteAlert-Python)) by *ilteoood* - Monitors websites and sends a notification on changes
426-
Want to have your bot listed here? Send a Telegram message to @eternnoir or @pevdh.
428+
Want to have your bot listed here? Send a Telegram message to @eternnoir or @pevdh.

‎README.rst‎

Lines changed: 82 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ API <https://core.telegram.org/bots/api>`__.
5252

5353
- `The Telegram Chat Group <#the-telegram-chat-group>`__
5454
- `More examples <#more-examples>`__
55+
- `Bots using this API <#bots-using-this-api>`__
5556

5657
Getting started.
5758
================
@@ -213,9 +214,39 @@ Outlined below are some general use cases of the API.
213214
Message handlers
214215
~~~~~~~~~~~~~~~~
215216

216-
A message handler is a function which is decorated with the
217-
``message_handler`` decorator of a TeleBot instance. The following
218-
examples illustrate the possibilities of message handlers:
217+
A message handler is a function that is decorated with the
218+
``message_handler`` decorator of a TeleBot instance. Message handlers
219+
consist of one or multiple filters. Each filter much return True for a
220+
certain message in order for a message handler to become eligible to
221+
handle that message. A message handler is declared in the following way
222+
(provided ``bot`` is an instance of TeleBot):
223+
224+
.. code:: python
225+
226+
@bot.message_handler(filters)
227+
def function_name(message):
228+
bot.reply_to(message, "This is a message handler")
229+
230+
``function_name`` is not bound to any restrictions. Any function name is
231+
permitted with message handlers. The function must accept at most one
232+
argument, which will be the message that the function must handle.
233+
``filters`` is a list of keyword arguments. A filter is declared in the
234+
following manner: ``name=argument``. One handler may have multiple
235+
filters. TeleBot supports the following filters:
236+
237+
+------------------+---------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
238+
| name | argument(s) | Condition |
239+
+==================+=============================================+=================================================================================================================================================================================+
240+
| content\_types | list of strings (default ``['text']``) | ``True`` if message.content\_type is in the list of strings. |
241+
+------------------+---------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
242+
| regexp | a regular expression as a string | ``True`` if ``re.search(regexp_arg)`` returns ``True`` and ``message.content_type == 'text'`` (See `Python Regular Expressions <https://docs.python.org/2/library/re.html>`__ |
243+
+------------------+---------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
244+
| commands | list of strings | ``True`` if ``message.content_type == 'text'`` and ``message.text`` starts with a command that is in the list of strings. |
245+
+------------------+---------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
246+
| func | a function (lambda or function reference) | ``True`` if the lambda or function reference returns ``True`` |
247+
+------------------+---------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
248+
249+
Here are some examples of using the filters and message handlers:
219250

220251
.. code:: python
221252
@@ -250,8 +281,15 @@ examples illustrate the possibilities of message handlers:
250281
def handle_text_doc(message)
251282
pass
252283
253-
*Note: all handlers are tested in the order in which they were declared*
254-
#### TeleBot
284+
# Handlers can be stacked to create a function which will be called if either message_handler is eligible
285+
# This handler will be called if the message starts with '/hello' OR is some emoji
286+
@bot.message_handler(commands=['hello'])
287+
@bot.message_handler(func=lambda msg: msg.text.encode("utf-8") == SOME_FANCY_EMOJI)
288+
def send_something(message):
289+
pass
290+
291+
**Important: all handlers are tested in the order in which they were
292+
declared** #### TeleBot
255293

256294
.. code:: python
257295
@@ -270,6 +308,11 @@ examples illustrate the possibilities of message handlers:
270308
# getMe
271309
user = tb.get_me()
272310
311+
# setWebhook
312+
tb.set_webhook(url="http://example.com", certificate=open('mycert.pem'))
313+
# unset webhook
314+
tb.remove_webhook()
315+
273316
# getUpdates
274317
updates = tb.get_updates()
275318
updates = tb.get_updates(1234,100,20) #get_Updates(offset, limit, timeout):
@@ -322,6 +365,14 @@ examples illustrate the possibilities of message handlers:
322365
# 'record_audio', 'upload_audio', 'upload_document' or 'find_location'.
323366
tb.send_chat_action(chat_id, action_string)
324367
368+
# getFile
369+
# Downloading a file is straightforward
370+
# Returns a File object
371+
import requests
372+
file_info = tb.get_file(file_id)
373+
374+
file = requests.get('https://api.telegram.org/file/bot{0}/{1}'.format(API_TOKEN, file_info.file_path))
375+
325376
Reply markup
326377
~~~~~~~~~~~~
327378

@@ -465,29 +516,31 @@ function as a listener to TeleBot. Example:
465516
bot.set_update_listener(handle_messages)
466517
bot.polling()
467518
468-
Using web hooks
469-
---------------
519+
Using webhooks
520+
--------------
521+
522+
When using webhooks telegram sends one Update per call, for processing
523+
it you should call process\_new\_messages([update.message]) when you
524+
recieve it.
470525

471-
If you prefer using web hooks to the getUpdates method, you can use the
472-
``process_new_messages(messages)`` function in TeleBot to make it
473-
process the messages that you supply. It takes a list of Message
474-
objects. This function is still incubating.
526+
There are some examples using webhooks in the
527+
*examples/webhook\_examples* directory.
475528

476529
Logging
477530
-------
478531

479532
You can use the Telebot module logger to log debug info about Telebot.
480-
Use ``telebot.logger`` to get the logger of the TeleBot module.
533+
Use ``telebot.logger`` to get the logger of the TeleBot module. It is
534+
possible to add custom logging Handlers to the logger. Refer to the
535+
`Python logging module
536+
page <https://docs.python.org/2/library/logging.html>`__ for more info.
481537

482538
.. code:: python
483539
540+
import logging
541+
484542
logger = telebot.logger
485-
formatter = logging.Formatter('[%(asctime)s] %(thread)d {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s',
486-
'%m-%d %H:%M:%S')
487-
ch = logging.StreamHandler(sys.stdout)
488-
logger.addHandler(ch)
489-
logger.setLevel(logging.DEBUG) # or use logging.INFO
490-
ch.setFormatter(formatter)
543+
telebot.logger.setLevel(logging.DEBUG) # Outputs debug messages to console.
491544
492545
F.A.Q.
493546
======
@@ -513,6 +566,8 @@ Get help. Discuss. Chat.
513566

514567
Join the `pyTelegramBotAPI Telegram Chat
515568
Group <https://telegram.me/joinchat/067e22c60035523fda8f6025ee87e30b>`__.
569+
We now have a Telegram Channel as well! Keep yourself up to date with
570+
API changes, and `join it <https://telegram.me/pytelegrambotapi>`__.
516571

517572
More examples
518573
=============
@@ -524,5 +579,14 @@ More examples
524579
- `next\_step\_handler
525580
Example <https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/step_example.py>`__
526581

582+
Bots using this API
583+
===================
584+
585+
- `SiteAlert bot <https://telegram.me/SiteAlert_bot>`__
586+
(`source <https://github.com/ilteoood/SiteAlert-Python>`__) by
587+
*ilteoood* - Monitors websites and sends a notification on changes
588+
Want to have your bot listed here? Send a Telegram message to
589+
@eternnoir or @pevdh.
590+
527591
.. |Build Status| image:: https://travis-ci.org/eternnoir/pyTelegramBotAPI.svg?branch=master
528592
:target: https://travis-ci.org/eternnoir/pyTelegramBotAPI
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Webhook examples using pyTelegramBotAPI
2+
3+
There are 3 examples in this directory using different libraries:
4+
5+
* **Python (CPython):** *webhook_cpython_echo_bot.py*
6+
* **Pros:**
7+
* Official python libraries, it works out of the box (doesn't require to
8+
install anything).
9+
* Works with Python 2 and Python 3 (need to be converted with 2to3).
10+
* **Cons:**
11+
* Ugly code.
12+
* Many things to handle yourself, this can lead to errors.
13+
* Not powerful, do the trick but the performance is low.
14+
15+
* **CherryPy (3.8.0):** *webhook_cherrypy_echo_bot.py*
16+
* **Pros:**
17+
* It's a web application framework, cleaner code, uses objects for defining
18+
the web application.
19+
* Very good performance.
20+
* The project seems to be active, latest version is recent.
21+
* Works with Python 2 and Python 3.
22+
* **Cons:**
23+
* Some things are not very intuitive, reading the doc is a must.
24+
25+
* **Flask (0.10.1):** *webhook_flask_echo_bot.py*
26+
* **Pros:**
27+
* It's a web application framework, cleaner code, uses decorator which can
28+
be nice.
29+
* Good performance.
30+
* It's intuitive if you know how web application works.
31+
* **Cons:**
32+
* The project seems not to be very active, latest version dates 2013.
33+
* They don't recommend to use it with Python 3, but may work.
34+
* May be a oversized for just handling webhook petitions.
35+
36+
*Latest update of this document: 2015-10-06*
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
# This is a simple echo bot using decorators and webhook with CherryPy
5+
# It echoes any incoming text messages and does not use the polling method.
6+
7+
import cherrypy
8+
import telebot
9+
import logging
10+
11+
12+
API_TOKEN = '<api_token>'
13+
14+
WEBHOOK_HOST = '<ip/host where the bot is running>'
15+
WEBHOOK_PORT = 8443 # 443, 80, 88 or 8443 (port need to be 'open')
16+
WEBHOOK_LISTEN = '0.0.0.0' # In some VPS you may need to put here the IP addr
17+
18+
WEBHOOK_SSL_CERT = './webhook_cert.pem' # Path to the ssl certificate
19+
WEBHOOK_SSL_PRIV = './webhook_pkey.pem' # Path to the ssl private key
20+
21+
# Quick'n'dirty SSL certificate generation:
22+
#
23+
# openssl genrsa -out webhook_pkey.pem 2048
24+
# openssl req -new -x509 -days 3650 -key webhook_pkey.pem -out webhook_cert.pem
25+
#
26+
# When asked for "Common Name (e.g. server FQDN or YOUR name)" you should reply
27+
# with the same value in you put in WEBHOOK_HOST
28+
29+
WEBHOOK_URL_BASE = "https://%s:%s" % (WEBHOOK_HOST, WEBHOOK_PORT)
30+
WEBHOOK_URL_PATH = "/%s/" % (API_TOKEN)
31+
32+
33+
logger = telebot.logger
34+
telebot.logger.setLevel(logging.INFO)
35+
36+
bot = telebot.TeleBot(API_TOKEN)
37+
38+
39+
# WebhookServer, process webhook calls
40+
class WebhookServer(object):
41+
@cherrypy.expose
42+
def index(self):
43+
if 'content-length' in cherrypy.request.headers and \
44+
'content-type' in cherrypy.request.headers and \
45+
cherrypy.request.headers['content-type'] == 'application/json':
46+
length = int(cherrypy.request.headers['content-length'])
47+
json_string = cherrypy.request.body.read(length)
48+
update = telebot.types.Update.de_json(json_string)
49+
bot.process_new_messages([update.message])
50+
return ''
51+
else:
52+
raise cherrypy.HTTPError(403)
53+
54+
55+
# Handle '/start' and '/help'
56+
@bot.message_handler(commands=['help', 'start'])
57+
def send_welcome(message):
58+
bot.reply_to(message,
59+
("Hi there, I am EchoBot.\n"
60+
"I am here to echo your kind words back to you."))
61+
62+
63+
# Handle all other messages
64+
@bot.message_handler(func=lambda message: True, content_types=['text'])
65+
def echo_message(message):
66+
bot.reply_to(message, message.text)
67+
68+
69+
# Remove webhook, it fails sometimes the set if there is a previous webhook
70+
bot.remove_webhook()
71+
72+
# Set webhook
73+
bot.set_webhook(url=WEBHOOK_URL_BASE+WEBHOOK_URL_PATH,
74+
certificate=open(WEBHOOK_SSL_CERT, 'r'))
75+
76+
# Start cherrypy server
77+
cherrypy.config.update({
78+
'server.socket_host': WEBHOOK_LISTEN,
79+
'server.socket_port': WEBHOOK_PORT,
80+
'server.ssl_module': 'builtin',
81+
'server.ssl_certificate': WEBHOOK_SSL_CERT,
82+
'server.ssl_private_key': WEBHOOK_SSL_PRIV
83+
})
84+
85+
cherrypy.quickstart(WebhookServer(), WEBHOOK_URL_PATH, {'/': {}})

0 commit comments

Comments
 (0)