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()
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." )
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))
# 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) except Exception as e:
# 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,
# 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. LED_PIN = 18 # GPIO pin connected to the pixels (18 uses PWM!). LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz)
'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 # -------------------------