Ejemplo n.º 1
0
class RelayLayer(YowInterfaceLayer):
    def __init__(self):
        super(RelayLayer, self).__init__()
        self.receiver = Receiver (host="localhost", port=4458)
        self.QUIT = False
        self.receiver.start()
        self.rcv = threading.Thread(target = self.startReceiver)
        self.rcv.daemon = True

    def startReceiver(self):
        self.receiver.message(self.main_loop())

    @ProtocolEntityCallback("success")  # we get this at the start of yowsup, only once.
    def onSuccess(self, ProtocolEntity):
        self.rcv.start()

    @coroutine
    def main_loop(self):
        while True:
            msg = (yield)
            if msg.event != "message":     #not a message
                continue         
            if msg.own:                    #message from us
                continue
            if msg.text == None:           #message not text
                continue
            outgoingMessageProtocolEntity = TextMessageProtocolEntity(    #currently broken, will crash on emoji and other symbols.
                msg.text, to = msg.peer.name + "@s.whatsapp.net")
            self.toLower(outgoingMessageProtocolEntity)
Ejemplo n.º 2
0
def connect():
    global RECEIVER, SENDER

    log.debug('> trying to connect: %s:%s' % (TB_TG_HOST, TB_TG_PORT))
    RECEIVER = Receiver(host=TB_TG_HOST, port=TB_TG_PORT)
    SENDER = Sender(host=TB_TG_HOST, port=TB_TG_PORT)

    RECEIVER.start()
    log.debug('< connected')

    return
Ejemplo n.º 3
0
    def checkTG(self):
	print "CheckTG Started";
	print "Running Threads: "+str(threading.activeCount());
	t = Timer(3600.0,self.checkTG).start();
	#print "Stop Old Receviver";
	if (self.receiver):
		try:
			self.receiver.stop();
			print "Receiver stopped ok";
		except:
			print "Unexpected error:", sys.exc_info()[0];
	try:
		print "Start TG Checker";
		self.receiver = Receiver(host="localhost",port=4458);
		self.receiver.start();
		self.receiver.message(self.example_function(self.receiver));
		self.receiver.stop();
		print "TG CHeck has stopped....";
		self.checkTG();
	except TypeError:
		print "Should really figure out where these type-errors come from";
	except:
		print sys.exc_info();
		print "Unexpected error 2:", sys.exc_info()[0];
		self.checkTG();
	return;
Ejemplo n.º 4
0
 def __init__(self):
     super(RelayLayer, self).__init__()
     self.receiver = Receiver (host="localhost", port=4458)
     self.QUIT = False
     self.receiver.start()
     self.rcv = threading.Thread(target = self.startReceiver)
     self.rcv.daemon = True
Ejemplo n.º 5
0
 def __init__(self):
     signal.signal(signal.SIGTERM, self.sigterm_handler)
     receiver = Receiver(host='tg', port=4458)
     sender = Sender(host='tg', port=4458)
     receiver.start()
     receiver.message(self.listen(receiver, sender))
     print("Program exiting. Stopped at:", time.strftime("%Y/%m/%d-%H:%M:%S"))
     receiver.stop()
Ejemplo n.º 6
0
 def __init__(self, from_users=[], to_users=None):
     """
     List of allowed user to send messages: from_users
     List of users that will receive the message: to_users
     """
     self.from_users = from_users
     self.to_users = to_users
     self.receiver = Receiver(port=PORT)
     self.sender = Sender(host=HOST, port=PORT)
     self.receiver.start()
     # start loop
     self.receiver.message(self.main_loop())
Ejemplo n.º 7
0
 def __init__(self, users=None, groups=None, config=None):
     """
     List of allowed user to send messages: users
     List of groups to reply and receive messages: groups
     """
     self.users = users
     self.groups = groups
     self.receiver = Receiver(port=PORT)
     self.sender = Sender(host=HOST, port=PORT)
     self.receiver.start()
     # extra config
     self.config = config or {}
     # start loop
     self.receiver.message(self.main_loop())
Ejemplo n.º 8
0
class TelegramClient(object):

    def __init__(self, users=None, groups=None, config=None):
        """
        List of allowed user to send messages: users
        List of groups to reply and receive messages: groups
        """
        self.users = users
        self.groups = groups
        self.receiver = Receiver(port=PORT)
        self.sender = Sender(host=HOST, port=PORT)
        self.receiver.start()
        # extra config
        self.config = config or {}
        # start loop
        self.receiver.message(self.main_loop())

    def _get_receiver(self, msg):
        # try to return message to group
        group_name = msg['receiver'].get('name')
        if group_name and group_name in self.groups:
            return self.groups[group_name]
        # try to return message to user
        user_name = msg['sender'].get('username')
        if user_name and user_name in self.users:
            return self.users[user_name]

    def send_reply(self, msg, message):
        self.send_message(self._get_receiver(msg), message)

    def send_message(self, to, message):
        self.sender.send_msg(to, message)

    def send_reply_photo(self, msg, file_path, caption=None):
        self.send_photo(self._get_receiver(msg), file_path, caption)

    def send_photo(self, to, file_path, caption=None):
        self.sender.send_photo(to, file_path, caption)

    def stop(self):
        self.receiver.stop()

    @coroutine
    def main_loop(self):
        try:
            while True:
                msg = (yield)
                if self.read_command(msg) == 'quit':
                    break
        except Exception as e:
            print(u"ERROR: {}".format(e))
        finally:
            self.stop()
Ejemplo n.º 9
0
    def start_Telegram(self):
        # link with telegram-cli
        PATH_TELEGRAM = self.conf['general']['path_telegram']
        PATH_PUBKEY = self.conf['general']['path_pubkey']

        self.receiver = Receiver()
        self.receiver.start()

        # Thread to dump received messages
        self.msg_dump = MessageReceiver(self)
        self.msg_dump.daemon = True
        self.msg_dump.start()

        self.tg = Telegram(telegram=PATH_TELEGRAM,
                           pubkey_file=PATH_PUBKEY)

        #self.receiver = self.tg.receiver
        self.sender = self.tg.sender
Ejemplo n.º 10
0
def main():
	# get a Receiver instance, to get messages.
	receiver = Receiver(host="localhost", port=4458)

	# get a Sender instance, to send messages, and other querys.
	sender = Sender(host="localhost", port=4458)

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

	# add "example_function" function as message listener. You can supply arguments here (like sender).
	receiver.message(example_function(sender))  # now it will call the example_function and yield the new messages.

	# 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!")
Ejemplo n.º 11
0
def main():
	# get a Receiver instance, to get messages.
	receiver = Receiver(host="localhost", port=4458)

	# get a Sender instance, to send messages, and other querys.
	sender = Sender(host="localhost", port=4458)

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

	order_poll = []
	fight_poll = deque([] for _ in range(0, 60))

	fight_codes = ["/f_IB941641", "/f_IA42478", "/f_I3269", "/f_I405985", "/f_I3C237", "/f_I8741134", "/f_I3C8593"]
	for code in fight_codes:
		fight_order(code, fight_poll)

	scheduler = BackgroundScheduler()
	scheduler.add_job(fight, 'interval', seconds=60, args=[sender, order_poll, fight_poll])

	collect(order_poll)
	scheduler.add_job(collect, 'interval', minutes=61, args=[order_poll])

	scheduler.add_job(send_order, 'interval', seconds=1, args=[sender, order_poll])

	scheduler.start()

	# add "example_function" function as message listener. You can supply arguments here (like sender).
	receiver.message(message_loop(sender, order_poll, fight_poll))  # now it will call the example_function and yield the new messages.

	# continues here, after exiting the while loop in example_function()

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

	# continues here, after exiting while loop in example_function()
	print("I am done!")
Ejemplo n.º 12
0
def main():
    sender = Sender("127.0.0.1", 4458)
    print sender.msg("KCTFBot", u"/start")
    receiver = Receiver(port=4458)
    receiver.start()
    receiver.message(example_function(receiver, sender))
Ejemplo n.º 13
0
from core.utils import *
from pytg.receiver import Receiver
from pytg.sender import Sender
from pytg.utils import coroutine
import json

tgreceiver = Receiver(host="localhost", port=config.keys.tg_cli_port)
tgsender = Sender(host="localhost", port=config.keys.tg_cli_port)


# Telegram-CLI bindings
def peer(chat_id):
    if chat_id > 0:
        peer = 'user#id' + str(chat_id)
    else:
        if str(chat_id)[1:].startswith('100'):
            peer = 'channel#id' + str(chat_id)[4:]
        else:
            peer = 'chat#id' + str(chat_id)[1:]
    return peer


def user_id(username):
    if username.startswith('@'):
        command = 'resolve_username ' + username[1:]
        resolve = tgsender.raw(command)
        dict = DictObject(json.loads(resolve))
    else:
        dict = tgsender.user_info(username)

    if 'peer_id' in dict:
Ejemplo n.º 14
0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
#from pytg import Telegram
#tg = Telegram(telegram="/home/pi/lecture/ch10/telegram/tg/bin/telegram-cli",
#            pubkey_file="/home/pi/lecture/ch10/telegram/tg/tg-server.pub")
#receiver = tg.receiver
#sender = tg.sender
from pytg.sender import Sender
from pytg.receiver import Receiver
from pytg.utils import coroutine
import pexpect

receiver = Receiver(host="localhost", port=4458)
sender = Sender(host="localhost", port=4458)

@coroutine
def main_loop():
    QUIT = False
    try:
        while not QUIT:
            msg = (yield)
            sender.status_online()
            if msg.event != "message" or msg.own:
                continue
            print "Message: ", msg.text
            if msg.text != None:
                child = pexpect.spawn('bash', ['-c', msg.text])
                index = child.expect(pexpect.EOF)
                body = child.before.strip()
                sender.send_msg(msg.peer.cmd, body.decode('utf-8'))
    except GeneratorExit:
Ejemplo n.º 15
0
from pytg.receiver import Receiver
from pytg.sender import Sender
import json

receiver = Receiver(host="localhost", port=4458)
sender = Sender(host="localhost", port=4458)


def peer(chat_id):
    if chat_id > 0:
        peer = 'user#id' + str(chat_id)
    else:
        peer = 'chat#id' + str(chat_id)[1:]
    return peer


def user_id(username):
    command = 'resolve_username ' + username
    resolve = sender.raw(command)
    dict = json.loads(resolve)
    if 'peer_id' in dict:
        return dict['peer_id']
    else:
        return False


# sending messages
def send_message(chat_id, text, reply_to_message_id=None):
    cid = peer(chat_id)
    if reply_to_message_id:
        return sender.reply_text(cid, text)
Ejemplo n.º 16
0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
#from pytg import Telegram
#tg = Telegram(telegram="/home/pi/lecture/ch10/telegram/tg/bin/telegram-cli",
#            pubkey_file="/home/pi/lecture/ch10/telegram/tg/tg-server.pub")
#receiver = tg.receiver
#sender = tg.sender
from pytg.sender import Sender
from pytg.receiver import Receiver
from pytg.utils import coroutine
import pexpect

receiver = Receiver(host="localhost", port=4458)
sender = Sender(host="localhost", port=4458)


@coroutine
def main_loop():
    QUIT = False
    try:
        while not QUIT:
            msg = (yield)
            sender.status_online()
            if msg.event != "message" or msg.own:
                continue
            print "Message: ", msg.text
            if msg.text != None:
                child = pexpect.spawn('bash', ['-c', msg.text])
                index = child.expect(pexpect.EOF)
                body = child.before.strip()
                sender.send_msg(msg.peer.cmd, body.decode('utf-8'))
Ejemplo n.º 17
0
 def __init__(self, bot):
     self.bot = bot
     self.receiver = Receiver(host="localhost", port=self.bot.config.bindings_token)
     self.sender = Sender(host="localhost", port=self.bot.config.bindings_token)
     logging.getLogger("pytg").setLevel(logging.WARNING)
Ejemplo n.º 18
0
class bindings(object):
    def __init__(self, bot):
        self.bot = bot
        self.receiver = Receiver(host="localhost", port=self.bot.config.bindings_token)
        self.sender = Sender(host="localhost", port=self.bot.config.bindings_token)
        logging.getLogger("pytg").setLevel(logging.WARNING)

    def get_me(self):
        msg = self.sender.get_self()
        return User(msg.peer_id, msg.first_name, None, msg.username)

    def convert_message(self, msg):
        id = msg['id']
        if msg.receiver.type == 'user':
            conversation = Conversation(msg.sender.peer_id)
            conversation.title = msg.sender.first_name
        else:
            if msg.receiver.type == 'channel':
                conversation = Conversation(- int('100' + str(msg.receiver.peer_id)))
            else:
                conversation = Conversation(- int(msg.receiver.peer_id))
            conversation.title = msg.receiver.title

        if msg.sender.type == 'user':
            sender = User(int(msg.sender.peer_id))
            if 'first_name' in msg.sender:
                sender.first_name = msg.sender.first_name
            if 'last_name' in msg.sender:
                sender.last_name = msg.sender.last_name
            if 'username' in msg.sender:
                sender.username = msg.sender.username
        else:
            if msg.sender.type == 'channel':
                sender = Conversation(- int('100' + str(msg.sender.peer_id)))
            else:
                sender = Conversation(- int(msg.sender.peer_id))
            sender.first_name = msg.sender.title

        date = msg.date

        # Gets the type of the message
        if 'text' in msg:
            type = 'text'
            content = msg.text
            extra = None
        elif 'media' in msg:
            type = msg.media.type
            content = msg.id
            if 'caption' in msg.media:
                extra = msg.media.caption
            else:
                extra = None
        elif msg.event == 'service':
            type = 'service'
            if msg.action.type == 'chat_del_user':
                content = 'left_user'
                extra = msg.action.user.peer_id
            elif msg.action.type == 'chat_add_user':
                content = 'join_user'
                extra = msg.action.user.peer_id
            elif msg.action.type == 'chat_add_user_link':
                content = 'join_user'
                extra = msg.sender.peer_id
            else:
                type = None
                content = None
                extra = None
        else:
            type = None
            content = None
            extra = None

        # Generates another message object for the original message if the reply.
        if 'reply_id' in msg:
            reply_msg = self.sender.message_get(msg.reply_id)
            reply = self.convert_message(reply_msg)

        else:
            reply = None

        return Message(id, conversation, sender, content, type, date, reply, extra)

    def receiver_worker(self):
        try:
            logging.debug('Starting receiver worker...')
            while self.bot.started:
                self.receiver.start()
                self.receiver.message(self.main_loop())
        except KeyboardInterrupt:
            pass

    def send_message(self, message):
        if not message.extra:
            message.extra = {}

        if message.type != 'text' and message.content.startswith('http'):
            message.content = download(message.content)
        elif message.type != 'text' and not message.content.startswith('/'):
            message.content = self.sender.load_file(message.content)

        if not message.extra or not 'caption' in message.extra:
            message.extra['caption'] = None

        if message.type == 'text':
            self.sender.send_typing(self.peer(message.conversation.id), 1)

            if 'format' in message.extra and message.extra['format'] == 'Markdown':
                message.content = remove_markdown(message.content)
            elif 'format' in message.extra and message.extra['format'] == 'HTML':
                message.content = self.convert_links(message.content)

            try:
                if 'format' in message.extra and message.extra['format'] == 'HTML':
                    self.sender.raw('[html] msg %s %s' % (self.peer(message.conversation.id), self.escape(message.content)), enable_preview=False)
                else:
                    self.sender.send_msg(self.peer(message.conversation.id), message.content, enable_preview=False)
            except Exception as e:
                logging.exception(e)

        elif message.type == 'photo':
            self.sender.send_typing(self.peer(message.conversation.id), 1)  # 7
            try:
                if message.reply:
                    self.sender.reply_photo(message.reply, message.content, message.extra['caption'])
                else:
                    self.sender.send_photo(self.peer(message.conversation.id), message.content, message.extra['caption'])
            except Exception as e:
                logging.exception(e)

        elif message.type == 'audio':
            self.sender.send_typing(self.peer(message.conversation.id), 1)  # 6
            try:
                if message.reply:
                    self.sender.reply_audio(message.reply, message.content)
                else:
                    self.sender.send_audio(self.peer(message.conversation.id), message.content)
            except Exception as e:
                logging.exception(e)

        elif message.type == 'document':
            self.sender.send_typing(self.peer(message.conversation.id), 1)  # 8
            try:
                if message.reply:
                    self.sender.reply_document(message.reply, message.content, message.extra['caption'])
                else:
                    self.sender.send_document(self.peer(message.conversation.id), message.content, message.extra['caption'])
            except Exception as e:
                logging.exception(e)

        elif message.type == 'sticker':
            if message.reply:
                self.sender.reply_file(message.reply, message.content)
            else:
                self.sender.send_file(self.peer(message.conversation.id), message.content)

        elif message.type == 'video':
            self.sender.send_typing(self.peer(message.conversation.id), 1)  # 4
            try:
                if message.reply:
                    self.sender.reply_video(message.reply, message.content, message.extra['caption'])
                else:
                    self.sender.send_video(self.peer(message.conversation.id), message.content, message.extra['caption'])
            except Exception as e:
                logging.exception(e)

        elif message.type == 'voice':
            self.sender.send_typing(self.peer(message.conversation.id), 5)
            try:
                if message.reply:
                    self.sender.reply_audio(message.reply, message.content)
                else:
                    self.sender.send_audio(self.peer(message.conversation.id), message.content)
            except Exception as e:
                logging.exception(e)

        elif message.type == 'location':
            self.sender.send_typing(self.peer(message.conversation.id), 1)  # 9
            if message.reply:
                self.sender.reply_location(message.reply, message.content['latitude'], message.content['longitude'])
            else:
                self.sender.send_location(self.peer(message.conversation.id), message.content['latitude'], message.content['longitude'])

        else:
            print('UNKNOWN MESSAGE TYPE: ' + message.type)
            logging.debug("UNKNOWN MESSAGE TYPE")


    @coroutine
    def main_loop(self):
        while self.bot.started:
            msg = (yield)
            if (msg.event == 'message' and msg.own == False) or msg.event == 'service':
                message = self.convert_message(msg)
                self.bot.inbox.put(message)

                try:
                    if message.conversation.id > 0:
                        self.sender.mark_read(self.peer(message.sender.id))
                    else:
                        self.sender.mark_read(self.peer(message.conversation.id))
                except Exception as e:
                    logging.error(e)


    def peer(self, chat_id):
        if chat_id > 0:
            peer = 'user#id' + str(chat_id)
        else:
            if str(chat_id)[1:].startswith('100'):
                peer = 'channel#id' + str(chat_id)[4:]
            else:
                peer = 'chat#id' + str(chat_id)[1:]
        return peer


    def user_id(self, username):
        if username.startswith('@'):
            command = 'resolve_username ' + username[1:]
            resolve = self.sender.raw(command)
            dict = DictObject(json.loads(resolve))
        else:
            dict = self.sender.user_info(username)

        if 'peer_id' in dict:
            return dict.peer_id
        else:
            return False


    def get_id(self, user):
        if isinstance(user, int):
            return user

        if user.isdigit():
            id = int(user)
        else:
            id = int(self.user_id(user))

        return id


    def escape(self, string):
        if string is None:
            return None

        CHARS_UNESCAPED = ["\\", "\n", "\r", "\t", "\b", "\a", "'"]
        CHARS_ESCAPED = ["\\\\", "\\n", "\\r", "\\t", "\\b", "\\a", "\\'"]

        for i in range(0, 7):
            string = string.replace(CHARS_UNESCAPED[i], CHARS_ESCAPED[i])
        return string.join(["'", "'"])  # wrap with single quotes.


    def convert_links(self, string):
        for link in BeautifulSoup(string, 'lxml').findAll("a"):
            string = string.replace(str(link), link.get("href"))
        return string


    # THESE METHODS DO DIRECT ACTIONS #
    def get_file(self, file_id):
        pass


    def invite_conversation_member(self, conversation_id, user_id):
        self.sender.chat_add_user(self.peer(conversation_id), self.peer(user_id))


    def kick_conversation_member(self, conversation_id, user_id):
        self.sender.chat_del_user(self.peer(conversation_id), self.peer(user_id))


    def unban_conversation_member(self, conversation_id, user_id):
        pass


    def conversation_info(self, conversation_id):
        self.api_request('sendContact', params)
Ejemplo n.º 19
0
def run_receiver():
    receiver = Receiver(host="localhost", port=4458)
    receiver.start()
    logger.info('receiver.message...')
    receiver.message(enqueue_msgs())
    receiver.stop()
Ejemplo n.º 20
0
class PyTelegram(object):
    def __init__(self):
        tgcli_port = 4458
        self.setlog()
        if not self.start(tgcli_port):
            sys.exit(1)

        self.receiver = Receiver(host="localhost", port=tgcli_port)
        self.sender = Sender(host="localhost", port=tgcli_port)

    def setlog(self):
        basepath = os.path.dirname(os.path.realpath(__file__))
        logdir = os.path.join(basepath, "./log")
        if not os.path.exists(logdir):
            os.mkdir(logdir)
        self.logname = os.path.join(basepath,
                                    "./log/%s.log" % time.strftime("%Y%m%d%H"))
        LOG_FORMAT = '[%(asctime)s] : %(levelname)s %(filename)s - %(funcName)s(%(lineno)d) - %(message)s'
        logging.basicConfig(
            format=LOG_FORMAT,
            level=0,
            handlers=[logging.FileHandler(self.logname, 'a', 'utf-8')])

    def need_proxy(self):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(('8.8.8.8', 1))
            selfip = s.getsockname()[0]
        except Exception as e:
            logging.error(e)
            return False

        if selfip.startswith("192.168.") or selfip.startswith("10.")\
                or selfip.startswith("172.1") or selfip.startswith("10.64."):
            logging.debug("need proxy")
            return True
        else:
            logging.debug("no need proxy")
            return False

    def start(self, tgcli_port):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            check = s.connect_ex(('127.0.0.1', tgcli_port))
            s.close()
        except Exception as e:
            logging.error(e)
            check = 1

        if check == 0:
            return True

        if self.need_proxy():
            cmd = """nohup proxychains telegram-cli --json --tcp-port %d >> %s 2>&1 &"""\
                % (tgcli_port, self.logname)
        else:
            cmd = """nohup telegram-cli --json --tcp-port %d >> %s 2>&1 &"""\
                % (tgcli_port, self.logname)

        logging.debug(cmd)
        ret = subprocess.Popen(cmd,
                               shell=True,
                               stderr=subprocess.PIPE,
                               stdout=subprocess.PIPE)
        ret.wait()
        logging.debug("ret wait")
        reterr = ret.stderr.read()
        logging.debug("ret err")
        retout = ret.stdout.read()
        logging.debug("ret out")
        if reterr:
            logging.error(reterr.decode("utf8"))
            return False
        logging.info(retout)
        return True

    def parse_recive(self, msg_dict):
        logging.debug(msg_dict)

    def receive_loop(self):
        @coroutine
        def receive_coroutine_loop():
            while 1:
                msg = (yield)
                self.parse_recive(msg)

        self.receiver.start()
        self.receiver.message(receive_coroutine_loop())

    def get_channel_list(self, limit=0, offset=0):
        if limit == 0 and offset == 0:
            channels = self.sender.channel_list()
        else:
            channels = self.sender.channel_list(limit, offset)
        return channels

    def get_dialog_list(self, limit=0, offset=0):
        if limit == 0 and offset == 0:
            dialogs = self.sender.dialog_list()
        else:
            dialogs = self.sender.dialog_list(limit, offset)
        return dialogs

    def channel_get_members(self, name):
        members = self.sender.channel_get_members(name)
        return members

    def chat_get_members(self, name):
        chat_info_dict = self.sender.chat_info(name)
        meminfo_list = chat_info_dict["members"]
        return meminfo_list

    def get_history(self, peer, limit=0, offset=0):
        if limit == 0:
            ret = self.sender.history(peer,
                                      retry_connect=10,
                                      result_timeout=100)
        elif offset == 0:
            ret = self.sender.history(peer, limit, retry_connect=10)
        else:
            ret = self.sender.history(peer, limit, offset, retry_connect=10)
        #logging.debug(ret)
        ret.reverse()
        history_dict = collections.OrderedDict()
        for chat_info in ret:
            try:
                if chat_info["event"] != "message":
                    continue
                chatid = chat_info["id"]
                history_dict[chatid] = chat_info
                logging.debug(chat_info)
            except Exception as e:
                logging.error(e)
        return history_dict

    def create_group(self, groupname, userlist):
        try:
            ret = self.sender.create_group_chat(groupname, userlist[0])
            logging.debug(ret)
        except Exception as e:
            logging.error(e)
            return False

        if len(userlist) == 1:
            return True

        for username in userlist[1:]:
            try:
                ret = self.sender.chat_add_user(groupname, username, 0)
                logging.debug(ret)
            except Exception as e:
                logging.error(e)
        return True
Ejemplo n.º 21
0
from pytg.sender import Sender
from pytg.receiver import Receiver
from pytg.utils import coroutine
from pytg.exceptions import ConnectionError
import base64
import threading
import sys
import psutil
import os
import signal


# Connect to telegram
print('Connecting to telegram...')

receiver = Receiver(host="localhost", port=4458)
sender = Sender(host="localhost", port=4458)

# Retrieve contact list

try:
    contacts = [c for c in sender.dialog_list()]
    for i, user in enumerate(contacts):
        print(unicode(i) + ': \t' + unicode(user['print_name']))
except ConnectionError:
    print('Could not connect to telegram-cli. Start it by issuing "telegram-cli --json -P 4458" in a separate console.')
    sys.exit(1)

# Ask user to choose contact
i = int(input('Telegram online, please enter contact to connect to (by number): '))
Ejemplo n.º 22
0
    sender.mark_read('@' + to)
    sender.send_msg('@' + to, message)


def fwd(to, message_id):
    sender.fwd('@' + to, message_id)


def update_order(order):
    current_order['order'] = order
    current_order['time'] = time()
    if order == castle:
        action_list.append(orders['cover'])
    else:
        action_list.append(orders['attack'])
    action_list.append(order)


def log(text):
    message = '{0:%Y-%m-%d %H:%M:%S}'.format(dt.datetime.now()) + ' ' + text
    print(message)
    log_list.append(message)


if __name__ == '__main__':
    receiver = Receiver(port=port)
    receiver.start()
    _thread.start_new_thread(queue_worker, ())
    receiver.message(work_with_message(receiver))
    receiver.stop()
Ejemplo n.º 23
0
class Telegram_ui:
    def __init__(self, conf):
        self.lock_receiver = True
        self.conf = conf

        self.boot_time = int(time.time())
        # Just shortcut for some configurations :
        self.DATE_FORMAT = self.conf['general']['date_format']
        self.NINJA_MODE = self.conf['general']['ninja_mode']
        self.INLINE_IMAGE = self.conf['general']['inline_image']

        self.start_Telegram()
        self.last_online = 1
        self.online_status = {}
        self.read_status = {}

        palette = [('status_bar', self.conf['style']['status_bar_fg'],
                    self.conf['style']['status_bar_bg']),
                   ('date', self.conf['style']['date'], ''),
                   ('hour', self.conf['style']['hour'], ''),
                   ('separator', self.conf['style']['separator'], ''),
                   ('reversed', 'standout', ''),
                   ('cur_chan', self.conf['style']['cur_chan'], '')]

        # Notification
        if self.conf['general']['notification']:
            Notify.init("ncTelegram")
            self.image = '/usr/share/ncTelegram/t_logo.png'

        self.current_chan = []
        self.last_media = {}

        # message buffer init
        self.msg_buffer = {}

        self.chan_widget = ChanWidget(self)

        self.print_title()
        self.me = self.sender.get_self()

        # message list
        self.msg_widget = MessageWidget(self)

        # message writing + status bar widget
        self.msg_send_widget = MessageSendWidget(self)

        # Right pannel
        self.right_side = urwid.Pile(
            [self.msg_widget, (2, self.msg_send_widget)])

        vert_separator = urwid.AttrMap(urwid.Filler(urwid.Columns([])),
                                       'status_bar')

        # Final arrangements
        self.main_columns = urwid.Columns([('weight', 1, self.chan_widget),
                                           (1, vert_separator),
                                           ('weight', 5, self.right_side)])

        self.main_loop = urwid.MainLoop((self.main_columns),
                                        palette,
                                        unhandled_input=self.unhandle_key,
                                        screen=urwid.raw_display.Screen())
        self.main_loop.screen.set_terminal_properties(colors=256)
        self.lock_receiver = False
        self.main_loop.run()

    def update_online_status(self, when, status, cmd):
        self.online_status[cmd] = (when, status)
        if cmd == self.current_chan['id']:
            self.msg_send_widget.update_status_bar()

    def update_read_status(self, cmd, bool):
        self.read_status[cmd] = bool
        if cmd == self.current_chan['id']:
            self.msg_send_widget.update_status_bar()

    def display_notif(self, msg):
        if self.conf['general']['notification']:
            text = msg['text']

            if msg['receiver']['type'] == 'user':
                sender = msg['sender']['first_name']
            else:
                sender = msg['receiver']['name'] + ": " + msg['sender'][
                    'first_name']

            Notify.Notification.new('', '<b>' + sender + '</b>\n' + text,
                                    self.image).show()

    def print_title(self):
        total_msg_waiting = sum(self.chan_widget.msg_chan.values())
        if total_msg_waiting == 0:
            sys.stdout.write("\x1b]2;ncTelegram\x07")
        else:
            sys.stdout.write("\x1b]2;ncTelegram (" + str(total_msg_waiting) +
                             ")\x07")

    def fill_msg_buffer(self, button):

        for chan in self.chan_widget.chans:
            cmd = chan['id']
            if cmd not in self.msg_buffer:
                print_name = chan['print_name']
                try:
                    self.msg_buffer[cmd] = self.sender.history(print_name, 100)
                except:
                    self.msg_buffer[cmd] = []
                if self.INLINE_IMAGE:
                    for msg in self.msg_buffer[cmd]:
                        if 'media' in msg:
                            image = self.msg_widget.get_inline_img(msg)

        self.chan_widget.update_chan_list()

    def is_image(self, path):
        return not path == None and (path.endswith('png') \
        or path.endswith('jpg') \
        or path.endswith('jpeg') \
        or path.endswith('JPG') \
        or path.endswith('PNG'))

    def download_media(self, msg):
        if 'url' in msg:
            return msg['url']
        else:
            mtype = msg['media']['type']
            mid = msg['id']

            #file = self.sender.load_file(mid)
            if mtype == 'photo':
                file = self.sender.load_photo(mid)

            elif mtype == 'document':
                file = self.sender.load_document(mid)
            else:
                file = None

            return file

    def open_file(self, path):
        if self.conf['general']['open_file'] and path != None:
            subprocess.Popen(['xdg-open', path],
                             stderr=subprocess.DEVNULL,
                             stdout=subprocess.DEVNULL)

    def start_Telegram(self):
        # link with telegram-cli
        PATH_TELEGRAM = self.conf['general']['path_telegram']
        PATH_PUBKEY = self.conf['general']['path_pubkey']

        self.receiver = Receiver()
        self.receiver.start()

        # Thread to dump received messages
        self.msg_dump = MessageReceiver(self)
        self.msg_dump.daemon = True
        self.msg_dump.start()

        self.tg = Telegram(telegram=PATH_TELEGRAM, pubkey_file=PATH_PUBKEY)

        #self.receiver = self.tg.receiver
        self.sender = self.tg.sender

    def stop_Telegram(self):
        self.sender.status_offline()

        #self.tg.stopCLI()
        # Because of a bug in pytg, this is stopCLI without the line "self._proc.communicate('quit\n')"

        self.sender.terminate(
        )  # not let the cli end close first -> avoid bind: port already in use.
        self.receiver.stop()

        self.sender.safe_quit()
        if self.tg._check_stopped(): return None

        self.sender.quit()
        if self.tg._check_stopped(): return None

        self.sender.stop(
        )  # quit and safe quit are done, we don't need the sender any longer.

        if self.tg._check_stopped(): return None

        if self.tg._check_stopped(): return None

        self.tg._proc.terminate()
        if self.tg._check_stopped(): return None

        self.tg._proc.kill()
        if self.tg._check_stopped(): return None

        self.tg._proc.wait()
        self.tg._check_stopped()

    def exit(self):
        if self.conf['general']['notification']:
            Notify.uninit()
        sys.stdout.write("\x1b]2;\x07")
        self.stop_Telegram()
        raise urwid.ExitMainLoop

    def unhandle_key(self, key):
        if key == self.conf['keymap']['quit']:
            self.exit()

        elif key == 'esc':
            self.msg_widget.draw_separator()

        elif key == self.conf['keymap']['prev_chan']:
            self.chan_widget.go_prev_chan()

        elif key == self.conf['keymap']['next_chan']:
            self.chan_widget.go_next_chan()

        elif key == self.conf['keymap']['open_file'] and \
                self.last_media != {} and \
                self.conf['general']['open_file']:
            path = self.download_media(self.last_media)
            self.open_file(path)

        elif key == self.conf['keymap']['insert_text']:
            self.main_columns.focus_position = 2
            self.right_side.focus_position = 1

        elif key == "'":
            self.main_columns.focus_position = 2
            self.right_side.focus_position = 1
            self.msg_send_widget.widgetEdit.insert_text("'")
Ejemplo n.º 24
0
def send_msg(to, message):
    sender.send_msg('@' + to, message)


def fwd(to, message_id):
    sender.fwd('@' + to, message_id)


def update_order(order):
    current_order['order'] = order
    current_order['time'] = time()
    if order == castle:
        action_list.append(orders['cover'])
    else:
        action_list.append(orders['attack'])
    action_list.append(order)


def log(text):
    message = '{0:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()) + ' ' + text
    print(message)
    log_list.append(message)


if __name__ == '__main__':
    receiver = Receiver(sock=socket_path) if socket_path else Receiver(port=port)
    receiver.start()  # start the Connector.
    _thread.start_new_thread(queue_worker, ())
    receiver.message(work_with_message(receiver))
    receiver.stop()
Ejemplo n.º 25
0
class Messager():
    lastcheck = 0;
    tg = None;
    sender = None
    receiver = None
    __shared_state = {}

    def __init__(self):
        self.__dict__ = self.__shared_state
	if (self.sender != None and self.receiver != None):
		print "TG is already running";
	else:
		print "TG isn't running, start";
		self.startTelegram();


    def strip_non_ascii(self,string):	
        ''' Returns the string without non ASCII characters'''
        stripped = (c for c in string if 0 < ord(c) < 127)
        return ''.join(stripped)

    def startTelegram(self):
	self.receiver = Receiver(host="localhost",port=4458);
	self.sender = Sender(host="localhost",port=4458);
	

    def sendToTG(self,group,msg):
#	print "Skip";
#	if (os.path.isfile("/tmp/meetingmode")):
#		return
#	
	print "SendToTG";
	self.sender.send_msg(unicode(group),unicode(msg));
	print "Done";

    def executeCommand(self,msg,channel,tguser):
	from Core.callbacks import Callbacks
	from Core.actions import Action

	user = User.byTguser(tguser);
	if (msg[0:1] == '%'):
		if (msg == '%whoami'):

			if (tguser == 'nouser'):

				message = Action();
				message.privmsg("You don't have a TG username you donut! Read https://telegram.org/faq#q-what-are-usernames-how-do-i-get-one before you bother me again!",channel);
	                        if (channel == Config.get('gateway','ircchan1')):
        	                        self.sendToTG(Config.get('gateway','tggroup1'),"You don't have a TG username you donut! Read https://telegram.org/faq#q-what-are-usernames-how-do-i-get-one before you bother me again!");
                	        if (channel == Config.get('gateway','ircchan2')):
                        	        self.sendToTG(Config.get('gateway','tggroup2'),"You don't have a TG username you donut! Read https://telegram.org/faq#q-what-are-usernames-how-do-i-get-one before you bother me again!");
	                        if (channel == Config.get('gateway','ircchan3')):
        	                        self.sendToTG(Config.get('gateway','tggroup3'),"You don't have a TG username you donut! Read https://telegram.org/faq#q-what-are-usernames-how-do-i-get-one before you bother me again!");

			else:
				message = Action();
				message.privmsg("Your TG username is "+tguser+". If you havn't already, you need to add this to the bot using .pref tguser="******"");
	                        if (channel == Config.get('gateway','ircchan1')):
	                                self.sendToTG(Config.get('gateway','tggroup1'),"Your TG username is "+tguser+". If you havn't already, you need to add this to the bot using .pref tguser="******"");
	                        if (channel == Config.get('gateway','ircchan2')):
	                                self.sendToTG(Config.get('gateway','tggroup2'),"Your TG username is "+tguser+". If you havn't already, you need to add this to the bot using .pref tguser="******"");
	                        if (channel == Config.get('gateway','ircchan3')):
	                                self.sendToTG(Config.get('gateway','tggroup3'),"Your TG username is "+tguser+". If you havn't already, you need to add this to the bot using .pref tguser="******"");
				


		elif (user is None):
			message = Action();
			message.privmsg("You must be registered with BowBot and have your TG user set to send commands from TG",channel);
			if (channel == Config.get('gateway','ircchan1')):
				self.sendToTG(Config.get('gateway','tggroup1'),"You must be registered with BowBot and have your TG user set to send commands from TG");
			if (channel == Config.get('gateway','ircchan2')):
                                self.sendToTG(Config.get('gateway','tggroup2'),"You must be registered with BowBot and have your TG user set to send commands from TG");
			if (channel == Config.get('gateway','ircchan3')):
                                self.sendToTG(Config.get('gateway','tggroup3'),"You must be registered with BowBot and have your TG user set to send commands from TG");

			
		else:
			msg = '!' + msg.lstrip("%");
			line = ":"+str(user.name)+"!~"+str(user.name)+"@"+str(user.name)+".users.netgamers.org PRIVMSG "+channel+" :"+msg+"";
			message = Action()
			message.parse(line);
			callback = Callbacks.callback(message);

    def sendExternal(self,message):
	print "Message Command:" + message._command;
        if (message._command == "PART" or message._command == "QUIT" or message._command == "KICK" or message._command == "KILL"):
                #Do we have a group for this channel
                if (message._channel == Config.get('gateway','ircchan1')):
                        if (Config.get('gateway','tggroup1') != ""):
                                self.sendToTG(Config.get('gateway','tggroup1'),'[IRC:'+message._nick+'@'+message._channel+'] '+message._nick+' has left '+message._channel);

                if (message._channel == Config.get('gateway','ircchan2')):
                        if (Config.get('gateway','tggroup2') != ""):
                                self.sendToTG(Config.get('gateway','tggroup2'),'[IRC:'+message._nick+'@'+message._channel+'] '+message._nick+' has left '+message._channel);


                if (message._channel == Config.get('gateway','ircchan3')):
                        if (Config.get('gateway','tggroup3') != ""):
                                self.sendToTG(Config.get('gateway','tggroup3'),'[IRC:'+message._nick+'@'+message._channel+'] '+message._nick+' has left '+message._channel);

	if (message._command == "JOIN"):
                #Do we have a group for this channel
                if (message._channel == Config.get('gateway','ircchan1')):
                        if (Config.get('gateway','tggroup1') != ""):
                                self.sendToTG(Config.get('gateway','tggroup1'),'[IRC:'+message._nick+'@'+message._channel+'] '+message._nick+' has joined '+message._channel);

                if (message._channel == Config.get('gateway','ircchan2')):
                        if (Config.get('gateway','tggroup2') != ""):
                                self.sendToTG(Config.get('gateway','tggroup2'),'[IRC:'+message._nick+'@'+message._channel+'] '+message._nick+' has joined '+message._channel);


                if (message._channel == Config.get('gateway','ircchan3')):
                        if (Config.get('gateway','tggroup3') != ""):
                                self.sendToTG(Config.get('gateway','tggroup3'),'[IRC:'+message._nick+'@'+message._channel+'] '+message._nick+' has joined '+message._channel);
	
	if (message._command == "PRIVMSG" and message._msg[0:5] != '[IRC:' and message._msg[0:4] != '[WA:' and message._msg[0:4] != '[TG:' ):
		#Do we have a group for this channel
		if (message._channel == Config.get('gateway','ircchan1')):
			if (Config.get('gateway','tggroup1') != ""):
				self.sendToTG(Config.get('gateway','tggroup1'),'[IRC:'+message._nick+'@'+message._channel+'] '+message._msg+'');

		if (message._channel == Config.get('gateway','ircchan2')):
			if (Config.get('gateway','tggroup2') != ""):
				self.sendToTG(Config.get('gateway','tggroup2'),'[IRC:'+message._nick+'@'+message._channel+'] '+message._msg+'');


		if (message._channel == Config.get('gateway','ircchan3')):
			if (Config.get('gateway','tggroup3') != ""):
				self.sendToTG(Config.get('gateway','tggroup3'),'[IRC:'+message._nick+'@'+message._channel+'] '+message._msg+'');


    def startTGCheck(self):
	t = Timer(5.0,self.checkTG).start();
	

    def checkTG(self):
	print "CheckTG Started";
	print "Running Threads: "+str(threading.activeCount());
	t = Timer(3600.0,self.checkTG).start();
	#print "Stop Old Receviver";
	if (self.receiver):
		try:
			self.receiver.stop();
			print "Receiver stopped ok";
		except:
			print "Unexpected error:", sys.exc_info()[0];
	try:
		print "Start TG Checker";
		self.receiver = Receiver(host="localhost",port=4458);
		self.receiver.start();
		self.receiver.message(self.example_function(self.receiver));
		self.receiver.stop();
		print "TG CHeck has stopped....";
		self.checkTG();
	except TypeError:
		print "Should really figure out where these type-errors come from";
	except:
		print sys.exc_info();
		print "Unexpected error 2:", sys.exc_info()[0];
		self.checkTG();
	return;

    @coroutine
    def example_function(self,receiver):
	try:
		while True:
                        print "Check";
                        msg = (yield)
                        act = Action();
                        print('Full dump: {array}'.format(array=str( msg )))
		
			if (msg.event == 'message'):
				if (hasattr(msg.sender,'username')):
					user = User.byTguser(msg.sender.username);
	
			                if user is not None:
		        	                displayUser = str(user.name);
					else:
						displayUser = str(msg.sender.name);
				else:
					displayUser = str(msg.sender.name);
					msg.sender.username = '******';
	
	
	
				msg.text = self.strip_non_ascii(msg.text);
				if (msg.receiver and str(msg.receiver.name) == Config.get("gateway","tggroup1") and msg.text[0:5] != '[IRC:' and msg.text[0:4] != '[WA:' and msg.text[0:4] != '[TG:' ):
					print "Send message to " + Config.get("gateway","ircchan1");
					self.actions = Action.privmsg(act,"[TG:"+displayUser+"] " + (msg.text.encode('utf_8','ignore')) , Config.get("gateway","ircchan1"))
					self.executeCommand(msg.text.encode('utf_8','ignore'),Config.get("gateway","ircchan1"),str(msg.sender.username));
	
				if (msg.receiver and str(msg.receiver.name) == Config.get("gateway","tggroup2") and msg.text[0:5] != '[IRC:' and msg.text[0:4] != '[WA:' and msg.text[0:4] != '[TG:' ):
					print "Send message to " + Config.get("gateway","ircchan2");
					self.actions = Action.privmsg(act,"[TG:"+displayUser+"] " + (msg.text.encode('utf_8','ignore')) , Config.get("gateway","ircchan2"))
					self.executeCommand(msg.text.encode('utf_8','ignore'),Config.get("gateway","ircchan2"),str(msg.sender.username));
	
				if (msg.receiver and str(msg.receiver.name) == Config.get("gateway","tggroup3") and msg.text[0:5] != '[IRC:' and msg.text[0:4] != '[WA:' and msg.text[0:4] != '[TG:' ):
					print "Send message to " + Config.get("gateway","ircchan3");
					self.actions = Action.privmsg(act,"[TG:"+displayUser+"] " + (msg.text.encode('utf_8','ignore')) , Config.get("gateway","ircchan3"))
					self.executeCommand(msg.text.encode('utf_8','ignore'),Config.get("gateway","ircchan3"),str(msg.sender.username));
			else:
				print "Not A Message";

	except AttributeError:
		print sys.exc_info();
		print "Nothing we need to worry about...";
		receiver.stop();
		self.checkTG();
	except UnicodeEncodeError:
		print "Characters we can't deal with!";
	except KeyboardInterrupt:
		receiver.stop()
		print("Exiting")
Ejemplo n.º 26
0
Archivo: macro.py Proyecto: ktchk/Bot
# coding=utf-8
from pytg.sender import Sender
from pytg.receiver import Receiver
from pytg.utils import coroutine
import re
import time
receiver = Receiver(host="localhost", port=1338)
sender = Sender(host="localhost", port=1338)
bot_username = '******'
bot_username1 = 'WastelandWarsHelperBot'
admin_username = '******'
import random

# Стартовать бота для корректного счетчика хилок уже с полным закупом!!
medpack = 3
medx1 = 2
buffout = 2
#/
on = 1
distance1 = None
distance2 = None
#
# ⛑Аптечка
# 💌 Медпак
# 💉 Мед-Х
# 💊 Баффаут
# 👣Пустошь
# ⚔️Дать отпор
# 👣Идти дальше
# ⛺️Лагерь
# 📟Пип-бой
Ejemplo n.º 27
0
def main():
    global sent, received, up, tun, encrypted, args

    # Process arguments
    parser = argparse.ArgumentParser(description='Teletun - IP over Telegram')
    parser.add_argument('peer_id', help='peer id (list for contact list)')
    parser.add_argument('-r', '--server', help='server', action='store_true')
    parser.add_argument('-e',
                        '--encrypted',
                        help='secret chat',
                        action='store_true')
    parser.add_argument('-p', '--src', help='peer address', default='10.8.0.2')
    parser.add_argument('-s',
                        '--dst',
                        help='server address',
                        default='10.8.0.1')
    parser.add_argument('-m', '--mask', help='mask', default='255.255.255.0')
    parser.add_argument('-n', '--mtu', help='MTU', default=1500)
    parser.add_argument('-H',
                        '--host',
                        help='Telegram host address',
                        default='localhost')
    parser.add_argument('-P', '--port', help='Telegram port', default=4458)
    parser.add_argument('-a',
                        '--auto',
                        help='autoconfig from server',
                        action='store_true')
    args = parser.parse_args()
    peer_id = None

    # Connect to telegram
    print('Connecting to Telegram...', file=sys.stderr)
    receiver = Receiver(host=args.host, port=args.port)
    sender = Sender(host=args.host, port=args.port)

    # Retrieve contact list

    try:
        contacts = [c for c in sender.dialog_list()]
        for i, user in enumerate(contacts):
            if args.peer_id == 'list':
                print('{:16s} {}'.format(str(user['peer_id']),
                                         str(user['print_name'])))
            elif str(user['peer_id']) == args.peer_id:
                peer_id = args.peer_id
                username = str(user['print_name'])
        if args.peer_id == 'list':
            sys.exit(0)
    except ConnectionError:
        print(
            'Could not connect to telegram-cli. Start it by issuing "telegram-cli --json -P 4458" in a separate console.',
            file=sys.stderr)
        sys.exit(1)

    if peer_id is None:
        print('Could not find peer_id in contact list.', file=sys.stderr)
        sys.exit(1)

    print('Connecting to partner: ' + username, file=sys.stderr)

    # Helper function that can be executed in a thread
    def main_loop_starter():
        receiver.start()
        # Start the receive loop
        receiver.message(main_loop())

    @coroutine
    def main_loop():
        global args, received, tun, encrypted
        while up:
            # Receive message from telegram, this includes ALL messages
            msg = (yield)
            # Check if it is an actual "message" message and if the sender is our peer
            if (msg is not None and msg.event == str('message') and not msg.own
                    and str(msg.sender.peer_id) == peer_id):
                print('Msg: ' + msg.text, file=sys.stderr)
                if msg.text[0] == '-' and msg.text[1] == '-':
                    if args.server:
                        if msg.text == '--encrypted':
                            print('Requested encyption for: ' + username,
                                  file=sys.stderr)
                            try:
                                sender.create_secret_chat(username)
                            except Exception:
                                pass
                            encrypted = True
                        elif msg.text == '--server':
                            command_line = '--src={} --dst={} --mask={} --mtu={:d}'.format(
                                args.src, args.dst, args.mask, args.mtu)
                            print('Requested encyption for: ' + command_line,
                                  file=sys.stderr)
                            print('Sending configuration:' + command_line,
                                  file=sys.stderr)
                            sender.msg(username, str(command_line))
                    else:
                        print('Receiving configuration:' + data,
                              file=sys.stderr)
                        args = parser.parse_args(sys.argv + data.split())
                        tun.down()
                        setup_tun()
                        tun.up()
                else:
                    # Decode data and write it to the tunnel
                    data = base64.b64decode(msg.text)
                    received += len(data)
                    tun.write(data)
                    #print('Packet written', file=sys.stderr)

    def setup_tun():
        if args.server:
            tun.addr = args.dst
            tun.dstaddr = args.src
        else:
            tun.addr = args.src + ' '
            tun.dstaddr = args.dst

        tun.netmask = args.mask
        tun.mtu = args.mtu

        print('\tSrc:  ' + tun.addr, file=sys.stderr)
        print('\tDst:  ' + tun.dstaddr, file=sys.stderr)
        print('\tMask: ' + tun.netmask, file=sys.stderr)
        print('\tMTU:  ' + str(tun.mtu), file=sys.stderr)

# Create TUN device for network capture and injections

    tun = TunTapDevice(name='teletun')

    print('Device ' + tun.name + ' has been created, information follows:',
          file=sys.stderr)

    if args.server or not args.auto:
        # Set IP address based on --server header
        setup_tun()

# Start TUN device
    tun.up()
    up = True

    print('Device ' + tun.name + ' is up.', file=sys.stderr)

    if not args.server and args.encrypted:
        print('Requesting encyption for: ' + username, file=sys.stderr)
        sender.msg(username, '--encrypted')
        time.sleep(3)

# Create the receive thread via our helper method
    thread = threading.Thread(target=main_loop_starter)

    # Start the thread for receiving
    print('Connecting...', file=sys.stderr)
    thread.start()

    if not args.server and args.auto:
        print('Waiting for configuration...', file=sys.stderr)
        command_line = '--server'
        sender.msg(username, str(command_line))

    while up:
        # Continually read from the tunnel and write data to telegram in base64
        # TODO: Telegram supports str, base64 can probably be replaced for something less overhead-inducing
        buf = tun.read(tun.mtu)
        data = base64.b64encode(buf)
        data = ''.join(map(chr, data))
        sent += len(data)
        if (not args.server and args.encrypted) or encrypted:
            sender.msg('!_' + username, data)
        elif not args.encrypted:
            sender.msg(username, data)


# Cleanup and stop application
    up = False
    tun.down()
    receiver.stop()

    print('Bytes sent via Telegram: ' + str(sent), file=sys.stderr)
    print('Bytes received via Telegram: ' + str(received), file=sys.stderr)
    print('Done.', file=sys.stderr)

    # Literally Overkill
    current_process = psutil.Process()
    os.kill(current_process.pid, signal.SIGKILL)
Ejemplo n.º 28
0
        return 'black'
    elif heroinf.find(orders['white']) != -1:
        return 'white'
    elif heroinf.find(orders['mint']) != -1:
        return 'mint'
    elif heroinf.find(orders['twilight']) != -1:
        return 'twilight'

def update_order(order):
    current_order['order'] = order
    current_order['time'] = time()
    if order == castle:
        action_list.append(orders['cover'])
    else:
        action_list.append(orders['attack'])
    action_list.append(order)
    action_list.append(orders['hero'])

def log(text):
    message = '{0:%Y-%m-%d %H:%M:%S}'.format(dt.datetime.now()) + ' ' + text
    print(message)
    log_list.append(message)


if __name__ == '__main__':
    receiver = Receiver(sock=socket_path) if socket_path else Receiver(port=port)
    receiver.start()  # start the Connector.
    _thread.start_new_thread(queue_worker, ())
    receiver.message(work_with_message(receiver))
    receiver.stop()
Ejemplo n.º 29
0
# -*- coding: utf-8 -*-
from pytg.receiver import Receiver
from pytg.utils import coroutine

@coroutine
def example_function(receiver):
  try:
    while True:
      msg = (yield)
      print('Full dump: {array}'.format(array=str( msg )))
  except KeyboardInterrupt:
    receiver.stop()
    print("Exiting")

if __name__ == '__main__':
  receiver = Receiver(port=4458) #get a Receiver Connector instance
  receiver.start() #start the Connector.
  receiver.message(example_function(receiver)) # add "example_function" function as listeners. You can supply arguments here (like receiver).
  # continues here, after exiting while loop in example_function()
  receiver.stop()
Ejemplo n.º 30
0
class Telegram_ui:
    def __init__(self, conf):
        self.lock_receiver = True
        self.conf = conf
        
        self.boot_time = int(time.time())
        # Just shortcut for some configurations :
        self.DATE_FORMAT = self.conf['general']['date_format']
        self.NINJA_MODE = self.conf['general']['ninja_mode']
        self.INLINE_IMAGE = self.conf['general']['inline_image']

        self.start_Telegram()
        self.last_online = 1
        self.online_status = {}
        self.read_status = {}

        palette = [('status_bar', self.conf['style']['status_bar_fg'], self.conf['style']['status_bar_bg']),
                   ('date', self.conf['style']['date'], ''),
                   ('hour', self.conf['style']['hour'], ''),
                   ('separator', self.conf['style']['separator'], ''),
                   ('reversed', 'standout', ''),
                   ('cur_chan', self.conf['style']['cur_chan'], '')]


        # Notification
        if self.conf['general']['notification']:
            Notify.init("ncTelegram")
            self.image = '/usr/share/ncTelegram/t_logo.png'

        self.current_chan = []
        self.last_media = {}

        # message buffer init
        self.msg_buffer = {}

        self.chan_widget = ChanWidget(self)

        self.print_title()
        self.me = self.sender.get_self()

        # message list
        self.msg_widget = MessageWidget(self)

        # message writing + status bar widget
        self.msg_send_widget = MessageSendWidget(self)

        # Right pannel
        self.right_side = urwid.Pile([self.msg_widget, (2, self.msg_send_widget)])

        vert_separator = urwid.AttrMap(urwid.Filler(urwid.Columns([])), 'status_bar')

        # Final arrangements
        self.main_columns = urwid.Columns([('weight', 1, self.chan_widget),
                                           (1, vert_separator),
                                           ('weight', 5, self.right_side)])

        self.main_loop = urwid.MainLoop((self.main_columns), palette, unhandled_input=self.unhandle_key, screen=urwid.raw_display.Screen())
        self.main_loop.screen.set_terminal_properties(colors=256)
        self.lock_receiver = False
        self.main_loop.run()

    def update_online_status(self, when, status, cmd):
        self.online_status[cmd] = (when, status)
        if cmd == self.current_chan['id']:
            self.msg_send_widget.update_status_bar()

    def update_read_status(self, cmd, bool):
        self.read_status[cmd] = bool        
        if cmd == self.current_chan['id']:
            self.msg_send_widget.update_status_bar()


    def display_notif(self, msg):
        if self.conf['general']['notification']:
            text = msg['text']

            if msg['receiver']['type'] == 'user':
                sender = msg['sender']['first_name']
            else:
                sender = msg['receiver']['name'] + ": " + msg['sender']['first_name']


            Notify.Notification.new('', '<b>' + sender + '</b>\n' + text, self.image).show()


    def print_title(self):
        total_msg_waiting = sum(self.chan_widget.msg_chan.values())
        if total_msg_waiting == 0:
            sys.stdout.write("\x1b]2;ncTelegram\x07")
        else:
            sys.stdout.write("\x1b]2;ncTelegram (" + str(total_msg_waiting) + ")\x07")


    def fill_msg_buffer(self, button):

        for chan in self.chan_widget.chans:
            cmd = chan['id']
            if cmd not in self.msg_buffer:
                print_name = chan['print_name']
                try:
                    self.msg_buffer[cmd] = self.sender.history(print_name, 100)
                except:
                    self.msg_buffer[cmd] = []
                if self.INLINE_IMAGE:
                    for msg in self.msg_buffer[cmd]:
                        if 'media' in msg:
                            image = self.msg_widget.get_inline_img(msg)

        self.chan_widget.update_chan_list()

    def is_image(self, path):
        return not path == None and (path.endswith('png') \
        or path.endswith('jpg') \
        or path.endswith('jpeg') \
        or path.endswith('JPG') \
        or path.endswith('PNG'))


    def download_media(self, msg):
        if 'url' in msg:
            return msg['url']
        else:
            mtype = msg['media']['type']
            mid = msg['id']

            #file = self.sender.load_file(mid)
            if mtype == 'photo':
                file = self.sender.load_photo(mid)

            elif mtype == 'document':
                file = self.sender.load_document(mid)
            else:
                file = None

            return file

    def open_file(self, path):
        if self.conf['general']['open_file'] and path != None:
            subprocess.Popen(['xdg-open', path], stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)


    def start_Telegram(self):
        # link with telegram-cli
        PATH_TELEGRAM = self.conf['general']['path_telegram']
        PATH_PUBKEY = self.conf['general']['path_pubkey']

        self.receiver = Receiver()
        self.receiver.start()

        # Thread to dump received messages
        self.msg_dump = MessageReceiver(self)
        self.msg_dump.daemon = True
        self.msg_dump.start()

        self.tg = Telegram(telegram=PATH_TELEGRAM,
                           pubkey_file=PATH_PUBKEY)

        #self.receiver = self.tg.receiver
        self.sender = self.tg.sender


    def stop_Telegram(self):
        self.sender.status_offline()

        #self.tg.stopCLI()
        # Because of a bug in pytg, this is stopCLI without the line "self._proc.communicate('quit\n')"

        self.sender.terminate() # not let the cli end close first -> avoid bind: port already in use.
        self.receiver.stop()

        self.sender.safe_quit()
        if self.tg._check_stopped(): return None

        self.sender.quit()
        if self.tg._check_stopped(): return None

        self.sender.stop() # quit and safe quit are done, we don't need the sender any longer.

        if self.tg._check_stopped(): return None

        if self.tg._check_stopped(): return None

        self.tg._proc.terminate()
        if self.tg._check_stopped(): return None

        self.tg._proc.kill()
        if self.tg._check_stopped(): return None

        self.tg._proc.wait()
        self.tg._check_stopped()


    def exit(self):
        if self.conf['general']['notification']:
            Notify.uninit()
        sys.stdout.write("\x1b]2;\x07")
        self.stop_Telegram()
        raise urwid.ExitMainLoop


    def unhandle_key(self, key):
        if key == self.conf['keymap']['quit']:
            self.exit()

        elif key == 'esc':
            self.msg_widget.draw_separator()

        elif key == self.conf['keymap']['prev_chan']:
            self.chan_widget.go_prev_chan()

        elif key == self.conf['keymap']['next_chan']:
            self.chan_widget.go_next_chan()

        elif key == self.conf['keymap']['open_file'] and \
                self.last_media != {} and \
                self.conf['general']['open_file']:
             path = self.download_media(self.last_media)
             self.open_file(path)

        elif key == self.conf['keymap']['insert_text']:
            self.main_columns.focus_position = 2
            self.right_side.focus_position = 1

        elif key == "'":
            self.main_columns.focus_position = 2
            self.right_side.focus_position = 1
            self.msg_send_widget.widgetEdit.insert_text("'")
Ejemplo n.º 31
0
class bindings(object):
    def __init__(self, bot):
        self.bot = bot
        self.receiver = Receiver(host='localhost',
                                 port=self.bot.config['bindings_token'])
        self.sender = Sender(host='localhost',
                             port=self.bot.config['bindings_token'])
        logging.getLogger('pytg').setLevel(logging.WARNING)

    def get_me(self):
        try:
            msg = self.sender.get_self()
            return User(msg.peer_id, msg.first_name, None, msg.username)
        except Exception as e:
            catch_exception(e, self.bot)
            return None

    def convert_message(self, msg):
        try:
            id = msg['id']
            if msg.receiver.type == 'user':
                conversation = Conversation(msg.sender.peer_id)
                conversation.title = msg.sender.first_name
            else:
                if msg.receiver.type == 'channel':
                    conversation = Conversation(
                        -int('100' + str(msg.receiver.peer_id)))
                else:
                    conversation = Conversation(-int(msg.receiver.peer_id))
                conversation.title = msg.receiver.title

            if msg.sender.type == 'user':
                sender = User(int(msg.sender.peer_id))
                if 'first_name' in msg.sender:
                    sender.first_name = msg.sender.first_name
                if 'last_name' in msg.sender:
                    sender.last_name = msg.sender.last_name
                if 'username' in msg.sender:
                    sender.username = msg.sender.username
            else:
                if msg.sender.type == 'channel':
                    sender = Conversation(-int('100' +
                                               str(msg.sender.peer_id)))
                else:
                    sender = Conversation(-int(msg.sender.peer_id))
                sender.first_name = msg.sender.title

            date = msg.date

            # Gets the type of the message
            if 'text' in msg:
                type = 'text'
                content = msg.text
                extra = None
            elif 'media' in msg:
                type = msg.media.type
                content = msg.id
                if 'caption' in msg.media:
                    extra = msg.media.caption
                else:
                    extra = None
            elif msg.event == 'service':
                type = 'notification'
                if msg.action.type == 'chat_del_user':
                    content = 'left_chat_member'
                    extra = msg.action.user.peer_id
                elif msg.action.type == 'chat_add_user':
                    content = 'new_chat_member'
                    extra = msg.action.user.peer_id
                elif msg.action.type == 'chat_add_user_link':
                    content = 'new_chat_member'
                    extra = msg.sender.peer_id
                else:
                    type = None
                    content = None
                    extra = None
            else:
                type = None
                content = None
                extra = None

            if not extra:
                extra = {}

            # Generates another message object for the original message if the reply.
            if 'reply_id' in msg:
                reply_msg = self.sender.message_get(msg.reply_id)
                reply = self.convert_message(reply_msg)

            else:
                reply = None

            return Message(id, conversation, sender, content, type, date,
                           reply, extra)
        except Exception as e:
            catch_exception(e, self.bot)

    def receiver_worker(self):
        logging.debug('Starting receiver worker...')
        try:
            self.receiver.start()
            self.receiver.message(self.main_loop())
        except Exception as e:
            catch_exception(e, self.bot)

    def send_message(self, message):
        try:
            if not message.extra:
                message.extra = {}

            if message.type != 'text' and message.content.startswith('http'):
                message.content = download(message.content)
            elif message.type != 'text' and not message.content.startswith(
                    '/'):
                message.content = self.sender.load_file(message.content)

            if not message.extra or not 'caption' in message.extra:
                message.extra['caption'] = None

            if message.type == 'text':
                self.sender.send_typing(self.peer(message.conversation.id), 1)
                if 'format' in message.extra and message.extra[
                        'format'] == 'Markdown':
                    message.content = remove_markdown(message.content)
                elif 'format' in message.extra and message.extra[
                        'format'] == 'HTML':
                    message.content = self.convert_links(message.content)

                if 'format' in message.extra and message.extra[
                        'format'] == 'HTML':
                    self.sender.raw('[html] msg %s %s' %
                                    (self.peer(message.conversation.id),
                                     self.escape(message.content)),
                                    enable_preview=False)
                else:
                    self.sender.send_msg(self.peer(message.conversation.id),
                                         message.content,
                                         enable_preview=False)

            elif message.type == 'photo':
                self.sender.send_typing(self.peer(message.conversation.id),
                                        1)  # 7
                if message.reply:
                    self.sender.reply_photo(message.reply, message.content,
                                            message.extra['caption'])
                else:
                    self.sender.send_photo(self.peer(message.conversation.id),
                                           message.content,
                                           message.extra['caption'])

            elif message.type == 'audio':
                self.sender.send_typing(self.peer(message.conversation.id),
                                        1)  # 6
                if message.reply:
                    self.sender.reply_audio(message.reply, message.content)
                else:
                    self.sender.send_audio(self.peer(message.conversation.id),
                                           message.content)

            elif message.type == 'document':
                self.sender.send_typing(self.peer(message.conversation.id),
                                        1)  # 8
                if message.reply:
                    self.sender.reply_document(message.reply, message.content)
                else:
                    self.sender.send_document(
                        self.peer(message.conversation.id), message.content)

            elif message.type == 'sticker':
                if message.reply:
                    self.sender.reply_file(message.reply, message.content)
                else:
                    self.sender.send_file(self.peer(message.conversation.id),
                                          message.content)

            elif message.type == 'video':
                self.sender.send_typing(self.peer(message.conversation.id),
                                        1)  # 4
                if message.reply:
                    self.sender.reply_video(message.reply, message.content)
                else:
                    self.sender.send_video(self.peer(message.conversation.id),
                                           message.content)

            elif message.type == 'voice':
                self.sender.send_typing(self.peer(message.conversation.id), 5)
                if message.reply:
                    self.sender.reply_audio(message.reply, message.content)
                else:
                    self.sender.send_audio(self.peer(message.conversation.id),
                                           message.content)

            elif message.type == 'location':
                self.sender.send_typing(self.peer(message.conversation.id),
                                        1)  # 9
                if message.reply:
                    self.sender.reply_location(message.reply,
                                               message.content['latitude'],
                                               message.content['longitude'])
                else:
                    self.sender.send_location(
                        self.peer(message.conversation.id),
                        message.content['latitude'],
                        message.content['longitude'])

            else:
                print('UNKNOWN MESSAGE TYPE: ' + message.type)
                logging.debug("UNKNOWN MESSAGE TYPE")

        except Exception as e:
            catch_exception(e, self.bot)

    @coroutine
    def main_loop(self):
        while self.bot.started:
            try:
                msg = (yield)
                if (msg.event == 'message'
                        and msg.own == False) or msg.event == 'service':
                    message = self.convert_message(msg)
                    self.bot.inbox.put(message)

                    if message.conversation.id > 0:
                        self.sender.mark_read(self.peer(message.sender.id))
                    else:
                        self.sender.mark_read(
                            self.peer(message.conversation.id))

            except Exception as e:
                catch_exception(e, self.bot)

    def peer(self, chat_id):
        if chat_id > 0:
            peer = 'user#id' + str(chat_id)
        else:
            if str(chat_id)[1:].startswith('100'):
                peer = 'channel#id' + str(chat_id)[4:]
            else:
                peer = 'chat#id' + str(chat_id)[1:]
        return peer

    def user_id(self, username):
        if username.startswith('@'):
            command = 'resolve_username ' + username[1:]
            resolve = self.sender.raw(command)
            dict = DictObject(json.loads(resolve))
        else:
            dict = self.sender.user_info(username)

        if 'peer_id' in dict:
            return dict.peer_id
        else:
            return False

    def get_id(self, user):
        if isinstance(user, int):
            return user

        if user.isdigit():
            id = int(user)
        else:
            id = int(self.user_id(user))

        return id

    def escape(self, string):
        if string is None:
            return None

        CHARS_UNESCAPED = ["\\", "\n", "\r", "\t", "\b", "\a", "'"]
        CHARS_ESCAPED = ["\\\\", "\\n", "\\r", "\\t", "\\b", "\\a", "\\'"]

        for i in range(0, 7):
            string = string.replace(CHARS_UNESCAPED[i], CHARS_ESCAPED[i])
        return string.join(["'", "'"])  # wrap with single quotes.

    def convert_links(self, string):
        for link in BeautifulSoup(string, 'html.parser').findAll("a"):
            string = string.replace(str(link), link.get("href"))
        return string

    # THESE METHODS DO DIRECT ACTIONS #
    def get_file(self, file_id):
        pass

    def invite_conversation_member(self, conversation_id, user_id):
        try:
            self.sender.chat_add_user(self.peer(conversation_id),
                                      self.peer(user_id))
        except Exception as e:
            catch_exception(e, self.bot)

    def kick_conversation_member(self, conversation_id, user_id):
        try:
            self.sender.chat_del_user(self.peer(conversation_id),
                                      self.peer(user_id))
        except Exception as e:
            catch_exception(e, self.bot)

    def unban_conversation_member(self, conversation_id, user_id):
        pass

    def conversation_info(self, conversation_id):
        pass
Ejemplo n.º 32
0
# -*- coding: utf-8 -*-
import time
from datetime import datetime, timedelta

from pytg.receiver import Receiver
from pytg.sender import Sender

from models.issue import DeveloperInTeam, Team, TEAMS, FlagType, \
    ISSUE_TYPE, DeveloperFlags
from models.issue_repository import Statuses
from models.jira_api import server

receiver = Receiver(host="localhost", port=2391)
sender = Sender(host="localhost", port=2391)

response = sender.execute_function(u"contacts_list")

INWORK_FILTER = U"status in ('{}','{}','{}','{}')".format(
    Statuses.in_dev.value, Statuses.system_analize.value,
    Statuses.review.value, Statuses.re_dev.value) + u" and assignee = {}"


def is_pause_overtime(flag_type, flag):
    return datetime.now() - timedelta(
        minutes=flag_type.repeat_time_minutes) > flag.start_time


def send_message(flag_type, developer):
    message = flag_type.message.format(developer.name)
    if (developer.region.is_working_time()):
        sender.execute_function(u"msg", developer.telegram, message)
Ejemplo n.º 33
0
                    get_info_diff = random.randint(420, 900)
                else:
                    get_info_diff = random.randint(600, 900)
                if bot_enabled:
                    send_msg('@', bot_username, orders['hero'])
                continue
            # if fight_path != '' and castle_name is not None:
            #     os.chdir(fight_path)
            #     for file_name in glob.glob(castle_name + "*"):
            #         if file_name[-4:] != port:
            #             f = open(file_name, 'r')
            #             action_list.append(f.readline())
            #             f.close
            #             os.remove(file_name)
            if len(action_list):
                log('Отправляем ' + action_list[0])
                send_msg('@', bot_username, action_list.popleft())
            sleep_time = random.randint(2, 5)
            sleep(sleep_time)
        except Exception as err:
            log('Ошибка очереди: {0}'.format(err))


# main function supposed to be in the end
if __name__ == '__main__':
    receiver = Receiver(host=host, port=port)
    receiver.start()  # start the Connector.
    _thread.start_new_thread(queue_worker, ())
    receiver.message(work_with_message(receiver))
    receiver.stop()
Ejemplo n.º 34
0
# -*- coding: utf-8 -*-
__author__ = 'luckydonald'
from pytg.receiver import Receiver
from pytg.utils import coroutine


@coroutine
def example_function(receiver):
    try:
        while True:
            msg = (yield)
            print('Full dump: {array}'.format(array=str(msg)))
    except KeyboardInterrupt:
        receiver.stop()
        print("Exiting")


if __name__ == '__main__':
    receiver = Receiver(port=4458)  #get a Receiver Connector instance
    receiver.start()  #start the Connector.
    receiver.message(
        example_function(receiver)
    )  # add "example_function" function as listeners. You can supply arguments here (like receiver).
    # continues here, after exiting while loop in example_function()
    receiver.stop()
Ejemplo n.º 35
0
    def startTelegram(self):
	self.receiver = Receiver(host="localhost",port=4458);
	self.sender = Sender(host="localhost",port=4458);
Ejemplo n.º 36
0
from pytg.sender import Sender
from pytg.receiver import Receiver
from pytg.utils import coroutine

from AdminCommands import AdminCommands
from RuleManager import RuleManager

import logging

logging.basicConfig(filename='runtime_log.log',
                    format='%(levelname)s:%(message)s',
                    level=logging.DEBUG)

logging.info("Running start")

receiver = Receiver(host="localhost", port=4458)
sender = Sender(host="localhost", port=4458)

admin = sender.get_self()
adminCommands = AdminCommands(admin)

print("Got: >%s<" % admin)
username = admin.username
print("my username is {user}".format(user=username))

sender.send_msg(admin['id'],
                "Reenvio de mensajes condicional activado",
                enable_preview=True)

receiver.start()
Ejemplo n.º 37
0
            if (bulls != '0'):
                cows = txt[11]
            else:
                cows = txt[8]
        proc.stdin.write(str.encode(bulls + ' ' + cows + '\n'))
        proc.stdin.flush()
        sender.send_msg("@bulls_n_cows_bot", proc.stdout.readline().decode())
        print(txt, bulls, cows)
        #exit(0)


started = (input("Telegram-cli is running? Yes No\n") == "Yes")
if not started:
    telegram = Telegram(telegram="/usr/bin/telegram-cli",
                        pubkey_file="/etc/telegram-cli/server.pub")
    sender = telegram.sender
else:
    sender = Sender(host="localhost", port=4458)
num = int(input("Number of games: "))
for i in range(num):
    proc = Popen(["./bulls"], stdout=PIPE, stdin=PIPE)
    ans = proc.stdout.readline()
    sender.send_msg("@bulls_n_cows_bot", ans.decode())
    if not started:
        receiver = telegram.receiver
    else:
        receiver = Receiver(host="localhost", port=4458)
    receiver.start()
    receiver.message(get_msg())
    receiver.stop()
Ejemplo n.º 38
-10
class TelegramClient(object):

    CMD_PREFIX = 'command__'

    def __init__(self, from_users=[], to_users=None):
        """
        List of allowed user to send messages: from_users
        List of users that will receive the message: to_users
        """
        self.from_users = from_users
        self.to_users = to_users
        self.receiver = Receiver(port=PORT)
        self.sender = Sender(host=HOST, port=PORT)
        self.receiver.start()
        # start loop
        self.receiver.message(self.main_loop())

    def command__hola(self, msg, *args):
        self.send_reply(msg, u'Hola!')

    def command__gracias(self, msg, *args):
        self.send_reply(msg, u'de nada!')

    def command__temp(self, msg, *args):
        humidity, temperature = Adafruit_DHT.read_retry(11, 4)
        if humidity is not None and temperature is not None:
            res = u'Temp={0:0.1f} C  Humidity={1:0.1f}%'.format(
                temperature, humidity
            )
        else:
            res = u'Failed to get reading. Try again!'
        self.send_reply(msg, res)

    def command__quit(self, msg, *args):
        self.send_reply(msg, u'Closing client. Good bye!')
        return 'quit'

    def send_reply(self, msg, message):
        to = msg['sender'].get('username')
        self.send_message(to, message)

    def send_message(self, to, message):
        if to in self.to_users:
            self.sender.send_msg(self.to_users[to], message)

    def is_valid(self, msg):
        return msg.get('sender') and msg['sender'].get('username') in self.from_users

    def read_command(self, msg):
        if self.is_valid(msg) and msg.get('text'):
            args = msg.get('text').split(' ')
            cmd = self.CMD_PREFIX + args[0].lower()
            if hasattr(self, cmd):
                return getattr(self, cmd)(*([msg]+args[1:]))
        return False

    def stop(self):
        self.receiver.stop()

    @coroutine
    def main_loop(self):
        try:
            while True:
                msg = (yield)
                if self.read_command(msg) == 'quit':
                    break
        except Exception as e:
            print(u"ERROR: {}".format(e))
        finally:
            self.stop()