def send_broadcast_message(group_name, broadcast_message): # create to address client = xmpp.Client(settings.JABBER_URL) client.connect(server=(settings.JABBER_SERVER, settings.JABBER_PORT)) client.auth(settings.BROADCAST_USER, settings.BROADCAST_USER_PASSWORD, 'broadcast') if group_name != 'all': group = Group.objects.get(name=group_name) for user in group.user_set.all(): auth_info = AuthServicesInfoManager.get_auth_service_info(user) if auth_info: if auth_info.jabber_username != "": to_address = auth_info.jabber_username + '@' + settings.JABBER_URL message = xmpp.Message(to_address, broadcast_message) message.setAttr('type', 'chat') client.send(message) client.Process(1) else: for user in User.objects.all(): auth_info = AuthServicesInfoManager.get_auth_service_info(user) if auth_info: if auth_info.jabber_username != "": to_address = auth_info.jabber_username + '@' + settings.JABBER_URL message = xmpp.Message(to_address, broadcast_message) message.setAttr('type', 'chat') client.send(message) client.Process(1) client.disconnect()
def presenceCB(self, conn, msg): try: presence_type = msg.getType() who = msg.getFrom() # This code provides for a fairly promiscous bot # a more secure bot should check an auth list and accept deny # based on the incoming who JID sendChat = True if self.jid.bareMatch(who): self.log.info("Potential message loop: " + str(msg)) sendChat = False if presence_type == "subscribe": # Tell the server that we accept their subscription request conn.send(xmpp.Presence(to=who, typ='subscribed')) # Ask to be their contact too conn.send(xmpp.Presence(to=who, typ='subscribe')) # Be friendly if sendChat: conn.send(xmpp.Message(who, "hi " + who.getNode(), typ='chat')) self.log.info("%s subscribed" % (who)) elif presence_type == "unsubscribe": if sendChat: conn.send(xmpp.Message(who, "bye " + who.getNode(), typ='chat')) conn.send(xmpp.Presence(to=who, typ='unsubscribed')) conn.send(xmpp.Presence(to=who, typ='unsubscribe')) self.log.info("%s unsubscribed" % (who)) except Exception as e: self.log.error("Exception in presenceCB " + str(e)) self.log.debug(traceback.format_exc())
def test_show_logs_and_stop(): bot, replies = fake_bot() bot.logger.info('Just a test message') message = xmpp.Message('user@server', 'show fish-slapping', frm='peer@server') bot.message_callback(None, message) bot.flush_logs() assert len(replies) == 1 assert 'Just a test message' in replies[-1].getBody() bot.logger.info('Another test message') bot.flush_logs() assert len(replies) == 2 assert 'Another test message' in replies[-1].getBody() bot.flush_logs() assert len(replies) == 2 message = xmpp.Message('user@server', 'stop', frm='peer@server') bot.message_callback(None, message) assert len(replies) == 3 assert replies[-1].getBody() == '--- end of logs' bot.logger.info('This is not supposed to be sent as msg') bot.flush_logs() assert len(replies) == 3
def Sendmsg(self, to, msg): self.Connect() for user in to: try: self.conn.send(xmpp.Message(user, msg)) except: print "conn err" self.Connect() self.conn.send(xmpp.Message(user, msg))
def flush_logs(self): for logname, log in self.logs.items(): message = log.flush() if message: for jid in log.session.receivers: self.client.send(xmpp.Message(jid, '\n' + message)) expired = log.session.expire() for jid in expired: self.client.send(xmpp.Message(jid, '--- fim de %s' % logname))
def testXMPPMessageMatchFalse(self): xmpptemplate = xmpp.Message() xmpptemplate.setFrom(xmpp.JID("sender1@host")) xmpptemplate.setTo(xmpp.JID("recv1@host")) message = xmpp.Message() message.setFrom(xmpp.JID("sender1@host")) message.setTo(xmpp.JID("recv2@host")) mt = spade.Behaviour.MessageTemplate(xmpptemplate) self.assertFalse(mt.match(message))
def test_command_is_chosen_based_on_its_name(): bot, replies = fake_bot() bot.commands['hello'] = lambda sender, msg: 'Hello back' bot.commands['hi'] = lambda sender, msg: 'Hi back' message = xmpp.Message('user@server', 'hello', frm='peer@server') bot.message_callback(None, message) assert len(replies) == 1 assert replies[-1].getBody() == 'Hello back' message = xmpp.Message('user@server', 'hi', frm='peer@server') bot.message_callback(None, message) assert len(replies) == 2 assert replies[-1].getBody() == 'Hi back'
def messageCB(session, message): """ handle messages """ if not message.getBody(): return # abort on empty message frm = message.getFrom() if frm.getNode() + "@" + frm.getDomain() == chatroom: if not frm.getResource() == nickname: # Message from chatroom #msg = xmpp.Message( # to=tojid, # body=escape(frm.getResource()+": "+message.getBody()), # typ="chat", # frm=username #) # Jolla XMPP would receive this msg = u"""<message from='{frm}' to='{to}' type='chat' id='e7e65551-2215-4a8d-8711-917980dda53f'> <body>{body} </body> <active xmlns='http://jabber.org/protocol/chatstates'/> </message> """.format(to=tojid, body=escape(frm.getResource() + ": " + message.getBody()), frm=username) client.send(msg) else: msg = xmpp.Message(to=chatroom, body=escape(message.getBody()), typ="groupchat", frm=username) client.send(msg)
def outputToOperator(msg): print msg try: if (inputMethod == 'commandByXMPP'): xmppClient.send(xmpp.Message(operator, msg)) except: pass
def msgSend(cl, jidTo, body, jidFrom, timestamp=0): msg = xmpp.Message(jidTo, body, "chat", frm=jidFrom) if timestamp: timestamp = time.gmtime(timestamp) msg.setTimestamp(time.strftime("%Y%m%dT%H:%M:%S", timestamp), xmpp.NS_DELAY) Sender(cl, msg)
def connect_and_sendto(self, user2notify=None, message=':)'): user2notify = user2notify or AUTH_USER message = unicode(message, 'utf-8', 'replace') out = False if xmpp.Client.connect(self, server=(self.servername, self.serverport)): self.user2notify = user2notify if ONLINE_ONLY: self.RegisterHandler('presence', self.cb_presence) if self.auth(self.jid.getNode(), self.jid_pswd): self.sendInitPresence() if ONLINE_ONLY: t = time.time() while self.doloop: self.Process(1) if (time.time() - t) > TIMEOUT: break send = (self.user_status == 'available') else: send = True if send: msgid = self.send(xmpp.Message(self.user2notify, message)) out = True else: self.error = 'Non autorizzato' else: self.error = 'Connessione impossibile' return out
def message_handler(connect_object, message_node): message = str(message_node.getBody()).lower() if message != "none": print message reply = chat_reply(message) print reply connect_object.send(xmpp.Message(message_node.getFrom(), reply))
def to_msg(username, password): msg = "This is Test. I'M " + username + " (from python msg)" client = xmpp.Client('im.e-u.cn') client.connect(server=('im.e-u.cn', 5223)) client.auth(username, password, 'botty') client.sendInitPresence() message = xmpp.Message(to, msg, typ='chat') client.send(message) time.sleep(0.2) for i in to: #print i client.sendInitPresence() message = xmpp.Message(i, msg, typ='chat') client.send(message) time.sleep(0.2)
def messageCB(sess, mess): nick = mess.getFrom().getResource() text = mess.getBody() fromUser = mess.getFrom() if text is not None: if "liveleak.com" in text: text_list = text.split() liveleak_link = None for t in text_list: if "liveleak.com" in t: liveleak_link = t if liveleak_link is None: print "no link found" return title = get_live_leak_title(liveleak_link) title = sanitize(title) r = requests.get(SOCIAL_SEARCH_URL + title) client = xmpp.Client(jid.getDomain(), debug=[]) client.connect(server=('chat.facebook.com', 5222)) client.auth(jid.getNode(), passwd) client.sendInitPresence() message = xmpp.Message(fromUser, r.text) message.setAttr('type', 'chat') client.send(message) else: print("no liveleak")
def messageCB(conn, mess): global ipmsg, oldtime, age, logfile, intv, lastreqtime text = mess.getBody() user = mess.getFrom() user.lang = 'en' # dup uid = str(user) if text: logfile.write(time.asctime() + ' ' + uid + '\n') #log user request newtime = time.time() if newtime - oldtime > age: ipfile = open('msnip.txt', 'r') ipmsg = ipfile.read() ipfile.close() oldtime = newtime if lastreqtime.has_key(uid) and newtime - lastreqtime[uid] < intv: return # do nothing if req from same uid comes with intv iplist = ipmsg.splitlines() nips = len(iplist) random.seed(user) mymsg = '' for id in range(0, 6): mymsg = mymsg + "\n" + iplist[random.randint(0, nips - 1)] conn.send(xmpp.Message(user, mymsg)) lastreqtime[uid] = newtime
def _delegate_command(self, command, *args, **kwargs): self._logger.debug('Delegating') if isinstance(command, tuple) and command[0] == Command.MESSAGE: self._logger.debug('Sending Message') # result = self._xmpp.send_message(mto=command[1], # mbody=command[2], # mtype='chat') message = xmpp.Message(command[1], command[2]) message.setAttr('type', 'chat') try: self._xmpp.send(message) except IOError as ex: try: self.connect() self._xmpp.send(message) except IOError as ex1: self._logger.error('Could not reconnect:' + str(ex1)) except Exception as ex1: self._logger.error('Could not reconnect error:' + str(ex1)) except Exception as ex: self._logger.error('Unknown Error: ' + str(ex)) # time.sleep(5) super(XMPP_Client, self)._delegate_command(command, *args, **kwargs)
def send_to_chat(self, message): ''' dump a message to the chatroom ''' msg = xmpp.Message(to='%s@%s' % (self.chatroom, self.chat_domain), typ='groupchat', body=message) self.client.send(msg) self.update_message_state()
def handle_delayed_messages(bot): """ If there are any message in the queue where it is now time to respond, respond to them. """ global __message_list # Don't do anything if we don't need to. if len(__message_list) == 0: print('Delay: Nothing to do.') return # Get list of messages that need to be sent. cur_dt = datetime.datetime.now() to_process_list = [ msg for msg in __message_list if (msg.delta - cur_dt).days < 0 ] for msg in __message_list: print('%s - %s = %s' % (msg.delta, cur_dt, (msg.delta - cur_dt).seconds)) print('Delay: Found %s message to process.' % (len(to_process_list))) # Nothing to do yet. if len(to_process_list) == 0: return # Remove messages from queue before processing. for msg in to_process_list: __message_list.remove(msg) #Send message print('Delay: Sending message to %s: %s' % (msg.who, msg.message)) print('preping: %s' % (msg.message)) bot.cl.send( xmpp.Message(msg.who, "Reminder:" + msg.message[0], typ="chat"))
def confirm(cnx, hero, message): for user in USERS.itervalues(): QUEUE.put( xmpp.Message(user.uri, u"Вызвался {} ({}): {}".format( hero.name, hero.uri, message), typ='chat'))
def command_topic(bot, room, nick, access_level, parameters, message): if not room in topic_db or len(topic_db[room]) == 0: return 'No topics added yet!' if not parameters: number = random.randint(1, len(topic_db[room])) else: try: number = int(parameters) except: search = parameters.lower() found = [] for i in xrange(len(topic_db[room])): if search in topic_db[room][i]['topic'].lower(): found.append(i) if len(found) == 0: return "No such text found in topics." elif len(found) == 1: number = found[0] + 1 else: return "Text found in topics %s." % (', '.join( ['#%d' % (x + 1) for x in found])) existent_topic = gettopic(bot, room, number) if not existent_topic: return "There's no topic #%d, and there are %d topics." % ( number, len(topic_db[room])) res = 'Topic #%d: %s' % (number, existent_topic['topic']) bot.client.send(xmpp.Message(room, None, 'groupchat', res)) if message.getType() != 'groupchat' and access_level >= LEVEL_ADMIN: t = timeformat(time.time() - existent_topic['time']) res = '%s\n(added by %s %s ago)' % (res, existent_topic['jid'], t) return res
def HandleMessage(self, client, message): ''' Handles a message being sent to us @param: client @param: message ''' if message is None or message.getBody() is None: print 'Message body is null' return user = message.getFrom() username = user.getStripped() body = message.getBody().strip() self.LogEvent(username, body, None, None, None) # Run the first command whose pattern matches the message for cmd_name, pattern, command in commands.command_list: if (not self.all_commands) and (cmd_name not in self.commands): continue if pattern.search(body): try: response = command(username, body) except Exception, e: response = 'error: %s' % str(e) traceback.print_exc() self.client.send( xmpp.Message(user, response, typ='chat', attrs={'iconset': 'round'})) break
def messageCB(client, message): text = message.getBody() user = message.getFrom() if not parseCommand(client, user, text): if text is not None: roster = xmppClient.getRoster() items = roster.getItems() sender = user.getNode() senderName = roster.getName(user.getStripped()) message = None if text[0:3] == '/me': if len(text) > 4 and text[3] == ' ': message = "/me %s: %s"%(senderName, text[4:]) else: # Don't send any message to every one in group. return else: message = "%s: %s"%(senderName, text) for item in items: itemJID = xmpp.JID(item) receiver = itemJID.getNode() if item <> currentUser and receiver <> sender: client.send(xmpp.Message(item, message))
def messageCB(sess, mess): commend = mess.getFrom() text = mess.getBody() if text is not None: ncommt = os.popen(text).read() cl.send(xmpp.Message(commend, ncommt))
def send_http_push_notification(sender, instance, created, **kwargs): userID = '*****@*****.**' password = '******' ressource = 'asim' room = "*****@*****.**" jid = xmpp.protocol.JID(userID) jabber = xmpp.Client(jid.getDomain(), debug=[]) connection = jabber.connect() if not connection: sys.stderr.write('Could not connect\n') else: sys.stderr.write('Connected with %s\n' % connection) auth = jabber.auth(jid.getNode(), password, ressource) if not auth: sys.stderr.write("Could not authenticate\n") else: sys.stderr.write('Authenticate using %s\n' % auth) jabber.sendInitPresence(requestRoster=1) message = xmpp.Message( room, "Se ha actualizado la BD ID {} Description {}".format( instance.id, instance.description)) message.setAttr('type', 'groupchat') jabber.send(message)
def send_message(username, password, to, message_text): client = xmpp.Client('172.16.10.121', debug=[]) client.connect(server=('172.16.10.121', 5222), secure=False) client.auth(username, password, 'Test Reporter') client.sendInitPresence() message = xmpp.Message(to, message_text) client.send(message)
def muc_set_subject(self, room, text): """Changes subject of muc Works only with sufficient rights.""" mess = xmpp.Message(to=room) mess.setAttr('type', 'groupchat') mess.setTagData('subject', text) self.connect().send(mess)
def messageCB(conn, mess): nick = mess.getFrom().getResource() text = mess.getBody() LOG(mess, nick, text) if text != None: text = mess.getBody() user = mess.getFrom() user.lang = 'en' # dup if text.find(' ') + 1: command, args = text.split(' ', 1) else: command, args = text, '' cmd = command.lower() if commands.has_key(cmd): reply = commands[cmd](user, command, args, mess) else: reply = ("UNKNOWN COMMAND", cmd) if type(reply) == type(()): key, args = reply if my_commands.has_key(key): pat = my_commands[key] elif my_commands.has_key(key): pat = my_commands[key] else: pat = "%s" if type(pat) == type(''): reply = pat % args else: reply = pat(**args) else: try: reply = my_commands[reply] except KeyError: try: reply = my_commands[reply] except KeyError: pass if reply: conn.send(xmpp.Message(mess.getFrom(), reply))
def sendMessage(destination, source, body=None, timestamp=0, typ="active", mtype="chat", mid=0): """ Sends message to destination from source Args: destination: to whom send the message source: from who send the message body: message body timestamp: message timestamp (XEP-0091) typ: xmpp chatstates type (XEP-0085) mtype: the message type """ msg = xmpp.Message(destination, body, mtype, frm=source) msg.setTag(typ, namespace=xmpp.NS_CHATSTATES) if timestamp: timestamp = time.gmtime(timestamp) msg.setTimestamp(time.strftime("%Y%m%dT%H:%M:%S", timestamp)) if mid: msg.setID(mid) executeHandlers("msg03", (msg, destination, source)) sender(Component, msg)
def process_message(self): message = datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S : ") + messages[random.randint( 0, len(messages) - 1)] self.connection.send( xmpp.Message(self.destination_user, message, typ="chat")) self.connection.Process(1)
def delivery(body): INFO["outmsg"] += 1 if INFO.get("creporter"): try: jClient.send(xmpp.Message(BOSS, body, 'chat')) except: print_exc() write_file("delivery.txt", body, "a")