#!/usr/bin/python import sys, os, xmpp, time, socket, re, MySQLdb class JabberBroadcaster: def __init__(self, server, port=5222): self.DB = {'user': 'foo', 'password': 'bar', 'db': 'baz'} self.client = xmpp.Client(server, port) self.client.connect() def auth(self, a, b, resource): return self.client.auth(a, b, resource=resource) def sendInitPresence(self): return self.client.sendInitPresence() def Process(self, a): return self.client.Process(a) def registerMyHandlers(self): print "registering handlers" self.client.RegisterHandler('message', self.xmppMessage) self.client.RegisterHandler('iq', self.xmppIq) def DisconnectHandler(self): print "got disconnected. now reconnecting." self.client.reconnectAndReauth() self.client.registerHandlers() self.client.sendInitPresence() def connect2SQL(self): db = MySQLdb.connect(user=self.DB['user'], passwd=self.DB['password'], db=self.DB['db']) c = db.cursor() return c def xmppIq(self, con, event): print "IQ received" def xmppMessage(self, con, event): print "I received a message" type = event.getType() fromjid, fromres = str(event.getFrom()).split('/', 1) print event.getFrom() if re.match('^list', event.getBody()): self.cmdList(event.getFrom()) elif re.match('^subscribe ', event.getBody()): self.cmdSubscribe(fromjid, event.getBody()) elif re.match('^unsubscribe ', event.getBody()): self.cmdUnsubscribe(fromjid, event.getBody()) elif re.match('^subscriptions', event.getBody()): self.cmdSubscriptions(fromjid) elif re.match('^create ', event.getBody()): self.cmdCreate(fromjid, event.getBody()) elif re.match('^msg ', event.getBody()): self.cmdMsg(fromjid, event.getBody()) else: self.client.send(xmpp.protocol.Message(event.getFrom(), self.getHelp(), typ='chat')) def cmdList(self, jid): channels = self.getChannels(); msg = 'Available channels are:\n' for chan in channels: msg += chan[0] + "\n" self.client.send(xmpp.protocol.Message(jid, msg, typ='chat')) def getChannels(self): c = self.connect2SQL() c.execute("""SELECT * FROM channels;""") res = c.fetchall() return res def channelExists(self, channel): c = self.connect2SQL() c.execute("""SELECT * FROM channels WHERE channel=%s""", (channel,)) if c.fetchone() != None: return True else: return False def hasSubscribed(self, jid, channel): c = self.connect2SQL() c.execute("""SELECT * FROM subscribers WHERE channel=%s AND subscriber=%s""", (channel, jid)) if c.fetchone() != None: return True else: return False def isValidCredential(self, channel, password): c = self.connect2SQL() c.execute("""SELECT * FROM channels WHERE channel=%s AND password=%s""", (channel, password)) if c.fetchone() != None: return True else: return False def cmdSubscribe(self, jid, msg): reres = re.match('^subscribe (\S*) (\S*)', msg) channel = reres.group(1) password = reres.group(2) self.subscribe(jid, channel, password) def subscribe(self, jid, channel, password): if self.channelExists(channel): if self.hasSubscribed(jid, channel): msg = 'You already subscribed to '+channel else: if self.isValidCredential(channel, password): c = self.connect2SQL() c.execute("""INSERT INTO subscribers (`subscriber`, `channel`) VALUES (%s, %s)""", (jid, channel)) msg = 'You successfully subscribed to '+channel else: msg = 'The password you entered was invalid' else: msg = 'The channel '+channel+' does not exist' self.client.send(xmpp.protocol.Message(jid, msg, typ='chat')) def cmdUnsubscribe(self, jid, msg): self.unsubscribe(jid, re.match('^unsubscribe (\S*)', msg).group(1)) def unsubscribe(self, jid, channel): if self.channelExists(channel): if self.hasSubscribed(jid, channel): c = self.connect2SQL() c.execute("""DELETE FROM subscribers WHERE subscriber=%s AND channel=%s""", (jid, channel)) msg = 'You successfully unsubscribed to '+channel else: msg = 'You did not subscribe for '+channel else: msg = 'The channel '+channel+' does not exist' self.client.send(xmpp.protocol.Message(jid, msg, typ='chat')) def cmdSubscriptions(self, jid): c = self.connect2SQL() msg = 'Your subscriptions are:\n' c.execute("""SELECT channel FROM subscribers WHERE subscriber=%s""", (jid,)) for chan in c.fetchall(): msg += chan[0] + "\n" self.client.send(xmpp.protocol.Message(jid, msg, typ='chat')) def cmdCreate(self, jid, msg): reres = re.match('^create (\S*) (\S*)', msg) channel = reres.group(1) password = reres.group(2) self.createChannel(jid, channel, password) self.subscribe(jid, channel, password) def createChannel(self, jid, channel, password): if self.channelExists(channel): msg = 'The channel '+channel+' exists already' else: c = self.connect2SQL() c.execute("""INSERT INTO channels (`channel`, `password`) VALUES (%s, %s)""", (channel, password)) msg = 'The channel '+channel+' was created successfully' self.client.send(xmpp.protocol.Message(jid, msg, typ='chat')) def cmdMsg(self, jid, msg): reres = re.match('^msg (\S*) (.*)', msg) channel = reres.group(1) message = reres.group(2) self.broadcast(jid, channel, message) def broadcast(self, jid, channel, message): if self.channelExists(channel): if self.hasSubscribed(jid, channel): c = self.connect2SQL() c.execute("""SELECT subscriber FROM subscribers WHERE channel=%s""", (channel,)) subscriberArray = c.fetchall() print subscriberArray for subscriber in subscriberArray: print subscriber[0] bcmsg = jid+' writes in '+channel+':\n'+message self.client.send(xmpp.protocol.Message(subscriber[0], bcmsg, typ='chat')) msg = 'As you see above your message has been broadcasted' else: msg = 'You are not allowed to broadcast on '+channel else: msg = 'The channel '+channel+' does not exist' self.client.send(xmpp.protocol.Message(jid, msg, typ='chat')) def getHelp(self): msg = '''Hi. I am a broadcasting bot. I broadcast messages to all subscribed members of a channel. The following are all commands implemented so far: - function - lists the available channels - subsribes you to the channel "channelname" - unsubscribes you to the channel "channelname" - creates a channel and seals it with the given password - broadcasts a message to the given channel - shows the channels you have subscribed to''' return msg if __name__ == '__main__': jidparams={'jid': 'broadcaster@your-domain.tld', 'password': '1337Password', 'resource': '/dev/random'} jid = xmpp.protocol.JID(jidparams['jid']) jc = JabberBroadcaster(jid.getDomain()) jc.auth(jid.getNode(), jidparams['password'], resource=jidparams['resource']) jc.registerMyHandlers() jc.sendInitPresence() print "handler is set. now looping." while 1: jc.Process(1)