1
0
mirror of https://github.com/eternnoir/pyTelegramBotAPI.git synced 2023-08-10 21:12:57 +03:00

First implementation attempt

This commit is contained in:
pieter 2015-07-03 19:22:26 +02:00
parent 645c0b7fb4
commit 0af4051dfd

View File

@ -2,6 +2,8 @@
from __future__ import print_function from __future__ import print_function
import threading import threading
import Queue
import time
import re import re
from telebot import apihelper, types from telebot import apihelper, types
@ -12,6 +14,49 @@ Module : telebot
API_URL = r"https://api.telegram.org/" API_URL = r"https://api.telegram.org/"
class ThreadPool:
class WorkerThread(threading.Thread):
count = 0
def __init__(self, queue):
threading.Thread.__init__(self, name="WorkerThread{0}".format(self.__class__.count + 1))
self.__class__.count += 1
self.queue = queue
self.daemon = True
self._running = True
self.start()
def run(self):
while self._running:
try:
task, args, kwargs = self.queue.get(False)
task(*args, **kwargs)
except Queue.Empty:
time.sleep(0)
pass
def stop(self):
self._running = False
def __init__(self, num_threads=4):
self.tasks = Queue.Queue()
self.workers = [self.WorkerThread(self.tasks) for _ in range(num_threads)]
self.num_threads = num_threads
def put(self, func, *args, **kwargs):
self.tasks.put((func, args, kwargs))
def close(self):
for worker in self.workers:
worker.stop()
for worker in self.workers:
worker.join()
class TeleBot: class TeleBot:
""" This is TeleBot Class """ This is TeleBot Class
@ -40,6 +85,8 @@ class TeleBot:
self.last_update_id = 0 self.last_update_id = 0
self.message_handlers = [] self.message_handlers = []
self.worker_pool = ThreadPool()
def get_update(self): def get_update(self):
""" """
@ -61,8 +108,9 @@ class TeleBot:
def __notify_update(self, new_messages): def __notify_update(self, new_messages):
for listener in self.update_listener: for listener in self.update_listener:
t = threading.Thread(target=listener, args=new_messages) self.worker_pool.put(listener, new_messages)
t.start() # t = threading.Thread(target=listener, args=new_messages)
# t.start()
def polling(self): def polling(self):
""" """
@ -312,8 +360,9 @@ class TeleBot:
for message in new_messages: for message in new_messages:
for message_handler in self.message_handlers: for message_handler in self.message_handlers:
if self._test_message_handler(message_handler, message): if self._test_message_handler(message_handler, message):
t = threading.Thread(target=message_handler['function'], args=(message,)) self.worker_pool.put(message_handler['function'], message)
t.start() # t = threading.Thread(target=message_handler['function'], args=(message,))
# t.start()
break break