Skip to content

Commit 3c8faa1

Browse files
committed
Created util.py to clean up __init__.py and apihelper.py and updated README accordingly
Fixed failing send_document_by_id and send_photo_by_id
1 parent 6f34a22 commit 3c8faa1

6 files changed

Lines changed: 161 additions & 171 deletions

File tree

‎README.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,7 @@ To enable this behaviour, create an instance of AsyncTeleBot instead of TeleBot.
282282
```python
283283
tb = telebot.AsyncTeleBot("TOKEN")
284284
```
285-
Now, every function that calls the Telegram API is executed in a separate Thread. The functions are modified to return an AsyncTask instance (defined in \__init__.py). Using AsyncTeleBot allows you to do the following:
285+
Now, every function that calls the Telegram API is executed in a separate Thread. The functions are modified to return an AsyncTask instance (defined in util.py). Using AsyncTeleBot allows you to do the following:
286286
```python
287287
import telebot
288288

@@ -300,12 +300,12 @@ result = task.wait() # Get the result of the execution
300300
### Sending large text messages
301301
Sometimes you must send messages that exceed 5000 characters. The Telegram API can not handle that many characters in one request, so we need to split the message in multiples. Here is how to do that using the API:
302302
```python
303-
from telebot import apihelper
303+
from telebot import util
304304
large_text = open("large_text.txt", "rb").read()
305305

306306
# Split the text each 3000 characters.
307307
# split_string returns a list with the splitted text.
308-
splitted_text = apihelper.split_string(large_text, 3000)
308+
splitted_text = util.split_string(large_text, 3000)
309309
for text in splitted_text:
310310
tb.send_message(chat_id, text)
311311
```

‎telebot/__init__.py‎

Lines changed: 16 additions & 102 deletions
Original file line numberDiff line numberDiff line change
@@ -2,67 +2,21 @@
22
from __future__ import print_function
33

44
import threading
5-
# Python3 queue support.
6-
try:
7-
import Queue
8-
except ImportError:
9-
import queue as Queue
105
import time
116

127
import logging
138
logging.basicConfig()
149
logger = logging.getLogger('Telebot')
1510
import re
16-
from telebot import apihelper, types
11+
12+
from telebot import apihelper, types, util
1713

1814
"""
1915
Module : telebot
2016
"""
2117

2218
API_URL = r"https://api.telegram.org/"
2319

24-
25-
class ThreadPool:
26-
class WorkerThread(threading.Thread):
27-
count = 0
28-
29-
def __init__(self, queue):
30-
threading.Thread.__init__(self, name="WorkerThread{0}".format(self.__class__.count + 1))
31-
self.__class__.count += 1
32-
self.queue = queue
33-
self.daemon = True
34-
35-
self._running = True
36-
self.start()
37-
38-
def run(self):
39-
while self._running:
40-
try:
41-
task, args, kwargs = self.queue.get()
42-
task(*args, **kwargs)
43-
except Queue.Empty:
44-
time.sleep(0)
45-
pass
46-
47-
def stop(self):
48-
self._running = False
49-
50-
def __init__(self, num_threads=4):
51-
self.tasks = Queue.Queue()
52-
self.workers = [self.WorkerThread(self.tasks) for _ in range(num_threads)]
53-
54-
self.num_threads = num_threads
55-
56-
def put(self, func, *args, **kwargs):
57-
self.tasks.put((func, args, kwargs))
58-
59-
def close(self):
60-
for worker in self.workers:
61-
worker.stop()
62-
for worker in self.workers:
63-
worker.join()
64-
65-
6620
class TeleBot:
6721
""" This is TeleBot Class
6822
Methods:
@@ -82,7 +36,6 @@ class TeleBot:
8236

8337
def __init__(self, token, create_threads=True, num_threads=4):
8438
"""
85-
8639
:param token: bot API token
8740
:param create_threads: Create thread for message handler
8841
:param num_threads: Number of worker in thread pool.
@@ -104,7 +57,7 @@ def __init__(self, token, create_threads=True, num_threads=4):
10457

10558
self.message_handlers = []
10659
if self.__create_threads:
107-
self.worker_pool = ThreadPool(num_threads)
60+
self.worker_pool = util.ThreadPool(num_threads)
10861

10962
def get_update(self):
11063
"""
@@ -158,7 +111,6 @@ def polling(self, none_stop=False, interval=0, block=True):
158111
if block:
159112
self.__stop_polling.wait()
160113

161-
162114
def __polling(self, none_stop, interval):
163115
logger.info('TeleBot: Started polling.')
164116

@@ -249,7 +201,7 @@ def send_audio(self, chat_id, audio, duration=None, performer=None, title=None,
249201
:param duration:Duration of the audio in seconds
250202
:param performer:Performer
251203
:param title:Track name
252-
:param reply_to_message_id:If the message is a reply, ID of the original messag
204+
:param reply_to_message_id:If the message is a reply, ID of the original message
253205
:param reply_markup:
254206
:return: Message
255207
"""
@@ -438,7 +390,7 @@ def _test_message_handler(message_handler, message):
438390
if message.content_type not in message_handler['content_types']:
439391
return False
440392
if 'commands' in message_handler and message.content_type == 'text':
441-
return apihelper.extract_command(message.text) in message_handler['commands']
393+
return util.extract_command(message.text) in message_handler['commands']
442394
if 'regexp' in message_handler and message.content_type == 'text' and re.search(message_handler['regexp'],
443395
message.text):
444396
return True
@@ -452,93 +404,55 @@ def _notify_command_handlers(self, new_messages):
452404
if self._test_message_handler(message_handler, message):
453405
if self.__create_threads:
454406
self.worker_pool.put(message_handler['function'], message)
455-
# t = threading.Thread(target=message_handler['function'], args=(message,))
456-
# t.start()
457407
else:
458408
message_handler['function'](message)
459409
break
460410

461411

462-
class AsyncTask:
463-
def __init__(self, target, *args, **kwargs):
464-
self.target = target
465-
self.args = args
466-
self.kwargs = kwargs
467-
468-
self.done = False
469-
self.thread = threading.Thread(target=self._run)
470-
self.thread.start()
471-
472-
def _run(self):
473-
try:
474-
self.result = self.target(*self.args, **self.kwargs)
475-
except Exception as e:
476-
self.result = e
477-
self.done = True
478-
479-
def wait(self):
480-
if not self.done:
481-
self.thread.join()
482-
if isinstance(self.result, Exception):
483-
raise self.result
484-
else:
485-
return self.result
486-
487-
488-
def async():
489-
def decorator(fn):
490-
def wrapper(*args, **kwargs):
491-
return AsyncTask(fn, *args, **kwargs)
492-
493-
return wrapper
494-
495-
return decorator
496-
497-
498412
class AsyncTeleBot(TeleBot):
499413
def __init__(self, *args, **kwargs):
500414
TeleBot.__init__(self, *args, **kwargs)
501415

502-
@async()
416+
@util.async()
503417
def get_me(self):
504418
return TeleBot.get_me(self)
505419

506-
@async()
420+
@util.async()
507421
def get_user_profile_photos(self, *args, **kwargs):
508422
return TeleBot.get_user_profile_photos(self, *args, **kwargs)
509423

510-
@async()
424+
@util.async()
511425
def send_message(self, *args, **kwargs):
512426
return TeleBot.send_message(self, *args, **kwargs)
513427

514-
@async()
428+
@util.async()
515429
def forward_message(self, *args, **kwargs):
516430
return TeleBot.forward_message(self, *args, **kwargs)
517431

518-
@async()
432+
@util.async()
519433
def send_photo(self, *args, **kwargs):
520434
return TeleBot.send_photo(self, *args, **kwargs)
521435

522-
@async()
436+
@util.async()
523437
def send_audio(self, *args, **kwargs):
524438
return TeleBot.send_audio(self, *args, **kwargs)
525439

526-
@async()
440+
@util.async()
527441
def send_document(self, *args, **kwargs):
528442
return TeleBot.send_document(self, *args, **kwargs)
529443

530-
@async()
444+
@util.async()
531445
def send_sticker(self, *args, **kwargs):
532446
return TeleBot.send_sticker(self, *args, **kwargs)
533447

534-
@async()
448+
@util.async()
535449
def send_video(self, *args, **kwargs):
536450
return TeleBot.send_video(self, *args, **kwargs)
537451

538-
@async()
452+
@util.async()
539453
def send_location(self, *args, **kwargs):
540454
return TeleBot.send_location(self, *args, **kwargs)
541455

542-
@async()
456+
@util.async()
543457
def send_chat_action(self, *args, **kwargs):
544458
return TeleBot.send_chat_action(self, *args, **kwargs)

‎telebot/apihelper.py‎

Lines changed: 6 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
# -*- coding: utf-8 -*-
22

33
import requests
4-
from six import string_types
54
import telebot
65
from telebot import types
6+
from telebot import util
77

88
logger = telebot.logger
99

@@ -115,7 +115,7 @@ def send_photo(token, chat_id, photo, caption=None, reply_to_message_id=None, re
115115
method_url = r'sendPhoto'
116116
payload = {'chat_id': chat_id}
117117
files = None
118-
if not is_string(photo):
118+
if not util.is_string(photo):
119119
files = {'photo': photo}
120120
else:
121121
payload['photo'] = photo
@@ -148,7 +148,7 @@ def send_video(token, chat_id, data, duration=None, caption=None, reply_to_messa
148148
method_url = r'sendVideo'
149149
payload = {'chat_id': chat_id}
150150
files = None
151-
if not is_string(data):
151+
if not util.is_string(data):
152152
files = {'video': data}
153153
else:
154154
payload['video'] = data
@@ -167,7 +167,7 @@ def send_voice(token, chat_id, voice, duration=None, reply_to_message_id=None, r
167167
method_url = r'sendVoice'
168168
payload = {'chat_id': chat_id}
169169
files = None
170-
if not is_string(voice):
170+
if not util.is_string(voice):
171171
files = {'voice': voice}
172172
else:
173173
payload['voice'] = voice
@@ -185,7 +185,7 @@ def send_audio(token, chat_id, audio, duration=None, performer=None, title=None,
185185
method_url = r'sendAudio'
186186
payload = {'chat_id': chat_id}
187187
files = None
188-
if not is_string(audio):
188+
if not util.is_string(audio):
189189
files = {'audio': audio}
190190
else:
191191
payload['audio'] = audio
@@ -206,7 +206,7 @@ def send_data(token, chat_id, data, data_type, reply_to_message_id=None, reply_m
206206
method_url = get_method_by_type(data_type)
207207
payload = {'chat_id': chat_id}
208208
files = None
209-
if not is_string(data):
209+
if not util.is_string(data):
210210
files = {data_type: data}
211211
else:
212212
payload[data_type] = data
@@ -229,49 +229,6 @@ def _convert_markup(markup):
229229
return markup.to_json()
230230
return markup
231231

232-
233-
def is_string(var):
234-
return isinstance(var, string_types)
235-
236-
237-
def is_command(text):
238-
"""
239-
Checks if `text` is a command. Telegram chat commands start with the '/' character.
240-
:param text: Text to check.
241-
:return: True if `text` is a command, else False.
242-
"""
243-
return text.startswith('/')
244-
245-
246-
def extract_command(text):
247-
"""
248-
Extracts the command from `text` (minus the '/') if `text` is a command (see is_command).
249-
If `text` is not a command, this function returns None.
250-
251-
Examples:
252-
extract_command('/help'): 'help'
253-
extract_command('/help@BotName'): 'help'
254-
extract_command('/search black eyed peas'): 'search'
255-
extract_command('Good day to you'): None
256-
257-
:param text: String to extract the command from
258-
:return: the command if `text` is a command (according to is_command), else None.
259-
"""
260-
return text.split()[0].split('@')[0][1:] if is_command(text) else None
261-
262-
263-
def split_string(text, chars_per_string):
264-
"""
265-
Splits one string into multiple strings, with a maximum amount of `chars_per_string` characters per string.
266-
This is very useful for splitting one giant message into multiples.
267-
268-
:param text: The text to split
269-
:param chars_per_string: The number of characters per line the text is split into.
270-
:return: The splitted text as a list of strings.
271-
"""
272-
return [text[i:i + chars_per_string] for i in range(0, len(text), chars_per_string)]
273-
274-
275232
class ApiException(Exception):
276233
"""
277234
This class represents an Exception thrown when a call to the Telegram API fails.

‎telebot/types.py‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@ class JsonSerializable:
2828
Subclasses of this class are guaranteed to be able to be converted to JSON format.
2929
All subclasses of this class must override to_json.
3030
"""
31-
3231
def to_json(self):
3332
"""
3433
Returns a JSON string representation of this class.
@@ -44,7 +43,6 @@ class JsonDeserializable:
4443
Subclasses of this class are guaranteed to be able to be created from a json-style dict or json formatted string.
4544
All subclasses of this class must override de_json.
4645
"""
47-
4846
@classmethod
4947
def de_json(cls, json_type):
5048
"""

0 commit comments

Comments
 (0)