Exemplo n.º 1
0
class HipchatObserver(AbstractNotificationObserver):
    """Implementation of observer to notify with HipChat 
    """
    def __init__(self):
        self.rooms = ['Kemono - Production Deploy Notification']
        self.color = 'green'
        self.is_notify = False
        self.hip_chat = HypChat(self._get_token())

    def add_room(self, room_name):
        self.rooms.append(room_name)
    
    def remove_room(self, room_name):
        self.rooms.remove(room_name)
    
    def update(self, event):
        """use hitchat API to send message to specified rooms
        """
        msg = self._build_msg(event)
        
        for room in self.rooms:
            r = self.hip_chat.get_room(room)
            r.message(msg, color=self.color, notify=self.is_notify)

    def _build_msg(self, event):
        """build message for event with default HTML format of hipchat message
        """
        msg = u'Process %(processname)s in group %(groupname)s exited unexpectedly (pid %(pid)s) from state %(from_state)s at %(happened_at)s<br /><br />Error log:<br />%(data)s' % event
        return msg
        
    def _get_token(self):
        config = _pit_get('hipchat',
                      {'require': {'token': 'your hipchat access token'}})
        return config['token']
Exemplo n.º 2
0
class TestToRally(object):
    """Tests documentation verifier"""

    def __init__(self, rally, config_file, regex_json):
        self.config_file = config_file
        handler = logging.FileHandler(self.config_file['RALLY_LOGGER'])
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        handler.setFormatter(formatter)
        log.addHandler(handler)
        self.rally = rally
        self.errors = {}
        self.authors_to_inform = {}

        with open(regex_json) as regex_file:
            regex_expressions = json.load(regex_file)

        self.file_types = {}
        for file_type, regex in regex_expressions['file_types'].items():
            if file_type not in self.file_types:
                self.file_types[file_type] = {}
            self.file_types[file_type]['test_case'] = re.compile(
                r'{0}'.format(regex['test_case']), re.IGNORECASE | re.MULTILINE | re.DOTALL
            )
            self.file_types[file_type]['test_type'] = re.compile(
                r'{0}'.format(regex['test_type']), re.IGNORECASE | re.DOTALL
            )

        self.ignored_tags = regex_expressions['ignored_tags']

        self.re_story_module = re.compile(
            r'{0}'.format(regex_expressions['user_story_module']), re.IGNORECASE | re.DOTALL
        )
        self.re_story_name = re.compile(
            r'{0}'.format(regex_expressions['user_story_name']), re.IGNORECASE | re.DOTALL
        )
        self.re_test_case_name = re.compile(
            r'{0}'.format(regex_expressions['test_case_name']), re.IGNORECASE | re.DOTALL
        )
        self.re_test_folder = re.compile(
            r'{0}'.format(regex_expressions['test_folder']), re.IGNORECASE | re.DOTALL
        )
        self.re_test_contract = re.compile(
            r'{0}'.format(regex_expressions['test_contract']), re.IGNORECASE | re.DOTALL
        )
        self.re_author_id = re.compile(r'.*?([0-9]+)\.js', re.DOTALL)

        #Hipchat integration
        try:
            self.hipster = HypChat(self.config_file['HIPCHAT_TOKEN'])
            self.qe_room = self.hipster.get_user(self.config_file['QE_CHAT']) \
                if 'QE_CHAT_IS_USER' in self.config_file and self.config_file['QE_CHAT_IS_USER'] \
                else self.hipster.get_room(self.config_file['QE_CHAT'])

        except Exception, details:
            log.info('Connection to HipChat was disabled.')
            log.info('REASON: {0}'.format(details))
Exemplo n.º 3
0
class HipchatObserver(AbstractNotificationObserver):
    """Implementation of observer to notify with HipChat 
    """
    def __init__(self):
        self.rooms = ['Kemono - Production Deploy Notification']
        self.color = 'green'
        self.is_notify = False
        self.hip_chat = HypChat(self._get_token())

    def add_room(self, room_name):
        self.rooms.append(room_name)

    def remove_room(self, room_name):
        self.rooms.remove(room_name)

    def update(self, event):
        """use hitchat API to send message to specified rooms
        """
        msg = self._build_msg(event)

        for room in self.rooms:
            r = self.hip_chat.get_room(room)
            r.message(msg, color=self.color, notify=self.is_notify)

    def _build_msg(self, event):
        """build message for event with default HTML format of hipchat message
        """
        msg = u'Process %(processname)s in group %(groupname)s exited unexpectedly (pid %(pid)s) from state %(from_state)s at %(happened_at)s<br /><br />Error log:<br />%(data)s' % event
        return msg

    def _get_token(self):
        config = _pit_get('hipchat',
                          {'require': {
                              'token': 'your hipchat access token'
                          }})
        return config['token']
Exemplo n.º 4
0
access_token_secret=os.environ['ACCESS_TOKEN_SECRET']

hc_room_id=os.environ['HC_ROOM_ID']
hc_token=os.environ['HC_TOKEN']
hc_server=os.environ['HC_SERVER']

twitter_user=os.environ['TWITTER_USER']

api = twitter.Api(consumer_key=consumer_key,
                  consumer_secret=consumer_secret,
                  access_token_key=access_token,
                  access_token_secret=access_token_secret)

statuses = api.GetUserTimeline(screen_name=twitter_user)
latest_status = statuses[0].text

print "Latest tweet=%s" % latest_status

hc = HypChat(hc_token, endpoint=hc_server)
room = hc.get_room(hc_room_id)
topic = room['topic']

print "Current topic=%s" % topic

if topic != latest_status:
    print "Topic doesn't match, setting to: %s" % latest_status
    room.topic(latest_status)
else:
    print "Topic is already set to latest tweet, ignoring"
    pass
Exemplo n.º 5
0
class HipchatPlugin(
        octoprint.plugin.StartupPlugin,
        octoprint.plugin.SettingsPlugin,
        octoprint.plugin.ProgressPlugin,
        octoprint.plugin.EventHandlerPlugin,
        #octoprint.plugin.AssetPlugin,
        octoprint.plugin.TemplatePlugin):

    ##~~ SettingsPlugin mixin

    def get_settings_defaults(self):
        return dict(token=None, room=None, api_url="https://api.hipchat.com")

    ##~~ AssetPlugin mixin

    def get_assets(self):
        # Define your plugin's asset files to automatically include in the
        # core UI here.
        return dict(js=["js/hipchat.js"],
                    css=["css/hipchat.css"],
                    less=["less/hipchat.less"])

    ##~~ Softwareupdate hook

    def get_update_information(self):
        # Define the configuration for your plugin to use with the Software Update
        # Plugin here. See https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update
        # for details.
        return dict(hipchat=dict(
            displayName="Hipchat Plugin",
            displayVersion=self._plugin_version,

            # version check: github repository
            type="github_release",
            user="******",
            repo="OctoPrint-HipChat",
            current=self._plugin_version,

            # update method: pip
            pip=
            "https://github.com/jabbrwcky/OctoPrint-HipChat/archive/{target_version}.zip"
        ))

    def get_template_configs(self):
        return [dict(type="settings", custom_bindings=False, name="HipChat")]

    def on_settings_save(self, data):
        octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
        self.connect_to_hipchat()

    def on_after_startup(self):
        token = self._settings.get(["token"])
        endpoint = self._settings.get(["api_url"])
        room = self._settings.get(["room"])

        self.connect_to_hipchat()

        if self.hc:
            self.room().notification(color="gray",
                                     message="OctoPrint started.")

        self._logger.info("HipChat notification plugin started.")

    def on_event(self, event, payload):
        if event == "PrintStarted":
            job = self._printer.get_current_job()
            self.room().notification(
                color="green",
                message="Printing of file %s started. EPT: %f.2" %
                (job["name"], payload["estimatedPrintTime"]))
        elif event == "PrintFailed":
            self.room().notification(
                color="red",
                message="Printing of file %s from %s failed." %
                (payload["file"], payload["origin"]))
        elif event == "PrintDone":
            self.room().notification(
                color="green",
                message=
                "Printing of file %s from %s has finished. Printing time: %f.2"
                % (payload["file"], payload["origin"], payload["time"]))
        elif event == "PrintCancelled":
            self.room().notification(
                color="red",
                message="Printing of file %s from %s has been cancelled." %
                (payload["file"], payload["origin"]))
        elif event == "PrintResumed":
            self.room().notification(
                color="greed",
                message="Printing of file %s from %s has been resumed." %
                (payload["file"], payload["origin"]))
        elif event == "PrintPaused":
            self.room().notification(
                color="yellow",
                message="Printing of file %s from %s has been paused." %
                (payload["file"], payload["origin"]))
        else:
            self._logger.debug("Event: %s => %s" % (event, payload))

    def on_print_progress(self, location, path, progress):
        self._logger.info(progress)
        if progress % 25 == 0:
            self._logger.info(self._printer.get_current_job())
            self.room().notification(
                color="gray",
                message="Printjob (%s from %s): %d%% complete." %
                (path, location, progress))

    def on_slicing_progress(self, slicer, source_location, source_path,
                            destination_location, destination_path, progress):
        pass

    def connect_to_hipchat(self):
        token = self._settings.get(["token"])
        endpoint = self._settings.get(["api_url"])
        room = self._settings.get(["room"])
        if token and room:
            self.hc = HypChat(token, endpoint=endpoint)
            self.room = lambda: self.hc.get_room(room)
            self._logger.info("Publishing to room %s via API endpoint %s" %
                              (room, endpoint))
        else:
            self.logger.warning(
                "Token and/or Room not set! Not connecting to HipChat. Please configure API TOken and HipChat room in the plugin settings."
            )
class HypchatHistory:
    """ might as well use a class. It'll make things easier later. """
    def __init__(self):
        """ init method, run at class creation """
        endpoint, token = self._get_token_endpoint()
        if token is None:
            raise SystemExit('Authorization token not detected! The token is '
                             'pulled from ~/.hypchat, /etc/hypchat, or the '
                             'environment variable HIPCHAT_TOKEN.')
        logger.debug("Connecting to HipChat (endpoint=%s)", endpoint)
        self.hipchat = HypChat(token, endpoint)
        logger.debug("Connected")

    def _get_token_endpoint(self):
        """get the API token - pulled from HypChat __main__.py"""
        token = None
        endpoint = None
        config = ConfigParser.ConfigParser()
        config.read([os.path.expanduser('~/.hypchat'), '/etc/hypchat'])

        # get token
        if config.has_section('HipChat'):
            token = config.get('HipChat', 'token')
        elif 'HIPCHAT_TOKEN' in os.environ:
            token = os.environ['HIPCHAT_TOKEN']

        # get endpoint
        if config.has_section('HipChat'):
            endpoint = config.get('HipChat', 'endpoint')
        elif 'HIPCHAT_ENDPOINT' in os.environ:
            endpoint = os.environ['HIPCHAT_ENDPOINT']
        else:
            endpoint = 'https://www.hipchat.com'
        return (endpoint, token)

    def _get_dates(self, hx_date, tz_name):
        """
        return start and end  datetimes for the given date string and TZ name
        """
        tz = timezone(tz_name)
        m = re.match(r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})',
                     hx_date)
        if m is None:
            raise SystemExit("ERROR: date must match YYYY-MM-DD format.")
        year = int(m.group('year'))
        month = int(m.group('month'))
        day = int(m.group('day'))
        start_dt = datetime(year, month, day, 0, 0, 0, tzinfo=tz)
        end_dt = datetime(year, month, day, 23, 59, 59, tzinfo=tz)
        return (start_dt, end_dt)

    def _get_hx(self, room, start_dt, end_dt):
        """
        HypChat's Room.history() method only takes a ``date`` argument, which
        fetches ALL history up to that date. We just want a specific date...
        """
        start_date, start_tz = mktimestamp(start_dt)
        end_date, end_tz = mktimestamp(end_dt)
        params = {
            'date': end_date,
            'end-date': start_date,
            'timezone': start_tz,
            'max-results': 1000,
        }
        resp = room._requests.get(room.url + '/history', params=params)
        return Linker._obj_from_text(resp.text, room._requests)

    def _dump_json(self, items):
        """print json"""
        json_items = []
        for i in items:
            i['date'] = str(i['date'])
            json_items.append(i)
            print(json.dumps(json_items))

    def _format_message(self, msg):
        from_s = ''
        if isinstance(msg['from'], dict):
            from_s = '@' + msg['from']['mention_name']
        else:
            from_s = msg['from'].encode('utf-8')
        date_s = msg['date'].strftime('%H:%M:%S')
        return "%s %s: %s" % (date_s, from_s, msg['message'].encode('utf-8'))

    def run(self, room_name, hx_date, tz_name='UTC', json_out=False):
        """ do stuff here """
        room = self.hipchat.get_room(room_name)
        start_dt, end_dt = self._get_dates(hx_date, tz_name)
        hx = self._get_hx(room, start_dt, end_dt)
        all_items = []
        for item in hx.contents():
            all_items.append(item)
        if json_out:
            self._dump_json(all_items)
            return
        for item in all_items:
            print(self._format_message(item))
Exemplo n.º 7
0
  outFile.write('\n')

if __name__ == '__main__':
  hc = HypChat(AUTH_TOKEN)

  startIndex = 0
  indexInterval = 150
  previousDate = 0
  totalTime = 0
  now = datetime.datetime.utcnow()

  totalContents = []

  # Get 8 * 150 results from the given room.
  for i in range(8):
    response = hc.get_room(roomId).history(now, maxResults=150, startIndex=startIndex)
    contents = list(response.contents())
    totalContents[:0] = contents
    startIndex += indexInterval
  for l in totalContents:
    date = l['date']
    name = l['from']

    # Plugins, such as Inc or Linky, do not produce actual names
    # So we remove them from the data
    if type(name) == unicode or type(name) == NoneType:
      continue
    
    name = name['name']
    name = name.split()[0].lower()
    if name not in allowedNames:
Exemplo n.º 8
0
Arquivo: async.py Projeto: exu/poligon
import asyncio
import datetime


from hypchat import HypChat
from os.path import expanduser
import datetime


def get_api_key():
    return open(api_file, 'r').read(40)


api_file = expanduser("~/.hypchat")
hc = HypChat(get_api_key())
room = hc.get_room("BotTest")
analyzed = []

def get_history():
    return list(room.history().contents())

def analyze(items):

    print(items)
    for item in items:
        analyzed.append(item["id"])
        mess = room.message("@response '" + item['message'] + "; looks weak!")
        print(mess)

    # print(analyzed)
Exemplo n.º 9
0
class HipMessage(object):
    '''
    Class that gets all messages from a given room, filters them through
    the classes from filter_classes and returns them when get_newest_messages
    is called.
    '''

    # A class that has implemented two methods
    #   - set_last_message_id(self._room_name, )
    #   - get_last_message_id()
    message_backend_class = None

    # Iterable of filter classes.
    # All messages will be passed through the is_ok method of this
    # classes and will include them only if the return Value is True
    filter_classes = None

    def __init__(self, token, room_name):
        self._token = token
        self._room_name = room_name
        self._hipchat_client = HypChat(token)
        self._room = self._hipchat_client.get_room(self.get_room_id(room_name))
        self._message_backend = self.message_backend_class(self._room_name)

    def get_room_id(self, room_name):
        rooms = self._hipchat_client.rooms()
        filtered_rooms = filter(lambda room: room['name'] == self._room_name,
                                rooms['items'])
        if not filtered_rooms:
            raise ValueError('No room with name {}'.format(self._room_name))

        return filtered_rooms[0]['id']

    def is_message_valid(self, message):
        if self.filter_classes:
            return all(
                map(lambda cls: cls().is_ok(message), self.filter_classes))
        return True

    def process_complete_history(self):
        date = datetime.datetime.utcnow()
        newest_id = None

        while True:
            messages_count = 0
            messages = self._room.history(maxResults=1000,
                                          date=date,
                                          reverse=False)
            for message in messages['items']:
                messages_count += 1
                if self.is_message_valid(message) is False:
                    continue

                self.process_message(message)
                newest_id = newest_id or message['id']

            date = message['date']

            if messages_count < 1000:
                return newest_id

    def get_newest_messages(self, max_results=500):
        last_message_id = self._message_backend.get_last_message_id()

        params = {}
        if last_message_id is not None:
            params = {'not_before': last_message_id}
        else:
            newest_id = self.process_complete_history()
            self._message_backend.set_last_message_id(newest_id)
            return

        last_message = None
        # The messages come in the order oldest to newest
        for msg in self._room.latest(**params)['items']:
            if self.is_message_valid(msg):
                self.process_message(msg)
                last_message = msg

        if last_message is not None:
            self._message_backend.set_last_message_id(last_message['id'])

    def process_message(self, msg):
        '''
        This is the method you override in your derived class.
        Method that takes as only argument a message and processes it.
        '''

    def run(self):
        self.get_newest_messages()
Exemplo n.º 10
0
class HipMessage(object):
    '''
    Class that gets all messages from a given room, filters them through
    the classes from filter_classes and returns them when get_newest_messages
    is called.
    '''

    # A class that has implemented two methods
    #   - set_last_message_id(self._room_name, )
    #   - get_last_message_id()
    message_backend_class = None

    # Iterable of filter classes.
    # All messages will be passed through the is_ok method of this
    # classes and will include them only if the return Value is True
    filter_classes = None

    def __init__(self, token, room_name):
        self._token = token
        self._room_name = room_name
        self._hipchat_client = HypChat(token)
        self._room = self._hipchat_client.get_room(self.get_room_id(room_name))
        self._message_backend = self.message_backend_class(self._room_name)

    def get_room_id(self, room_name):
        rooms = self._hipchat_client.rooms()
        filtered_rooms = filter(
            lambda room: room['name'] == self._room_name, rooms['items'])
        if not filtered_rooms:
            raise ValueError('No room with name {}'.format(self._room_name))

        return filtered_rooms[0]['id']

    def is_message_valid(self, message):
        if self.filter_classes:
            return all(
                map(lambda cls: cls().is_ok(message), self.filter_classes))
        return True

    def process_complete_history(self):
        date = datetime.datetime.utcnow()
        newest_id = None

        while True:
            messages_count = 0
            messages = self._room.history(
                maxResults=1000, date=date, reverse=False)
            for message in messages['items']:
                messages_count += 1
                if self.is_message_valid(message) is False:
                    continue

                self.process_message(message)
                newest_id = newest_id or message['id']

            date = message['date']

            if messages_count < 1000:
                return newest_id

    def get_newest_messages(self, max_results=500):
        last_message_id = self._message_backend.get_last_message_id()

        params = {}
        if last_message_id is not None:
            params = {'not_before': last_message_id}
        else:
            newest_id = self.process_complete_history()
            self._message_backend.set_last_message_id(newest_id)
            return

        last_message = None
        # The messages come in the order oldest to newest
        for msg in self._room.latest(**params)['items']:
            if self.is_message_valid(msg):
                self.process_message(msg)
                last_message = msg

        if last_message is not None:
            self._message_backend.set_last_message_id(last_message['id'])

    def process_message(self, msg):
        '''
        This is the method you override in your derived class.
        Method that takes as only argument a message and processes it.
        '''

    def run(self):
        self.get_newest_messages()
Exemplo n.º 11
0
hipchat_uri = os.environ.get("TWITCH_HIPCHAT_BASE_URI", "")
hipchat_room = os.environ.get("TWITCH_HIPCHAT_ROOM", "")

if "" in [token, twitch_games, hipchat_uri, hipchat_room]:
    if token == "":
        logging.error("The Environment variable TWITCH_HIPCHAT_TOKEN_V2 is missing")
    if twitch_games == [""]:
        logging.error("The Environment variable TWITCH_GAMES is missing")
    if hipchat_uri == "":
        logging.error("The Environment variable TWITCH_HIPCHAT_BASE_URI is missing")
    if hipchat_room == "":
        logging.error("The Environment variable TWITCH_HIPCHAT_ROOM is missing")
    sys.exit(1)

hipchat_connection = HypChat(token, hipchat_uri)
twitch_room = hipchat_connection.get_room(hipchat_room)
stream_monitor = sched.scheduler(time.time, time.sleep)
logging.basicConfig(level=logging.INFO)

active_streams = {}


def main():
    twitch_room.notification("Twitch Monitor has started on {}".format(socket.gethostname()), "green", "False", "text")
    logging.info("Twitch Monitor has started on {}".format(socket.gethostname()))

    try:
        for game in twitch_games:
            # suppress notifications for first run so we don't spam the channel
            update_active_streams(game, True)
        while True:
Exemplo n.º 12
0
class HipchatPlugin(octoprint.plugin.StartupPlugin,
					octoprint.plugin.SettingsPlugin,
					octoprint.plugin.ProgressPlugin,
					octoprint.plugin.EventHandlerPlugin,
					#octoprint.plugin.AssetPlugin,
					octoprint.plugin.TemplatePlugin):

	##~~ SettingsPlugin mixin

	def get_settings_defaults(self):
		return dict(
			token=None,
			room=None,
			api_url="https://api.hipchat.com"
		)

	##~~ AssetPlugin mixin

	def get_assets(self):
		# Define your plugin's asset files to automatically include in the
		# core UI here.
		return dict(
			js=["js/hipchat.js"],
			css=["css/hipchat.css"],
			less=["less/hipchat.less"]
		)

	##~~ Softwareupdate hook

	def get_update_information(self):
		# Define the configuration for your plugin to use with the Software Update
		# Plugin here. See https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update
		# for details.
		return dict(
			hipchat=dict(
				displayName="Hipchat Plugin",
				displayVersion=self._plugin_version,

				# version check: github repository
				type="github_release",
				user="******",
				repo="OctoPrint-HipChat",
				current=self._plugin_version,

				# update method: pip
				pip="https://github.com/jabbrwcky/OctoPrint-HipChat/archive/{target_version}.zip"
			)
		)

	def get_template_configs(self):
		return [
			dict(type="settings", custom_bindings=False, name="HipChat")
		]

	def on_settings_save(self, data):
		octoprint.plugin.SettingsPlugin.on_settings_save(self,data)
		self.connect_to_hipchat()

	def on_after_startup(self):
		token = self._settings.get(["token"])
		endpoint= self._settings.get(["api_url"])
		room = self._settings.get(["room"])

		self.connect_to_hipchat()

		if self.hc:
			self.room().notification(color="gray", message="OctoPrint started.")

		self._logger.info("HipChat notification plugin started.")

	def on_event(self, event, payload):
		if event == "PrintStarted":
			job = self._printer.get_current_job()
			self.room().notification(color="green", message="Printing of file %s started. EPT: %f.2" % (job["name"], payload["estimatedPrintTime"]))
		elif event == "PrintFailed":
			self.room().notification(color="red", message="Printing of file %s from %s failed." % (payload["file"], payload["origin"]))
		elif event == "PrintDone":
			self.room().notification(color="green", message="Printing of file %s from %s has finished. Printing time: %f.2" % (payload["file"], payload["origin"], payload["time"]))
		elif event == "PrintCancelled":
			self.room().notification(color="red", message="Printing of file %s from %s has been cancelled." % (payload["file"], payload["origin"]))
		elif event == "PrintResumed":
			self.room().notification(color="greed", message="Printing of file %s from %s has been resumed." % (payload["file"], payload["origin"]))
		elif event == "PrintPaused":
			self.room().notification(color="yellow", message="Printing of file %s from %s has been paused." % (payload["file"], payload["origin"]))
		else:
			self._logger.debug("Event: %s => %s" % ( event, payload ))

	def on_print_progress(self, location, path, progress):
		self._logger.info(progress)
		if progress % 25 == 0:
			self._logger.info(self._printer.get_current_job())
			self.room().notification(color="gray", message="Printjob (%s from %s): %d%% complete." % (path, location, progress))

	def on_slicing_progress(self, slicer, source_location, source_path, destination_location, destination_path, progress):
		pass

	def connect_to_hipchat(self):
		token = self._settings.get(["token"])
		endpoint= self._settings.get(["api_url"])
		room = self._settings.get(["room"])
		if token and room:
			self.hc = HypChat(token, endpoint=endpoint)
			self.room = lambda: self.hc.get_room(room)
			self._logger.info("Publishing to room %s via API endpoint %s" % (room, endpoint))
		else:
			self.logger.warning("Token and/or Room not set! Not connecting to HipChat. Please configure API TOken and HipChat room in the plugin settings.")
Exemplo n.º 13
0
class HypeBot(ClientXMPP):
    def __init__(self, config_file):
        # setup configuration
        self.config = ConfigParser.RawConfigParser()
        self.config.read(config_file)

        self.user_nickname = self.config.get(CONFIG_AUTH, 'user_nickname')
        self.user_jid = self.config.get(CONFIG_AUTH, 'user_jid')
        self.user_pwd = self.config.get(CONFIG_AUTH, 'user_pwd')
        self.user_api_token = self.config.get(CONFIG_AUTH, 'user_api_token')

        # setup xmpp client
        ClientXMPP.__init__(self, self.user_jid, self.user_pwd)

        self.add_event_handler("session_start", self.session_start)
        self.add_event_handler("message", self.message)

        # register plugins for additional functionality
        self.register_plugin('xep_0030')  # Service Discovery
        self.register_plugin('xep_0004')  # Data Forms
        self.register_plugin('xep_0045')  # MUC
        self.register_plugin('xep_0060')  # PubSub
        self.register_plugin('xep_0199')  # Ping

        # Setup message handler
        self.msg_handler = MessageHandler(self)

        # Setup HypChat api client
        self.hc = HypChat(self.user_api_token)

        # get jid to room map
        self.jid_to_room = dict()

        # Join rooms on startup
        startup_rooms = self.config.get(CONFIG_GENERAL, 'startup_rooms_to_join').split(',')
        for room in startup_rooms:
            self.join_room_by_name(room)

        print('Bot initialized')

    def session_start(self, event):
        self.get_roster()
        self.send_presence(ppriority=0)

        # enable keepalive, times are in seconds
        self.plugin['xep_0199'].enable_keepalive(interval=30, timeout=30)

    def populate_jid_to_room(self, room_name):
        room = self.hc.get_room(room_name)
        self.jid_to_room[room['xmpp_jid']] = room
        return room
        # rooms = self.hc.rooms()
        # room_list = list(rooms.contents())
        # for room in room_list:
        #     room_self = room.self()
        #     self.jid_to_room[room_self['xmpp_jid']] = room

    # Join a hipchat room
    def join_room(self, room_jid):
        self.plugin['xep_0045'].joinMUC(room_jid, self.user_nickname, maxhistory=None, wait=True)

    def join_room_by_name(self, room_name):
        # Populate a map from jid to room
        # and return the room at the same time
        # this should help with rate-limiting on api calls
        print("Joining room: " + room_name)
        room_to_join = self.populate_jid_to_room(room_name)
        if room_to_join is None:
            return False

        self.join_room(room_to_join['xmpp_jid'])
        return True

    def reply_room_name(self, room_name, body):
        room_to_reply = self.hc.get_room(room_name)
        if room_to_reply is None:
            return False
        self.send_message(mto=room_name, mbody=body, mtype='groupchat')
        return True

    def reply_room(self, msg, body):
        print(msg['from'].bare)
        self.send_message(mto=msg['from'].bare, mbody=body, mtype='groupchat')

    def message(self, msg):
        self.msg_handler.handle(msg)

    def notify_room_html(self, text, jid):
        self.jid_to_room[jid].notification(text, format='html')
Exemplo n.º 14
0
from hypchat import HypChat

hc = HypChat("yB4hIv2w4A6IziKVMB1nThhgrhWpLuoqX6Exv0Xn")
room = hc.get_room('2050370')
room.message('Hello World', "green")
Exemplo n.º 15
0
 def __init__(self, token, room_id):
     chat = HypChat(token)
     self._room = chat.get_room(room_id)
     self._latest_date = None
Exemplo n.º 16
0
 def send_message_to(self, room_id, message):
     hipchat = HypChat(self.token)
     room = hipchat.get_room(self.config.get_room_id('bot'))
     room.notification(message, color=self.config.color)
Exemplo n.º 17
0
class HypchatHistory:
    """ might as well use a class. It'll make things easier later. """

    def __init__(self):
        """ init method, run at class creation """
        endpoint, token = self._get_token_endpoint()
        if token is None:
            raise SystemExit('Authorization token not detected! The token is '
                             'pulled from ~/.hypchat, /etc/hypchat, or the '
                             'environment variable HIPCHAT_TOKEN.')
        logger.debug("Connecting to HipChat (endpoint=%s)", endpoint)
        self.hipchat = HypChat(token, endpoint)
        logger.debug("Connected")

    def _get_token_endpoint(self):
        """get the API token - pulled from HypChat __main__.py"""
        token = None
        endpoint = None
        config = ConfigParser.ConfigParser()
        config.read([os.path.expanduser('~/.hypchat'), '/etc/hypchat'])

        # get token
        if config.has_section('HipChat'):
            token = config.get('HipChat', 'token')
        elif 'HIPCHAT_TOKEN' in os.environ:
            token = os.environ['HIPCHAT_TOKEN']

        # get endpoint
        if config.has_section('HipChat'):
            endpoint = config.get('HipChat', 'endpoint')
        elif 'HIPCHAT_ENDPOINT' in os.environ:
            endpoint = os.environ['HIPCHAT_ENDPOINT']
        else:
            endpoint = 'https://www.hipchat.com'
        return (endpoint, token)

    def _get_dates(self, hx_date, tz_name):
        """
        return start and end  datetimes for the given date string and TZ name
        """
        tz = timezone(tz_name)
        m = re.match(r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})',
                     hx_date)
        if m is None:
            raise SystemExit("ERROR: date must match YYYY-MM-DD format.")
        year = int(m.group('year'))
        month = int(m.group('month'))
        day = int(m.group('day'))
        start_dt = datetime(year, month, day, 0, 0, 0, tzinfo=tz)
        end_dt = datetime(year, month, day, 23, 59, 59, tzinfo=tz)
        return (start_dt, end_dt)

    def _get_hx(self, room, start_dt, end_dt):
        """
        HypChat's Room.history() method only takes a ``date`` argument, which
        fetches ALL history up to that date. We just want a specific date...
        """
        start_date, start_tz = mktimestamp(start_dt)
        end_date, end_tz = mktimestamp(end_dt)
        params = {
            'date': end_date,
            'end-date': start_date,
            'timezone': start_tz,
            'max-results': 1000,
        }
        resp = room._requests.get(room.url + '/history', params=params)
        return Linker._obj_from_text(resp.text, room._requests)

    def _dump_json(self, items):
        """print json"""
        json_items = []
        for i in items:
            i['date'] = str(i['date'])
            json_items.append(i)
            print(json.dumps(json_items))

    def _format_message(self, msg):
        from_s = ''
        if isinstance(msg['from'], dict):
            from_s = '@' + msg['from']['mention_name']
        else:
            from_s = msg['from'].encode('utf-8')
        date_s = msg['date'].strftime('%H:%M:%S')
        return "%s %s: %s" % (date_s, from_s, msg['message'].encode('utf-8'))

    def run(self, room_name, hx_date, tz_name='UTC', json_out=False):
        """ do stuff here """
        room = self.hipchat.get_room(room_name)
        start_dt, end_dt = self._get_dates(hx_date, tz_name)
        hx = self._get_hx(room, start_dt, end_dt)
        all_items = []
        for item in hx.contents():
            all_items.append(item)
        if json_out:
            self._dump_json(all_items)
            return
        for item in all_items:
            print(self._format_message(item))
Exemplo n.º 18
0
if repo_path == None:
    print 'Must enter a Git repository path. Exiting.'
    exit(-1)

# Set up HipChat stuff
hipchat_access_token = options.hipchat_token
hipchat_room_name = options.hipchat_room
hc = None
hc_room = None

if hipchat_access_token != None:
    do_hipchat = True
    print 'Will be sending messages to HipChat room: ' + hipchat_room_name
    hc = HypChat(hipchat_access_token)
    hc_room = hc.get_room(hipchat_room_name)

# Set up Slack stuff
slack_access_token = options.slack_token
slack_room_name = options.slack_room
slack = None

if slack_access_token != None:
    do_slack = True
    print 'Will be sending message to Slack channel: ' + slack_room_name
    slack = Slacker(slack_access_token)

# Set up JIRA stuff
jira_url = options.jira_url
jira_project = None
jira_connection = None