Beispiel #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)
Beispiel #2
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()
Beispiel #3
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()
Beispiel #4
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()
Beispiel #5
0
def main():
    """
    starts dataset collector on port provided in sys.argv[1], where telegram-cli runs.
    """

    arg_port = int(sys.argv[1])
    logging.basicConfig(filename="dataset_collector.log", level=logging.INFO)

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

    receiver.start()

    receiver.message(message_rec(sender))

    receiver.stop()
Beispiel #6
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!")
Beispiel #7
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!")
Beispiel #8
0
def main():
    # get a Receiver instance, to get messages.
    msg_receiver = Receiver(host="localhost", port=4458)

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

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

    # add "alert" function as message listener. You can supply arguments here (like sender).
    msg_receiver.message(
        alert(msg_sender)
    )  # now it will call the "alert" 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() )
    msg_receiver.stop()

    print("Shutting down app! CLI will still be running")
Beispiel #9
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!")
Beispiel #10
0
                                if msg['online'] else colorama.Fore.RED +
                                'offline') + colorama.Fore.RESET
                userId = msg['user']['id']
                userName = msg['user']['print_name']
                nickName = colorama.Fore.YELLOW + userName + colorama.Fore.RESET
                lastChange = ''
                if last is not {} and userId in last:
                    diff = relativedelta(now, last[userId])
                    lastChange = ' [%02d:%02d:%02d]' % (
                        diff.hours, diff.minutes, diff.seconds)
                    if not msg['online']:
                        lastChange = lastChange + ' (%d msgs)' % msg_counter.get(
                            userId, 0)
                        msg_counter[userId] = 0
                last[userId] = now
                print(date + ': ' + nickName + ': ' + onlineStatus +
                      lastChange)
            elif msg['event'] == 'message':
                userId = msg['sender']['id']
                msg_counter[userId] = msg_counter.get(userId, 0) + 1
    except KeyboardInterrupt:
        receiver.stop()
        print("Exiting")


if __name__ == '__main__':
    receiver = Receiver(port=4458)
    receiver.start()
    receiver.message(stalk(receiver))
receiver.stop()
Beispiel #11
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))
            sender.first_name = msg.sender.first_name
            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.title = 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 = remove_html(message.content)

            try:
                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.
Beispiel #12
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")
Beispiel #13
0
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:
        pass
    else:
        pass

receiver.start()
receiver.message(main_loop())
receiver.stop()
Beispiel #14
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)
Beispiel #15
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()
Beispiel #16
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()
Beispiel #17
0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from pytg.sender import Sender
from pytg.receiver import Receiver
from pytg.utils import coroutine

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 == u'hello':
                sender.send_msg(msg.peer.cmd, u'world')
    except GeneratorExit:
        pass
    else:
        pass

receiver.start()
receiver.message(main_loop())
receiver.stop
Beispiel #18
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))
Beispiel #19
0
            # print('Full dump: {array}'.format(array=str(telegram_msg)))
            # check for admin
            if adminCommands.handle(telegram_msg):
                continue

            for rule in RuleManager.rules:
                rule.execute(telegram_msg)

        except KeyboardInterrupt:
            receiver.stop()
            break
        except Exception as ex:
            global ERROR_COUNT_LIMIT
            logging.exception(ex, exc_info=True)
            ERROR_COUNT_LIMIT -= 1
            if ERROR_COUNT_LIMIT == 0:
                sender.send_msg(
                    admin['id'],
                    "El programa se apagará por motivos de seguridad.")
                raise ex
            else:
                sender.send_msg(
                    admin['id'], "Quedan " + str(ERROR_COUNT_LIMIT) +
                    " errores antes de que se apague el programa.")


receiver.message(example_function(receiver))

sender.send_msg(admin['id'],
                "El reenvio de mensajes condicional está desactivado")
Beispiel #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
Beispiel #21
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()
Beispiel #22
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()
Beispiel #23
0

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()
Beispiel #24
0
def run_receiver():
    receiver = Receiver(host="localhost", port=4458)
    receiver.start()
    logger.info('receiver.message...')
    receiver.message(enqueue_msgs())
    receiver.stop()
Beispiel #25
-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()