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
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 campfire_notify(deployed=False): """Hop in Campfire and notify your developers of the time and commit SHA of an app deploy. Requires the pinder Python package and the env keys: deployment_type - app environment release - the commit SHA or git tag of the deployed version scm_http_url - path to an HTTP view of the remote git repository campfire_subdomain - subdomain of your Campfire account campfire_token - API token for Campfire campfire_room - the room to join and notify (the string name, e.g. "Developers") """ require('deployment_type') require('release') if (deployed and env.campfire_subdomain and env.campfire_token and env.campfire_room): from pinder import Campfire deploying = local('git rev-list --abbrev-commit %s | head -n 1' % env.release, capture=True) branch = utils.branch(env.release) if env.tagged: require('release') branch = env.release name = env.unit deployer = os.getlogin() deployed = env.deployed_version target = env.deployment_type.lower() source_repo_url = env.scm_http_url compare_url = ('%s/compare/%s...%s' % (source_repo_url, deployed, deploying)) campfire = Campfire(env.campfire_subdomain, env.campfire_token, ssl=True) room = campfire.find_room_by_name(env.campfire_room) room.join() if deployed: message = ('%s is deploying %s %s (%s..%s) to %s %s' % (deployer, name, branch, deployed, deploying, target, compare_url)) else: message = ('%s is deploying %s %s to %s' % (deployer, name, branch, target)) room.speak(message) print 'Campfire notified that %s' % message
def manage_campfire(): import json f = open('config.json', 'r') config = json.load(f) f.close() cf = Campfire(config['campfire_prefix'], config['auth_token']) room = cf.find_room_by_name(config['room_name']) room.join() print 'Ready' do_election_updates(room) # Block forever room.listen(handle_message, handle_exception)
def setUp(self): self.response = utils.MockResponse() self.campfire = Campfire('foobar') response = self.response HTTPConnection.request = lambda self, m, l, b, h: None HTTPConnection.getresponse = lambda self: response httplib2.Response = utils.MockHttplib2Response
class CampfireConnection(): connection = None subdomain = None token = None room_name = None room = None def connect(self): self.connection = Campfire(self.subdomain, self.token) self.room = self.connection.find_room_by_name(self.room_name) self.room.join() def __init__(self, subdomain, token, room_name): self.subdomain = subdomain self.token = token self.room_name = room_name def send(self, msg, paste): try: if paste: self.room.paste(msg) else: self.room.speak(msg) except: print 'Oh no, caught an exception talking to the room' def quit(self, reason): if reason: try: self.room.speak('Quitting: %s' % reason) except: print 'Oh no, caught an exception talking to the room' self.room.leave()
def startup(self): self.campfire = Campfire( settings.CAMPFIRE_DOMAIN, ssl=settings.CAMPFIRE_SSL ) self.campfire.login(settings.CAMPFIRE_LOGIN, settings.CAMPFIRE_PASSWORD) self.room = self.campfire.find_room_by_name(settings.CAMPFIRE_ROOM) self.room.join() self.room.speak("I'm alive!")
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 __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 imap_to_campfire(imap_login, campfire_login): """ Checks IMAP inbox and posts info to Campfire. """ # connect to IMAP i = imaplib.IMAP4_SSL(imap_login['server']) i.login(imap_login['user'], imap_login['password']) # connect to Campfire c = Campfire(campfire_login['subdomain']) c.login(campfire_login['user'], campfire_login['password']) room = c.find_room_by_name(campfire_login['room']) typ, data = i.select("INBOX") msg_total = int(data[0]) #import pdb; pdb.set_trace() for msg_id in range(1, msg_total+1): typ, data = i.fetch(msg_id, "(BODY[HEADER.FIELDS (TO SUBJECT)])") #retrieve relative part of message msg_info = data[0][1] #archive message i.store(msg_id, "+FLAGS", r'(\Deleted)') #post to Campfire room.paste("*New Message*\r\n%s" % msg_info) i.close() i.logout() c.logout()
def load(): campfire = Campfire(options.domain, options.token) room = campfire.find_room_by_name(options.room) users = defaultdict(lambda: Markov(int(options.order))) ignore = options.ignore.split(",") names = {} def name(user): if not user in names: names[user] = campfire.user(user)["user"]["name"] return names[user] if not os.path.exists("cache"): os.makedirs("cache") for i in range(0, int(options.days)): day = date.today() - timedelta(i) path = os.path.join("cache", str(day)) transcripts = None if os.path.exists(path): sys.stdout.write("got %s from cache ... " % day) transcripts = pickle.loads(open(path).read()) else: sys.stdout.write("fetching %s from campfire ... " % day) transcripts = room.transcript(date.today() - timedelta(i)) open(path, "w+").write(pickle.dumps(transcripts)) for msg in transcripts: if msg["user_id"] and msg["body"]: username = name(msg["user_id"]) if not username in ignore: users[username].add(msg["body"].encode("utf-8")) sys.stdout.write("processed %d messages\n" % len(transcripts)) print "computing probability trees ... " for generator in users.values(): generator.compute() return users
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 manage_campfire(images, conf): global quote_image_list random.shuffle(images) quote_image_list = images global catch_phrase catch_phrase = conf['Dubya']['catch_phrase'] global match_phrase match_phrase = conf['Dubya']['match_phrase'] subdomain = conf['Campfire']['domain_prefix'] room_name = conf['Campfire']['room'] auth_token = conf['Campfire']['auth_token'] global cf, room cf = Campfire(subdomain, auth_token) room = cf.find_room_by_name(room_name) room.join() print 'ready' # Block forever room.listen(handle_message, handle_exception)
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 decorated(*args, **kwargs): from pinder import Campfire if not 'campfire_domain' in env: return if not 'current_release' in env: releases() if 'git_branch' not in env: env.git_branch = "master" deployed = run("cd %(current_release)s; git rev-parse HEAD" % env)[:7] deploying = run( "cd %(current_release)s; git fetch deploy; git rev-parse deploy/%(git_branch)s" % env)[:7] return_value = func(*args, **kwargs) c = Campfire(env.campfire_domain, env.campfire_token, ssl=True) room = c.find_room_by_name(env.campfire_room) compare_url = "%(repo_url)s/compare/%(deployed)s...%(deploying)s" % { 'repo_url': env.github_url, 'deployed': deployed, 'deploying': deploying } room.speak("%s has deployed new code on %s : %s" % (env.user, env.name, compare_url)) return return_value
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() print self.commands while len(self.rooms) > 0: try: self._fetch_messages() sleep(2) # have a rest, pewbot except Exception as e: print e
def connect(self): self.connection = Campfire(self.subdomain, self.token) self.room = self.connection.find_room_by_name(self.room_name) self.room.join()
class Bob(object): room = None campfire = None stdin_path = '/dev/null' stdout_path = settings.LOG_FILE stderr_path = settings.ERROR_FILE pidfile_path = settings.LOCK_FILE pidfile_timeout = settings.LOCK_TIMEOUT files_preserve = [settings.DB_FILE, ] def startup(self): self.campfire = Campfire( settings.CAMPFIRE_DOMAIN, ssl=settings.CAMPFIRE_SSL ) self.campfire.login(settings.CAMPFIRE_LOGIN, settings.CAMPFIRE_PASSWORD) self.room = self.campfire.find_room_by_name(settings.CAMPFIRE_ROOM) self.room.join() self.room.speak("I'm alive!") # Main function def run(self): if self.is_reset_mode(): self.reset_db() else: self.startup() self.db = self.get_db_cursor() while True: entry = self.get_next_entry() while entry: self.room.ping() if self.is_entry_interesting(entry): self.report_entry(entry) self.record_processed(entry) entry = self.get_next_entry() time.sleep(30) def stop(self, *args, **kwargs): print args print kwargs self.room.speak("I'm going down!") self.room.leave() self.campfire.logout() # Campfire Fuctions def report_entry(self, entry): msg = self.gen_message(entry) self.room.speak(msg) # SVN Functions def get_next_entry(self): last_rev = self.get_last_entry() if last_rev: next = last_rev + 1 target_rev = pysvn.Revision(pysvn.opt_revision_kind.number, next) else: target_rev = pysvn.Revision(pysvn.opt_revision_kind.head) try: client = pysvn.Client() entries = client.log( settings.SVN_SERVER, revision_start = target_rev, discover_changed_paths = True, limit = 1 ) entry = entries[0] except pysvn.ClientError: entry = None return entry def get_last_entry(self): query = "SELECT rev FROM svn_log ORDER BY processed DESC LIMIT 1" result = self.db.execute(query) rev = result.fetchone() if rev: rev = rev[0] return rev def is_entry_interesting(self, entry): interesting = False for change in entry.changed_paths: for prefix in settings.SVN_WATCH_PATHS: if change.path.startswith(prefix): interesting = True break return interesting def gen_message(self, entry): rev = entry.revision.number url = settings.COMMIT_URL % rev msg = '[%d] %s - "%s" (%s)' % (rev, entry.author, entry.message, url) return msg def record_processed(self, entry): rev = entry.revision.number now = datetime.now().isoformat() query = "INSERT OR IGNORE INTO svn_log (rev, processed) VALUES (:rev, :now)" result = self.db.execute(query, {'rev': rev, 'now': now}) self.db.connection.commit() # Database Functions def reset_db(self): if os.path.exists(settings.DB_FILE): os.remove(settings.DB_FILE) db = self.get_db_cursor() query = "CREATE TABLE svn_log (rev INTEGER PRIMARY KEY, processed);" result = db.execute(query) db.connection.commit() print query def get_db_cursor(self): conn = sqlite3.connect(settings.DB_FILE) db = conn.cursor() return db def is_reset_mode(self): parser = OptionParser() parser.add_option("-R", "--resetdb", action="store_true", dest="reset_db", default=False, help="Reset the db file.") (options, args) = parser.parse_args() return options.reset_db
class CampfireTest(unittest.TestCase): def setUp(self): self.response = utils.MockResponse() self.campfire = Campfire('foobar') response = self.response HTTPConnection.request = lambda self, m, l, b, h: None HTTPConnection.getresponse = lambda self: response httplib2.Response = utils.MockHttplib2Response def test_creation(self): self.assertEqual('foobar', self.campfire.subdomain) self.assertEqual(False, self.campfire.logged_in) self.assertEqual(None, self.campfire.cookie) uri = 'http://foobar.campfirenow.com' self.assertEqual(urlparse(uri), self.campfire.uri) self.assertEqual(self.campfire._uri_for(), '%s/' % uri) def test_ssl(self): campfire = Campfire('foobar', True) uri = 'https://foobar.campfirenow.com' self.assertEqual(urlparse(uri), campfire.uri) def test_verify_response_success(self): self.response.status = 200 self.assertEqual(True, self.campfire._verify_response(self.response, success=True)) def test_verify_response_redirect_true(self): self.response.status = 302 self.assertEqual(True, self.campfire._verify_response(self.response, redirect=True)) def test_verify_response_redirect_false(self): self.response.status = 200 self.assertEqual(False, self.campfire._verify_response(self.response, redirect=True)) def test_verify_response_redirect_to(self): self.response.status = 304 self.assertEqual(True, self.campfire._verify_response(self.response, redirect_to='/foobar')) def test_verify_response_redirect_to_without_redirect(self): self.response.status = 200 self.assertEqual(False, self.campfire._verify_response(self.response, redirect_to='/foobar')) def test_verify_response_redirect_to_wrong_path(self): response = utils.MockResponse() response.headers['location'] = '/baz' response.status = 304 self.assertEqual(False, self.campfire._verify_response(response, redirect_to='/foobar')) def test_prepare_request(self): headers = self.campfire._prepare_request() self.assert_('User-Agent' in headers) self.assert_(headers['User-Agent'].startswith('Pinder/')) headers = self.campfire._prepare_request(ajax=True) self.assert_('X-Requested-With' in headers) self.campfire.cookie = 'cookie' headers = self.campfire._prepare_request() self.assertEqual(headers['cookie'], self.campfire.cookie) def test_perform_request(self): response = self.campfire._perform_request('GET', '') self.assertEqual(self.campfire.cookie, response.getheader('set-cookie')) def test_login(self): utils.FIXTURE = 'default' self.response.headers['location'] = self.campfire._uri_for() self.response.status = 302 self.assertEqual(True, self.campfire.login('foo', 'foopass')) def test_find_room_by_name(self): utils.FIXTURE = 'rooms_names' room = self.campfire.find_room_by_name('Room A') self.assert_(room is not None) self.assert_(self.campfire.find_room_by_name('No Room') is None) def test_find_room_by_name_no_rooms(self): utils.FIXTURE = 'no_rooms' self.assert_(self.campfire.find_room_by_name('Room A') is None) def test_create_room(self): utils.FIXTURE = 'rooms_names' name = 'New Room' self.assert_(self.campfire.find_room_by_name(name) is None) new_room_markup = self.response.read().splitlines() new_room_markup.append(""" <div id="room_1234" class="room available shaded"><h2> <a href="http://sample.campfirenow.com/room/1234">%s</a> </h2> </div>""" % name) self.response.read = lambda: '\n'.join(new_room_markup) self.assert_(self.campfire.find_room_by_name(name) is not None) def test_users_rooms_empty(self): utils.FIXTURE = 'chat_rooms_empty' self.assert_(not self.campfire.users()) def test_users_rooms_one_empty(self): utils.FIXTURE = 'chat_rooms_one_empty' self.assert_('Tom Jones' in self.campfire.users('Room A')) self.assert_(not self.campfire.users('Room B')) def test_users_rooms_not_empty(self): utils.FIXTURE = 'chat_rooms_not_empty' users = self.campfire.users() self.assertEqual(['Tom Jones', 'Gloria Estefan'], list(users)) def test_rooms_names(self): utils.FIXTURE = 'rooms_names' self.assertEqual(['Room A', 'Room B'], self.campfire.rooms_names()) def test_rooms(self): utils.FIXTURE = 'rooms_names' from pinder import Room self.assert_(isinstance(self.campfire.rooms()[0], Room)) def test_find_or_create_room_by_name(self): utils.FIXTURE = 'chat_rooms_empty' room = self.campfire.find_room_by_name('Room A') self.assertEqual(room, self.campfire.find_or_create_room_by_name( 'Room A')) def test_room_id_from_url(self): self.assertEqual(None, self.campfire._room_id_from_uri( 'http://www.google.com')) self.assertEqual('1234', self.campfire._room_id_from_uri( 'http://foo.campfirenow.com/room/1234/foo/bar')) def test_transcripts(self): utils.FIXTURE = 'transcripts' transcripts = self.campfire.transcripts() self.assertEqual(2, len(transcripts.keys())) self.assert_('12345' in transcripts.keys()) self.assertEqual(2001, transcripts['12345'][0].year) def test_transcripts_empty(self): utils.FIXTURE = 'no_transcripts' transcripts = self.campfire.transcripts() self.assertEqual({}, transcripts)
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)
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)
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()
import sys import re import urlparse 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']
import os import sys import yaml from pinder import Campfire # load configuration config = yaml.load(open('config.yaml', 'r')) campfire = Campfire(config['campfire']['domain'], config['campfire']['token'], config['campfire']['ssl']) room = campfire.find_room_by_name(config['campfire']['room']) url = "%s/room/%d/uploads.xml" % (campfire.uri.geturl(), room.id) for filename in sys.argv[1:]: x = (config['campfire']['token'], filename, url) os.system('curl -X POST -u %s:X -F "upload=@%s" %s -o /dev/null -#' % x)
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()
def send(self, payload): campfire = Campfire(self.options['subdomain'], self.options['token']) room = campfire.find_room_by_name(self.options['room']) if room is None: logger.error("Could not join the room %s to send payload %r Options: %r", self.options['room'], payload, self.options) return if payload['model'] == 'Comment': message = '%s %s. commented "%s" on %s "%s" (#%s) %s' % ( payload['attributes']['created_by']['first_name'], payload['attributes']['created_by']['last_name'][0], '%s...' % payload['attributes']['body'][0:50], payload['attributes']['item']['type'], payload['attributes']['item']['title'], payload['attributes']['item']['number'], payload['attributes']['item']['short_url']) elif payload['model'] == 'Item': message = '%s %s. created the %s "%s" (#%s) %s' % ( payload['attributes']['created_by']['first_name'], payload['attributes']['created_by']['last_name'][0], payload['attributes']['type'], payload['attributes']['title'], payload['attributes']['number'], payload['attributes']['short_url']) if payload['attributes']['assigned_to'] and \ payload['attributes']['assigned_to']['id'] != \ payload['attributes']['created_by']['id']: message += ' and assigned it to %s %s.' % ( payload['attributes']['assigned_to']['first_name'], payload['attributes']['assigned_to']['last_name'][0]) elif payload['model'] == 'Block': message = '%s %s. indicated the %s "%s" (#%s) %s is blocked on the %s "%s" (#%s) %s' % ( payload['attributes']['user']['first_name'], payload['attributes']['user']['last_name'][0], payload['attributes']['blocked']['type'], payload['attributes']['blocked']['title'], payload['attributes']['blocked']['number'], payload['attributes']['blocked']['short_url'], payload['attributes']['item']['type'], payload['attributes']['item']['title'], payload['attributes']['item']['number'], payload['attributes']['item']['short_url']) if payload['attributes']['item']['assigned_to']: message += ', which is owned by %s %s.' % ( payload['attributes']['item']['assigned_to']['first_name'], payload['attributes']['item']['assigned_to']['last_name'][0]) elif payload['model'] == 'Favorite': message = '%s %s. favorited the %s "%s" (#%s) %s' % ( payload['attributes']['user']['first_name'], payload['attributes']['user']['last_name'][0], payload['attributes']['item']['type'], payload['attributes']['item']['title'], payload['attributes']['item']['number'], payload['attributes']['item']['short_url']) elif payload['model'] == 'Deploy': message = '%s %s. deployed %s items to %s.' % ( payload['attributes']['user']['first_name'], payload['attributes']['user']['last_name'][0], len(payload['attributes']['items']), payload['attributes']['environment']) else: message = None if not message: return room.join() result = room.speak(message)
"Content-type": "application/xml", "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,
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()