def xmpp_presence_callback(self, client, presence): """ XMPP presence handler callback """ sender = presence.getFrom() resource = sender.getResource() pres_type = presence.getType() pres_status = presence.getStatus() if pres_type is None: pres_type = "online" self.logger.debug("XMPP presence received from '%s'" % sender) self.producer.publish({ "action": "%s.presence" % (self.name), "params": { "sender": { "domain": sender.getDomain(), "resource": sender.getResource(), "node": sender.getNode() }, "resource": resource, "type": pres_type } }) if pres_type == "subscribe": self.logger.debug("Presence subscription from '%s'" % (sender)) client.send(xmpp.Presence(to=sender, typ="subscribed")) client.send(xmpp.Presence(to=sender, typ="subscribe"))
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 presenceCB(conn,msg): print str(msg) prs_type=msg.getType() who=msg.getFrom() if prs_type == "subscribe": conn.send(xmpp.Presence(to=who, typ = 'subscribed')) conn.send(xmpp.Presence(to=who, typ = 'subscribe'))
def run_client(client_jid, client_password, authorized_jids): """ Initializes and runs a fresh xmpp client (blocking). """ high_load = 5 commands = { "stats": lambda *args: os.popen("uptime").read().strip(), } # Initialize and connect the client. jid = xmpp.JID(client_jid) client = xmpp.Client(jid.domain) if not client.connect(): return # Authenticate. if not client.auth(jid.node, client_password, jid.resource): return # Register the message handler which is used to respond # to messages from the authorized contacts. message_callback = handle_messages(authorized_jids, commands) client.RegisterHandler("message", message_callback) # Register the presence handler which is used to automatically # authorize presence-subscription requests from authorized contacts. presence_callback = handle_presences(authorized_jids) client.RegisterHandler("presence", presence_callback) # Go "online". client.sendInitPresence() client.Process() # Finally, loop, update the presence according to the load and # "sleep" for a while. previous_load_maximum = 0 while client.isConnected(): # Determine the load averages and the maximum of the 1, 10 and 15 minute # averages. # In case the maximum is above the "high_load" value, the status will be # set to "do not disturb" with the load averages as status message. # The status will be updated continuously once we reached high load. # When the load decreases and the maximum is below the "high_load" value # again, the status is reset to "available". load = os.getloadavg() load_string = "load: %s %s %s" % load load_maximum = max(list(load)) if load_maximum >= high_load: client.send(xmpp.Presence(show="dnd", status=load_string)) elif load_maximum < high_load and previous_load_maximum >= high_load: client.send(xmpp.Presence()) previous_load_maximum = load_maximum # Handle stanzas and sleep. client.Process() handle_responses(client) time.sleep(1)
def presence_handler(self, conn, msg): """ Always accepts a subscribe request from any user. override this method to change it""" msg_type = msg.getType() who = msg.getFrom() if msg_type == "subscribe": self.log('subscribe request sent by <%s>, accepting ' % (who)) conn.send(xmpp.Presence(to=who, typ='subscribed')) conn.send(xmpp.Presence(to=who, typ='subscribe'))
def _process(self): msg = None msg = self._receive(block=True) if msg: #self.myAgent.DEBUG("AMS received presence message "+ str(msg),"info", "ams") typ = msg.getType() frm = msg.getFrom() status = msg.getStatus() show = msg.getShow() reply_address = frm if typ == "subscribe": frm = AID.aid(name=str(frm), addresses=["xmpp://" + str(frm)]) aad = AmsAgentDescription() aad.name = frm if status: aad.state = status if show: aad.ownership = show else: aad.ownership = frm.getName() if frm.getName() not in list( self.myAgent.agentdb.keys()): self.myAgent.agentdb[frm.getName()] = aad elif self.myAgent.agentdb[frm.getName()].getOwnership( ) == aad.getOwnership(): self.myAgent.agentdb[frm.getName()] = aad else: presence = xmpp.Presence(reply_address, typ="unsubscribed", xmlns=xmpp.NS_CLIENT) presence.setFrom(self.myAgent.JID) self.myAgent.send(presence) return self.myAgent.DEBUG( "AMS succesfully registered agent " + frm.getName(), "ok", "ams") presence = xmpp.Presence(reply_address, typ="subscribed") presence.setFrom(self.myAgent.JID) self.myAgent.DEBUG("AMS sends " + str(presence), "info") self.myAgent.send(presence) elif typ == "unsubscribe": if str(frm) in list(self.myAgent.agentdb.keys()): del self.myAgent.agentdb[str(frm)] self.myAgent.DEBUG( "Agent " + str(frm) + " deregistered from AMS", "ok", "ams") else: self.myAgent.DEBUG( "Agent " + str(frm) + " deregistered from AMS", "error", "ams") return
def send_hello(): to_list = ['admin', 'control', 'ruller' ] + [x['login'] for x in bot.bots.values()] for _bot in to_list: jid = '{}@172.20.0.3'.format(_bot) if jid != bot.ja.jid: bot.ja.ja_client.send(xmpp.Presence(to=jid, typ='subscribe')) bot.ja.ja_client.send(xmpp.Presence(to=jid, typ='available'))
def xmpp_presence(con, event): print str(event) logging.info("presence message!") logging.info(event) prs_type = event.getType() logging.info("presence type is %s" % (prs_type)) who = event.getFrom() if prs_type == "subscribe": con.send(xmpp.Presence(to=who, typ='subscribed')) con.send(xmpp.Presence(to=who, typ='subscribe'))
def xmppPresence(self, st): """ Little helper to for easy presence setting @type st: string @param st: New presence string """ if self.rc_enable == "true": presence = xmpp.Presence(status=st, show='xa', priority='1') else: presence = xmpp.Presence(status=st, show='xa', priority='-1') self.conn.send(presence)
def __join_muc(self): for room_config in self._settings.groupchat: if isinstance(room_config, dict): for k, v in room_config.iteritems(): presence = xmpp.Presence(to="%s/%s" % (k, self._settings.chat_name)) presence.setTag( 'x', namespace='http://jabber.org/protocol/muc').setTagData( 'password', v) else: presence = xmpp.Presence( to="%s/%s" % (room_config, self._settings.chat_name)) self._conn.send(presence)
def xmpp_presence(self, conn, presence_node): #print presence_node if presence_node.getFrom().bareMatch(self.remotejid): if presence_node.getType() == 'subscribe': replypres=xmpp.Presence(typ='subscribed',to=presence_node.getFrom()) conn.send(replypres) replypres.setType('subscribe') conn.send(replypres) elif presence_node.getType() == 'probe': replypres = xmpp.Presence(to=presence_node.getFrom(), show='chat', status=self.presencestr) conn.send(replypres) elif ((not presence_node.getShow() is None) and \ presence_node.getShow != '') : pass
def test_presence(self): """Make sure presence subscription behaves reasonably """ b = bot.BenderJab() b.jid = '*****@*****.**' b.configure_logging() b.cl = MockClient() who = '*****@*****.**' b.presenceCB(b.cl, xmpp.Presence(to=b.jid, frm=who, typ='subscribe')) self.assertTrue(b.cl.msgs) b.cl = MockClient() b.presenceCB(b.cl, xmpp.Presence(to=b.jid, frm=b.jid, typ='subscribe')) self.assertTrue(isinstance(b.cl.msgs[-1], xmpp.protocol.Presence))
def __init__(self): try: self._mongodb_client = MongoClient(config.MONGODB_URL) except: print "MongoDB instance " + url + " can't be connected." print "Please install the mongDB, pymongo module." sys.exit(-1) print "MongoDB init" try: self._graphite_client = CarbonClientService( config.GRAPHITE_IP, config.GRAPHITE_PORT) except: print "Graphite instance on " + config.GRAPHITE_IP + ":" + config.GRAPHITE_PORT + " can't be connected" print "Please install the txCarbonClient module." print "Graphite Client init" self._pserver_client = ProgressionServerClient( ) if config.ENABLE_PROGRESSION else None self._task = Queue() if config.ENABLE_CONTEXT: self.xmpp_wait = False self.xmpp_user = UserData() #self.xmpp_context = ContextData() self.client = xmpp.Client(config.XMPP_SERVER) self.client.connect(server=(config.XMPP_IP, config.XMPP_PORT)) self.client.auth(config.XMPP_USER, config.XMPP_PASS) self.client.sendInitPresence(requestRoster=0) mes = xmpp.Presence(to=config.XMPP_NICK) self.client.send(mes) self.client.Process(1) if config.ENABLE_PUB: self.client.RegisterHandler('message', self.message_handler)
def xmpp_presence(self, conn, event): """Responds to the receipt of a presence message, by telling the sender that we are subscribing to their presence and that they should do the same. Args: conn: The connection that the message was received on. event: The actual message that was received. """ logging.info("received a presence from {0}, with payload {1}" \ .format(event.getFrom().getStripped(), event.getPayload())) prs_type = event.getType() logging.info("presence type is {0}".format(prs_type)) who = event.getFrom() if prs_type == "subscribe": conn.send(xmpp.Presence(to=who, typ='subscribed')) conn.send(xmpp.Presence(to=who, typ='subscribe'))
class Bot: def message_handler(connect_object, message_node): command1 = str(unicode(message_node.getBody()).encode('utf-8')) command2 = str(message_node.getFrom().getStripped()) #the fun begins from this place.. connect_object.send(xmpp.Message(command2, (k.respond(command1)))) b = datetime.now().strftime('%Y-%m-%d %H:%M:%S') a.write(str(b) + " " + command2 + " >>> " + k.respond(command1) + "\n") jid = xmpp.JID(user) connection = xmpp.Client(server) connection.connect() result = connection.auth(jid.getNode(), passwd) connection.RegisterHandler('message', message_handler, "") connection.RegisterHandler('presence', presence_handler, "") connection.sendInitPresence() press = xmpp.Presence() press.setStatus( "Hi from bot...i will chat with you and tell you new things you might like" ) connection.send(press) while (1): connection.Process(1)
class IdentiCa: def message_handler(connect_object, message_node): command1 = str(unicode(message_node.getBody()).encode('utf-8')) command2 = str(message_node.getFrom().getStripped()) c3 = command2.replace("@", " [at] ") c4 = c3.replace(".", " [dot] ") # now define a message msg = command1 # url encode it nicely and set your own client name – no links in source! themsg = urlencode({ 'status': msg, 'source': 'CollaborativeMicroblogging' }) # and send the notice urllib2.urlopen(apibase + '/statuses/update.json?s', themsg) connect_object.send( xmpp.Message(message_node.getFrom(), ("Posted your message on Twitter " + command1))) jid = xmpp.JID(user) connection = xmpp.Client(server) connection.connect() result = connection.auth(jid.getNode(), passwd) connection.RegisterHandler('message', message_handler, "") connection.sendInitPresence() press = xmpp.Presence() press.setStatus("Hi from Federated Microblogging App") connection.send(press) while (1): connection.Process(1)
def main(): jid = xmpp.protocol.JID(JABBERID) global cl cl = xmpp.Client(jid.getDomain(), debug=[]) cl.connect((SERVER, PORT)) cl.auth(jid.getNode(), PASSWORT) cl.sendInitPresence() cl.RegisterHandler('message', messageCB) cl.RegisterHandler('presence', presenceCB) for raum in RAUMLISTE: cl.send(xmpp.Presence(to=raum + "/" + BOTNAME)) load_plugins() global bothelp bothelp = "Folgende Funktionen werden angeboten:\n" for name, description in COMMANDS.items(): anhang = eval(str(description)) liste = anhang['examples'] if liste[0] == '': bothelp = bothelp + name + " - " + anhang['description'] + "\n" else: bothelp = bothelp + name + " - " + anhang[ 'description'] + " - Beispiel: " + liste[0] + "\n" GoOn(cl)
def __muc_join(self, room, nick, pword): """send XMPP stanzas to join a muc and raise MUCJoinFailure if error""" # build the room join stanza NS_MUC = 'http://jabber.org/protocol/muc' nick = self.mucs[room]['nick'] room_jid = room + '/' + nick # request no history and add password if we need one pres = xmpp.Presence(to=room_jid) pres.setTag('x', namespace=NS_MUC).setTagData('history', '', attrs={'maxchars': '0'}) if pword is not None: pres.setTag('x', namespace=NS_MUC).setTagData('password', pword) # try to join and wait for response self.log.debug('Attempting to join room "%s"' % room) self.last_muc = room try: result = self.conn.SendAndWaitForResponse(pres) except IOError: self.disconnected(self.ConnectFailure) # result is None for timeout if not result: raise MUCJoinFailure('timeout') # check for error error = result.getError() if error: raise MUCJoinFailure(error) # we joined successfully self.mucs[room]['status'] = self.MUC_OK
class CollaborativeMicroblogging: def message_handler(connect_object, message_node): command1 = str(unicode(message_node.getBody()).encode('utf-8')) command2 = str(message_node.getFrom().getStripped()) c3 = command2.replace("@", " [at] ") c4 = c3.replace(".", " [dot] ") auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_KEY, ACCESS_SECRET) api = tweepy.API(auth) api.update_status(command1) connect_object.send( xmpp.Message(message_node.getFrom(), ("Posted your message on Twitter " + command1))) jid = xmpp.JID(user) connection = xmpp.Client(server) connection.connect() result = connection.auth(jid.getNode(), passwd) connection.RegisterHandler('message', message_handler, "") connection.sendInitPresence() press = xmpp.Presence() press.setStatus("Hi from Collaborative Microblogging App") connection.send(press) while (1): connection.Process(1)
def connect(self): if isinstance(self.jid, basestring): self.jid = xmpp.JID(self.jid) if self.client is None: self.client = xmpp.Client(self.jid.getDomain(), debug=[]) self.connected = self.client.connect(self.server) if not self.connected: raise BotConnectionException("Could not connect to server") if self.connected != 'tls' and self.require_tls: raise BotConnectionException("Connection does not use TLS") # setup handlers self.client.RegisterHandler('message', self.message_handler) self.client.RegisterHandler('presence', self.presence_handler) # authenticate if not self.resource: self.resource = platform.node() self.authenticated = self.client.auth(self.jid.getNode(), self.password, self.resource) if not self.authenticated: raise BotAuthenticationException("Failed to authenticate") # set initial presence self.client.sendInitPresence() self._status = xmpp.Presence() # fetch the roster self.roster = self.client.getRoster() # do custom startup self.startup()
def create_room(room_name): """Create and configure a room. Documentation to create and configure a room: https://xmpp.org/extensions/xep-0045.html#createroom Parameters ---------- room_name: string The name of the room you want to create. """ client = _connect() client.send( xmpp.Presence( to=f"{room_name}@{settings.XMPP_CONFERENCE_DOMAIN}/admin", payload=[xmpp.Node(tag="x", attrs={"xmlns": xmpp.NS_MUC})], ) ) client.send( xmpp.Iq( to=f"{room_name}@{settings.XMPP_CONFERENCE_DOMAIN}", frm=settings.XMPP_PRIVATE_ADMIN_JID, typ="set", queryNS=xmpp.NS_MUC_OWNER, payload=[ xmpp.DataForm( typ="submit", data=[ xmpp.DataField( typ="hidden", name="FORM_TYPE", value=xmpp.NS_MUC_ROOMCONFIG ), # Make Room Persistent? xmpp.DataField( typ="boolean", name="muc#roomconfig_persistentroom", value=1 ), # Make room publicly searchable? xmpp.DataField( typ="boolean", name="muc#roomconfig_publicroom", value=0 ), # Nobody can send private message xmpp.DataField( typ="list-single", name="muc#roomconfig_allowpm", value="none", ), # Nobody can send private message xmpp.DataField( typ="boolean", name="muc#roomconfig_allowinvites", value=0 ), # Nobody can change the subject xmpp.DataField( typ="boolean", name="muc#roomconfig_changesubject", value=0 ), ], ) ], ) )
def connection(self, nick=u'client_test', room=u'*****@*****.**', account=u'*****@*****.**', password=u'testing123testing'): self.jid = xmpp.protocol.JID(account) self.node = self.jid.getNode() self.domain = self.jid.getDomain() self.password = password self.nick = nick self.room = room self.client = xmpp.Client(self.domain, debug=[]) self.connection = self.client.connect() self.client.RegisterHandler('message', self.message_handler) self.client.RegisterHandler('presence', self.presence_handler) self.auth = self.client.auth(self.node, self.password) self.client.sendInitPresence() pres = xmpp.Presence(to='/'.join([self.room, self.nick])) pres.setTag('x', namespace=xmpp.NS_MUC).setTagData('password', '') pres.getTag('x').addChild('history', { 'maxchars': '0', 'maxstanzas': '0' }) try: self.client.send(pres) except: self.on_disconnect() else: self.cc = '0' thread.start_new_thread(self.listen, ())
def connect_jabber(): client = xmpp.Client(JABBER_SERVER) client.connect(server=(JABBER_SERVER, JABBER_PORT)) client.auth(JABBER_USER, JABBER_PASS, JABBER_NAME) client.sendInitPresence() client.send(xmpp.Presence(to="%s/%s" % (JABBER_ROOM, JABBER_NAME))) return client
def __connect(self): self._jid = xmpp.JID(self._settings.jid) if not self._conn: if not self._options.debug: conn = xmpp.Client(self._jid.getDomain()) else: conn = xmpp.Client(self._jid.getDomain(), debug=[]) res = conn.connect() if not res: logging.error("Unable to connect to server %s." % self._jid.getDomain()) exit() if res <> 'tls': logging.warning("Unable to establish TLS connection.") res = conn.auth(self._jid.getNode(), self._settings.password, self._settings.chat_name) if not res: logging.error("Unable to authenticate this connection.") exit() if res <> 'sasl': logging.warning("Unable to get SASL creditential for: %s." % self.jid.getDomain()) conn.RegisterHandler('message', self.message_handler) conn.RegisterHandler('presence', self.presence_handler) conn.sendInitPresence() self.roster = conn.Roster.getRoster() self._conn = conn if hasattr(self._settings, 'default_status'): self._conn.send( xmpp.Presence(status=self._settings.default_status)) if hasattr(self._settings, 'groupchat'): self.__join_muc()
def joinRoom(self, room, username=None, password=None): """ Join the specified multi-user chat room (muc) @param room: Name of the muc @type room: string @param username: Username to use as room member @type username: string @param password: Password to use when the muc is password protected @type password: string """ NS_MUC = 'http://jabber.org/protocol/muc' self.log.info('Joining room: ' + room) if username is None: username = self._username.split('@')[0] room_jid = '/'.join((room, username)) pres = xmpp.Presence(to=room_jid) self.log.debug("*** room = %s" % room) self.log.debug("*** room_jid = %s" % room_jid) self.log.debug("*** username = %s" % username) self.log.info("%s entered room %s" % (username, room)) if password is not None: pres.setTag('x',namespace=NS_MUC).setTagData('password',password) if room not in self._joinedRooms: self._joinedRooms.append(room) self.conn.send(pres)
def is_alive(self): try: self.conn.send(xmpp.Presence(status=None, show=None)) alive = True except IOError: alive = False return alive
def __run(self): retries = 0 while True: try: if not self._conn.isConnected(): logging.info('Bot not connected, reconnecting...') self._conn.reconnectAndReauth() self._conn.RegisterHandler('message', self.message_handler) self._conn.RegisterHandler('presence', self.presence_handler) self._conn.sendInitPresence() self.roster = self._conn.Roster.getRoster() if hasattr(self._settings, 'default_status'): self._conn.send( xmpp.Presence( status=self._settings.default_status)) if hasattr(self._settings, 'groupchat'): self.__join_muc() self._conn.Process(1) except KeyboardInterrupt: logging.info('Signal catched, shutting down.') break except: logging.error('Unexpected error') if retries <= 3: retries += 1 time.sleep(2) continue else: break logging.info('Exiting. Bye.') exit()
def join(self, room, nick=None): """ Joins a MUC room. Only works after a successful connect(). Arguments: room -- the JID of the room to join nick -- the nickname to join the room with. If not given, the node name from the jid passed to connect() will be used. """ if not nick: nick = self.jid.getNode() if type(room) != object: room = xmpp.protocol.JID(room) # use our own desired nickname as resource part of the room's JID gjid = room.getStripped() + "/" + nick #create presence stanza join = xmpp.Presence(to=gjid) #announce full MUC support join.addChild(name='x', namespace='http://jabber.org/protocol/muc') self.xmpp.send(join) self.info('joined room %s' % room.getStripped()) self.room = room self.nick = nick return True
def sendPresence(destination, source, pType=None, nick=None, reason=None, hash=None, show=None): """ Sends a presence to destination from source Args: destination: whom send the presence to source: who send the presence from pType: the presence type nick: add <nick> tag reason: set status message hash: add caps hash show: add status show """ presence = xmpp.Presence(destination, pType, frm=source, status=reason, show=show) if nick: presence.setTag("nick", namespace=xmpp.NS_NICK) presence.setTagData("nick", nick) if hash: presence.setTag("c", { "node": CAPS_NODE, "ver": hash, "hash": "sha-1" }, xmpp.NS_CAPS) executeHandlers("prs02", (presence, destination, source)) sender(Component, presence)
def main(): Counter = [0, 0] getPid() initDatabase(DatabaseFile) globals()["Component"] = xmpp.Component(Host, debug=DEBUG_XMPPPY) Print("\n#-# Connecting: ", False) if not Component.connect((Server, Port)): Print("fail.\n", False) else: Print("ok.\n", False) Print("#-# Auth: ", False) if not Component.auth(TransportID, Password): Print( "fail (%s/%s)!\n" % (Component.lastErr, Component.lastErrCode), True) disconnectHandler(False) else: Print("ok.\n", False) Component.RegisterHandler("iq", iqHandler) Component.RegisterHandler("presence", prsHandler) Component.RegisterHandler("message", msgHandler) Component.RegisterDisconnectHandler(disconnectHandler) Print("#-# Initializing users", False) with Database(DatabaseFile) as db: users = db("select jid from users").fetchall() for user in users: Print(".", False) Sender(Component, xmpp.Presence(user[0], "probe", frm=TransportID)) Print("\n#-# Finished.") if allowBePublic: makeMeKnown()