Beispiel #1
0
 def post(self):
     msg = xmpp.Message(self.request.POST)
     if 'help' in msg.body:
         msg.reply(
             '\r\n<姓名> <年齡> <計算流年(民國年)> 或是參閱說明文件:http://bit.ly/9KaYWJ')
     elif 'htsay' in msg.body:
         try:
             st = msg.body.split(' ')
             msg.reply(htls.htexp(st[1].encode('utf-8')))
         except:
             msg.reply('輸入錯誤!請參考說明文件:http://bit.ly/9KaYWJ ')
     elif 'ht' in msg.body:
         hts = htls.htls().hts
         re = ''
         for i in hts:
             re += i + '→'
         msg.reply(re)
     elif 'ls' in msg.body:
         lss = htls.htls().lss
         re = ''
         for i in lss:
             re += i + '→'
         msg.reply(re)
     else:
         try:
             st = msg.body.split(' ')
             re = htls.htls(st[0].encode('utf-8')).all(st[1], st[2])
             msg.reply('\r\n' + re)
             logging.info('HTLS: %s' % re)
         except:
             msg.reply('輸入錯誤!請參考說明文件:http://bit.ly/9KaYWJ')
     #msg.reply(msg.body)
     logging.info(self.request.POST)
     logging.info('Msg status: %s' % msg.body)
Beispiel #2
0
 def post(self, **kwargs):
     try:
         self.xmpp_message = xmpp.Message(self.request.form)
     except xmpp.InvalidMessageError, e:
         logging.error('Invalid XMPP request: Missing required field %s',
                       e[0])
         return self.app.response_class('')
Beispiel #3
0
 def join_command(self, message=None):
     message = xmpp.Message(self.request.POST)
     user = message.sender.rpartition("/")[0]
     room = message.arg
     add_to_room(room, user, "xmpp")
     memcache.set(key=user, value=room, time=1800)
     message.reply("Congrats, you joined the room '" + room + "'")
    def post(self):
        message = xmpp.Message(self.request.POST)
        sender = cgi.escape(self.request.get('from')).split("/")[0]
        bodystart = message.body.lower()[0:2]

        with open('data.txt') as f:
            content = f.readlines()

        if bodystart == 'mo':
            message.reply(content[0] + '\n' + content[1] + '\n' + content[2] + '\n' + content[3] + '\n' + content[4] + '\n')

        elif bodystart == 'tu':
            message.reply(content[5] + '\n' + content[6] + '\n' + content[7] + '\n' + content[8] + '\n' + content[9] + '\n')

        elif bodystart == 'we':
            message.reply(content[10] + '\n' + content[11] + '\n' + content[12] + '\n' + content[13] + '\n' + content[14] + '\n')

        elif bodystart == 'th':
            message.reply(content[15] + '\n' + content[16] + '\n' + content[17] + '\n' + content[18] + '\n' + content[19] + '\n')

        elif bodystart == 'fr':
            message.reply(content[20] + '\n' + content[21] + '\n' + content[22] + '\n' + content[23] + '\n' + content[24] + '\n')

        elif bodystart == 'sa':
            message.reply(content[25] + '\n' + content[26] + '\n' + content[27] + '\n' + content[28] + '\n' + content[29] + '\n')

        elif bodystart == 'su':
            message.reply(content[30] + '\n' + content[31] + '\n' + content[32] + '\n' + content[33] + '\n' + content[34] + '\n')

        else :
            message.reply('Invalid query!! Enter the first two letters of the day of the week. For example, enter `sa` for Saturday\'s menu.')
Beispiel #5
0
 def help_command(self, message=None):
     message = xmpp.Message(self.request.POST)
     help_msg = "This is a simple chatroom client which can be used both from the web, or from an XMPP client:\n\n" \
       "/join XYZ -> joins the XYZ room\n\n" \
       "/help ->  get help message\n"
     message.reply(help_msg)
     message.reply(message.body)
Beispiel #6
0
def xmpp_handler(request):
    try:
        # logging.info('received xmpp_request %r'%(request,))
        if request.method == 'POST':
            message = xmpp.Message(request.POST)
            receiver, ignore, body = message.body.partition(' ')
            # logging.info(' receiver=%r body=%r'%(receiver, body))
            if '@' not in receiver:
                message.reply(
                    'Please start your message with email address of the receiver.'
                )
            else:
                sender = message.sender.partition('/')[0]
                sent_count = 0
                for handler in [handler1, handler2]:
                    sent_count += handler(sender, receiver, body)
                if not sent_count:
                    message.reply('Could not send message to ' + receiver)
                elif sent_count == 1:
                    message.reply('Sent your message')
                else:
                    message.reply('Sent your message to %d session(s)' %
                                  (sent_count, ))
            return HttpResponse()
        else:
            return HttpResponseNotAllowed()

    except:
        logging.info('xmpp_handler exception %r' % (sys.exc_info(), ))
        return HttpResponseServerError()
Beispiel #7
0
 def post(self):
     try:
         self.xmpp_message = xmpp.Message(self.request.form)
     except xmpp.InvalidMessageError, e:
         logging.error("Invalid XMPP request: Missing required field %s",
                       e[0])
         return
Beispiel #8
0
    def post(self):
        msg = xmpp.Message(self.request.POST)
        logging.debug(self.request.body + "$" + str(msg))
        commands = [
            'status', 'help', 'update', 'home', 'shorten', 'remind', 'verify'
        ]
        msgSplit = msg.body.split(' ')

        self.user = GrafiteUser.getUser(username=self._getUserName(msg.sender))
        if self.user is None and msgSplit[0].lower() != "verify":
            msg.reply(STR_HELLO + "\n" + STR_PROMPT_REGISTER)
            return

        logging.debug("*CHAT*: " + self.user.key().name())
        #login the user!
        if self.user:
            res = GrafiteUser.login(self.user.key().name(), self.user.password,
                                    "XMPP")
            self.user.accessToken = res[1]
        elif msgSplit[0].lower() != 'verify':
            msg.reply(
                "Hey, I couldn't really identify who you are! :-( Please register yourself.."
            )
            return
        if msgSplit[0].lower() in commands:
            try:
                getattr(self, "cmd_" + msgSplit[0].lower())(msg)
            except Exception, e:
                msg.reply("Error!\n" + str(e))
                import traceback
                msg.reply(traceback.format_exc())
Beispiel #9
0
 def post(self):
   try:
     self.xmpp_message = xmpp.Message(self.request.POST)
   except xmpp.InvalidMessageError as e:
     logging.error("Invalid XMPP request: Missing required field %s", e[0])
     return
   self.message_received(self.xmpp_message)
Beispiel #10
0
    def post(self):
        message = xmpp.Message(self.request.POST)

        answer = do_arithmetic(message.body)
        if answer is None:
            message.reply('I didn\'t understand: ' + message.body)
        else:
            message.reply('The answer is: ' + answer)
Beispiel #11
0
 def text_message(self, message=None):
     message = xmpp.Message(self.request.POST)
     user = message.sender.rpartition("/")[0]
     msg = {
         "message": strip_tags(message.body),
         "name": user
     }
     room = memcache.get(key=user)
     send_to_room(room, msg)
Beispiel #12
0
 def post(self):
     message = None
     try:
         message = xmpp.Message(self.request.POST)
     except xmpp.InvalidMessageError, e:
         logging.error("Invalid XMPP request: %s", e[0])
         logging.error(self.request.body)
         logging.error(self.request.POST)
         return
Beispiel #13
0
  def help_command(self, message=None):
    message = xmpp.Message(self.request.POST)
    help_msg = "It's not even alpha ready, but you could play with following commands:\n\n" \
               "/hello -> about me\n\n" \
	       "/subscribe <url>\n/unsubscribe <url|'all'> -> subscribe or unsubscribe to a feed\n\n" \
	       "/list <page_index> ->  list subscriptions, default to page 1\n\n" \
	       "/help ->  get help message\n"
    message.reply(help_msg)
    message.reply(message.body)
Beispiel #14
0
  def post(self):
    message = xmpp.Message(self.request.POST)
    user = models.get_user_(users.User(message.sender.split('/')[0]))
    if user is not None:
      models.create_comment(user, message.body)
      memcache.delete("comments")

      body = user.nickname + '> ' + message.body
      xmpp.send_message(models.get_jids(), body, APP_URL + ".appspot.com", xmpp.MESSAGE_TYPE_CHAT)
Beispiel #15
0
    def post(self):
        j = self.request.get('from').split('/')[0]
        u = User.gql('WHERE jid = :1', j).get()
        if not u:
            u = User(jid=j)
            u.put()
        message = xmpp.Message(self.request.POST)

        r = query_bitly(message.body.strip().split(' ')[0], u)
        message.reply('\n' + r)  # replied
        return
Beispiel #16
0
    def post(self):
        logging.info('ChatHandler: %r' % self.request.POST)

        message = xmpp.Message(self.request.POST)
        user = ChatUser.get_or_insert(truncate_jid(message.sender))
        user.jid = message.sender
        user.last_chat_message = message.body
        user.put()

        message.reply('I got your message! '
                      'It had %d characters.' % len(message.body))
Beispiel #17
0
def incoming_chat(request):
    """/_ah/xmpp/message/chat/

  This handles incoming XMPP (chat) messages.

  Just reply saying we ignored the chat.
  """
    try:
        msg = xmpp.Message(request.POST)
    except xmpp.InvalidMessageError, err:
        logging.warn('Incoming invalid chat message: %s' % err)
        return HttpTextResponse('')
Beispiel #18
0
    def post(self):
        message = xmpp.Message(self.request.POST)

        mesFrom = message.sender.split('/')[0]
        mesTo = message.to.split('/')[0]
        mesBody = message.body

        if mesFrom.lower() != PSTO_BOT.lower() and mesFrom.lower(
        ) != JUICK_BOT.lower() and mesFrom.lower() != PSTO_ANOTHER_BOT.lower(
        ):  # and mesFrom.lower() != BNW_BOT.lower() and mesFrom.lower() != NYA_BOT.lower() :
            self.parseMessageFromJid(message, mesFrom)
        else:
            self.parseMessageFromBot(message, mesFrom)
Beispiel #19
0
    def post(self):
        logging.info('message! %s', self.request.POST)
        message = xmpp.Message(self.request.POST)

        try:
            parsed = json.loads(message.body)

        except Exception as ex:
            logging.warn("Error parsing message %s", message.body)
            return

        from_jid, resource = split_jid(message.sender)

        device = model.Device.from_resource(resource, from_jid)
        if device == None:
            logging.debug("Message from unknown device %s/%s", from_jid,
                          resource)
            return

        cmd = parsed['cmd']
        logging.debug('---- COMMAND: %s', cmd)

        if cmd == 'get_relays':
            logging.debug("NEW RELAYS: %s", parsed.get('data', None))

            data = parsed['data']

            if device.relays is None: device.relays = {}

            for relay, state in data['relays'].iteritems():
                device.relays[relay] = state

            logging.debug("Updated relays for %s : %s", message.sender, data)
            device.put()

            # pass the message on to the web UI user
            channel_id = device.owner.user_id()
            data['device_id'] = device.id
            channel.send_message(channel_id,
                                 json.dumps({
                                     "cmd": cmd,
                                     "data": data
                                 }))

        elif cmd == 'readings':
            channel_id = device.owner.user_id()
            parsed['data']['device_id'] = device.id
            channel.send_message(channel_id, json.dumps(parsed))

        else:
            logging.warn("Unknown command: %s", cmd)
    def post(self):

        message = xmpp.Message(self.request.POST)

        #DEBUG: log xmmp input
        log_xmpp_in = db.xmpp_in(From=message.sender)
        log_xmpp_in.Body = message.body
        log_xmpp_in.When = datetime.datetime.now()
        log_xmpp_in.put()

        #Split message body into args array
        args = message.body.split(" ")
        command = args[0]

        #try to read parameters ?
        try:
            repo = args[1]
        except IndexError:
            repo = ""

        #Parse sender JID to extract email
        email_pattern = re.compile('([\w\-\.]+@(\w[\w\-]+\.)+[\w\-]+)')
        result = email_pattern.match(message.sender)
        email = result.group(0)

        if (command == '!mute'):
            #mute (or stop watching) all or one repository
            self.mute_command(email, repo)
        elif (command == '!unmute'):
            #unmute (or start watching) all or one repository
            self.unmute_command(email, repo)
        elif (command == '!watch'):
            #start watching one repository
            self.watch_command(email, repo)
        elif (command == '!unwatch'):
            #stop watching one/all repository
            self.unwatch_command(email, repo)
        else:
            #Display usage if unkown command
            usage = "Watch command:\n"
            usage += "    !watch  %repo_name%    -> start watching this repository\n"
            usage += "Unmute command:\n"
            usage += "    !unmute    -> unmute notifications about all previously watched repositories\n"
            usage += "    !unmute %repo_name%     -> unmute notifications about this repository or start watching it\n"
            usage += "Mute command:\n"
            usage += "    !mute     -> mute notifications about all watched repositories\n"
            usage += "    !mute %RepoName%    -> mute notifications about this repository\n"

            xmpp.send_message(message.sender,
                              "Unknown command: " + command + "\n" + usage)
Beispiel #21
0
def gae_xmpp(environ, start_response):
    from google.appengine.api import xmpp
    content_type = environ['CONTENT_TYPE']
    content_type_boundary = re.search(r'boundary="(.+?)"',
                                      content_type).group(1)
    data = environ['wsgi.input'].read()
    params = dict(
        m.group(1, 2)
        for m in (re.search('name="(\\w+)"\r\n\r\n(.+?)$', x.strip('\r\n-'))
                  for x in data.split(content_type_boundary)) if m)
    logging.info('xmpp receive params=%s', params)
    message = xmpp.Message(params)
    message.reply(message.body)
    return ['']
Beispiel #22
0
 def post(self):
   try:
     message = xmpp.Message(self.request.POST)
   except xmpp.InvalidMessageError:
     return
   content = message.body
   if not content:
     return
   self._jid = message.sender.split('/')[0]
   args = content.strip().split(' ')
   try:
     func = getattr(self, args[0].lower())
   except AttributeError, e:
     message.reply(e.message)
Beispiel #23
0
 def subscribe_command(self, message=None):
   message = xmpp.Message(self.request.POST)
   subscriber = message.sender.rpartition("/")[0]
   subscription = Subscription(key_name=hashlib.sha224(message.arg + subscriber).hexdigest(), feed=message.arg, jid=subscriber)
   subscription.put() # saves the subscription
   result = superfeedr("subscribe", subscription)
   if result.status_code == 204:
     logging.info("Subscription success! %s", message.arg)
     message.reply("Successfully subscribed to " + message.arg + "!")
   elif result.status_code == 202:
     message.reply("Subscribing to " + message.arg + ", you should get a confirmation soon.")
   else:
     message.reply("Could not subscribe to " + message.arg + ", looks like AppEngine got a small glitch. Please try again!")
     logging.error("Sorry, couldn't subscribe ( Status %s - Error %s) to %s",  message.arg, result.status_code, result.content)
Beispiel #24
0
    def post(self):
        message = xmpp.Message(self.request.POST)
        user_address = self.request.get('from').split('/')[0]
        msg = ""

        if message.body[0:6].lower() == 'status':
            # Look up their URL(s) and list status(es)
            q = db.GqlQuery("SELECT * FROM LogUser " + "WHERE userName = :1",
                            string.lower(user_address))

            msg = "For user: '******'\n"
            if q.count() > 0:
                results = q.fetch(500)
                for p in results:
                    msg += "URL: " + p.serverName + ":"
                    if p.userActive:
                        msg += "Active"
                    else:
                        msg += "Inactive"
                    msg += "\n"
            else:
                msg += "No URLs defined for user\n"
            chat_message_sent = False
        elif message.body[0:4].lower() == 'stop':
            # Look up their URL(s) and disable them
            q = db.GqlQuery("SELECT * FROM LogUser " + "WHERE userName = :1",
                            string.lower(user_address))
            results = q.fetch(500)
            for p in results:
                p.userActive = False
                p.put()
            msg = "Alerts disabled for user: '******'\n"
        elif message.body[0:5].lower() == 'start':
            # Look up their URL(s) and disable them
            q = db.GqlQuery("SELECT * FROM LogUser " + "WHERE userName = :1",
                            string.lower(user_address))
            results = q.fetch(500)
            for p in results:
                p.userActive = True
                p.put()
            msg = "Alerts enabled for user: '******'\n"
        else:
            msg = "Available messages are:\n'Status' to list current conditions\n'Start' to enable messages\n'Stop' to disable messages."

        if msg != "":
            if xmpp.get_presence(user_address):
                status_code = xmpp.send_message(user_address, msg)
                chat_message_sent = (status_code == xmpp.NO_ERROR)
                chat_message_sent = False
Beispiel #25
0
 def post(self):
     msg = xmpp.Message(self.request.POST)
     fields = msg.body.split(';')
     try:
         if len(fields) < 2:
             xmpp.send_message(
                 msg.sender, 'Invalid message. Syntax: \
                               <dest - user or group>;\
                               <talk or mail(ignore for talk)>;\
                               <message>')
         else:
             sender = msg.sender.split('/')[0]
             self.parse_message(fields, sender)
     except Exception, e:
         xmpp.send_message(msg.sender, 'Error sending message - ' + str(e))
Beispiel #26
0
def message():
        import logging
        message1 =  request.vars
        logging.debug("honey I'm HOME! " + str(message1))
        #user_address = '*****@*****.**'
        message = xmpp.Message(message1)
        if message.body[0:5].lower() == 'hello':
            person = message.sender
            message.reply("Greetings!" + person)
        else:
            message.reply("I have no idea.")
        #xmpp.send_invite(user_address)
        #msg = "hi there chris:)"
        #xmpp.send_message(user_address, msg)
        return message
Beispiel #27
0
 def unsubscribe_command(self, message=None):
   message = xmpp.Message(self.request.POST)
   subscriber = message.sender.rpartition("/")[0]
   if message.arg == "all":
     query = Subscription.all().filter("jid =",subscriber).order("feed")
     subscriptions = query.fetch(query.count() + 1)
     db.delete(subscriptions)
     message.reply("Well done! We deleted all your subscriptions!")
   else :
     subscription = Subscription.get_by_key_name(hashlib.sha224(message.arg + subscriber).hexdigest())
     if(subscription == None):
       message.reply("Looks like you were not susbcribed to " + message.arg)
     else:
       result = superfeedr("unsubscribe", subscription)
       subscription.delete() # deletes the subscription
       message.reply("Well done! You're not subscribed anymore to " + message.arg)
Beispiel #28
0
    def post(self):
        message = xmpp.Message(self.request.POST)

        to_address = message.to.split('@')[0]
        from_email_address = message.sender.split('/')[0]
        logging.info('xmpp searching for: ' + to_address + ' from ' +
                     from_email_address)

        chat_message_sent = False
        gae_klazz_user = utils.loadModuleType("Friends", "Friends_User")
        uq = gae_klazz_user.all()
        uq.filter('nick =', to_address)
        friend = uq.get()

        uq = gae_klazz_user.all()
        uq.filter('emailAddress =', from_email_address)
        sender = uq.get()

        if friend and sender:
            status_code = xmpp.send_message(friend.emailAddress, message.body)
            chat_message_sent = (status_code != xmpp.NO_ERROR)
            logging.info('XMPP send to:' + friend.emailAddress + ' = ' +
                         str(status_code))

            if not chat_message_sent:
                logging.info('Failed to send message')
                gae_klazz_queue = utils.loadModuleType("Friends",
                                                       "Friends_Queue")
                q = gae_klazz_queue(key_name=utils.new_key())
                q.owner = sender.name
                q.targetUser = to_address
                q.comments = message.body
                q.org = 'ParabayOrg'
                q.isPrivate = False
                q.itemType = 1
                q.updated = datetime.datetime.now()
                q.bookmark = utils.bookmark_for_kind('Friends_Queue',
                                                     sender.name, q.updated)
                q.put()
                message.reply(
                    "The user is currently offline. Your message will be delivered when the user is online."
                )
            else:
                logging.info('Sent message')
        else:
            logging.info('invalid friend:' + to_address + ', ' +
                         from_email_address)
Beispiel #29
0
    def post(self):
        message = xmpp.Message(self.request.POST)

        clients = db.GqlQuery("SELECT * FROM Client", email=message.sender)
        if not clients.get():
            message.reply(
                "Please visit https://tzwmtest.appspot.com/ to get start")
            return

        access_token_key = clients.get().twitter_actoken_key
        access_token_secret = clients.get().twitter_actoken_secret

        api = twitter.Api(consumer_key=config.TWITTER_CONSUMER_KEY,
                          consumer_secret=config.TWITTER_CONSUMER_SECRET,
                          access_token_key=access_token_key,
                          access_token_secret=access_token_secret)
        api.PostUpdate(message.body)
Beispiel #30
0
    def post(self):
        message = xmpp.Message(self.request.POST)

        user_address = '*****@*****.**'
        chat_message_sent = False

        status_code = xmpp.send_message(user_address, 'got message')
        chat_message_sent = (status_code != xmpp.NO_ERROR)

        if not chat_message_sent:
            chat = datamodel.UserChat()
            chat.sender = message.sender
            chat.receiver = message.to
            chat.body = message.body
            chat.put()
            message.reply(
                "The user is currently offline. Your message will be delivered when the user is online."
            )