Exemplo n.º 1
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
Exemplo n.º 2
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))
Exemplo n.º 3
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)
Exemplo n.º 4
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)
Exemplo n.º 5
0
    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'
        )
Exemplo n.º 6
0
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'])
Exemplo n.º 7
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
Exemplo n.º 8
0
    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'])
Exemplo n.º 9
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))
Exemplo n.º 10
0
Arquivo: chats.py Projeto: 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."
        )
Exemplo n.º 11
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()
Exemplo n.º 12
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))
Exemplo n.º 13
0
#!/usr/bin/python3

# Access to mattermost
from matterhook import Webhook

import datetime
import html2text

from calendarBot.calendarBotSettings import *
from calendarBot.calendarApi import *
from calendarBot.calendarTimer import *

# Initialize Mattermost access
mattermostHook = Webhook(mattermostSettings['URL'],
                         mattermostSettings['ApiKey'])
mattermostHook.username = mattermostSettings['Username']
mattermostHook.icon_url = mattermostSettings['IconURL']


def checkCalendarForUpcomingEvents():
    """
    Checks calendar for upcoming events
    """
    nowDate = datetime.datetime.now()
    laterDate = nowDate + datetime.timedelta(
        minutes=calendarSettings['TimespanToCheck'])
    successful, res = showAgenda('', nowDate.strftime("%d.%m.%Y %H:%M"),
                                 laterDate.strftime("%d.%m.%Y %H:%M"), True)
    if successful:
        for item in res:
            eventContent = '### **{0}**\nTime: {1} - {2} (KIT time)\nDetails: {3}Location: {4}\n\n'.format(
Exemplo n.º 14
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)
Exemplo n.º 15
0
from matterhook import Webhook, Attachment
from tabulate import tabulate

url = "https://mattermost.MYCOMPANY.com"
api_key = "API_KEY"

mhw = Webhook(url, api_key)

data = [
    {
        "name": "Monty Python and the Holy Grail",
        "relevant thing": ":rabbit:",
        "date": "1975",
    },
    {
        "name": "Monty Python's Life of Brian",
        "relevant thing": ":innocent:",
        "date": "1979",
    },
    {
        "name": "Monty Python's The Meaning of Life",
        "relevant thing": ":tropical_fish:",
        "date": "1983",
    },
]

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"
#!/usr/bin/python3

# Access to mattermost
from matterhook import Webhook

import datetime
import html2text


from calendarBot.calendarBotSettings import *
from calendarBot.calendarApi import *
from calendarBot.calendarTimer import *

# Initialize Mattermost access
mattermostHook = Webhook(mattermostSettings['URL'], mattermostSettings['ApiKey'])
mattermostHook.username = mattermostSettings['Username']
mattermostHook.icon_url = mattermostSettings['IconURL']

def checkCalendarForUpcomingEvents():
    """
    Checks calendar for upcoming events
    """
    nowDate = datetime.datetime.now()
    laterDate = nowDate + datetime.timedelta(minutes = calendarSettings['TimespanToCheck'])
    successful, res = showAgenda('', nowDate.strftime("%d.%m.%Y %H:%M"), laterDate.strftime("%d.%m.%Y %H:%M"), True)
    if successful:
        for item in res:
            eventContent = '### **{0}**\nTime: {1} - {2} (KIT time)\nDetails: {3}Location: {4}\n\n'.format(item.subject,item.start.astimezone(EWSTimeZone.timezone('Europe/Copenhagen')).strftime('%H:%M'),item.end.astimezone(EWSTimeZone.timezone('Europe/Copenhagen')).strftime('%H:%M'), html2text.html2text(item.body), item.location)
            for subcalendar in item.categories:
                try:
                    mattermostHook.send(eventContent, channel=subcalendar)
Exemplo n.º 17
0
    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)
Exemplo n.º 18
0
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()
Exemplo n.º 19
0
    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')
Exemplo n.º 20
0
def send_mattermost(msg, wh_url, api_key):
    mm_bot = Webhook(mattermostwh["wh_url"], mattermostwh["apikey"])
    mm_bot.send(msg)
Exemplo n.º 21
0
    action="store_true",
    help=
    'Test mode: send the message to the "TEST_CHANNEL_NAME"\nchannel as user "DripBot Test"',
)
args = parser.parse_args()

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
Exemplo n.º 22
0
 def setup(self):
     c = self.config['webhook_url'].split('/hooks/')
     self.mattermost_bot = Webhook(c[0], c[1])
Exemplo n.º 23
0
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    "%Y-%m-%d %H:%M:%S")
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(fh)
logger.addHandler(ch)
logger.info("INFO logging enabled.")
logger.debug("DEBUG logging enabled.")

# Mattermost setup
dripbot = Webhook('https://MATTERMOST.EXAMPLE.COM', 'API_KEY_HERE')
dripbot.username = '******'
dripbot.icon_url = "location/of/CoffeePot.png"
dripbot.channel = "CHANNEL_NAME"

# Drip words generator setup
drip = DripWords()

# Button hardware setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_UP)
button_processing = False

# NeoPixel ring setup
# LED strip configuration:
LED_COUNT = 16  # Number of LED pixels.
            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'))
Exemplo n.º 25
0
    def __init__(self, args, conf):
        self.is_exit = False
        try:
            if args is None:
                try:
                    self.args = self.get_arg_parser().parse_args()
                except SystemExit:
                    self.is_exit = True
                    sys.exit(0)
                except:
                    print(exception_helper())
                    sys.exit(0)

                if not len(sys.argv) > 1:
                    print("No arguments. Type -h for help.")
                    self.is_exit = True
                    sys.exit(0)
            else:
                self.args = args

            if hasattr(self.args, 'version') and self.args.version:
                print("Version %s" % VERSION)
                self.is_exit = True
                sys.exit(0)

            if self.args.packet_name is None:
                print("Argument --packet-name not found!")
                self.is_exit = True
                sys.exit(0)

            if self.args.db_name is None:
                print("Argument --db-name not found!")
                self.is_exit = True
                sys.exit(0)

            self.sys_conf = SysConf(conf)

            packet_dir = os.path.join(self.sys_conf.current_dir, 'packets', self.args.packet_name)
            if not os.path.isdir(packet_dir) or len(self.args.packet_name) == 0:
                print("Invalid --packet-name=%s" % self.args.packet_name)
                self.is_exit = True
                sys.exit(0)

            if self.args.packet_name.isdigit():
                print("Wrong format of --packet-name=%s: only digits are not allowed!" % self.args.packet_name)
                self.is_exit = True
                sys.exit(0)

            if len(self.args.packet_name) < 3:
                print("Wrong format of --packet-name=%s: minimal length is 3 symbols!" % self.args.packet_name)
                self.is_exit = True
                sys.exit(0)

            prepare_dirs(self.sys_conf.current_dir, ["log"])

            # ========================================================================
            # check --template arg
            # How to run test: --packet-name=test_template --db-name=* --template=test
            if self.args.template is not None:
                template_dir = os.path.join(
                    self.sys_conf.current_dir,
                    "packets",
                    "templates",
                    self.args.template
                )

                if os.path.isdir(template_dir):
                    for f_name in [
                        f for f in os.listdir(template_dir)
                            if f.endswith('.sql') and os.path.isfile(os.path.join(template_dir, f))
                    ]:
                        print("Copying %s to %s" % (f_name, packet_dir))
                        shutil.copy(os.path.join(template_dir, f_name), packet_dir)
                else:
                    print("Directory %s is not exists!" % template_dir)
                    self.is_exit = True
                    sys.exit(0)
            # ========================================================================
            if hasattr(self.args, 'conf') and self.args.conf != '':
                try:
                    conf_json = json.loads(self.args.conf.replace("""\'""", "\""))
                    for key, value in conf_json.items():
                        if key in ('execute_sql', 'detailed_traceback', 'db_name_all_confirmation'):
                            conf_json[key] = read_conf_param_value(value, boolean=True)
                        if key in ('cancel_wait_tx_timeout', 'cancel_blocker_tx_timeout'):
                            conf_json[key] = """'%s'""" % read_conf_param_value(value)
                    self.sys_conf.__dict__.update(conf_json)
                except:
                    raise Exception('Invalid value in --conf parameter')

            if hasattr(self.args, 'placeholders') and self.args.placeholders != '':
                try:
                    self.placeholders = json.loads(self.args.placeholders.replace("""\'""", "\""))
                except:
                    raise Exception('Invalid value in --placeholders parameter')

            replace_symbols = ['*', '?', ':']
            log_name_part = self.args.db_name
            for s in replace_symbols:
                log_name_part = log_name_part.replace(s, "_")
            self.logger = PSCLogger.instance(
                "dbc_" + log_name_part + "_" + self.args.packet_name,
                log_level=logging._nameToLevel[self.sys_conf.log_level.upper()],
                max_bytes=1024*1000*self.sys_conf.file_maxmbytes,
                backup_count=self.sys_conf.file_backupcount,
                delay=1
            )

            if self.sys_conf.matterhook_conf is not None:
                self.matterhooks = {}
                for chat, key in self.sys_conf.matterhook_conf["chat_keys"].items():
                    self.matterhooks[chat] = Webhook(self.sys_conf.matterhook_conf["url"], key)

            else:
                self.matterhook = None

        except SystemExit as e:
            sys.exit(0)
        except:
            print("Can't initialize application. Exiting...")
            print(exception_helper())
            sys.exit(0)
Exemplo n.º 26
0
def create_table_output(data):
    # Create table output
    top = sorted(data.items(), key=lambda x: x[1], reverse=True)
    table_output = "|User|Stolper|\n"
    table_output += "|:------------ | -----:|\n"
    for user, stolper in top:
        table_output += "|{}|{}|\n".format(user, stolper)

    return table_output


if __name__ == '__main__':
    # Ready the mm integration
    from matterhook import Webhook
    mwh = Webhook(MATTERMOST_URL, MATTERMOST_HOOK)

    parser = argparse.ArgumentParser(description='Print stolpejakten data to Mattermost')
    parser.add_argument('-d', '--debug', action='store_true', help='Debug the application')
    parser.add_argument('-t', '--toplist', action='store_true', help='Send top list only')
    parser.add_argument('-m', '--mattermost', action='store_false', help='Send data to mattermost')

    args = parser.parse_args()
    if args.debug:
        print("Debug is ON")
    if args.mattermost:
        print("Sending data to mattermost")
    else:
        print("Not sending data to mattermost")
    if args.toplist:
        print("Sending top list even if no change")