Beispiel #1
0
class CampfireBot(Emitter):
    def __init__(self, subdomain, token):
        super(Emitter, self).__init__()
        logger.info('Making Campfire...')
        self.camp = Campfire(subdomain, token)
        logger.info('Rooms...')
        self.rooms = {}
        logger.info('Room...')
        self.camp.find_room_by_name('Testing').join()
        self.results = {}
        try:
            threading.Thread(target=reactor.run).start()
        except Exception:
            pass

    def message(msg):
        if not msg['body'].find('sauron'):
            try:
                self.rooms[msg['room_id']].speak(repr(self.metrics))
            except KeyError:
                self.rooms[msg['room_id']] = self.camp.room(msg['room_id'])
        logger.info(repr(msg))

    def err(msg):
        logger.error(repr(msg))

    def metrics(self, metrics):
        self.results = metrics
class CampfireBot(Emitter):
    def __init__(self, subdomain, token):
        super(Emitter, self).__init__()
        logger.info("Making Campfire...")
        self.camp = Campfire(subdomain, token)
        logger.info("Rooms...")
        self.rooms = {}
        logger.info("Room...")
        self.camp.find_room_by_name("Testing").join()
        self.results = {}
        try:
            threading.Thread(target=reactor.run).start()
        except Exception:
            pass

    def message(msg):
        if not msg["body"].find("sauron"):
            try:
                self.rooms[msg["room_id"]].speak(repr(self.metrics))
            except KeyError:
                self.rooms[msg["room_id"]] = self.camp.room(msg["room_id"])
        logger.info(repr(msg))

    def err(msg):
        logger.error(repr(msg))

    def metrics(self, metrics):
        self.results = metrics
Beispiel #3
0
class Pewbot(object):
    commands = []
    rooms = []
    campfire = None
    message_log = []
    first_run = True
    pewbot_userid = 1429837
    ignore_users = []

    def __init__(self, *kwargs, **args):
        self.campfire = Campfire(CAMPFIRE_DOMAIN, API_KEY)
        self.ignore_users.append(self.pewbot_userid)

        for room in CAMPFIRE_ROOMS:
            croom = self.campfire.room(room)
            croom.join()
            self.rooms.append(croom)

        self.commands = self._discover_commands()

        if 'test' in args:
            _handle_message('melbourne', None)
        else:
            while len(self.rooms) > 0:
                try:
                    self._fetch_messages()
                    sleep(2)  # have a rest, pewbot
                except Exception as e:
                    print e

    def _discover_commands(self):
        command_dir = os.path.join('./pewbot/', 'commands')
        try:
            commands = []
            for f in os.listdir(command_dir):
                if not f.startswith('_') and f.endswith(
                        '.py') and f not in 'base.py':
                    module = import_module('pewbot.commands.%s' % (f[:-3]))
                    commands.append(module.Command())
            return commands
        except OSError:
            return []

    def _fetch_messages(self):
        for room in self.rooms:
            for message in room.transcript(date.today()):
                if message['id'] not in self.message_log:
                    self.message_log.append(message['id'])
                    print self.first_run, message['user_id'], message[
                        'id'], message['type'], message['body']
                    self._handle_message(message, room)
        self.first_run = False  # so that we don't spam the room reading the transcript

    def _handle_message(self, message, room):
        body = message['body']
        if body == 'pewbot help me' and not self.first_run:
            self.help(room)
            return

        if not self.first_run and body and message[
                'user_id'] not in self.ignore_users:
            for c in self.commands:
                try:
                    messages = c.handle(body, room)
                    if messages:
                        for m in messages:
                            room.speak(m)
                except Exception as e:
                    print e

    def help(self, room):
        help_messages = []
        for c in self.commands:
            help_message = c.help
            if len(help_message) > 0:
                room.speak(help_message)
Beispiel #4
0
class Pewbot(object):
    commands = []
    rooms = []
    campfire = None
    message_log = []
    first_run = True
    pewbot_userid = 1429837
    ignore_users = []

    def __init__(self, *kwargs, **args):
        self.campfire = Campfire(CAMPFIRE_DOMAIN, API_KEY)
        self.ignore_users.append(self.pewbot_userid)

        for room in CAMPFIRE_ROOMS:
            croom = self.campfire.room(room)
            croom.join()
            self.rooms.append(croom)

        self.commands = self._discover_commands()

        if "test" in args:
            _handle_message("melbourne", None)
        else:
            while len(self.rooms) > 0:
                try:
                    self._fetch_messages()
                    sleep(2)  # have a rest, pewbot
                except Exception as e:
                    print e

    def _discover_commands(self):
        command_dir = os.path.join("./pewbot/", "commands")
        try:
            commands = []
            for f in os.listdir(command_dir):
                if not f.startswith("_") and f.endswith(".py") and f not in "base.py":
                    module = import_module("pewbot.commands.%s" % (f[:-3]))
                    commands.append(module.Command())
            return commands
        except OSError:
            return []

    def _fetch_messages(self):
        for room in self.rooms:
            for message in room.transcript(date.today()):
                if message["id"] not in self.message_log:
                    self.message_log.append(message["id"])
                    print self.first_run, message["user_id"], message["id"], message["type"], message["body"]
                    self._handle_message(message, room)
        self.first_run = False  # so that we don't spam the room reading the transcript

    def _handle_message(self, message, room):
        body = message["body"]
        if body == "pewbot help me" and not self.first_run:
            self.help(room)
            return

        if not self.first_run and body and message["user_id"] not in self.ignore_users:
            for c in self.commands:
                try:
                    messages = c.handle(body, room)
                    if messages:
                        for m in messages:
                            room.speak(m)
                except Exception as e:
                    print e

    def help(self, room):
        help_messages = []
        for c in self.commands:
            help_message = c.help
            if len(help_message) > 0:
                room.speak(help_message)
Beispiel #5
0
class MyNotify(object):
    def __init__(self):
        super(MyNotify, self).__init__()

        # connect to Campfire
        self.c = Campfire(SUBDOMAIN, SECRET_TOKEN, ssl=True)
        if ROOM_ID:
            self.room = self.c.room(ROOM_ID)
        else:
            self.room = self.c.find_room_by_name(ROOM_NAME)
        self.room.join()

        print 'Begin...'
        self.room.listen(self.callback_for_campfire, self.error_callback)
        print 'End...'


    def callback_for_campfire(self, mes):
        print '***** Simple callback *****'
        print mes
        print '****** End callback *****'

        if mes['type']=='TextMessage':
            user = self.c.user(mes['user_id'])['user']
            gravatar_hash = hashlib.md5(user['email_address'].lower()).hexdigest()
            title = user['name']
            body = mes['body']

        elif mes['type']=='TopicChangeMessage':
            user = self.c.user(mes['user_id'])['user']
            gravatar_hash = hashlib.md5(user['email_address'].lower()).hexdigest()
            title = 'Topic has been changed'
            body = '%s changed the room’s topic to "%s"' % (user['name'],
                                                            mes['body'])

        elif mes['type']=='LeaveMessage':
            user = self.c.user(mes['user_id'])['user']
            gravatar_hash = hashlib.md5(user['email_address'].lower()).hexdigest()
            title = 'Someone has left the room'
            body = '%s has left the room' % user['name']

        elif mes['type']=='EnterMessage':
            user = self.c.user(mes['user_id'])['user']
            gravatar_hash = hashlib.md5(user['email_address'].lower()).hexdigest()
            title = 'Someone has joined the room'
            body = '%s has entered the room' % user['name']

        elif mes['type']=='UploadMessage':
            user = self.c.user(mes['user_id'])['user']
            gravatar_hash = hashlib.md5(user['email_address'].lower()).hexdigest()
            title = 'New file uploaded'
            body = '%s uploaded %s' % (user['name'],
                                         mes['body'])

        else:
            return


        n = pynotify.Notification(title, body)

        if gravatar_hash and SHOW_GRAVATAR:
            source = urllib.urlopen('http://www.gravatar.com/avatar/' + gravatar_hash)
            contents = source.read()
            get_image = gtk.gdk.PixbufLoader()
            get_image.write(contents)
            get_image.close()
            n.set_icon_from_pixbuf(get_image.get_pixbuf())

        if PLAY_SOUND:
            pipeline = gst.Pipeline('mypipeline')
            audiotestsrc = gst.element_factory_make('audiotestsrc', 'audio')
            audiotestsrc.set_property('freq', FREQUENCY)
            pipeline.add(audiotestsrc)
            sink = gst.element_factory_make('alsasink', 'sink')
            pipeline.add(sink)
            audiotestsrc.link(sink)
            pipeline.set_state(gst.STATE_PLAYING)
            print '============== Sound =============='

        n.show()

        if PLAY_SOUND:
            time.sleep(DURATION)
            pipeline.set_state(gst.STATE_READY)

    def error_callback(self, expt):
        print '***** Error callback *****'
        print expt
        print '***** End callback *****'
        n = pynotify.Notification('Whoops!', 'An error occurred', 'dialog-error')
        n.show()
Beispiel #6
0
from time import sleep
from datetime import date
from pinder import Campfire

try:
    from campsettings import *
except:
    sys.exit('Please add a campsettings.py file as outlined in the documentation.')

# Create Campfire Connection
c = Campfire(CAMPFIRE_DOMAIN, API_KEY)

rooms = []
for r in CAMPFIRE_ROOMS:
    rooms.append(c.room(r))

if len(rooms) == 0:
    sys.exit('Unfortunately none of your rooms worked. Not much point then, is there?')
visited = []
first_run = True

while True:
    print "Checking for new messages"
    for room in rooms:
        for comment in room.transcript(date.today()):
            content = comment['body']
            if content and 'http' in content:
                urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', content)
                for url in urls:
                    if url not in visited:
Beispiel #7
0
class CampfireBot(object):
    """This is where all the actual message handling takes place.
    
    """
    def __init__(self, subdomain, room_name, token, ssl=False):
        self.campfire = Campfire(subdomain, token, ssl)
        self.room = self.campfire.find_room_by_name(room_name)
        self.me = self.campfire.me()
        self.auth_token = token
        self.xmpp = None
        if not self.room:
            raise RuntimeError("Could not find room %s" % room)
        self.users = {}
        self.joined = False

    def connectionMade(self):
        print "connectionMade"

    def connectionFailed(self, why):
        print "connectionFailed"

    def get_user(self, user_id):
        if user_id in self.users:
            return self.users[user_id]
        else:
            u = self.campfire.user(user_id)
            self.users[user_id] = u
            return u

    def formatMessage(self, msg):
        fwd_msg = None
        user = ('user_id' in msg and msg['user_id'] is not None) and self.get_user(msg['user_id']) or None
        if msg['type'] == 'TextMessage':
            fwd_msg = "%s: %s" % (user['user']['name'], msg['body'])
        elif msg['type'] == 'LeaveMessage' or msg['type'] == 'KickMessage':
            fwd_msg = "- %s has left the room" % user['user']['name']
        elif msg['type'] == 'EnterMessage':
            fwd_msg = "- %s has entered the room" % user['user']['name']
        elif msg['type'] == 'PasteMessage':
            fwd_msg = "- %s pasted:\n%s" % (user['user']['name'], msg['body'])
        elif msg['type'] == 'UploadMessage':
            fwd_msg = "- %s uploaded %s" % (user['user']['name'], msg['body'])
        elif msg['type'] == 'TimestampMessage':
            fwd_msg = "- timestamp %s" % (msg['created_at'])
        return fwd_msg

    def messageReceived(self, msg):
        print unicode(msg)
        if 'user_id' in msg and msg['user_id'] == self.me['id']:
            # skip my own messages
            if msg['type'] in ('TextMessage', 'PasteMessage'):
                return
        if msg['type'] in ('TextMessage', 'LeaveMessage', 'KickMessage', 'EnterMessage', 'PasteMessage', 'UploadMessage'):
            fwd_msg = self.formatMessage(msg)
            if fwd_msg:
                if self.xmpp:
                    self.xmpp.forwardMessage(fwd_msg)
                else:
                    print fwd_msg

    def _registerProtocol(self, protocol):
        self._streamProtocol = protocol

    def disconnect(self):
        print "disconnect"
        if hasattr(self, "_streamProtocol"):
            self._streamProtocol.factory.continueTrying = 0
            self._streamProtocol.transport.loseConnection()
        else:
            raise RuntimeError("not connected")
    
    def forwardMessage(self, msg):
        if msg[0] == "!":
            fwd_msg = "Unknown command"
            if msg == "!users":
                room = self.campfire.room(self.room.id)
                users = ', '.join([u['name'] for u in room.data['users']])
                fwd_msg = "Active users: %s" % users
            elif msg == "!uploads":
                files = self.room.uploads()
                file_str = '\n'.join([f['full_url'].replace(' ', '%20') for f in files])
                fwd_msg = "Uploaded files:\n%s" % file_str
            elif msg == "!room":
                fwd_msg = "Room URL: %s/room/%d" % (self.campfire.uri.geturl(),
                                                    self.room.id)
            elif msg == "!leave":
                self.leave()
                fwd_msg = "Left room"
            elif msg == "!join":
                self.join()
                fwd_msg = "Joined room"
            elif msg == "!transcript":
                today = date.today()
                fwd_msg = "Transcript URL: %s/room/%d/transcript/%04d/%02d/%02d" % (self.campfire.uri.geturl(),
                                                                                    self.room.id,
                                                                                    today.year,
                                                                                    today.month,
                                                                                    today.day)
            self.xmpp.forwardMessage("# %s" % fwd_msg)
        else:
            if '\n' in msg:
                self.room.paste(msg)
            else:
                self.room.speak(msg)

    def join(self):
        if self.room and not self.joined:
            self.joined = True
            self.room.join()
    
    def leave(self):
        if self.room and self.joined:
            self.joined = False
            self.room.leave()
    
    def keepAlive(self):
        if self.room and self.joined:
            self.room.join()
Beispiel #8
0
    "Accept": "application/xml",
    "Authorization": "Basic %s" % base64.b64encode("%s:%s" % (CODEBASE_USERNAME, CODEBASE_APIKEY)),
}
r = requests.get(url, headers=headers)

# parse answer
tree = etree.parse(r)
root = tree.getroot()


db = sqlite3.connect(DB_file)
cursor = db.cursor()

# connect to Campfire
c = Campfire(SUBDOMAIN, SECRET_TOKEN, ssl=True)
room = c.room(ROOM_ID)
room.join()


for child in root:
    cursor.execute("select id from Messages where id=?", (child.findall("id")[0].text,))
    messages = cursor.fetchall()
    if messages:
        continue
    # write to DB
    my_data = (
        child.findall("title")[0].text,
        child.findall("id")[0].text,
        child.findall("timestamp")[0].text,
        child.findall("type")[0].text,
        child.findall("html-title")[0].text,
Beispiel #9
0
class MyNotify(object):
    def __init__(self):
        super(MyNotify, self).__init__()
        
        # connect to Campfire
        self.c = Campfire(SUBDOMAIN, SECRET_TOKEN, ssl=True)
        if ROOM_ID:
            self.room = self.c.room(ROOM_ID)
        else:
            self.room = self.c.find_room_by_name(ROOM_NAME)
        self.room.join()
        
        print 'Begin...'
        self.room.listen(self.callback_for_campfire, self.error_callback)
        print 'End...'

        
    def callback_for_campfire(self, mes):
        print '***** Simple callback *****'
        print mes
        print '****** End callback *****'
        
        if mes['type']=='TextMessage':
            user = self.c.user(mes['user_id'])['user']
            gravatar_hash = hashlib.md5(user['email_address'].lower()).hexdigest()
            title = user['name']
            body = mes['body']
            
        elif mes['type']=='TopicChangeMessage':
            user = self.c.user(mes['user_id'])['user']
            gravatar_hash = hashlib.md5(user['email_address'].lower()).hexdigest()
            title = 'Topic has been changed'
            body = '%s changed the room’s topic to "%s"' % (user['name'], 
                                                            mes['body'])
                                                          
        elif mes['type']=='LeaveMessage':
            user = self.c.user(mes['user_id'])['user']
            gravatar_hash = hashlib.md5(user['email_address'].lower()).hexdigest()
            title = 'Someone has left the room'
            body = '%s has left the room' % user['name']
                                                                      
        elif mes['type']=='EnterMessage':
            user = self.c.user(mes['user_id'])['user']
            gravatar_hash = hashlib.md5(user['email_address'].lower()).hexdigest()
            title = 'Someone has joined the room'
            body = '%s has entered the room' % user['name']

        elif mes['type']=='UploadMessage':
            user = self.c.user(mes['user_id'])['user']
            gravatar_hash = hashlib.md5(user['email_address'].lower()).hexdigest()
            title = 'New file uploaded'
            body = '%s uploaded %s' % (user['name'], 
                                         mes['body'])

        else:
            return                                                                     
                                                          

        n = pynotify.Notification(title, body)
        if gravatar_hash and SHOW_GRAVATAR:
            source = urllib.urlopen('http://www.gravatar.com/avatar/' + gravatar_hash)
            contents = source.read()
            get_image = gtk.gdk.PixbufLoader()
            get_image.write(contents)
            get_image.close()
            n.set_icon_from_pixbuf(get_image.get_pixbuf())
        n.show()

    def error_callback(self, expt):
        print '***** Error callback *****'
        print expt
        print '***** End callback *****'
        n = pynotify.Notification('Whoops!', 'An error occurred', 'dialog-error')
        n.show()