Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions examples/multiple_handlers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
#!/usr/bin/python
# -*- coding: iso-8859-15 -*-

"""
This will show how you could split logic processing into multiple_handlers
"""

from pytg import Telegram
from pytg.utils import coroutine

def main():

tg = Telegram(
telegram="/usr/bin/telegram-cli",
pubkey_file="/etc/share/telegram-cli/server.pub"
)

# get a Receiver instance, to get messages.
receiver = tg.receiver

# get a Sender instance, to send messages, and other querys.
sender = tg.sender

# start the Receiver, so we can get messages!
receiver.start() # note that the Sender has no need for a start function.

# add handlers to the receiver
receiver.add_handler(text_handler(sender))
receiver.add_handler(media_handler(sender))

# start processing the handlers
receiver.process_handlers()

# please, no more messages. (we could stop the the cli too, with sender.safe_quit() )
receiver.stop()

# continues here, after exiting while loop in example_function()
print("I am done!")

# the sender will disconnect after each send, so there is no need to stop it.
# if you want to shutdown the telegram cli:
# sender.safe_quit() # this shuts down the telegram cli.
# sender.quit() # this shuts down the telegram cli, without waiting for downloads to complete.

# end def main

@coroutine
def text_handler(sender):
try:
while True:
msg = (yield)
print(msg)
sender.status_online()

if 'text' in msg and msg.text == "/hello":
sender.reply(msg.id, 'detected text: ' + msg.text)

except GeneratorExit:
# the generator (pytg) exited (got a KeyboardIterrupt).
pass
except KeyboardInterrupt:
# we got a KeyboardIterrupt(Ctrl+C)
pass
else:
# the loop exited without exception, because _quit was set True
pass

@coroutine
def media_handler(sender):
try:
while True:
msg = (yield)
sender.status_online()

if 'media' in msg:
sender.reply(msg.id, 'media detectado')

except GeneratorExit:
# the generator (pytg) exited (got a KeyboardIterrupt).
pass
except KeyboardInterrupt:
# we got a KeyboardIterrupt(Ctrl+C)
pass
else:
# the loop exited without exception, because _quit was set True
pass

# # program starts here # #
if __name__ == '__main__':
main() # executing main function.
# Last command of file (so everything needed is already loaded above)
21 changes: 16 additions & 5 deletions pytg/receiver.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ class Receiver(object):
_queue = deque()
_new_messages = threading.Semaphore(0)
_queue_access = threading.Lock()

_handlers = []

def __init__(self, host="localhost", port=4458, append_json=False):
"""
:param append_json: if the dict should contain the original json.
Expand Down Expand Up @@ -199,17 +200,27 @@ def _add_message(self, text):
self._new_messages.release()
# end def

@coroutine
def message(self, function):
if not isinstance(function, GeneratorType):

def add_handler(self, handler):
if not isinstance(handler, GeneratorType):
raise TypeError('Target must be GeneratorType')
self._handlers.append(handler)

def del_handler(self, handler):
if not isinstance(handler, GeneratorType):
raise TypeError('Target must be GeneratorType')
self._handlers.remove(handler)

@coroutine
def process_handlers(self):
try:
while not self._do_quit:
self._new_messages.acquire() # waits until at least 1 message is in the queue.
with self._queue_access:
message = self._queue.popleft() # pop oldest item
logger.debug('Messages waiting in queue: %d', len(self._queue))
function.send(message)
for handler in self._handlers:
handler.send(message)
except GeneratorExit:
pass
except KeyboardInterrupt:
Expand Down