예제 #1
0
    def post(self, request, board_id):
        json_data = loads(request.body.decode('utf-8'))

        action = json_data['action']
        action_type = action['type']
        board = slugify(json_data['model']['name'])

        bridges = Bridge.objects.filter(board__id=board_id)
        if not bridges:
            print("no configuration for this board :: board={}".format(board))
            return HttpResponse()

        if action_type not in self.supported_action:
            print("trello action not implemented :: action={}".format(action_type))
            return HttpResponse()

        action_parser = getattr(self, action_type)
        payload = action_parser(action=action)

        for bridge in bridges:
            if action_type not in bridge.events:
                print("no subscribe for this action :: board={} :: action={}".format(board, action_type))
                continue

            try:
                print("subscribe for this action :: board={} :: action={}".format(board, action_type))
                mwh = Webhook(*bridge.webhook.incoming_webhook_url.split("/hooks/"))
                mwh.username = bridge.webhook.username
                mwh.icon_url = bridge.webhook.icon_url
                mwh.send(payload)
            except Exception as e:
                print("unable to send mattermost message :: {}".format(e))
            continue

        return HttpResponse()
예제 #2
0
파일: chats.py 프로젝트: cgwire/zou
def send_to_mattermost(webhook, userid, message):
    if webhook:
        if userid:
            try:
                arg = webhook.split("/")
                server = "%s%s//%s" % (arg[0], arg[1], arg[2])
                hook = arg[4]

                # mandatory parameters are url and your webhook API key
                mwh = Webhook(server, hook)
                mwh.username = "******" % (message["project_name"])
                mwh.icon_url = "%s://%s/img/kitsu.b07d6464.png" % (
                    config.DOMAIN_PROTOCOL,
                    config.DOMAIN_NAME,
                )

                # send a message to the API_KEY's channel
                mwh.send(message["message"], channel="@%s" % userid)

            except Exception:
                logger.info(
                    "Exception when sending a Mattermost notification:")
                logger.info(traceback.format_exc())
        else:
            logger.info("The userid of Mattermost user is not defined.")
    else:
        logger.info(
            "The webhook of Mattermost for sending notifications is not defined."
        )
예제 #3
0
class MongoopTrigger(BaseTrigger):

    def __init__(self, *args, **kwargs):
        super(MongoopTrigger, self).__init__(*args, **kwargs)

        self.mwh = Webhook(self.params['url'], self.params['api_key'])
        self.mwh.username = self.params.get('username', 'Mongoop')
        self.mwh.icon_url = self.params.get('icon_url', 'https://plugins.qgis.org/static/cache/c8/13/c813bff978535a743f63161bc3a7f937.png')

    def send_hook(self, message):
        try:
            self.mwh.send(message, channel=self.params['channel'])
            logging.info('run :: {}'.format(self.name))
        except Exception as e:
            logging.error('unable to run :: {} :: {}'.format(self.name, e))
            return False
        else:
            return True

    def op_nok(self, operations):
        for op in operations:
            payload = 'slow operation \n```json\n'
            for key, values in op.items():
                payload += '{}: {}\n'.format(key, values)
            payload += '```'
            self.send_hook(message=payload)

    def op_ok(self):
        return self.send_hook(message='op ok')

    def balancer_nok(self, state):
        return self.send_hook(message='balancer nok :: state={}'.format(state))

    def balancer_ok(self, state):
        return self.send_hook(message='balancer ok :: state={}'.format(state))
예제 #4
0
def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.

    response = exception_handler(exc, context)
    # Now add the HTTP status code to the response.

    if response is not None:
        response.data['status_code'] = response.status_code
    else:
        mwh = Webhook('https://meeting.ssafy.com',
                      'wx9hjk1nn3buxr9q7nb1yf1jar')
        json_data1 = json.dumps('##### SEVER ERROR')
        json_data2 = json.dumps(">" + str(exc), ensure_ascii=False)
        attachments = []
        message = {}
        message['color'] = '#88fc03'
        message[
            'image_url'] = 'https://about.mattermost.com/wp-content/uploads/2017/08/Mattermost-Logo-Blue.svg'
        markdown_msg = '##### SERVER ERROR OCCUR\n'
        markdown_msg += str(exc)
        message['text'] = markdown_msg
        attachments.append(message)
        mwh.send(attachments=attachments)

    return response
예제 #5
0
    def post_receive(self, alert):
        if alert.repeat:
            return

        mwh = Webhook(MATTERMOST_URL, MATTERMOST_TOKEN)
        mwh.username = MATTERMOST_USERNAME
        message = self._prepare_payload(alert)
        LOG.debug('Mattermost: %s', message)
        mwh.send(message)
예제 #6
0
    def post_receive(self, alert):
        if alert.repeat:
            return

        mwh = Webhook(MATTERMOST_URL, MATTERMOST_TOKEN)
        mwh.username = MATTERMOST_USERNAME
        message = self._prepare_payload(alert)
        LOG.debug('Mattermost: %s', message)
        mwh.send(message)
예제 #7
0
파일: bot.py 프로젝트: itsjw/captain_hook
class MattermostComm(BaseComm):
    def setup(self):
        c = self.config['webhook_url'].split('/hooks/')
        self.mattermost_bot = Webhook(c[0], c[1])

    def communicate(self, message):
        if not message:
            return None
        self.mattermost_bot.send(message, channel=self.config[
            'channel'], username=self.config['bot_name'])
예제 #8
0
def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.

    response = exception_handler(exc, context)
    # Now add the HTTP status code to the response.

    if response is not None:
        response.data['status_code'] = response.status_code
    else:
    # if response.data['status_code']//100 == 5:
        mwh = Webhook('https://meeting.ssafy.com', 'g5paiizrbjrt8n5xyswhj5jgpy')
        json_data = json.dumps(str(exc), ensure_ascii=False)
        mwh.send(json_data)

    return response
예제 #9
0
class MattermostComm(BaseComm):
    def setup(self):
        pass

    def communicate(self, message):
        if not message:
            return None

        hooks = self.project_service_config.get('webhooks')
        if hooks:
            for hook in hooks:
                c = hook.split('/hooks/')
                self.mattermost_bot = Webhook(c[0], c[1])
                self.mattermost_bot.send(message,
                                         username=self.config['bot_name'])

        else:
            c = self.config['webhook_url'].split('/hooks/')
            self.mattermost_bot = Webhook(c[0], c[1])
            self.mattermost_bot.send(
                message, username=self.project_service_config['bot_name'])
예제 #10
0
    def __call__(self):
        try:
            for key, values  in settings.get('boards', {}).items():
                board_name = slugify(values['name'])
                logging.info('{} :: {}'.format(self.board, board_name))
                if self.board != board_name:
                    continue
                
                for k, v in values['mattermost'].items():
                    if not self.allow_action(config=v):
                        logging.info('{} :: {} :: no subscribe for this event :: {}'.format(
                            key, v['channel'], self.action['type']))
                        continue

                    logging.info('{} :: send event to {}'.format(k, v['channel']))
                    mwh = Webhook(v['incoming_webhook_url'], v['incoming_webhook_key'])
                    mwh.username = v.get('username', 'Matterllo')
                    mwh.icon_url = v.get('icon_url', 'http://maffrigby.com/wp-content/uploads/2015/05/trello-icon.png')
                    mwh.send(self.payload, channel=v['channel'])
        except Exception as e:
            logging.error('unable to send payload :: {}'.format(e))
예제 #11
0
class MongoopTrigger(BaseTrigger):
    def __init__(self, *args, **kwargs):
        super(MongoopTrigger, self).__init__(*args, **kwargs)

        self.mwh = Webhook(self.params['url'], self.params['api_key'])
        self.mwh.username = self.params.get('username', 'Mongoop')
        self.mwh.icon_url = self.params.get(
            'icon_url',
            'https://plugins.qgis.org/static/cache/c8/13/c813bff978535a743f63161bc3a7f937.png'
        )

    def send_hook(self, message):
        try:
            self.mwh.send(message, channel=self.params['channel'])
            logging.info('run :: {}'.format(self.name))
        except Exception as e:
            logging.error('unable to run :: {} :: {}'.format(self.name, e))
            return False
        else:
            return True

    def op_nok(self, operations):
        for op in operations:
            payload = 'slow operation \n```json\n'
            for key, values in op.items():
                payload += '{}: {}\n'.format(key, values)
            payload += '```'
            self.send_hook(message=payload)

    def op_ok(self):
        return self.send_hook(message='op ok')

    def balancer_nok(self, state):
        return self.send_hook(message='balancer nok :: state={}'.format(state))

    def balancer_ok(self, state):
        return self.send_hook(message='balancer ok :: state={}'.format(state))
예제 #12
0
    change = False
    for gi in group_info['results']:
        user, stolper, rank = gi['user_name'], gi['score'], gi['rank']
        if args.debug:
            print(user, stolper, rank)
        group_data[user] = int(float(stolper))
        if group_view:
            if group_view[user] < stolper:
                diff = int(stolper) - int(group_view[user])
                text = "{} has {} more stolper than last check. " \
                       "New overall rank is {}. Total number of stolper: {}".format(user, diff, rank, stolper)
                if args.debug:
                    print(text)
                change = True
                if args.mattermost:
                    mwh.send(text)

        output += "{},{},{}\n".format(user, stolper, rank)

    if change or args.debug or args.toplist:
        table_output = create_table_output(group_data)
        if args.mattermost:
            mwh.send(table_output)
        if args.debug:
            print(table_output)

    fi = open(DB_FILE, 'w')
    fi.write(output)
    fi.close()
    if args.debug:
        print(group_info)
예제 #13
0
def notify_mattermost(msg,
                      channel=None,
                      host='drago',
                      url=None,
                      api_key=None,
                      **kwargs):
    """Send a message on mattermost.

    Parameters
    ----------
    msg : str
        Message to display on mattermost.
    channel : str | None
        Mattermost channel to display the message on. If None, this message
        will be sent to the default channel for the webhook.
    host : str
        Name of the bot sending the message. This will be used to find the bot
        icon in `icons` that should be a png file.
    url : str | None
        Url of the mattermost server. If it is none, it should be provided
        either through an env variable MATTERHOOK_URL or in the config file.
    api_key : str | None
        API key of the mattermost server. If it is none, it should be
        provided either through an env variable MATTERHOOK_API_KEY or
        through the config file.
    **kwargs
        Additional keyword arguments you can pass to the payload.
        Overwrites existing arguments.
        See https://docs.mattermost.com/developer/message-attachments.html
    """

    if api_key is None:
        api_key = get_setting('api_key')
    assert api_key, (
        "No API key was provided for Mattermost. It can either be passed "
        "directly to the function, by env variable MATTERHOOK_API_KEY, or "
        "set in a config file.\nSee README.md for more info.")

    if url is None:
        url = get_setting('url')
    assert url, (
        "No URL was provided for Mattermost. It can either be passed "
        "directly to the function, by env variable MATTERHOOK_URL, or "
        "set in a config file.\nSee README.md for more info.")

    # mandatory parameters are url and your webhook API key
    mwh = Webhook(url, api_key)

    payload = {
        'author_name':
        host,
        'thumb_url':
        ('https://raw.githubusercontent.com/tomMoral/mattermost_notifier'
         f'/main/icons/{host}.png'),
        'text':
        msg
    }
    payload.update(kwargs)

    # send a message to the API_KEY's channel
    mwh.send(attachments=[payload], channel=channel)
예제 #14
0
markdown_table = tabulate(data, headers="keys", tablefmt="github")

author_icon = "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c0/Terry_Jones_Monty_Python_O2_Arena_%28cropped%29.jpg/220px-Terry_Jones_Monty_Python_O2_Arena_%28cropped%29.jpg"  # noqa
author_link = "https://en.wikipedia.org/wiki/Terry_Jones"
thumb = "https://en.wikipedia.org/static/images/project-logos/enwiki.png"

text = "#### Movies\n"
text += markdown_table
text += "\n"
text += "#### Other informations\n"
text += "[Search Wikipedia](https://en.wikipedia.org/w/index.php?cirrusUserTesting=glent_m0&search=monty%20python&title=Special%3ASearch&fulltext=1&ns0=1)"  # noqa

attachments = []
attachment = Attachment(
    "Markdown Table Example",
    color="#00FFFF",
    pretext="This appears before the attachement box",
    text=text,
    author_name="Terry Jones",
    author_link=author_link,
    author_icon=author_icon,
    title="Monty Python",
    title_link="https://www.github.com",
    thumb_url=thumb,
)
attachments.append(attachment.payload)

mhw.send(username="******",
         icon_url=author_icon,
         attachments=attachments)
예제 #15
0
파일: __init__.py 프로젝트: elixx/newsbot
class NewsBot(object):
    def __init__(self,filename='config.conf'):
        signal.signal(signal.SIGINT, self.signal_handler)
        self.config = Config(filename)
        self.firstrun = True
        self.conf()
        self.kill = False # for SIGHUP handler to tell whether we are actially trying to exit.

    ## reload config object from file and propgate settings into allfeeds{}.
    def conf(self):
        self.allfeeds = {}
        self.config.reload()
        self.config.outputdelay = self.config.refresh*60 / len(self.config.feedURLs) # each feed broadcast is distributed evenly across the refresh time window

        # config has been [re]loaded. check for and load .nbfeed cache
        try:
            assert(os.path.isfile('.nbfeed') == True)
            file = open('.nbfeed','rb')
            self.allfeeds = pickle.load(file)
            file.close()
            z("conf(): Loaded article cache from .nbfeed!",debug=self.config.debug)
            cacheloaded=True
        except:
            z("conf():  No persistent data found.",debug=self.config.debug)
            cacheloaded=False

        # add all feeds that are listed in config; pickle may have already loaded .nbfeed into allfeeds.
        for url in self.config.feedURLs:
            found = False
            for feed in self.allfeeds.values():
                if(feed.source == url):
                    found = True
                    z("conf(): added feed from .nbfeed: " + url,debug=self.config.debug)
            if(found == False):
                z("conf(): new feed loaded from config: " + url,debug=self.config.debug)
                self.allfeeds[url] = RSSfeed(url=url,config=self.config)

        # remove any feeds not present in config file's feeds
        rmlist = []
        for feed in self.allfeeds.values():
            if(feed.source not in [url for url in self.config.feedURLs]):
                z("conf(): going to rm " + feed.source + " from allfeeds.",debug=self.config.debug)
                rmlist.append(feed.source)
                continue
            feed.config = self.config
            feed.max = self.config.maxi
        for rm in rmlist:
            z('del ' + rm,debug=self.config.debug) 
            del self.allfeeds[rm]

        # write out allfeeds to .nbfeed, to reflect any cleanup that may have occurred.
        file = open('.nbfeed','wb')
        pickle.dump(self.allfeeds,file,protocol=pickle.HIGHEST_PROTOCOL)
        file.close()
        nbsize = os.path.getsize('.nbfeed')

        # announce startup
        initstr = '### :skull: NewsBot ' + self.config.VERSION + ' starting...\n'
        cfgstr = 'feeds:`' + str(len(self.config.feedURLs)) + '` ' + 'refresh:`'
        cfgstr += str(self.config.refresh) + ' min` delay:`' + str(self.config.outputdelay) + ' sec` cachesize:`' + str(nbsize) + ' bytes`\n'
        if(cacheloaded != True):
            initstr += "#### :skull_and_crossbones: " + cfgstr
        else:
            initstr += ":globe_with_meridians: " + cfgstr
        if(self.config.broadcast == True and self.firstrun == True):
            self.firstrun = False
            self.mwh = Webhook(self.config.baseURL, self.config.hook)
            self.mwh.send(initstr)
        elif self.config.broadcast == False:
            print(initstr)

    ## tight loop through allfeeds{} - refresh and output the feeds
    def run(self):
        while True:
            count = 0
            for feed in self.allfeeds.values():
                count += 1
                print("NewsBot - Fetching " + str(count) + ' of ' + str(len(self.allfeeds)) + ' - ' + feed.source)
                feed.refresh()
                self.kill = False
                if(feed.unseen() > 0):
                    output = feed.output() + "\n:hourglass_flowing_sand: _" + str(count) + '/' + str(len(self.allfeeds)) + "_\n"
                    print(output.replace('\n','\n\t'))
                    if self.config.broadcast:
                        try:
                            self.mwh.send(output)
                        except:
                            print("*** run(): problem sending to mattermost ***")
                    z("NewsBot - Storing state to .nbfeed",debug=self.config.debug)
                    file = open('.nbfeed','wb')
                    pickle.dump(self.allfeeds,file,protocol=pickle.HIGHEST_PROTOCOL)
                    file.close()
                z("NewsBot -  sleeping outputdelay",self.config.outputdelay,"...",debug=self.config.debug)
                sleep(self.config.outputdelay)

    ## handler for when a SIGHUP (or ctrl-c) is received
    def signal_handler(self,sig=0,frame=0):
        if(self.kill):
            exit()
        else:
            print("SIGHUP! reloading config. ^C twice to exit.")
            self.conf()
            self.kill=True
            self.run()
            i for i, p in zip(cfg.printers, ping_async) if p.get()
        ]
        inactive_printers = [
            i for i, p in zip(cfg.printers, ping_async) if not p.get()
        ]

    if inactive_printers and not quiet:
        for printer in inactive_printers:
            error += '{}: host \'{}\' unknown or offline\n'.format(
                printer.split('.')[0].upper(), printer)

    #Running queries in parallel
    with mp.Pool(32) as pool:
        err = []
        for printer in active_printers:
            err.append(
                pool.apply_async(get_printer_errors,
                                 args=(printer, cfg.ignore_list, all_errors)))

        if err:
            err = [str(e.get()) for e in err]
            err = list(filter(None, err))
            error += ''.join(err)
            error = error.strip('\n')

    if len(error) > 0:
        mwh = Webhook(cfg.webhook_url, cfg.webhook_key)
        mwh.send(
            error.replace('\xe6', 'ae').replace('\xf8',
                                                'oe').replace('\xe5', 'aa'))
예제 #17
0
def send_mattermost(msg, wh_url, api_key):
    mm_bot = Webhook(mattermostwh["wh_url"], mattermostwh["apikey"])
    mm_bot.send(msg)
예제 #18
0
if args.test is True:
    args.channel = "TEST_CHANNEL_NAME"
    args.username = "******"

# -------------------------
# Webhook setup
# -------------------------

# mandatory parameters are url and your webhook API key
dripbot = Webhook('https://mattermost.example.com', 'API_KEY_HERE')
dripbot.username = args.username
dripbot.icon_url = args.iconurl

# -------------------------
# Test log prints
# -------------------------

# print(f"Message: {args.message}")
# print(f"Channel: {args.channel}")
# print(f"User name: {args.username}")
# print(f"Icon Url: {args.iconurl}")
# print(f"Test: {args.test}")

# -------------------------
# Send the message
# -------------------------

# send a message to the API_KEY's channel
# "scratch-area" for testing
dripbot.send(args.message, channel=args.channel)