예제 #1
0
class HipChatBot(object):
    def __init__(self, options):
        self.options = options
        self.hc = HypChat(options["token"])
        self.hc.capabilities.url = "{hipchat}/capabilities".format(
            hipchat=self.options["server"])
        self.hc.emoticons.url = "{hipchat}/emoticon".format(
            hipchat=self.options["server"])
        self.hc.rooms.url = "{hipchat}/room".format(
            hipchat=self.options["server"])
        self.hc.users_url = "{hipchat}/user".format(
            hipchat=self.options["server"])

    def msg_to_rooms(self, text, format="text", color="gray"):
        for name in self.options["rooms"]:
            url = "{hipchat}/room/{room}".format(
                hipchat=self.options["server"], room=name)
            room = Room(self.hc.fromurl(url))
            room._requests = self.hc._requests
            room.message(message=text, format=format, notify="0", color=color)

    def msg_to_users(self, text):
        for name in self.options["users"]:
            full_name = "%s@%s" % (name, self.options["domain"])
            url = "{hipchat}/user/{user}".format(
                hipchat=self.options["server"], user=full_name)
            user = User(self.hc.fromurl(url))
            user._requests = self.hc._requests
            user.message(text)
예제 #2
0
파일: alert.py 프로젝트: Labgoo/cabot
def _send_hipchat_alert(message, color='green'):
    room_id = int(settings.HIPCHAT_ALERT_ROOM)
    api_key = settings.HIPCHAT_API_KEY
    hc = HypChat(api_key)
    rooms = hc.rooms()
    room = filter(lambda x: x['id'] == room_id, rooms['items'])[0]
    room.message(message, color=color, notify=True, format='text')
예제 #3
0
 def start(self):
     if not self.__config['token'] or not self.__config['endpoint']:
         print("HipChat configuration is missing %s" % self.__config)
         raise AttributeError
     elif self.__config['endpoint']:
         return HypChat(self.__config['token'], endpoint=self.__config['endpoint'])
     else:
         return HypChat(self.__config['token'])
예제 #4
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))
 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")
예제 #6
0
def send_notify(data):

    hp = HypChat(__token__)
    for user in __users__:
        try:
            t_user = hp.get_user(user)
            message = wrap(data)
            t_user.message(message)
        except Exception as e:
            print e
    return True
예제 #7
0
 def __init__(self, options):
     self.options = options
     self.hc = HypChat(options["token"])
     self.hc.capabilities.url = "{hipchat}/capabilities".format(
         hipchat=self.options["server"])
     self.hc.emoticons.url = "{hipchat}/emoticon".format(
         hipchat=self.options["server"])
     self.hc.rooms.url = "{hipchat}/room".format(
         hipchat=self.options["server"])
     self.hc.users_url = "{hipchat}/user".format(
         hipchat=self.options["server"])
예제 #8
0
파일: notify.py 프로젝트: chenyuntc/crawler
def send_notify(data):

    hp = HypChat(__token__)
    for user in __users__:
        try:
            t_user = hp.get_user(user)
            message=wrap(data)
            t_user.message(message)
        except Exception as e:
            print e
    return True
예제 #9
0
 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."
         )
예제 #10
0
 def __init__(self,
              access_token,
              room_name,
              endpoint='https://api.hipchat.com',
              notification_only=False):
     logging.Handler.__init__(self)
     if notification_only:
         self.notification = partial(HypChat(access_token,
                                             endpoint).send_notification,
                                     id_or_name=room_name)
     else:
         self.notification = partial(
             HypChat(access_token,
                     endpoint).get_room(room_name).notification)
예제 #11
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']
예제 #12
0
    def safe_init(self):
        self.channels = {}
        self.adapter_redis = DWhoAdapterRedis(self.config, prefix='hipchat')

        if 'hipchat' not in self.config['plugins']:
            return

        for channel, params in self.config['plugins']['hipchat'].iteritems():
            self.channels[channel] = {
                'conn': HypChat(**params['options']),
                'id': None,
                'name':
                "%s://%s/%s" % (self.PLUGIN_NAME, channel, params['room']),
                'room': params['room'],
                'token': params['options']['token'],
                'out': params['out'],
                'me': None,
                'storage': self.adapter_redis
            }

            ref_chan = self.channels[channel]
            ref_chan['me'] = ref_chan['conn'].fromurl(
                '{0}/v2/oauth/token/{1}'.format(ref_chan['conn'].endpoint,
                                                ref_chan['token']))
            CHANNELS.register(BotbondChannel(ref_chan))
예제 #13
0
 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")
예제 #14
0
	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.")
예제 #15
0
class HipChatHandler(logging.Handler):

    def __init__(self, access_token, room_name, endpoint='https://api.hipchat.com'):
        logging.Handler.__init__(self)
        self.room = HypChat(access_token, endpoint).get_room(room_name)

    def emit(self, record):
        if hasattr(record, "color"):
            color = record.color
        else:
            color = self.__color_for_level(record.levelno)
        if hasattr(record, "notify"):
            notify = bool(record.notify)
        else:
            notify = self.__notify_for_level(record.levelno)
        print 'calling emit'
        self.room.notification(
            message=self.format(record),
            color=color,
            notify=notify
        )

    def __color_for_level(self, levelno):
        if levelno > logging.WARNING:
            return 'red'
        if levelno == logging.WARNING:
            return 'yellow'
        if levelno == logging.INFO:
            return 'green'
        if levelno == logging.DEBUG:
            return 'gray'
        return 'purple'

    def __notify_for_level(self, levelno):
        if levelno > logging.WARNING:
            return True
        if levelno == logging.WARNING:
            return False
        if levelno == logging.INFO:
            return False
        if levelno == logging.DEBUG:
            return False
        return False
예제 #16
0
class HipChatHandler(logging.Handler):
    def __init__(self,
                 access_token,
                 room_name,
                 endpoint='https://api.hipchat.com'):
        logging.Handler.__init__(self)
        self.room = HypChat(access_token, endpoint).get_room(room_name)

    def emit(self, record):
        if hasattr(record, "color"):
            color = record.color
        else:
            color = self.__color_for_level(record.levelno)
        if hasattr(record, "notify"):
            notify = bool(record.notify)
        else:
            notify = self.__notify_for_level(record.levelno)
        self.room.notification(message=self.format(record),
                               color=color,
                               notify=notify)

    def __color_for_level(self, levelno):
        if levelno > logging.WARNING:
            return 'red'
        if levelno == logging.WARNING:
            return 'yellow'
        if levelno == logging.INFO:
            return 'green'
        if levelno == logging.DEBUG:
            return 'gray'
        return 'purple'

    def __notify_for_level(self, levelno):
        if levelno > logging.WARNING:
            return True
        if levelno == logging.WARNING:
            return False
        if levelno == logging.INFO:
            return False
        if levelno == logging.DEBUG:
            return False
        return False
예제 #17
0
    def __init__(self, jid, password):
        super(HipChat, self).__init__(jid, password)
        self.register_plugin('xep_0030')  # Service Discovery
        self.register_plugin('xep_0045')  # Multi-User Chat
        self.register_plugin('xep_0004')  # Multi-User Chat backward compability (necessary for join room)
        self.register_plugin('xep_0199')  # XMPP Ping
        self.register_plugin('xep_0203')  # XMPP Delayed messages
        self.register_plugin('xep_0249')  # XMPP direct MUC invites
        self.register_plugin('xep_0060')  # PubSub
        # self.register_plugin('xep_0071')

        self.auto_authorize = True
        self.auto_subscribe = True
        self.whitespace_keepalive = True
        self.whitespace_keepalive_interval = 60
        self.end_session_on_disconnect = False

        self.ca_certs = '/etc/ssl/certs/ca-certificates.crt'

        self.add_event_handler('session_start', self.session_start)
        self.add_event_handler('message', self.handle_message)
        self.add_event_handler('groupchat_invite', self.auto_accept_invite)

        zmq_thread = threading.Thread(target=self.zmq_handler)
        zmq_thread.daemon = True
        zmq_thread.start()

        self.rooms = []

        self.api_conn = HypChat(TOKEN)

        self.rooms_in_hipchat = self.api_conn.rooms(expand='items')

        with file('./rooms.json', 'r') as fp:
            try:
                self.rooms = json.load(fp)
            except ValueError as _:
                self.rooms = []

        self.recovery_rooms_on_startup(self.rooms)
예제 #18
0
    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')
예제 #19
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']
예제 #20
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."
            )
예제 #21
0
from hypchat import HypChat

hc = HypChat("yB4hIv2w4A6IziKVMB1nThhgrhWpLuoqX6Exv0Xn")
room = hc.get_room('2050370')
room.message('Hello World', "green")
예제 #22
0
 def __init__(self):
     self.rooms = ['Kemono - Production Deploy Notification']
     self.color = 'green'
     self.is_notify = False
     self.hip_chat = HypChat(self._get_token())
예제 #23
0
def get_hipchat_users():
    config = settings.load()
    raw_users = HypChat(config['hipchat']['token']).users()
    return raw_users['items']
예제 #24
0
 def __init__(self, token, room_id):
     chat = HypChat(token)
     self._room = chat.get_room(room_id)
     self._latest_date = None
예제 #25
0
def get_client(config):
    client = HypChat(config.get('hipchat', 'token'))
    return client
예제 #26
0
 def __init__(self):
     self.rooms = ['Kemono - Production Deploy Notification']
     self.color = 'green'
     self.is_notify = False
     self.hip_chat = HypChat(self._get_token())
예제 #27
0
 def __init__(self, access_token, room_name, endpoint='https://api.hipchat.com'):
     logging.Handler.__init__(self)
     self.room = HypChat(access_token, endpoint).get_room(room_name)
예제 #28
0
#! /usr/bin/env python
# coding: utf-8
# LICENSE:
# Date:
# Author: konglx
# File:
# Description:

__author__ = 'Konglx'

from hypchat import HypChat
from tombot.common.log import logger

TOKEN = 'DZttvKCWeU4GpXxoqwJc4IG8bH636MjaCmLNZqc8'

hc = HypChat(TOKEN)

logger.debug('Hipchat rooms: {0}'.format(hc.rooms()))
logger.debug('Hipchat users: {0}'.format(hc.users()))
예제 #29
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()
예제 #30
0
from dateutil.tz import tzutc
from hypchat import HypChat
import time
import json
import re
import os
from collections import OrderedDict

secret_path = sys.argv[1]

with open(secret_path) as secretf:
    token = secretf.read().rstrip()

CUTOFF_DATE = datetime.datetime(2016, 1, 1, tzinfo=tzutc())

hc = HypChat(token)


def get_active_rooms():
    rooms = hc.rooms()
    active_rooms = []
    for room in rooms['items']:
        if room['is_archived'] or re.search("Bot:|Meetings ::", room['name']):
            print("skipping " + room['name'])
            continue
        time.sleep(2)  # API rate limiting
        active_room = hc.get_room(room['id'])
        if active_room[
                'last_active'] and active_room['last_active'] > CUTOFF_DATE:
            print("appending room: " + active_room['name'])
            active_rooms.append(active_room)
예제 #31
0
 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)
예제 #32
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()
예제 #33
0
twitch_games = os.environ.get("TWITCH_GAMES", "").split(";")
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)
예제 #34
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
예제 #35
0
class JiraService:
    def __init__(self):
        self.jira = JIRA(server=os.environ['JIRA_INSTANCE'], basic_auth=(os.environ['JIRA_USER'], os.environ['JIRA_PASSWORD']))
        self.hipchat = HypChat(os.environ['HIPCHAT_TOKEN'], endpoint = "https://puppet.hipchat.com")

        # map of <field-id> -> <field-name>, used to make querying custom fields more readable.
        self.name_map = {field['id'] : field['name'] for field in self.jira.fields()}

    # applies the passed-in JQL filter and returns an array of tickets that match it
    def get_tickets(self, search_filter):
        def process_ticket(ticket):
            ticket_fields = self.get_fields(ticket)
            return {
                "ticket" : ticket.key,
                "status" : ticket_fields["Status"]["name"]
            }

        return [process_ticket(ticket) for ticket in self.jira.search_issues(search_filter)]

    # returns a dictionary with the following keys:
    #   (1) involved_devs
    #         Nested structure with the following keys:
    #            -Everything that dev_info returns
    #            -category (Either "Assignee", "Watcher", or "Reporter", in that order)
    #   (2) team
    #         Lists the team associated with the ticket
    #
    # NOTE: Some puppet employees might have their e-mails end in @puppetlabs.com instead of
    # @puppet.com -- if this happens, then the code should be modified to try both e-mails when
    # acquiring the dev info.
    #
    # TODO: What if ticket does not have a field? E.g. No team, no assignee, etc. Handle this
    # case!
    def ticket_info(self, ticket):
        def involved_dev_info(involved_dev, category):
            dev_info = self.dev_info("*****@*****.**" % involved_dev['key'])
            dev_info['category'] = category
            return dev_info

        ticket_info = self.get_fields(self.jira.issue(ticket))
        ticket_watchers = self.jira.watchers(ticket)

        # calculate the involved devs
        (assignee, reporter) = tuple(
            [[involved_dev_info(ticket_info[dev_type], dev_type)] if ticket_info[dev_type] else [] for dev_type in ("Assignee", "Reporter")]
        )
        watchers = [involved_dev_info(watcher.raw, "Watcher") for watcher in ticket_watchers.watchers]
        return {
            "involved_devs" : assignee + watchers + reporter,
            "team" : ticket_info["Team"]["value"] if ticket_info["Team"] else None
        }

    # returns a dictionary with the following keys:
    #   (1) name
    #   (2) email
    #   (3) hipchat_alias
    def dev_info(self, dev_email):
        hipchat_info = self.hipchat.get_user(dev_email)
        return {
            'name' : hipchat_info['name'],
            'email' : dev_email,
            'hipchat_alias' : hipchat_info['mention_name']
        }

    # TODO: Make this private after everything's tested
    def get_fields(self, jira_issue):
        return {self.name_map[field_id] : field_value for field_id, field_value in jira_issue.raw['fields'].items()}
예제 #36
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)
예제 #37
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.")
예제 #38
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))
예제 #39
0
class HipChat(ClientXMPP):
    def __init__(self, jid, password):
        super(HipChat, self).__init__(jid, password)
        self.register_plugin('xep_0030')  # Service Discovery
        self.register_plugin('xep_0045')  # Multi-User Chat
        self.register_plugin('xep_0004')  # Multi-User Chat backward compability (necessary for join room)
        self.register_plugin('xep_0199')  # XMPP Ping
        self.register_plugin('xep_0203')  # XMPP Delayed messages
        self.register_plugin('xep_0249')  # XMPP direct MUC invites
        self.register_plugin('xep_0060')  # PubSub
        # self.register_plugin('xep_0071')

        self.auto_authorize = True
        self.auto_subscribe = True
        self.whitespace_keepalive = True
        self.whitespace_keepalive_interval = 60
        self.end_session_on_disconnect = False

        self.ca_certs = '/etc/ssl/certs/ca-certificates.crt'

        self.add_event_handler('session_start', self.session_start)
        self.add_event_handler('message', self.handle_message)
        self.add_event_handler('groupchat_invite', self.auto_accept_invite)

        zmq_thread = threading.Thread(target=self.zmq_handler)
        zmq_thread.daemon = True
        zmq_thread.start()

        self.rooms = []

        self.api_conn = HypChat(TOKEN)

        self.rooms_in_hipchat = self.api_conn.rooms(expand='items')

        with file('./rooms.json', 'r') as fp:
            try:
                self.rooms = json.load(fp)
            except ValueError as _:
                self.rooms = []

        self.recovery_rooms_on_startup(self.rooms)

    def send_api_message(self, room_id, fr, message, message_format='html'):
        base = {'format': 'json', 'auth_token': self.token}
        red_data = {'room_id': room_id, 'from': fr, 'message': utf8(message), 'message_format': message_format}
        req = Request(url=HIPCHAT_MESSAGE_URL + '?' + urlencode(base), data=urlencode(red_data))
        return json.load(urlopen(req))

    def recovery_rooms_on_startup(self, rooms):
        for room in rooms:
            muc = self.plugin['xep_0045']
            muc.joinMUC(room, nick=NICK_NAME, wait=True)

    def auto_accept_invite(self, message):
        room = message['from']
        muc = self.plugin['xep_0045']
        muc.joinMUC(room, nick=NICK_NAME, wait=True)
        self.rooms.append(str(room))
        logger.debug('Rooms: {}'.format(self.rooms))
        with open('./rooms.json', 'w') as fp:
            json.dump(self.rooms, fp)

    def session_start(self, event):
        self.get_roster()
        self.send_presence()

    def handle_message(self, message):
        type = message['type']
        if type not in ('chat', 'groupchat'):
            return
        content = message['body']
        message['from'] = re.sub(r'/.*$', '', str(message['from']))
        id = str(message['from'])
        # xmpp only, qq is different
        user = id

        msg = {'content': content.encode('utf-8'),
               'id': id,
               'type': type,
               'user': user}
        socket.send_json(msg)
        logger.info('send message to server: {}'.format(msg))

    def zmq_handler(self):
        while True:
            # xmppmsg = self.Message()
            message = socket.recv_json()
            # message = json.loads(message[0])
            if message['html']:
                logger.debug('hipchat receive html message {}'.format(message))
                # content = xhtml2hipchat(message['html'])
                room = self.get_room_by_jid(message['id'])
                content = message['content']
                room.notification(content, color='random', notify=True, format='html')
            else:
                logger.debug('hipchat receive message {}'.format(message))
                self.send_message(mto=message['id'],
                                  mbody=message['content'],
                                  mtype=message['type'])

    def get_room_by_jid(self, room_jid):
        for r in self.rooms_in_hipchat['items']:
            if r['xmpp_jid'] == room_jid:
                return r
        return None
예제 #40
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')
예제 #41
0
파일: hcmsg.py 프로젝트: maklaut/hcmsg
                    help="Show available rooms and exit")

args = parser.parse_args()

config = ConfigParser.RawConfigParser({'token': None, 'hipchat_url': HIPCHAT_DEFAULT_URL})
config.read(CONFIG_FILE)
token = config.get('DEFAULT', 'token')
HIPCHAT_URL = config.get('DEFAULT', 'hipchat_url')

if not token:
    print "Can't read token from config file {config}\n\nConfig example (don't forget chmod 600):\n" + \
          "[DEFAULT]\ntoken = 012345678901234567890\nhipchat_url = {url}".format(
              config=CONFIG_FILE, url=HIPCHAT_DEFAULT_URL)
    exit(1)

hc = HypChat(token)
hc.capabilities.url = '{hipchat}/capabilities'.format(hipchat=HIPCHAT_URL)
hc.emoticons.url = '{hipchat}/emoticon'.format(hipchat=HIPCHAT_URL)
hc.rooms.url = '{hipchat}/room'.format(hipchat=HIPCHAT_URL)
hc.users_url = '{hipchat}/user'.format(hipchat=HIPCHAT_URL)

if args.list_rooms:
    rooms = hc.rooms()
    i = 0
    if 'items' in rooms and rooms['items']:
        print 'Cnt\tID\tName'
        print '----\t----\t----'
        for room in rooms['items']:
            i += 1
            print '{num}:\t{id}\t{name_}'.format(num=i, id=room.id, name_=room.name)
    exit(0)
예제 #42
0
    def __init__(self):
        self.jira = JIRA(server=os.environ['JIRA_INSTANCE'], basic_auth=(os.environ['JIRA_USER'], os.environ['JIRA_PASSWORD']))
        self.hipchat = HypChat(os.environ['HIPCHAT_TOKEN'], endpoint = "https://puppet.hipchat.com")

        # map of <field-id> -> <field-name>, used to make querying custom fields more readable.
        self.name_map = {field['id'] : field['name'] for field in self.jira.fields()}
예제 #43
0
 def __init__(self,
              access_token,
              room_name,
              endpoint='https://api.hipchat.com'):
     logging.Handler.__init__(self)
     self.room = HypChat(access_token, endpoint).get_room(room_name)
예제 #44
0
파일: async.py 프로젝트: 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)
예제 #45
0
 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)
예제 #46
0

def writeLine(time, name, messageLength, timeDiff, timeSinceStart):
  outFile.write(str(time))
  outFile.write(',')
  outFile.write(name)
  outFile.write(',')
  outFile.write(str(messageLength))
  outFile.write(',')
  outFile.write(str(timeDiff))
  outFile.write(',')
  outFile.write(str(timeSinceStart))
  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
예제 #47
0
    branch = 'master'

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
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))