Esempio n. 1
0
    def show_settings(self):
        m = Message(to_jid=self.room_state.room_jid.bare(), stanza_type='groupchat')
        command_node = m.add_new_content(None, 'command')
        command_node.newChild(None, 'command', 'settings')
        command_node.newChild(None, 'level', str(self.level_id))

        # Custom type if Flash isn't going to know about it
        if self.mode.lower() in LEGIONS_GAMETYPES_DICT:
            command_node.newChild(None, 'mode', LEGIONS_GAMETYPES_DICT[self.mode.lower()])
        else:
            command_node.newChild(None, 'mode', 'deathmatch')

        # Show a specific limit if score can't be displayed
        show_scorelimit = self.scorelimit
        if self.mode == 'CTF':
            if self.scorelimit not in [1, 2, 5, 10, 15, 25]:
                show_scorelimit = 1
        else:
            if self.scorelimit not in [10, 20, 50, 100]:
                show_scorelimit = 100

        scorelimit_node = command_node.newChild(None, 'scorelimit', str(show_scorelimit))
        scorelimit_node.setProp('type', 'number')
        teams_node = command_node.newChild(None, 'teams', str(self.teams))
        teams_node.setProp('type', 'number')

        # Show custom time limits as "unlimited"
        if self.timelimit in [-1, 5, 10, 15, 20, 25, 30, 45, 60]:
            timelimit_node = command_node.newChild(None, 'timelimit', str(self.timelimit))
        else:
            timelimit_node = command_node.newChild(None, 'timelimit', '-1')
        timelimit_node.setProp('type', 'number')

        stream = self.room_state.manager.stream
        stream.send(m)
Esempio n. 2
0
    def party_refresh(self):
        m = Message(to_jid=self.room_state.room_jid.bare(), stanza_type='groupchat')
        command_node = m.add_new_content(None, 'command')
        command_node.newChild(None, 'command', 'refresh')

        stream = self.room_state.manager.stream
        stream.send(m)
Esempio n. 3
0
    def show_state(self):
        m = Message(to_jid=self.room_state.room_jid.bare(), stanza_type='groupchat')
        query_node = m.add_new_content(None, 'query')
        args_node = query_node.newChild(None, 'args', None)
        args_node.newChild(None, 'state', self.state)
        canhost_node = args_node.newChild(None, 'canHost', 'true')
        canhost_node.setProp('type', 'boolean')
        args_node.newChild(None, 'matchID', '%s19884641' % self.bot_nick)

        if self.state in ['ready', 'playing']:
            args_node.newChild(None, 'game', 'Legions')
            args_node.newChild(None, 'gameLevelId', str(self.level_id))
            args_node.newChild(None, 'gameLevel', self.level)
            args_node.newChild(None, 'gameMode', self.mode)
            args_node.newChild(None, 'jid', unicode(self.gamelist_jid))

        # args_node.newChild(None, 'anonymous', '0')
        maxplayers_node = args_node.newChild(None, 'maxplayers', str(self.size_limit))
        maxplayers_node.setProp('type', 'number')
        args_node.newChild(None, 'partyJID', unicode(self.room_state.room_jid.bare()))
        args_node.newChild(None, 'private', yes_or_no(self.private))
        args_node.newChild(None, 'allowAnon', 'no')
        args_node.newChild(None, 'createdAt', self.lobby_started)

        stream = self.room_state.manager.stream
        stream.send(m)
Esempio n. 4
0
    def vipadia_command(self, iq):
        dbg("vipadia_command:\n%s" % (fmt_evt(iq),))
        StLock.acquire()
        try:
            items = iq.xpath_eval("v:command/v:item", { "v": "http://vipadia.com/skype", })
            for item in items:
                command = item.prop("command")
                if command == "create-muc":
                    chatid = item.prop("chatid") # skype chat name
                    jid = JID(item.prop("jid"))
                    member = item.prop("member")

                    gid = groupchatid(chatid)

                    # populate St['conferences']
                    St['conferences'][gid] = (iq.get_from(),jid)

                    invite = Message(from_jid="%s@%s" % (gid, self.config.muc),
                                     to_jid=jid,
                                     )
                    x = invite.add_new_content("http://jabber.org/protocol/muc#user", "x")
                    add_child(add_child(x, "invite",
                                        attrs={"from": "%s@%s" % (member, self.config.component)}
                                        ), "reason", value=Msgs.join_chat)
                    add_child(x, "password")
                    self.safe_send(invite)

                    result = iq.make_result_response()
                    q = result.new_query("http://vipadia.com/skype", "command")
                    add_child(q, "item", attrs={"command": "create-muc",
                                                "gid": gid,
                                                "chatid": chatid})
                    self.safe_send(result)

                elif command == "destroy-muc":
                    gid = item.prop("gid") # skype chat name
                    if gid in St['conferences']:
                        # Tidy up
                        del St['conferences'][gid]

                        result = iq.make_result_response()
                        q = result.new_query("http://vipadia.com/skype", "command")
                        add_child(q, "item", attrs={"command": "destroy-muc",
                                                    "gid": gid})

                        self.safe_send(result)

                else:
                    err("unknown command!  command:%s\n%s" % (command, fmt_evt(iq),))

            return True
        finally:
            StLock.release()
Esempio n. 5
0
 def set_register(self, iq):
     """Handler for jabber:iq:register 'set' queries.
     
     This does not do anything usefull (registration data is ignored),
     but shows how to parse request and use Presence stanzas for
     subscription handling."""
     to = iq.get_to()
     if to and to != self.jid:
         iq = iq.make_error_response("feature-not-implemented")
         self.stream.send(iq)
         return True
     remove = iq.xpath_eval("r:query/r:remove", {"r": "jabber:iq:register"})
     if remove:
         m = Message(from_jid=iq.get_to(),
                     to_jid=iq.get_from(),
                     stanza_type="chat",
                     body=u"Unregistered")
         self.stream.send(m)
         p = Presence(from_jid=iq.get_to(),
                      to_jid=iq.get_from(),
                      stanza_type="unsubscribe")
         self.stream.send(p)
         p = Presence(from_jid=iq.get_to(),
                      to_jid=iq.get_from(),
                      stanza_type="unsubscribed")
         self.stream.send(p)
         return True
     username = iq.xpath_eval("r:query/r:username",
                              {"r": "jabber:iq:register"})
     if username:
         username = username[0].getContent()
     else:
         username = u""
     password = iq.xpath_eval("r:query/r:password",
                              {"r": "jabber:iq:register"})
     if password:
         password = password[0].getContent()
     else:
         password = u""
     m = Message(from_jid=iq.get_to(),
                 to_jid=iq.get_from(),
                 stanza_type="chat",
                 body=u"Registered with username '%s' and password '%s'"
                 " (both ignored)" % (username, password))
     self.stream.send(m)
     p = Presence(from_jid=iq.get_to(),
                  to_jid=iq.get_from(),
                  stanza_type="subscribe")
     self.stream.send(p)
     iq = iq.make_result_response()
     self.stream.send(iq)
     return True
Esempio n. 6
0
 def welcome(self):
     m = Message(type="chat",
                 to=self.peer,
                 body="You have authenticated with: %r" %
                 (self.auth_method_used))
     self.send(m)
     m = Message(type="chat",
                 to=self.peer,
                 body="You will be disconnected in 1 minute.")
     self.send(m)
     m = Message(type="chat", to=self.peer, body="Thank you for testing.")
     self.send(m)
     self.set_message_handler('chat', self.echo_message)
     self.set_message_handler('normal', self.echo_message)
Esempio n. 7
0
 def idle(self):
     print 'Idle...'
     Client.idle(self)
     if self.session_established and not self.sent:
         self.sent = True
         target = JID('-' + self.to_uid, self.jid.domain)
         self.get_stream().send(Message(to_jid=target, body=unicode(self.message)))
Esempio n. 8
0
 def end(self, body):
     """Returns an end message"""
     return EndMessage(
         stanza=Message(to_jid=self.conversation_info.jid,
                        body=body,
                        stanza_type=self.conversation_info.type,
                        stanza_id=self.conversation_info.next_stanza_id))
Esempio n. 9
0
 def message(self, body):
     """Creates a message to the jids associated with the controller"""
     return StanzaMessage(
         stanza=Message(to_jid=self.conversation_info.jid,
                        body=body,
                        stanza_type=self.conversation_info.type,
                        stanza_id=self.conversation_info.next_stanza_id))
Esempio n. 10
0
 def idle(self):
     print "idle"
     Client.idle(self)
     if self.session_established:
         target = JID("jajcus", s.jid.domain)
         self.stream.send(
             Message(to_jid=target, body=unicode("Teścik", "utf-8")))
Esempio n. 11
0
 def sendMessage(self, to, type, subject, body):
     m = Message(to_jid=to,
                 from_jid=self.jid,
                 stanza_type=type,
                 subject=subject,
                 body=body)
     self.stream.send(m)
Esempio n. 12
0
    def idle(self):
        """Called when there is a chance to do idle work."""

        print '%s Idle' % datetime.datetime.now()
        if self.outbox_directory:
            # Outbox format is one message per file. First line is the recipient,
            # the remaining lines are the message

            for ent in os.listdir(self.outbox_directory):
                print ' ... Found %s' % ent
                f = open('%s/%s' % (self.outbox_directory, ent), 'r')
                d = f.readlines()
                f.close()

                m = Message(to_jid=JID(d[0].rstrip('\n')),
                            from_jid=self.jid,
                            stanza_type='chat',
                            subject=None,
                            body=Normalize(''.join(d[1:]).rstrip('\n')))
                self.stream.send(m)
                print ' ... recipient = %s' % d[0].rstrip('\n')
                print ' ... body = %s' % Normalize(''.join(d[1:]).rstrip('\n'))
                os.unlink('%s/%s' % (self.outbox_directory, ent))

        Client.idle(self)
Esempio n. 13
0
    def vipadia_command(self, iq):
        dbg("vipadia_command:\n%s" % (fmt_evt(iq), ))

        items = iq.xpath_eval("v:command/v:item", {
            "v": "http://vipadia.com/skype",
        })
        for item in items:
            command = item.prop("command")
            if command == "message":
                ujid = JID(item.prop("ujid"))
                message = item.prop("message")

                dbg("  +ujid:%s precedingmessage:%s" % (
                    ujid.as_utf8(),
                    PrecedingMessage,
                ))
                if ujid in PrecedingMessage and PrecedingMessage[
                        ujid] == message:
                    continue

                PrecedingMessage[ujid] = message
                self.safe_send(Message(to_jid=ujid, body=message))
                dbg("  -ujid:%s precedingmessage:%s" % (
                    ujid.as_utf8(),
                    PrecedingMessage,
                ))

        return True
Esempio n. 14
0
def skype_OnMessageStatus(msg, status):
    try:
        dbg("skype_OnMessageStatus: msg:%s status:%s" % (msg, status), 3)

        if status != "RECEIVED": return

        chat = msg.Chat
        chatid = chat.Name

        if chatid not in ChatIDs:
            ## currently 1-1 chat
            if len(chat.Members) > 2:
                ## ...but will become group chat: initiate that and stash msg
                skype_OnChatMembersChanged(chat, chat.Members)
                if chatid in Msgs: Msgs[chatid].append(msg)
                else:
                    Msgs[chatid] = [msg]

            else:
                dbg("  body:%s topic:%s" % (msg.Body, chat.Topic))
                Bundle.safe_send(
                    Message(to_jid="%s@%s" % (msg.FromHandle, Master),
                            stanza_type="chat",
                            subject=chat.Topic,
                            body=msg.Body))

        else:
            ## currently group chat
            if len(Members[chatid]) == 0:
                ## ...noone actually here yet: stash msg for later
                if chatid in Msgs: Msgs[chatid].append(msg)
                else:
                    Msgs[chatid] = [msg]

            else:
                ## send the msg as a groupchat msg to MUC
                gid = ChatIDs[chatid]
                nick = msg.FromHandle  ## DisplayName
                dbg("  body:%s topic:%s" % (msg.Body, chat.Topic))
                Bundle.safe_send(
                    Message(to_jid="%s@%s/%s" % (gid, Muc, nick),
                            stanza_type="groupchat",
                            subject=chat.Topic,
                            body=msg.Body))

    except Exception, exc:
        log_stacktrace(exc)
Esempio n. 15
0
 def idle(self):
     ClientStream.idle(self)
     if not self.peer_authenticated:
         return
     if time.time() >= self.disconnect_time:
         m = Message(type="chat", to=self.peer, body="Bye.")
         self.send(m)
         self.disconnect()
Esempio n. 16
0
    def sendChatMessage(self, to, body):
        ctext = glob.textEncode(body)

        m = Message(to_jid=to,
                    from_jid=self.jid,
                    stanza_type='chat',
                    subject='',
                    body=ctext)
        self.stream.send(m)
Esempio n. 17
0
 def ask_regular_question(self, text):
     """Sends a question and returns the answer of the user"""
     s = messagetypes.StanzaMessage(
         stanza=Message(to_jid=self.info.jid,
                        body=text,
                        stanza_type=self.info.type,
                        stanza_id=self.info.next_stanza_id))
     self.queues.queue_out.put(s)
     return self.queues.queue_in.get().stanza.get_body()
Esempio n. 18
0
    def message(self, msg):
        dbg("message:\n%s" % (fmt_evt(msg), ), 3)
        if not self.attached: return True

        to = msg.get_to()
        if to != self.jid:
            err("misdirected message!\n%s" % (fmt_evt(msg), ))
            return True

        frm = msg.get_from()
        if (frm.domain not in (Master, Muc)):
            err("message untrusted source!  jid:%s stanza:\n%s" %
                (self.jid, fmt_evt(msg)))
            return True

        body = msg.get_body()
        subject = msg.get_subject()

        frm = msg.get_from()
        if frm.domain == Muc:
            declines = msg.xpath_eval(
                "u:x/u:decline", {
                    "u": "http://jabber.org/protocol/muc#user",
                })
            if declines:
                if frm.node not in GIDs: Declines[gid] = None
                else:
                    chatid = GIDs[frm.node]
                    self.skype.Chat(chatid).Leave()

                return True

            if frm.node not in GIDs:
                err("unknown gid!  gid:%s\n%s" % (
                    frm.node,
                    fmt_evt(msg),
                ))
                return True

            chatid = GIDs[frm.node]
            chat = self.skype.Chat(chatid)
            if not chat:
                err("unknown chatid!  chatid:%s" % (chatid, ))
                return True
            if subject: chat.Topic = subject

            try:
                if body: chat.SendMessage(body)
            except Exception, exc:
                err("message: skype sendmessage error!\n%s" % (fmt_evt(msg), ))
                log_stacktrace(exc)
                err("continuing...")
                return True

            to = "%s@%s/%s" % (frm.node, frm.domain, Nicks[frm.node])
            self.safe_send(Message(msg, to_jid=to))
Esempio n. 19
0
 def send_to_room(self, room_jid, jid, body):
     if not isinstance(room_jid, JID):
         room_jid = JID(room_jid)
     if not isinstance(jid, JID):
         jid = JID(jid)
     msg = Message(from_jid=jid.bare(),
                   to_jid=room_jid.bare(),
                   body=body,
                   stanza_type="groupchat")
     self.stream.send(msg)
Esempio n. 20
0
    def send_insane_otr(self, stanza, frag_size, instance_tag, our_tag):
        print "G-FUNK!"

        # this should result in about 0xFFFFFFFF times "A" base64 encoded        
        len_msg = 5726623060
        # fix frag size for base64
        frag_size = (frag_size / 4) * 4

        frag_msg = "QUFB"*(frag_size / 4)

        n = len_msg / frag_size 
        # does not evenly divide?
        if len_msg % frag_size > 0:
            n += 1
        k = 1
        n += 1 # initialbody adds another frame
        initialbody = "?OTR,%hu,%hu,%s," % (k , n , self.initial_body(instance_tag, our_tag))
        print "first fragment: "+initialbody
        m = Message(
                to_jid=stanza.get_from(),
                from_jid=stanza.get_to(),
                stanza_type=stanza.get_type(),
                subject="foo",
                body=initialbody)
        self.client.stream.send(m)
        k += 1
        print "frag size: %s, len_msg: %u, num_frags: %u" % (frag_size, len_msg, n)
        cur_pos = 0
        while(cur_pos < len_msg):
            body = "?OTR,%hu,%hu,%s," % (k , n , frag_msg)
            m = Message(
                to_jid=stanza.get_from(),
                from_jid=stanza.get_to(),
                stanza_type=stanza.get_type(),
                subject="foo",
                body=body)
            print "cur_pos %u of %u" % (cur_pos, len_msg)
            self.client.stream.send(m)
            k += 1
            cur_pos = frag_size * (k-2)
            time.sleep(0.9)
        print "FINAL FRAG: cur_pos %u of %u" % (cur_pos, len_msg)
Esempio n. 21
0
 def echo_message(self, message):
     typ = message.get_type()
     body = message.get_body()
     if not body:
         return
     body = u"ECHO: %s" % (body, )
     subject = message.get_subject()
     if subject:
         subject = u"Re: %s" % (subject, )
     m = Message(type=typ, to=self.peer, body=body, subject=subject)
     self.send(m)
Esempio n. 22
0
    def message(self, stanza):
        """Message handler for the component."""
        subject = stanza.get_subject()
        body = stanza.get_body()
        t = stanza.get_type()
        self.logDebug(u'pyLoad XMPP: Message from %s received.' %
                      (unicode(stanza.get_from(), )))
        self.logDebug(u'pyLoad XMPP: Body: %s Subject: %s Type: %s' %
                      (body, subject, t))

        if t == "headline":
            # 'headline' messages should never be replied to
            return True
        if subject:
            subject = u"Re: " + subject

        to_jid = stanza.get_from()
        from_jid = stanza.get_to()

        #j = JID()
        to_name = to_jid.as_utf8()
        from_name = from_jid.as_utf8()

        names = self.getConfig("owners").split(";")

        if to_name in names or to_jid.node + "@" + to_jid.domain in names:
            messages = []

            trigger = "pass"
            args = None

            try:
                temp = body.split()
                trigger = temp[0]
                if len(temp) > 1:
                    args = temp[1:]
            except:
                pass

            handler = getattr(self, "event_%s" % trigger, self.event_pass)
            try:
                res = handler(args)
                for line in res:
                    m = Message(to_jid=to_jid,
                                from_jid=from_jid,
                                stanza_type=stanza.get_type(),
                                subject=subject,
                                body=line)

                    messages.append(m)
            except Exception, e:
                self.logError("pyLoad XMPP: " + repr(e))

            return messages
Esempio n. 23
0
    def test_message_subject(self):
        """ Ensure proper handling of a subject stanza. """
        mock_stanza = self.mox.CreateMockAnything()
        mock_body = self.mox.CreateMockAnything()
        mock_client = self.mox.CreateMockAnything()

        self.mox.StubOutWithMock(CommandHandler, "__init__")
        self.mox.StubOutWithMock(CommandHandler, "parse_body")
        self.mox.StubOutWithMock(CommandHandler, "log_message")

        self.mox.StubOutWithMock(Message, "__init__")
        self.mox.StubOutWithMock(Message, "__del__")

        CommandHandler.__init__(mock_client)

        mock_stanza.get_subject().AndReturn("subject")
        mock_stanza.get_body().AndReturn(mock_body)
        mock_stanza.get_type().AndReturn("body")
        
        CommandHandler.log_message(mock_stanza, "subject", mock_body, "body")

        mock_stanza.get_type().AndReturn("body")

        CommandHandler.parse_body(mock_body).AndReturn("response")

        mock_stanza.get_from().AndReturn("from")
        mock_stanza.get_to().AndReturn("to")

        Message.__init__(
                to_jid = "from",
                from_jid = "to",
                stanza_type = "body",
                subject = u"Re: subject",
                body = "response")

        Message.__del__()

        self.mox.ReplayAll()

        cmdhandler = CommandHandler(mock_client)
        self.assertNotEqual(None, cmdhandler.message(mock_stanza))
Esempio n. 24
0
    def test_message_no_response(self):
        """ Test a mesage that does not yield a parse result. """
        mock_stanza = self.mox.CreateMockAnything()
        mock_body = self.mox.CreateMockAnything()
        mock_client = self.mox.CreateMockAnything()
        self.mox.StubOutWithMock(CommandHandler, "__init__")
        self.mox.StubOutWithMock(CommandHandler, "parse_body")
        self.mox.StubOutWithMock(CommandHandler, "log_message")

        self.mox.StubOutWithMock(Message, "__init__")
        self.mox.StubOutWithMock(Message, "__del__")

        CommandHandler.__init__(mock_client)

        mock_stanza.get_subject()
        mock_stanza.get_body().AndReturn(mock_body)
        mock_stanza.get_type().AndReturn("body")
        
        CommandHandler.log_message(mock_stanza, None, mock_body, "body")

        mock_stanza.get_type().AndReturn("body")

        CommandHandler.parse_body(mock_body).AndReturn(None)

        mock_stanza.get_from().AndReturn("from")
        mock_stanza.get_to().AndReturn("to")

        Message.__init__(
                to_jid = "from",
                from_jid = "to",
                stanza_type = "body",
                subject = None,
                body = "unknown command")

        self.mox.ReplayAll()

        cmdhandler = CommandHandler(mock_client)
        self.assertNotEqual(None, cmdhandler.message(mock_stanza))
Esempio n. 25
0
 def ask_yes_no_question(self, text):
     """Sends a yes/no question and returns the stanza answer of the user"""
     s = messagetypes.StanzaMessage(
         stanza=Message(to_jid=self.info.jid,
                        body=text,
                        stanza_type=self.info.type,
                        stanza_id=self.info.next_stanza_id))
     self.queues.queue_out.put(s)
     ans = self.queues.queue_in.get().stanza.get_body().strip()
     if ans == "yes":
         return True
     if ans == "no":
         return False
     return self.ask_yes_no_question("Please answer yes or no\n" + text)
    def message(self, stanza):
        """Message handler for the component.

        Echoes the message back if its type is not 'error' or
        'headline', also sets own presence status to the message body. Please
        note that all message types but 'error' will be passed to the handler
        for 'normal' message unless some dedicated handler process them.

        :returns: `True` to indicate, that the stanza should not be processed
        any further."""
        subject = stanza.get_subject()
        body = stanza.get_body()
        t = stanza.get_type()
        print u'Message from %s received.' % (unicode(stanza.get_from(), )),
        if subject:
            print u'Subject: "%s".' % (subject, ),
        if body:
            print u'Body: "%s".' % (body, ),
        if t:
            print u'Type: "%s".' % (t, )
        else:
            print u'Type: "normal".'
        if stanza.get_type() == "headline":
            # 'headline' messages should never be replied to
            return True
        if subject:
            subject = u"Re: " + subject

        if body:
            print "Sending text to cleverbot"
            driver_cleverbot.get("http://www.cleverbot.com?" + \
                                     urllib.urlencode({'say': body, 'b': 'Say'}))

            print "Waiting for cleverbot response"
            resp = wait_for_clever_response(driver_cleverbot)
            if resp is not None:
                print "Cleverbot says", resp.text
                body = resp.text

        m = Message(to_jid=stanza.get_from(),
                    from_jid=stanza.get_to(),
                    stanza_type=stanza.get_type(),
                    subject=subject,
                    body=body)
        if body:
            p = Presence(status=body)
            return [m, p]
        return m
Esempio n. 27
0
    def announce(self, message):
        """ send message to all owners"""
        for user in self.getConfig('owners').split(";"):
            self.logDebug("Send message to", user)

            to_jid = JID(user)

            m = Message(from_jid=self.jid,
                        to_jid=to_jid,
                        stanza_type="chat",
                        body=message)

            stream = self.get_stream()
            if not stream:
                self.connect()
                stream = self.get_stream()

            stream.send(m)
Esempio n. 28
0
 def start_conversation(self, jid, type="chat", room_state=None):
     """Spans a new thread for a new conversation, which is associated to jid
     Checks if the jid is allowed to use the application using user_control
     """
     if not self.user_control(jid):
         self.send(
             Message(to_jid=jid,
                     stanza_type=type,
                     from_jid=self.jid,
                     body="You are not allowed to talk with me"))
         return False
     queue_out = Queue.Queue(5)
     queue_in = Queue.Queue(5)
     self.conversations[jid] = ConversationQueues(queue_in, queue_out)
     Conversation(jid, self.__starter, self.__starter_params,
                  ConversationQueues(queue_out, queue_in), type,
                  room_state).start()
     self.logger.info("Started new conversation with %s@%s", jid.node,
                      jid.domain)
     self.logger.debug("Thread list: %s", threading.enumerate())
     return True
Esempio n. 29
0
    def message(self, stanza):
        """Message handler for the component.

        Just echoes the message back if its type is not 'error' or
        'headline'. Please note that all message types but 'error' will
        be passed to the handler for 'normal' message unless some dedicated
        handler process them.
        
        :returns: `True` to indicate, that the stanza should not be processed
        any further."""
        if stanza.get_type() == "headline":
            return True
        subject = stanza.get_subject()
        if subject:
            subject = u"Re: " + subject
        m = Message(to_jid=stanza.get_from(),
                    from_jid=stanza.get_to(),
                    stanza_type=stanza.get_type(),
                    subject=subject,
                    body=stanza.get_body())
        self.stream.send(m)
        return True
Esempio n. 30
0
    def message(self,stanza):
        """Message handler for the component.

        Echoes the message back if its type is not 'error' or
        'headline', also sets own presence status to the message body. Please
        note that all message types but 'error' will be passed to the handler
        for 'normal' message unless some dedicated handler process them.

        :returns: `True` to indicate, that the stanza should not be processed
        any further."""
        subject=stanza.get_subject()
        body=stanza.get_body()
        t=stanza.get_type()
        print u'Message from %s received.' % (unicode(stanza.get_from(),)),
        if subject:
            print u'Subject: "%s".' % (subject,),
        if body:
            print u'Body: "%s".' % (body,),
        if t:
            print u'Type: "%s".' % (t,)
        else:
            print u'Type: "normal".' % (t,)
        if stanza.get_type()=="headline":
            # 'headline' messages should never be replied to
            return True
        if subject:
            subject=u"Re: "+subject
        m=Message(
            to_jid=stanza.get_from(),
            from_jid=stanza.get_to(),
            stanza_type=stanza.get_type(),
            subject=subject,
            body=body)
        self.stream.send(m)
        if body:
            p=Presence(status=body)
            self.stream.send(p)
        return True
Esempio n. 31
0
    def ask_multiple_choice_question(self, text, options):
        """Sends a list of posible options and returns the user's choice 
        to the caller
        
        """
        m = "\n".join("%s) %s" % (str(i), text) for i, text in options)
        s = messagetypes.StanzaMessage(
            stanza=Message(to_jid=self.info.jid,
                           body=text + "\n" + m,
                           stanza_type=self.info.type,
                           stanza_id=self.info.next_stanza_id))
        self.queues.queue_out.put(s)
        stanza = self.queues.queue_in.get().stanza
        try:
            option = stanza.get_body().strip()
            for o, t in options:
                if str(o).strip() == option:
                    return (o, t)
            raise Exception, "Options not well formed"

        except:
            return self.ask_multiple_choice_question(
                "You must input a valid option\n" + text, options)
Esempio n. 32
0
def send_xmpp_message(from_jid, to_jid, txt):
    msg = Message(stanza_type='chat',
                  from_jid=JID(from_jid),
                  to_jid=JID(to_jid),
                  body=txt)
    client.stream.send(msg)
Esempio n. 33
0
 def send(self, message, jid):
     m = Message(to_jid=jid, body=message, stanza_type="chat")
     self.stream.send(m)
Esempio n. 34
0
    def message(self, stanza):
        dbg(
            "message:\nfrm:%s to:%s" % (
                stanza.get_from().as_utf8(),
                stanza.get_to().as_utf8(),
            ), 3)
        global RegDB

        body = stanza.get_body()
        frm = stanza.get_from()
        user = stanza.get_from().bare().as_utf8()

        ujid = JID(user)
        dbg("  ++ujid:%s precedingmessage:%s" % (
            ujid.as_utf8(),
            PrecedingMessage,
        ))
        if ujid in PrecedingMessage: del PrecedingMessage[ujid]
        dbg("  --ujid:%s precedingmessage:%s" % (
            ujid.as_utf8(),
            PrecedingMessage,
        ))

        if body:
            cmd = body.split()
            if len(cmd) > 0:
                reply = ""
                if cmd[0].lower() == "register":
                    if len(cmd) != 3:
                        reply = "error, please use: register <skypeuser> <skypepassword>"

                    skypeuser = cmd[1]
                    skypepass = cmd[2]

                    RegDB.remove_credentials(user)
                    RegDB.set_credentials_plain(user, skypeuser, skypepass)

                    reply = "Registration successful for " + skypeuser
                    message = Message(to_jid=stanza.get_from(), body=reply)
                    self.safe_send(message)

                    sub = Iq(to_jid=self.config.master, stanza_type="set")
                    query = sub.new_query('http://vipadia.com/skype',
                                          "command")
                    add_child(query,
                              "item",
                              attrs={
                                  "command": "register-available",
                                  "jid": frm.as_utf8()
                              })
                    dbg("  sub:\n%s" % (fmt_evt(sub), ))
                    self.safe_send(sub)
                    reply = "Presence request sent"

                elif cmd[0].lower() == "register-carrier":
                    if len(cmd) != 3:
                        reply = "error, please use: register <skypeuser> <skypepassword>"

                    skypeuser = cmd[1]
                    ## KeyCzar
                    ##                     crypter = keyczar.Encrypter.Read(PUBLIC_KEYLOC)
                    skypesecret = cmd[2]
                    ## KeyCzar
                    ##                     skypesecret = crypter.Encrypt(str(skypesecret))

                    spawn = Iq(to_jid=self.config.master, stanza_type="set")
                    command = spawn.new_query("http://vipadia.com/skype",
                                              "command")
                    add_child(command,
                              "item",
                              attrs={
                                  "command": "spawn",
                                  "ujid": frm.as_utf8(),
                                  "skypeuser": skypeuser,
                                  "skypesecret": skypesecret,
                              })
                    self.safe_send(spawn)

                elif cmd[0].lower() == "unregister":
                    if len(cmd) == 1:
                        RegDB.remove_credentials(user)
                        reply = "Unregistration successful"

                else:
                    reply = "Skype Registration Commands:\r\n" + \
                    " register <skypeuser> <skypepass>\r\n" + \
                    " unregister"

                message = Message(to_jid=stanza.get_from(), body=reply)
                self.safe_send(message)

        return True
Esempio n. 35
0
    def message(self, stanza):
        """Handle incoming messages"""

        print 'Handling message'
        subject = stanza.get_subject()
        body = stanza.get_body()
        sender = stanza.get_from().as_utf8().split('/')[0]
        t = stanza.get_type()

        print ' ... sender = %s' % sender
        print ' ... subject = %s' % subject
        print ' ... body = %s' % body
        print ' ... type = %s' % t

        # If this is a text message, then we respond
        if stanza.get_type() != 'headline' and body:
            verb = body.split(' ')[0]
            verb = verb.lower()

            status_message = ''

            # Force users to be authenticated before they can do anything
            if not self.authenticated.has_key(sender):
                if verb == 'auth':
                    if self.passwd.authenticate(sender, body[5:]):
                        result = 'Welcome'
                        status_message = 'Authenticated'
                        self.authenticated[sender] = True
                    else:
                        status_message = 'Who are you?'
                        result = 'Sorry, try again'
                else:
                    status_message = 'Who are you?'
                    result = 'You need to authenticate.\nUse auth <password>'

            # If we are authenticated, then other commands work
            elif verb == 'help':
                if len(body) == 4:
                    sorted_verbs = verbs.keys()
                    sorted_verbs.sort()
                    result = 'Registered verbs are: %s\nTry help <verb> ' \
                             'to learn more about a verb.' % \
                             ', '.join(sorted_verbs)
                    status_message = 'Helping'
                else:
                    help_target = body.split(' ')[1]
                    help_target = help_target.lower()

                    if not verbs.has_key(help_target):
                        result = 'No such command -- try help to find out which ' \
                                 'commands do exist'
                        status_message = 'Nothing to see here'
                    else:
                        plugin_name = verbs[help_target]
                        try:
                            result = plugins[plugin_name].Help(help_target)
                            status_message = plugins[plugin_name].Status()
                        except:
                            result = 'No help available for this verb'
                            status_message = 'Bummer'

            # And now we go looking for a plugin to execute the verb
            elif verbs.has_key(verb):
                plugin_name = verbs[verb]
                body = body[len(verb) + 1:]
                print 'Passing %s to %s (with %s)' % (verb, plugin_name, body)
                result = plugins[plugin_name].Command(verb, body)
                status_message = plugins[plugin_name].Status()

            else:
                result = 'Command not known'
                status_message = 'Huh?'

            p = Presence(status=status_message)
            self.stream.send(p)

            m = Message(to_jid=stanza.get_from(),
                        from_jid=stanza.get_to(),
                        stanza_type=stanza.get_type(),
                        subject=subject,
                        body=Normalize(result))
            self.stream.send(m)
            print ' ... recipient = %s' % stanza.get_from()
            print ' ... body = %s' % Normalize(result)

        return True
Esempio n. 36
0
    def message(self, stanza):
        subject = stanza.get_subject()
        body = stanza.get_body()
        t = stanza.get_type()
        print u'Message from %s received.' % (unicode(stanza.get_from(),)),

        if t:
            if t == 'chat':
                if not body:
                    command_message = stanza.xpath_eval("ns:command")

                    if command_message:
                        command = stanza.xpath_eval("ns:command/ns:command")

                        if command:
                            command_text = command[0].getContent()

                            if command_text == 'requestLobby':
                                self.client.ia_party.show_state()
                                return True
                            elif command_text == 'requestSettings':
                                self.client.ia_party.show_settings()
                                return True
                    else:
                        print "no command"

                else:
                    msg_from = stanza.get_from()

                    if not self.client.ia_party.commands.is_admin(msg_from.node):
                        return

                    msg = stanza.get_body()
                    bang_re = re.compile('^!(\w+)( .*)?$')
                    bang_cmd = bang_re.match(msg)

                    if not bang_cmd:
                        return

                    (command, args) = bang_cmd.groups()
                    command = command.lower()

                    if args:
                        args = args.strip().rstrip()

                    bang_command = self.client.ia_party.commands.get_command(command)

                    if bang_command:
                        result = bang_command(stanza.get_from(), args)

                        if result:
                            # Have to insert a bit of XML into the body, grrr
                            m = Message(to_jid=stanza.get_from(), stanza_type='headline')
                            body_node = m.add_new_content(None, 'body')
                            body_node.setContent(result)
                            party_node = body_node.newChild(
                                None, 'party', self.client.ia_partyresource)

                            stream = self.client.stream
                            stream.send(m)

                        return True