示例#1
0
 def toGroup_command(self, message=None):
     content = message.body.split('/toGroup')[1].strip()
     sender = message.sender.split('/')[0]
     sender = sender.split('@')[0]
     receiver = content.split(' ')[0]
     content = group_controller.getGroupName() + '-' + sender + ':' + content.split(' ')[1]
     xmpp.send_message(receiver, content)
示例#2
0
    def post(self):
        global WANT_TEA
        global NEWBIE_GREETING
        global teacountdown
        global informed

        fromaddr = self.request.get('from').split("/")[0]
        person = Roster.get_or_insert(key_name=fromaddr, jid=fromaddr)

        if (person.newbie):
            xmpp.send_message(fromaddr, NEWBIE_GREETING)
            person.newbie = False
            person.put()

        if (not person.askme):
            xmpp.send_presence(fromaddr,
                               status=":( Haven't heard from " +
                               getSalutation(fromaddr) + " in a while...",
                               presence_type=xmpp.PRESENCE_TYPE_AVAILABLE)
        else:
            xmpp.send_presence(fromaddr,
                               status="",
                               presence_type=xmpp.PRESENCE_TYPE_AVAILABLE)

        if (teacountdown and person.askme and fromaddr not in informed):
            send_random(fromaddr, WANT_TEA)
            informed.add(fromaddr)
示例#3
0
def chat_send():
    # 5a) We only send the message to the main site XMPP user
    from_jid = '*****@*****.**' % g.member.first_name
    message = request.json['message']
    if message:
        xmpp.send_message('*****@*****.**', message, from_jid=from_jid)
    return '', 200
示例#4
0
def show_new_mentions(gid, since_id):
    oauth_token, oauth_secret = get_user_oauth_info(gid)
    a = fanfou.fanfou(settings.consumer_key, settings.consumer_secret, oauth_token, oauth_secret)
    if since_id == '': #手动查看新 mentions
        response, content = a.statuses_mentions()
        content = json.loads(content)
        for item in reversed(content):
            message_count = get_max_message_count()
            message_id = item['id']
            if not status_exists(message_id):
                memcache_add('%s%s'%(NUMBER_TO_ID_PREFIX, `message_count`), message_id)
                conversation = '%s: %s'%(item['user']['screen_name'], item['text'])
                memcache_add('%s%s'%(CONTENT_PREFIX, `message_count`), conversation)
                memcache_add('%s%s'%(SCREEN_NAME_PREFIX, `message_count`), item['user']['screen_name'])
                inc_max_message_count()
                update_last_mention(gid, item['id'])
                xmpp.send_message(gid, '%s #%s'%(conversation, message_count))
    else: #自动获取新 mentions
        since_id = db.GqlQuery("SELECT * FROM users WHERE gid='%s'"%(gid))[0].last_mentions
        response, content = a.statuses_mentions(since_id=since_id)
        content = json.loads(content)
        for item in reversed(content):
            message_count = get_max_message_count()
            message_id = item['id']
            if not status_exists(message_id):
                memcache_add('%s%s'%(NUMBER_TO_ID_PREFIX, `message_count`), message_id)
                conversation = '%s: %s'%(item['user']['screen_name'], item['text'])
                memcache_add('%s%s'%(CONTENT_PREFIX, `message_count`), conversation)
                memcache_add('%s%s'%(SCREEN_NAME_PREFIX, `message_count`), item['user']['screen_name'])
                inc_max_message_count()
                update_last_mention(gid, item['id'])
                xmpp.send_message(gid, '%s #%s'%(conversation, message_count))
示例#5
0
    def _notify_answers(self, domain, notify_answers):
        all_answers = []
        for question, answers in notify_answers.iteritems():
            for answer in answers:
                answer['question'] = question

            all_answers.extend(answers)

        short_urls = self._shorten_answers_urls(domain, all_answers)

        for question in notify_answers:
            answers = notify_answers[question]
            for answer in answers:
                owner = answer['owner']
                if 'display_name' in owner:
                    name = owner['display_name']
                else:
                    name = owner['user_id']

                url = short_urls[answer['answer_id']]

                if 'last_edit_date' in answer:
                    msg = "Answer from %s edited: %s" % (name, url)
                else:
                    msg = "New answer from %s: %s" % (name, url)

                followers = list(question.followers)
                jids = map(lambda follower: follower.follower.address,
                           followers)
                if len(jids) > 0:
                    logging.debug('sending message to %s' % (jids, ))
                    send_message(jids, msg)
                else:
                    logging.debug('no follower')
示例#6
0
 def post(self):
   '''show 可以是 away、dnd(忙碌)或空(在线)'''
   jid, resource = self.request.get('from').split('/', 1)
   status = self.request.get('status')
   show = self.request.get('show')
   logging.debug(u'%s 的状态: %s (%s)' % (jid, status, show))
   try:
     show = gaetalk.STATUS_CODE[show]
   except KeyError:
     logging.error('%s has sent an incorrect show code %s' % (jid, show))
     return
   try:
     gaetalk.send_status(self.request.get('from'))
   except xmpp.Error:
     logging.error('Error while sending presence to %s' % jid)
     return
   u = gaetalk.get_user_by_jid(jid)
   if u is not None:
     modified = False
     if resource not in u.resources:
       u.resources.append(resource)
       modified = True
     if u.avail != show:
       if u.avail == gaetalk.OFFLINE:
         u.last_online_date = datetime.datetime.now()
       u.avail = show
       modified = True
     if modified:
       gaetalk.log_onoff(u, show, resource)
       u.put()
     if config.warnGtalk105 and resource.startswith('Talk.v105'):
       xmpp.send_message(jid, u'您的客户端使用明文传输数据,为了大家的安全,请使用Gtalk英文版或者其它使用SSL加密的客户端。')
   else:
     gaetalk.try_add_user(jid, show, resource)
示例#7
0
def reply(jid,m):
	t = reduce(lambda s, (a,b): s.replace(a,b), repls, unicode(m))
	while len(t)>32768:
		xmpp.send_message(jid,t[:32768],from_jid=MyJID)
		t = t[32768:]
	#logging.info('XMPP: ' + t)
	xmpp.send_message(jid,t,from_jid=MyJID)
示例#8
0
 def post(self):
     fromEmail = self.request.get('from').split('/')[0].lower()
     logging.info("""%s is available""" % fromEmail)
     theUser = None
     for aUser in db.Query(oneUser).filter('emailString =',str(fromEmail)):
         logging.debug('The user has id %s' % aUser.key().name())
         theUser = aUser
     if theUser == None:
         logging.error("Received available signal from user %s. However no user with this email could be found" % fromEmail)
         return
     previousLastSeen = theUser.lastSeen
     theUser.lastSeen = datetime.today()
     #theUser.lastSeen = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
     theUser.xmppEnabled = True
     theUser.put()
     
     availableReleases = []
     for aSubscription in db.Query(subscription).filter('emailStr =',str(fromEmail)).filter('channel =', 'xmpp').filter('subscribed =',True):
         logging.info('Subscribed to %s' % aSubscription.projectStage.key().name())
         for aFacet in db.Query(Facet).filter('projectStage =',aSubscription.projectStage).filter('logDate >', previousLastSeen).order('-logDate').fetch(1):
             logging.info('%s is available' % aFacet.key().id())
             availableReleases.append(aFacet)
     
     
     for oneRelease in availableReleases:
         messageText = """new Release available for %s at stage %s. Download it from %s""" % (oneRelease.project.label, oneRelease.projectStage.label, oneRelease.projectStage.downloadLinks()[2])
         #xmpp.send_invite(myConfig.emailFrom,'%s___%s@%s.appspotchat.com' % (myConfig.namespace,self.key().name(),config.get('Architecture','appengineId')))
         xmpp.send_message(theUser.emailString, messageText, from_jid='%s@%s.appspotchat.com' % (config.get('xmpp','fromAddress'), config.get('General','appName')))
示例#9
0
	def post(self):
		action = self.request.get('action')
		if action in all_actions:
			param = self.request.get('param')
			ex_param = self.request.get('ex_param')
			task = Task(action=action, param=param, status='waiting')
			if ex_param is not None:
				task.ex_param = ex_param
			if action in ['tweet', 'delete', 'follow', 'unfollow', 'retweet', 'direct_message',
						  'update_name', 'update_url', 'update_location', 'favorite', 'un-favorite']:
				task.status = 'ready'
		else:
			if self.request.get('redirect_url'):
				self.redirect(self.request.get('redirect_url'))
			else:
				self.response.out.write('{"status": "error"}')
			return

		if task.status == 'ready':
			last_time = memcache.get('last_time')
			if last_time <> None and (time.time()-last_time) > 60*10 or last_time == None:
				task.status = 'completed'
				response = do_task(task)

		task.put()

		if JABBER_UID is not None or len(JABBER_UID) > 0:
			xmpp.send_message(JABBER_UID, '%s: /%s %s %s'%(self.request.remote_addr, action, param, ex_param is not None and ex_param or ''))

		if self.request.get('redirect_url'):
			self.redirect(self.request.get('redirect_url'))
		else:
			self.response.out.write('{"status": "ok"}')
示例#10
0
 def notify(self, sender, user, tipo, message):
     if tipo == 'talk':
         xmpp.send_message(user.talk, 'From: ' + sender + ' - ' + message)
     elif tipo == 'mail':
         mail.send_mail(user.mail,
                        user.mail, 'GAE Notify',
                        'From: ' + sender + ' - ' + message)
示例#11
0
def publish_next():
    items_to_publish = models.PublishableItem.query().fetch(1)
    if items_to_publish is not None:
        for itemToPublish in items_to_publish:

            publish = models.GalleryItem.query(models.GalleryItem.id == itemToPublish.id).get()
            if publish is not None:
                image = get_resize(publish)

                files = fetch_image_to_attach(image, publish)
                if files is None:
                    msg = (
                        "Could not retrieve image when publishing "
                        + publish.path
                        + " image : "
                        + utils.image_url(publish.path, image)
                    )
                    xmpp.send_message("*****@*****.**", msg)

                url = publish_photo(files, publish)

                # Remove the item we just published so it doesn't go again
                itemToPublish.key.delete()
                return "Published: " + url

    return "Nothing published"
示例#12
0
文件: matcher.py 项目: a37912/gaeaib
  def post(self):

    post = matcher.get_document(self.request.form)
    send = post.data

    for sub_id in self.request.form.getlist('id'):
      logging.info("send post to %s" % sub_id)

      if send.get('evt') == 'online' and '@' in sub_id:
        continue

      if '@' in sub_id:
        jid = sub_id.split('/')[0]
        whoami = '%(board)[email protected]' % send
        MSG = """Posted http://42ch.org/%(board)s/%(thread)d/#p%(last)d\n\n%(text)s""" % send
        xmpp.send_message(jid, MSG, from_jid=whoami)
        continue

      try:
        channel.send_message(sub_id, dumps(send))
      except channel.InvalidChannelClientIdError:
        logging.error("inval client id %r" % sub_id)
      except channel.InvalidMessageError:
        logging.error("inval msg: %r" % dumps(send))

    return Response("ok")
示例#13
0
    def post(self):
        """Sends an XMPP from this app to itself. """
        @db.transactional
        def update_state(key):
            metadata = db.get(key)
            if metadata is None:
                XmppMetadata(key_name=TEST_KEYNAME,
                             state=XmppMessages.SENT).put()
            else:
                # The 'received' handler may have already updated the state.
                assert metadata.state == XmppMessages.RECEIVED

        xmpp.send_message(MY_JABBER_ID, XmppMessages.HELLO)

        entity_key = db.Key.from_path('XmppMetadata', TEST_KEYNAME)
        update_state(entity_key)

        # write out the result, in json
        self.response.headers['Content-Type'] = "application/json"
        self.response.out.write(
            json.dumps({
                'status': True,
                'exists': True,
                'state': XmppMessages.SENT
            }))
示例#14
0
文件: bot.py 项目: melmothx/jsonbot
 def outnocb(self,
             jids,
             txt,
             how="msg",
             event=None,
             origin=None,
             from_jid=None,
             message_type=None,
             raw_xml=False,
             groupchat=False,
             *args,
             **kwargs):
     """ output xmpp message. """
     from google.appengine.api import xmpp
     if not message_type: message_type = xmpp.MESSAGE_TYPE_CHAT
     if type(jids) != types.ListType: jids = [
             jids,
     ]
     txt = self.normalize(txt)
     logging.debug(u"%s - xmpp - out - %s - %s" %
                   (self.name, unicode(jids), txt))
     xmpp.send_message(jids,
                       txt,
                       from_jid=from_jid,
                       message_type=message_type,
                       raw_xml=raw_xml)
示例#15
0
def processOperatorMsg(message=None, answer=None):
    '''Обработка сообщения от оператора
    '''
    result = appOperators.all().filter('active =', True).filter(
        'isweb =', False).filter('jid =',
                                 message.sender.split('/')[0]).get()
    opinfo = memcache.get(result.login)
    # проверка связи с пользователем
    if opinfo is None or opinfo.get('users') == None or opinfo.get(
            'web') == None:
        logging.debug(u'что-то не так в processOperatorMsg(operator info)')
        answer.write(u'\nВ данный момент вы ни с кем не переписываетесь!')
    else:
        # пишем сообщение в хранилище
        m = appOperatorsMsg(sender=message.sender.split('/')[0],
                            to=opinfo['users'][0],
                            text=CheckMessageText(message.body),
                            date=datetime.datetime.now(),
                            read=True)
        m.put()
        # пересылаем сообщение оператору
        xmpp.send_message(m.to, m.text)
        # обновляем timeout беседы
        memcache.set(result.login, opinfo, TALK_TIMEOUT)
        userinfo = memcache.get(m.to)
        if userinfo is None:
            answer.write(
                u'\nНеожиданное отсутствие связи с пользователем(processOperatorMsg)'
            )
        else:
            memcache.set(m.to, userinfo, TALK_TIMEOUT)
示例#16
0
def send_posts(posts, subscriber, search_term):
    message_builder = MessageBuilder()
    for post in posts:
        xmpp.send_message(subscriber,
                          message_builder.build_message_from_post(
                              post, search_term),
                          raw_xml=False)
示例#17
0
    def send_to_bots(self, message, mesFrom) :
        mesText = message.body.strip()
        if mesText.find("-j") == 0 :
	  # Sending to juick only
	  mesText = mesText.replace("-j ", "", 1)
	  juick_status = xmpp.send_message(JUICK_BOT, mesText, mesFrom)
	  message.reply("Sent to juick succesfully: " + str(juick_status == xmpp.NO_ERROR))
	elif mesText.find("-p") == 0 :
	  # Sending to psto only
	  mesText = mesText.replace("-p ", "", 1)
	  psto_status = xmpp.send_message(PSTO_BOT, mesText, mesFrom)
	  message.reply("Sent to psto succesfully: " + str(psto_status == xmpp.NO_ERROR))
	#elif mesText.find("-b") == 0 :
	  # Sending to bnw only.
	  #mesText = mesText.replace("-b ", "", 1)
	  #bnw_status = xmpp.send_message(BNW_BOT, mesText, mesFrom)
	  #message.reply("Sent to bnw succesfully: " + str(bnw_status == xmpp.NO_ERROR))
	#elif mesText.find("-n") == 0 :
	  # Sending to nya only.
	  #mesText = mesText.replace("-n ", "", 1)
	  #nya_status = xmpp.send_message(NYA_BOT, mesText, mesFrom)
	  #message.reply("Sent to nya succesfully: " + str(nya_status == xmpp.NO_ERROR))
	else :
	  # Sending to all.
	  juick_status = xmpp.send_message(JUICK_BOT, mesText, mesFrom)
	  psto_status = xmpp.send_message(PSTO_BOT, mesText, mesFrom)
	  #bnw_status = xmpp.send_message(BNW_BOT, mesText, mesFrom)
	  #nya_status = xmpp.send_message(NYA_BOT, mesText, mesFrom)

	  message.reply("Sent to juick succesfully: " + str(juick_status == xmpp.NO_ERROR))
	  message.reply("Sent to psto succesfully: " + str(psto_status == xmpp.NO_ERROR))
示例#18
0
文件: ui.py 项目: vtgav/remoht.us
    def post(self, device_id, relay):
        logging.debug("Toggle relay %s", relay)

        user = users.get_current_user()
        if not user: return self.unauthorized()

        device = model.Device.get_by_id(int(device_id))
        if device is None: return self.notfound()

        state = self.request.get("state", None)
        msg = {
            "cmd": "toggle_relay",
            "params": {
                "relay_id": relay,
                "state": int(state)
            }
        }

        to_jid = device.full_jid

        logging.debug("Sending toggle_relay to %s, %s=%s", to_jid, relay,
                      state)
        #        from_jid = "%s/user-%s" % (base_jid, user.user_id())
        xmpp.send_message(to_jid, json.dumps(msg))  #, from_jid=from_jid)
        self.render_json({"msg": "OK", "relays": device.relays})
示例#19
0
    def do_work(cls, args):
        logging.debug('%s working with %s' % (cls, args))
        result = []
        data = cls.do_work_core(args)
        for title, content in data:
            ret = ProcItem.add_item(cls.__module__ + '.' + cls.__name__, title,
                                    content)
            if ret:
                content['title'] = title
                result.append(content)
            else:
                logging.debug('store item fail: %s' % title)

        if 'xmpp' in args and args['xmpp'].strip():
            msg = cls.render_msg(args, result)
            if msg: xmpp.send_message([args['xmpp']], msg)

        if 'post' in args:
            #ret = requests.post(args['post'], json={'items': result})
            ret = urlfetch.fetch(args['post'],
                                 payload=json.dumps(result),
                                 method=urlfetch.POST)
            if ret.status_code != 200:
                logging.warn('data post failed: %d' % ret.status_code)

        return result
示例#20
0
    def post(self):
        cursor = int(self.request.get("cursor", default_value=0))
        tokens = OAuthAccessToken.all().fetch(10, offset = cursor)

        for token in tokens:
            if xmpp.get_presence(token.email):
                client = OAuthClient('twitter', self, token.email)
                
                user_cache = memcache.get("user_cache_" + token.email)
                
                if user_cache is not None and user_cache.since_id is not None:
                    #response = client.get('/statuses/home_timeline', count = 5, 
                    #                  since_id = last_sent_id)
                    logging.info('since_id:' +  str(user_cache.since_id))
                    response = self.fetchTweets(client, token.email, 
                                    '/statuses/home_timeline', count = 5, 
                                      since_id = user_cache.since_id)
                else:
                    response = self.fetchTweets(client, token.email, 
                                    '/statuses/home_timeline', count = 5)
                
                if len(response) > 0:
                    xmpp.send_message(token.email, 'Some recent tweets:' + getFormattedMessage(response))
        
        if len(tokens) == 10:
            taskqueue.add(url='/sendrecentworker', 
                          params={'cursor': cursor + 10})
示例#21
0
    def get(self):
        if users.get_current_user():
            devicekey = self.request.get('device')
            link = "http://www.pushthepage.com/Hello" 
            query = Devices.all()
            query.filter("devicekey =", devicekey)
            query.filter("user ="******"ios":
                    logging.debug("Sending UA Push to: " + r.token)
                    application_key = creds.ua_application_key
					master_secret = creds.ua_master_secret
                    airship = urbanairship.Airship(application_key, master_secret)
                    airship.push({'aps': {'alert': link, 'sound': 'bing'}}, device_tokens=[r.token])
                elif r.devicetype == "xmpp":
                    logging.debug("Sending XMPP to: " + r.token)
                    xmpp.send_message(r.token, link)   
                self.redirect("http://www.pushthepage.com/congratulations")
示例#22
0
    def get(self):
        if users.get_current_user():
            devicekey = self.request.get('device')
            if len(self.request.get('url')) > 100:
                link = shorten(self.request.get('url'))                
            else:
                link = self.request.get('url') 
            query = Devices.all()
            query.filter("devicekey =", devicekey)
            query.filter("user ="******"ios":
                    logging.debug("Sending UA Push to: " + r.token)
                    application_key = creds.ua_application_key
					master_secret = creds.ua_master_secret
                    try:
                        airship = urbanairship.Airship(application_key, master_secret)
                        airship.push({'aps': {'alert': link, 'sound': 'bing'}}, device_tokens=[r.token])
                        self.redirect(link)
                    except: 
                        template_values = {'errortext' : str(sys.exc_info()[1][1])}
                        path = os.path.join(os.path.dirname(__file__), 'uaerror.html')
                        self.response.out.write(template.render(path, template_values))
                elif r.devicetype == "xmpp":
                    logging.debug("Sending XMPP to: " + r.token)
                    xmpp.send_message(r.token, link)   
                    self.redirect(link)
示例#23
0
文件: gaetalk.py 项目: Vayn/gaetalk
  def do_quiet(self, args):
    '''禁言某人,参数为昵称和时间(默认单位秒)'''
    if len(args) != 2:
      self.msg.reply('请给出昵称和时间。')
      return
    else:
      try:
        n = utils.parseTime(args[1])
      except ValueError:
        self.msg.reply('Sorry,我无法理解你说的时间。')
        return

    target = get_user_by_nick(args[0])
    if target is None:
      self.msg.reply('Sorry,查无此人。')
      return

    target.black_before = datetime.datetime.now() + datetime.timedelta(seconds=n)
    target.put()
    self.msg.reply(u'OK,禁言 %s %s。' % (target.nick, utils.displayTime(n)))
    send_to_all_except((self.sender.jid, target.jid),
                       (u'%s 已被禁言 %s。' % (target.nick, utils.displayTime(n))) \
                       .encode('utf-8'))
    xmpp.send_message(target.jid, u'你已被管理员禁言 %s。' % utils.displayTime(n))
    log_admin(self.sender, BLACK % (target.nick, n))
示例#24
0
    def post(self):
        """ 
        Function to handle received messages

        @rtype: None
        """
        #TODO: Delete this variable.
        dummy_email = "*****@*****.**" #: Dummy Email. Will be used for user_2 if there is no match.
        message = xmpp.Message(self.request.POST) 
        pass_message = True #: Whether the message will be passed to partner

        sender = message.sender.split("/")[0] # Remove the identifier string from JID
        conversation = Conversation(user_1 = sender, user_2 = dummy_email ,location = db.GeoPt(41,28)) # Create a new conversation
        conversation = conversation.getPartner(sender) # Try to get a partner

        if message.body[0] == "|": # If this is a custom message
            pass_message = self.customMessageHandler(conversation,message)

        if conversation.is_started == True: # If this conversation has started
            if conversation.user_1 == sender: 
                partner = conversation.user_2
            else:
                partner = conversation.user_1
            
            if pass_message == True: # If we need to pass this message to client (See custom messages)
                xmpp.send_message(partner, message.body) # Send this message to partner
示例#25
0
 def post(self):
   global ON_YOUR_OWN
   global WELL_VOLUNTEERED
   global OTHEROFFERED
   
   global drinkers
   global teacountdown
   global doublejeopardy    
   global lastround  
   global informed
   
   if len(drinkers) == 1:
     for n in drinkers:
       send_random(n, ON_YOUR_OWN)
   elif len(drinkers) > 0:        
     # Select someone who wasn't the last person to make the tea 
     doublejeopardy = teamaker = selectByMadeVsDrunkRatio(filter(lambda n : n != doublejeopardy, drinkers))
     
     for person in drinkers:
       if person == teamaker:
         statDrinker(person, len(drinkers))
         statRound  (person, len(drinkers))
         
         xmpp.send_message(person, buildWellVolunteeredMessage(person))
       else:
         send_random(person, OTHEROFFERED, getSalutation(teamaker))
         statDrinker(person)
     
   teacountdown = False     
   drinkers = set([])
   settingprefs = set([])
   informed = set([])
   lastround = datetime.now()
示例#26
0
    def _notify_comments(self, domain, comments):
        short_urls = self._shorten_comments(domain, comments)

        for question in comments:
            followers = list(question.followers)
            jids = map(lambda follower: follower.follower.address, followers)
            for comment in comments[question]:
                owner = comment['owner']
                if 'display_name' in owner:
                    name = owner['display_name']
                else:
                    name = owner['user_id']

                body = comment['body']

                html = markdown(body)
                text = ''.join(BeautifulSoup(html).findAll(text=True))

                url = short_urls[comment['comment_id']]
                msg = "%s said: %s %s" % (name, text, url)
                if len(jids) > 0:
                    logging.debug('sending message to %s' % (jids, ))
                    send_message(jids, msg)
                else:
                    logging.debug('no follower')
示例#27
0
def send(self=None, operator=None):
    '''сохраняет и пересылает сообщение
    '''
    try:
        result = appOperators.all().filter('active =', True).filter('isweb =', True).filter('login ='******'users') == None or opinfo.get('web') == None:
            logging.debug(u'web: что-то не так в processOperatorMsg(operator info)')
            raise Exception()
        else:
            # пишем сообщение в хранилище
            m = appOperatorsMsg(
                                sender=result.jid,
                                to=opinfo['users'][0],
                                text=CheckMessageText(self.request.get('msg')),
                                date=datetime.datetime.now(),
                                read=True
                                )
            m.put()
            # пересылаем сообщение пользователю
            xmpp.send_message(m.to, m.text)
            # обновляем timeout беседы
            memcache.set(result.login, opinfo, TALK_TIMEOUT)
            userinfo = memcache.get(m.to)
            if userinfo is None:
                answer.write(u'\nНеожиданное отсутствие связи с пользователем(processOperatorMsg)')
                raise Exception()
            else:
                memcache.set(m.to, userinfo, TALK_TIMEOUT)
            #вернуть что-нибудь
            self.response.out.write("{'status': 'ok'}")
    except Exception:
        pass
示例#28
0
def processOperatorMsg(message=None, answer=None):
    '''Обработка сообщения от оператора
    '''
    result = appOperators.all().filter('active =', True).filter('isweb =', False).filter('jid =', message.sender.split('/')[0]).get()
    opinfo = memcache.get(result.login)
    # проверка связи с пользователем
    if opinfo is None or opinfo.get('users') == None or opinfo.get('web') == None:
        logging.debug(u'что-то не так в processOperatorMsg(operator info)')
        answer.write(u'\nВ данный момент вы ни с кем не переписываетесь!')
    else:
        # пишем сообщение в хранилище
        m = appOperatorsMsg(
                            sender=message.sender.split('/')[0],
                            to=opinfo['users'][0],
                            text=CheckMessageText(message.body),
                            date=datetime.datetime.now(),
                            read=True
                            )
        m.put()
        # пересылаем сообщение оператору
        xmpp.send_message(m.to, m.text)  
        # обновляем timeout беседы
        memcache.set(result.login, opinfo, TALK_TIMEOUT)
        userinfo = memcache.get(m.to)
        if userinfo is None:
            answer.write(u'\nНеожиданное отсутствие связи с пользователем(processOperatorMsg)')            
        else:
            memcache.set(m.to, userinfo, TALK_TIMEOUT)              
示例#29
0
    def post(self):
        global ON_YOUR_OWN
        global WELL_VOLUNTEERED
        global OTHEROFFERED

        global drinkers
        global teacountdown
        global doublejeopardy
        global lastround
        global informed

        if len(drinkers) == 1:
            for n in drinkers:
                send_random(n, ON_YOUR_OWN)
        elif len(drinkers) > 0:
            # Select someone who wasn't the last person to make the tea
            doublejeopardy = teamaker = selectByMadeVsDrunkRatio(
                filter(lambda n: n != doublejeopardy, drinkers))

            for person in drinkers:
                if person == teamaker:
                    statDrinker(person, len(drinkers))
                    statRound(person, len(drinkers))

                    xmpp.send_message(person,
                                      buildWellVolunteeredMessage(person))
                else:
                    send_random(person, OTHEROFFERED, getSalutation(teamaker))
                    statDrinker(person)

        teacountdown = False
        drinkers = set([])
        settingprefs = set([])
        informed = set([])
        lastround = datetime.now()
示例#30
0
 def get(self):
         reminders = Reminder.all().filter('enabled =', True).fetch(1000)
         for reminder in reminders:
                 if xmpp.get_presence(reminder.recipient, from_jid=chatbot_name):
                         xmpp.send_message(reminder.recipient, reminder.text, from_jid=chatbot_name)
                 else:
                         logging.info(reminder.recipient + ' was not online.')
示例#31
0
 def Reply(self, user, message):
   try:
     xmpp.send_message(user, message)
   except xmpp.Error, xmpp.NoBodyError:
     logging.exception('Caught error when trying to send.')
     # Create a deferred call.
     deferred.defer(xmpp.send_message, jids=user, body=message)
示例#32
0
 def process(self):
     global _locale
     try:
         message = xmpp.Message(self.request.POST)
     except xmpp.InvalidMessageError:
         return
     jid = message.sender.split("/")[0]
     self._google_user = GoogleUser.get_by_jid(jid)
     if self._google_user is None:
         self._google_user = GoogleUser.add(jid)
     _locale = self._google_user.locale
     if self._google_user.enabled_user:
         self._twitter_user = TwitterUser.get_by_twitter_name(self._google_user.enabled_user, self._google_user.jid)
         self._api = Dummy()
         if self._twitter_user is None:
             self._google_user.enabled_user = ""
         else:
             self._api = twitter.Api(
                 consumer_key=config.OAUTH_CONSUMER_KEY,
                 consumer_secret=config.OAUTH_CONSUMER_SECRET,
                 access_token_key=self._twitter_user.access_token_key,
                 access_token_secret=self._twitter_user.access_token_secret,
             )
             try:
                 self._user = self._api.verify_credentials()
                 if not self._user:
                     raise twitter.TwitterAuthenticationError
             except twitter.TwitterAuthenticationError:
                 self._google_user.retry += 1
                 if self._google_user.retry >= config.MAX_RETRY:
                     GoogleUser.disable(self._google_user.jid)
                     xmpp.send_message(self._google_user.jid, _("NO_AUTHENTICATION"))
                 else:
                     Db.set_datastore(self._google_user)
                 return
             else:
                 if self._google_user.retry > 0:
                     self._google_user.retry = 0
                 if self._twitter_user.twitter_name != self._user["screen_name"]:
                     self._twitter_user.twitter_name = self._user["screen_name"]
                     self._google_user.enabled_user = self._user["screen_name"]
     else:
         self._twitter_user = Dummy()
         self._api = Dummy()
         self._user = Dummy()
     utils.set_jid(self._google_user.jid)
     result = self.parse_command(message.body)
     if result is None:
         return
     if result:
         while CapabilitySet("xmpp").is_enabled():
             try:
                 message.reply(result)
             except xmpp.Error:
                 pass
             else:
                 break
     IdList.flush(self._google_user.jid)
     Db.set_datastore(self._google_user)
示例#33
0
def add_new_beacon_discovery(app_user, beacon_uuid, beacon_name):
    '''A human user has discovered a beacon'''
    beacon_uuid = beacon_uuid.lower()
    beacon = get_beacon(beacon_uuid, beacon_name)
    if not beacon:
        logging.warn("Beacon not found: {uuid: %s, name: %s}", beacon_uuid, beacon_name)
        return None, None

    keyy = BeaconDiscovery.create_key(app_user, beacon.service_identity_user)
    beaconDiscovery = BeaconDiscovery.get(keyy)
    if beaconDiscovery:
        return beacon.service_identity_user, beacon.tag

    BeaconDiscovery(key=keyy, creation_time=now()).put()

    si = get_service_identity(beacon.service_identity_user)
    if not si:
        logging.error("Service identity not found for service_identity_user: %s" % beacon.service_identity_user)
    elif not si.beacon_auto_invite:
        logging.info("Beacon detected but %s does not allow auto invite {user %s, uuid: %s, name: %s}",
                     beacon.service_identity_user, app_user, beacon_uuid, beacon_name)
    elif get_app_id_from_app_user(app_user) not in si.appIds:
        logging.info("Beacon detected but %s does not contain app_id of user %s: {uuid: %s, name: %s}",
                     beacon.service_identity_user, app_user, beacon_uuid, beacon_name)
        return None, None
    elif get_friend_serviceidentity_connection(app_user, beacon.service_identity_user):
        logging.info("Beacon detected but %s and %s were already friends: {uuid: %s, name: %s}",
                     app_user, beacon.service_identity_user, beacon_uuid, beacon_name)
    else:
        # Fake a deleted connection between service and human user to be able to show the service's avatar on the phone
        friend_map = get_friends_map(app_user)
        friend_map.generation += 1
        friend_map.version += 1
        friend_map.put()

        friend_detail = FriendDetails().addNew(remove_slash_default(beacon.service_identity_user),
                                               si.name, si.avatarId, type_=FriendDetail.TYPE_SERVICE)
        friend_detail.relationVersion = -1

        from rogerthat.bizz.job.update_friends import _do_update_friend_request
        _do_update_friend_request(app_user, friend_detail, UpdateFriendRequestTO.STATUS_ADD, friend_map,
                                  extra_conversion_kwargs=dict(existence=FriendTO.FRIEND_EXISTENCE_DELETED,
                                                               includeServiceDetails=False))

        user_profile = get_user_profile(app_user)
        app_name = get_app_name_by_id(user_profile.app_id)
        m = localize(user_profile.language, "_automatic_detection_invitation", app_name=app_name, service_name=si.name)
        _send_invitation_message_from_service_to_user(app_user, beacon.service_identity_user, m,
                                                      si.descriptionBranding, user_profile.language,
                                                      ORIGIN_BEACON_DETECTED, BEACON_DISCOVERY)

        message = "Beacon detected at %s (%s) with tag: %s" % (si.name.encode('utf8'),
                                                               remove_slash_default(si.service_identity_user).email().encode('utf8'),
                                                               beacon.tag.encode('utf8'))

        server_settings = get_server_settings()
        xmpp.send_message(server_settings.xmppInfoMembers, message, message_type=xmpp.MESSAGE_TYPE_CHAT)

    return beacon.service_identity_user, beacon.tag
示例#34
0
def task_xmpp_send_message(jid, message):
    """
    Deferred task to send an XMPP message. One shot; ignore all errors.
    """
    try:
        xmpp.send_message(jid, message)
    except:
        pass
示例#35
0
def new_dm_notification(gid):
    oauth_token, oauth_secret = get_user_oauth_info(gid)
    a = fanfou.fanfou(settings.consumer_key, settings.consumer_secret, oauth_token, oauth_secret)
    response, content = a.account_notification()
    content = json.loads(content)
    new_dm_num = content['direct_messages']
    if new_dm_num:
        xmpp.send_message(gid, '你有 %s 封新私信'%(new_dm_num))
示例#36
0
文件: bot.py 项目: melmothx/jsonbot
 def outnocb(self, jids, txt, how="msg", event=None, origin=None, from_jid=None, message_type=None, raw_xml=False, groupchat=False, *args, **kwargs):
     """ output xmpp message. """
     from google.appengine.api import xmpp
     if not message_type: message_type = xmpp.MESSAGE_TYPE_CHAT
     if type(jids) != types.ListType: jids = [jids, ]
     txt = self.normalize(txt)
     logging.debug(u"%s - xmpp - out - %s - %s" % (self.name, unicode(jids), txt))             
     xmpp.send_message(jids, txt, from_jid=from_jid, message_type=message_type, raw_xml=raw_xml)
示例#37
0
文件: main.py 项目: toomore/HTLS
 def get(self):
   umail = users.get_current_user().email()
   xmpp.send_invite(umail)
   xmpp.send_message('*****@*****.**', '#NEWUSER %s' % umail)
   logging.info('#NEWUSER %s' % umail)
   ## todo: send a guild mail to the first time invited user.
   tv = {'umail': umail}
   self.response.out.write(template.render('./template/hh_invite.htm',{'tv': tv}))
示例#38
0
 def get(self):
     id = str(uuid4())
     xmpp.send_message('*****@*****.**', '.ping %s' % id)
     ping = Ping()
     ping.uuid = id
     ping.name = 'GeoChat (XMPP)'
     ping.date_sent = datetime.now()
     ping.put()
示例#39
0
def sendInviteIM(user, invite):
    toEmail = invite.toEmail
    if xmpp.get_presence(toEmail):
        xmpp.send_message(
            toEmail,
            user.nickname() +
            ' has invited you to play a game of chess. http://your-move.appspot.com?i='
            + str(invite.key()))
示例#40
0
def SendMessage(users, portal, url):
  portal_keyname = portal.key().name()
  emails = [
      user.email for user in users
      if memcache.add('%s|||%s' % (portal_keyname, user.email), 1, time=120)]
  if emails:
    msg = 'Alert! *%s* is under attack! %s' % (portal.title, url)
    xmpp.send_message(emails, msg)
示例#41
0
    def post(self):
        From = self.request.get("From")
        CallStatus = self.request.get("CallStatus")

        xmpp.send_message(USERJID, "Call from: " + From + " status:" + CallStatus)
        path = os.path.join(os.path.dirname(__file__), "receivecall.xml")
        template_vars = {"callbackurl": "/recording"}
        self.response.out.write(template.render(path, template_vars))
示例#42
0
文件: main.py 项目: nic0d/squashtai
  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)
示例#43
0
文件: xmppio.py 项目: yunfan/jyf-code
    def post(self):
        jid = self.request.get("from")
        body = self.request.get("body")

        req = {}
        req["from"] = {"full": jid, "node": jid.split("/")[0].split("@")[0], "domain": jid.split("/")[0].split("@")[1], "resource": jid.split("/")[1]}
        req["raw"] = body
        response = bot.main(req)
        xmpp.send_message(jid, response)
示例#44
0
文件: main.py 项目: yehchge/HTLS
 def get(self):
     umail = users.get_current_user().email()
     xmpp.send_invite(umail)
     xmpp.send_message('*****@*****.**', '#NEWUSER %s' % umail)
     logging.info('#NEWUSER %s' % umail)
     ## todo: send a guild mail to the first time invited user.
     tv = {'umail': umail}
     self.response.out.write(
         template.render('./template/hh_invite.htm', {'tv': tv}))
示例#45
0
 def dispatch(cls, notice):
     jid = notice.channel.outlet.get_param('jid')
     if xmpp.get_presence(jid):
         body = "%s: %s" % (notice.title,
                            notice.text) if notice.title else notice.text
         xmpp.send_message(
             jid, "%s %s [%s]" %
             (body, notice.link or '', notice.source.source_name))
     return None
示例#46
0
 def post(self):
   user = self.request.get('user')
   stack = self.request.get('stack')
   stacks = stack.split('\n')
   for i in Admins.all():
     if not i.nb_lines or not i.user or not i.user.email():
       continue
     stack_text = '\n'.join(stacks[-min(len(stacks), i.nb_lines):])
     text = '%s:\n%s' % (user, stack_text)
     xmpp.send_message(i.user.email(), text)
    def unmute_command(self, email, repo):

        if (repo == ""):
            db.enable_subscriptions(email)
            message = "All repositories you subscribed are now unmuted !"
        else:
            db.enable_subscription(email, repo)
            message = "Repository " + repo + " is now unmuted !"

        xmpp.send_message(email, message)
    def unwatch_command(self, email, repo):

        if (repo == ""):
            db.delete_subscribtions(email)
            message = "All your subscribtions were removed from database !"
        else:
            db.delete_subscribtion(email, repo)
            message = "The repository is not watched anymore !"

        xmpp.send_message(email, message)
示例#49
0
文件: tagliner.py 项目: PEZ/MooTalk
 def get(self):
     chats = get_chats_with_taglines()
     for chat in chats:
         tagline = get_random_tagline(chat)
         addresses = [
             u.address for u in chat.listeners
             if xmpp.get_presence(u.address, chat.jid)
         ]
         xmpp.send_message(addresses, messages.TAGLINE_MESSAGE % tagline,
                           chat.jid)
示例#50
0
def send_message(users, portal, url, attacker):
    portal_keyname = portal.key().name()
    emails = [
        user.email for user in users
        if memcache.add('%s|||%s' % (portal_keyname, user.email), 1, time=120)
    ]
    if emails:
        msg = 'Alert! *%s* (%s) is under attack%s! %s' % (
            portal.title.strip(), portal.address,
            (' by *%s*' % attacker) if attacker else '', url)
        xmpp.send_message(emails, msg)
示例#51
0
 def me_command(self, message=None):
     if self.set_chat_and_user(message):
         msg = message.arg.strip()
         recipients = [
             r for r in self.chat.participants if r != self.sender.address
         ]
         if len(recipients) > 0:
             xmpp.send_message(
                 recipients,
                 messages.ME_MESSAGE % (self.sender.nickname, msg),
                 message.to)
示例#52
0
def send_message_to_subscribers(subscribers, body):
    subscribers = [canonical_user(subscriber) for subscriber in subscribers]
    active_subscribers = [
        subscriber.key().name()
        for subscriber in UpdateSubscriber.get_by_key_name(subscribers)
        if subscriber and (subscriber.available or subscriber.send_always)
    ]

    logging.debug('sending to %s ' % str(active_subscribers))
    if active_subscribers:
        xmpp.send_message(active_subscribers, body=body)
示例#53
0
 def receive(self, email_message):
     if self.set_chat_and_user(email_message):
         message_template = messages.EMAIL_MESSAGE
         recipients = [r.address for r in self.chat.listeners]
         if len(recipients) > 0:
             message = get_header(email_message.subject)
             message = message_template % (self.sender.nickname, message)
             logging.info(
                 "Email handler sending message. Chat-jid: %s, message: %s"
                 % (self.chat.jid, message))
             xmpp.send_message(recipients, message, self.chat.jid)
示例#54
0
 def post(self):
     """Handles new content notifications."""
     feed = feedparser.parse(self.request.body)
     id = find_self_url(feed.feed.links)
     subscription = Subscription.get_by_key_name(id)
     subscriber_keys = Subscriber.all(
         keys_only=True).ancestor(subscription).fetch(1000)
     subscriber_addresses = [x.name() for x in subscriber_keys]
     if not subscription:
         logging.warn("Discarding update from unknown feed '%s'", id)
         return
     for entry in feed.entries:
         message = "%s (%s)" % (entry.title, entry.link)
         xmpp.send_message(subscriber_addresses, message)
    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)
示例#56
0
 def _handle_timeline_notification(self, data):
     """Handle timeline notification."""
     for user_action in data.get('userActions', []):
         if user_action.get('type') == 'SHARE':
             # Fetch the timeline item.
             item = self.mirror_service.timeline().get(
                 id=data['itemId']).execute()
             attachments = item.get('attachments', [])
             media = None
             if attachments:
                 # Get the first attachment on that timeline item and do stuff with it.
                 attachment = self.mirror_service.timeline().attachments(
                 ).get(itemId=data['itemId'],
                       attachmentId=attachments[0]['id']).execute()
                 resp, content = self.mirror_service._http.request(
                     attachment['contentUrl'])
                 if resp.status == 200:
                     media = MediaIoBaseUpload(io.BytesIO(content),
                                               attachment['contentType'],
                                               resumable=True)
                 else:
                     logging.info('Unable to retrieve attachment: %s',
                                  resp.status)
             body = {
                 'text':
                 'Echoing your shared item: %s' % item.get('text', ''),
                 'notification': {
                     'level': 'DEFAULT'
                 }
             }
             self.mirror_service.timeline().insert(
                 body=body, media_body=media).execute()
             # Only handle the first successful action.
             break
         elif user_action.get('type') == 'REPLY':
             # Fetch the timeline item.
             item = self.mirror_service.timeline().get(
                 id=data['itemId']).execute()
             logging.info("User replied: %s", item.get('text'))
             memcache.set('recent_message',
                          item.get('text'))  #for simple page
             addr = XMPP_addr_access.get_addr_from_id(
                 data.get('userToken', ''))
             if addr is not None:
                 xmpp.send_message(addr, item.get('text'))
         else:
             logging.info(
                 "I don't know what to do with this notification: %s",
                 user_action)
示例#57
0
文件: main.py 项目: nic0d/squashtai
  def post(self):
    if not requires_registered(self):
      return

    if self.request.get('text'):
      text = self.request.get('text')
      user = models.get_user_(users.get_current_user())
      models.create_comment(user, text)
      memcache.delete("comments")

      body = user.nickname + '> ' + text
      xmpp.send_message(models.get_jids(), body, APP_URL + ".appspot.com", xmpp.MESSAGE_TYPE_CHAT)

    self.redirect('/comment')
    return
示例#58
0
def send_to_room(room, msg):
    listeners = []
    try:
        listeners = simplejson.loads(memcache.get(key=room))
    except:
        # Well huh
        listeners = []

    for listener in listeners:
        logging.info(listener[0])
        if listener[0] == "http":
            channel.send_message(listener[1], simplejson.dumps(msg))
        elif listener[0] == "xmpp":
            xmpp.send_message(listener[1],
                              msg["name"] + " : " + msg["message"])
示例#59
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))
示例#60
0
文件: ui.py 项目: vtgav/remoht.us
    def get(self, device_id, relay=None):
        logging.debug("Get relay %s", relay)

        user = users.get_current_user()
        if not user: return self.unauthorized()

        logging.info("Device ID: %d", int(device_id))
        device = model.Device.get_by_id(int(device_id))
        if device is None: return self.notfound()

        msg = {"cmd": "get_relays", "params": {"relay_id": relay}}

        logging.debug("Sending get_relay to %s", device.full_jid)
        xmpp.send_message(device.full_jid, json.dumps(msg))
        self.render_json({"msg": "OK", "relays": device.relays})