def run_zephyr(): zephyr.init() subs = zephyr.Subscriptions() logging.info("Subscribing to: " + ','.join(zephyr_classes.keys())) for c in zephyr_classes.keys(): subs.add((c, '*', '')) while not SHUTDOWN: while True: try: m = from_jabber_q.get(False) except Queue.Empty: break (src, sender, msg) = m if src not in jabber_chats: continue note = zephyr.ZNotice() note.fields = [src, msg] note.sender = sender note.auth = False note.cls = jabber_chats[src] note.instance = '' note.opcode = 'jabber' note.send() note = zephyr.receive(False) if note: body = note.fields[1] if len(note.fields) > 1 else '' logging.debug("ZEPHYR: %s/%s[%s]: %s", note.sender, note.cls, note.opcode, body) if note.opcode.lower() not in ('jabber', 'ping'): from_zephyr_q.put((note.cls, note.sender.split('@')[0], body)) else: select.select([zephyr._z.getFD()], [], [], 1)
def receive_zephyr(): '''Receives a Zephyr and decodes strings to unicode.''' z = zephyr.receive() if z is None: return z.auth = z.auth or _check_hmac(z) if hasattr(z, 'charset') and z.charset.lower() != 'unknown': charset = z.charset.lower() else: charset = 'utf-8' def decode(s): try: return s.decode(charset) except UnicodeDecodeError as e: logger.warning(u'Failed to decode string %r' % s, exc_info=True) return s.decode(charset, 'replace') return zephyr.ZNotice( uid=z.uid, kind=z.kind, auth=z.auth, cls=decode(z.cls), instance=decode(z.instance), recipient=decode(z.recipient), sender=decode(z.sender), opcode=decode(z.opcode), message=decode(z.message) )
def listen_zephyr(): subs = zephyr.Subscriptions() subs.add(('garywang-slack-test', '*', '*')) subs.add(('thetans', '*', '*')) while True: msg = zephyr.receive(True) if msg is not None: log('Receive', msg.__dict__) on_zephyr(msg)
def main(cls, match_engine, options): #pylint:disable=unused-argument """Main function for running Chiron with Zephyr""" zephyr_setup(match_engine.classes, not match_engine.ignore_personals) print("Listening...") while True: zgram = zephyr.receive(True) if not zgram: continue if zgram.opcode.lower() in ('auto', 'ping'): continue msg = cls(zgram) match_engine.process(msg)
def main(cls, match_engine, options): zephyr_setup(match_engine.classes, not match_engine.ignore_personals) print "Listening..." while True: zgram = zephyr.receive(True) if not zgram: continue if zgram.opcode.lower() == 'kill': print "Killing per request -- message:" msg.log_arrival() sys.exit(0) if zgram.opcode.lower() in ('auto', 'ping'): continue msg = cls(zgram) match_engine.process(msg)
def main(): setup() print "Waiting..." while True: zgram = zephyr.receive(True) if not zgram or zgram.opcode == 'PING': continue if zgram.opcode.lower() == 'kill': sys.exit(0) print '%s: [%s] -c %s -i "%s": %s -> %s' % ( datetime.datetime.now(), zgram.opcode, zgram.cls, zgram.instance, zgram.sender, zgram.recipient, ) if zgram.opcode.lower() == 'auto': print " -> auto; ignoring" continue handle_zgram(zgram)
def main(match_engine): last_seen = {} zephyr_setup(match_engine.classes) print "Listening..." while True: try: zgram = zephyr.receive(True) if not zgram: continue if zgram.opcode.lower() == 'kill': sys.exit(0) orig_class = False if "-test" in zgram.cls: orig_class = zgram.cls zgram.cls = zgram.instance tickets = match_engine.find_ticket_info(zgram) messages = format_tickets(last_seen, zgram, tickets) if messages: if orig_class: zgram.cls = orig_class send_response(zgram, messages) except UnicodeDecodeError: pass
def main(match_engine): last_seen = {} zephyr_setup(match_engine.classes) print "Listening..." while True: try: zgram = zephyr.receive(True) if not zgram: continue if zgram.opcode.lower() == 'kill': sys.exit(0) print '%s: -c %s -i "%s": %s -> %s' % ( datetime.datetime.now(), zgram.cls, zgram.instance, zgram.sender, zgram.recipient, ) # We have default fetchers for some classes. This adds two more ways # to trigger default fetchers behavior: # - test classes (for easier testing of defaults) # - instanced personals (to facilitate looking up many tickets for one project) # # This is implemented by copying the instance to the class while # processing matchers (and then undoing it), which is admittedly a bit # hacky. :/ orig_class = False if ("-test" in zgram.cls) or (is_personal(zgram) and zgram.instance != 'personal'): orig_class = zgram.cls zgram.cls = zgram.instance tickets = match_engine.find_ticket_info(zgram) messages = format_tickets(last_seen, zgram, tickets) if orig_class: zgram.cls = orig_class send_response(zgram, messages) except UnicodeDecodeError: pass
def main(): zephyr.init() subs = zephyr.Subscriptions() subs.add(('broder-test', '*', '*')) subs.add(('debathena', '*', '*')) subs.add(('undebathena', '*', '*')) while True: zgram = zephyr.receive(True) if not zgram: continue if zgram.opcode.lower() == 'kill': sys.exit(0) messages = [] for tracker, ticket in find_ticket_info(zgram): fetcher = fetchers.get(tracker) if fetcher: if (zgram.opcode.lower() != 'auto' and last_seen.get((tracker, ticket, zgram.cls), 0) < time.time() - seen_timeout): if zgram.cls == 'undebathena': u, t = undebathena_fun() else: u, t = fetcher(ticket) if not t: t = 'Unable to identify ticket %s' % ticket messages.append('%s ticket %s: %s' % (tracker, ticket, t)) last_seen[(tracker, ticket, zgram.cls)] = time.time() if messages: z = zephyr.ZNotice() z.cls = zgram.cls z.instance = zgram.instance z.recipient = zgram.recipient z.opcode = 'auto' z.sender = 'debothena' z.fields = [u, '\n'.join(messages)] z.send()
def poll(self, onReceive): m = zephyr.receive(False) if m: [_, body] = m.message.split("\x00") onReceive(m.sender, m.cls, m.instance, body)
return render_template('subbed.html', subbed=subbed, there=cls) def listen_for_zephyrs(): subs = zephyr.Subscriptions() count = ZClass.select().count() print "Subscribing to zephyrs (%s current subs)..." % count for z in ZClass.select(): try: subs.add((z.name, '*', '*')) subs.add(('un%s' % z.name, '*', '*')) subs.add(('unun%s' % z.name, '*', '*')) except Exception, e: print "Failed to sub to %s (%s)" % (z.name, e) print "Listening for zephyrs (%s current subs)..." % count while True: nz = zephyr.receive(block=True) if nz.cls.lower() == 'message' and nz.instance.lower() == 'personal': continue try: sender = nz.sender.replace("@ATHENA.MIT.EDU", "") print "[%s] Class: %s Instance: %s Sender: %s" % (str(datetime.datetime.now()), nz.cls, nz.instance, sender) zclass = ZClass.get_or_create(name=nz.cls) zuser = ZUser.get_or_create(name=sender) zsub = ZSub.get_or_create(zuser=sender, zclass=nz.cls) zsub.last_spoke = datetime.datetime.now() zsub.save() zephyr_obj = Zephyr.get_or_create( uid = nz.uid.time, sender = sender, zclass = nz.cls.decode('utf-8'), instance = nz.instance.decode('utf-8'), zsig = nz.fields[0].decode('utf-8'),
def receive_from_subs(self, return_sender=False): """ Receive a message from the cls specified in the init method, and returns the message and the sender of the message if return_sender is True. """ received = False while not received: # loop until you recieve a message try: m = zephyr.receive(True) received = True except KeyboardInterrupt: self.send("Dodona is no longer running.") raise except: continue # ignore messages from yourself while m.sender == '*****@*****.**': try: m = zephyr.receive(True) except KeyboardInterrupt: self.send("Dodona is no longer running.") raise except: continue # ignore empty messages while m.__dict__['fields'][1].lower().strip() == "": try: m = zephyr.receive(True) except KeyboardInterrupt: self.send("Dodona is no longer running.") raise except: continue # ignore messages from anywhere except the specified # class while m.cls != self.cls: try: m = zephyr.receive(True) except KeyboardInterrupt: self.send("Dodona is no longer running.") raise except: continue print "From: ", m.sender print "Instance: ", m.instance print "Message: ", m.__dict__['fields'][1] sender = m.sender m = m.__dict__['fields'][1] # clean the message of trailing whitespce # and convert it to lowercase try: m = str(m.strip().lower()) except KeyboardInterrupt: self.send("Dodona is no longer running.") raise except: print traceback.format_exc() if return_sender: return [m, sender] else: return m
zephyr.init() fb = Firebase('http://gamma.firebase.com/mikexstudios/zephyr') #Subscribe to the most popular zephyr classes zephyr.Subscriptions().add(('help', '*', '*')) zephyr.Subscriptions().add(('sipb', '*', '*')) zephyr.Subscriptions().add(('mxh', '*', '*')) #for testing #To send a message, ex. #zephyr.ZNotice(cls='sipb', message="zsig\x00Message body\n", ...).send() #Wait for messages. It's probably better to poll for messages than to use #blocking loop. print 'Listening to zephyr messages...' while True: m = zephyr.receive(True) #True -> blocks up to a minute [zsig, body] = m.message.split("\x00") body = body.strip() #Send message to Firebase ref = fb.child(m.cls) #separate by class ref.push({'class': m.cls, 'instance': m.instance, 'sender': m.sender, 'time': m.time, #seconds since epoch 'zsig': zsig, 'body': body,}) print "%s / %s / %s %s (%s)\n %s" % (m.cls, m.instance, m.sender, time.ctime(m.time), zsig, body)
if __name__ == "__main__": # Initialize the zephyr library zephyr.init() # Subscribe to messages subs = zephyr.Subscriptions() subs.add((config.zclass,"*","*")); last_send = 0 next_send = 0 while True: if time.time() - last_send > next_send: print "Saying hello!\nMessage: " + say_hello() last_send = time.time() next_send = random_with_variance(config.hello_interval, config.hello_interval_variance) print "Sending next automatic message in " + str(float(next_send)/config.HOUR) + " hours." m = zephyr.receive() if m != None and m.sender != config.zsender and m.cls == config.zclass and \ m.fields[1] != "": contents = m.fields[1] print "Got message: " + contents time.sleep(random_with_variance(3,2)) responded = False for match in config.special_messages.keys(): if match(contents): print "Responding to keyword with: " + send_special(match,m.instance) responded = True break;