def test_send_sectioned_message(): """ This sends a message with sections. """ # start the message teams_message = pymsteams.connectorcard(os.getenv("MS_TEAMS_WEBHOOK")) teams_message.text("This is the main title.") teams_message.title("Sectioned Message Title") # section 1 section_1 = pymsteams.cardsection() section_1.title("Section 1 title") section_1.activityTitle("my activity title") section_1.activitySubtitle("my activity subtitle") section_1.activityImage("https://raw.githubusercontent.com/rveachkc/pymsteams/develop/test/desk_toys_1.jpg") section_1.activityText("This is my activity Text. You should see an activity image, activity title, activity subtitle, and this text (of course).") section_1.addFact("Fact", "this is fine") section_1.addFact("Fact", "this is also fine") section_1.text("This is my section 1 text. This section has an activity above and two facts below.") teams_message.addSection(section_1) # section 2 section_2 = pymsteams.cardsection() section_2.text("This is section 2. You should see an image. This section does not have facts or a title.") section_2.addImage("https://raw.githubusercontent.com/rveachkc/pymsteams/develop/test/desk_toys_2.jpg", ititle="Pew Pew Pew") teams_message.addSection(section_2) # send teams_message.send() assert isinstance(teams_message.last_http_status.status_code, int)
def test_message_size(): def getMsg(card): msg = pymsteams.connectorcard(os.getenv("MS_TEAMS_WEBHOOK")) msg.title('Simple Message Title') msg.summary('Simple Summary') msg.addSection(card) return msg # setup text that's too large failure_char_count = 21000 text = 'a' * failure_char_count card = pymsteams.cardsection() card.text(text) msg = getMsg(card) with pytest.raises(pymsteams.TeamsWebhookException): msg.send() card1 = pymsteams.cardsection() card2 = pymsteams.cardsection() card1.text(text[:int(len(text) / 2)]) card2.text(text[int(len(text) / 2):]) msg = getMsg(card1) assert msg.send() msg = getMsg(card2) assert msg.send()
def message_content(conn): try: message = conn # Definindo titulo da Mensagem message.title("Release %s.%s do projeto %s" % (os.environ['PROJECT_VERSION'],os.environ['BUILD_NUMBER'],os.environ['PROJECT_NAME'])) message.text("Publicado no ambiente **%s**." % (os.environ['RELEASE_STAGE'])) message.addLinkButton("Link para acesso ao ambiente %s." % (os.environ['RELEASE_STAGE']), os.environ['RELEASE_STAGE_URL']) # Create ChangeSet Section ChangeSetBody = os.environ['CHANGESET'] ChangeSet = pymsteams.cardsection() ChangeSet.text(ChangeSetBody) # Create Authorizers Section Authorizers = pymsteams.cardsection() response = req.get("https://vsrm.dev.azure.com/%s/%s/_apis/release/releases/%s?api-version=5.0" % (os.environ['ORG_NAME'],os.environ['PROJECT_NAME'],os.environ['RELEASE_ID']), auth=(os.environ['VSTS_USER'], os.environ['VSTS_PAT'])) try: AUTHORIZERS=json.dumps(response.json()['environments'][0]['preDeployApprovals'][0]['approver']['displayName']) except: AUTHORIZERS=os.environ['BUILDERS'] Authorizers.text("Release criada por **%s** e autorizada por **%s**." % (os.environ['BUILDERS'],AUTHORIZERS)) # Anexando message.addSection(ChangeSet) message.addSection(Authorizers) return message except Exception as e: print("Message Content Error: "+str(e))
def post(): #creates a connector card using webhook url from MS teams myTeamsMessage = pymsteams.connectorcard(webhook) #get current hour and time now = datetime.now() h = now.hour time = now.strftime("%H:%M") #compose core of message and add text text1 = "Good "+get_part_of_day(h)+" team! As of "+time+", the temperature in Canberra is "+getTemp()+"c, and "+getRecoveries()+" healthy people have recovered from Covid-19 in Australia!" myTeamsMessage.text(text1) #caveat to include in case things go wrong text2 = "-This has been an automated message, please let Mick know if things have gone awry" # Create Section 1, used for 'everything is fine' image Section1 = pymsteams.cardsection() Section1.addImage("https://i.imgur.com/B7ZtJwD.png") # Create Section 2, used for caveat Section2 = pymsteams.cardsection() Section2.text(text2) # Add sections to message myTeamsMessage.addSection(Section1) myTeamsMessage.addSection(Section2) # send the message. myTeamsMessage.send() print("Message sent to team")
def sendTeamsMessage(data_dict): """ Sendet eine Message bei Teams in die 'corona'-Gruppe vom 'hr-Datenteam' :param data_dict: gesammeltes Dict ueber die Werte ['Hospitalisierungsinzidenz', 'Intensivbettenauslastung', 'Normalbettenauslastung', 'Impfstatus Hospitalisierte', 'Impfquote'] wird von der main erstellt (durch Aufruf der verschiedenen get...()-Funktionen und Zusammenfuegen in ein gemeinsames Dict) """ # hrDatenteamCorona = pymsteams.connectorcard('https://hrhessen.webhook.office.com/webhookb2/7cea83e5-54d9-4ef1-b745-29a8c632ad00@daaae532-0750-4b35-8f3f-fdd6ba4c86f0/IncomingWebhook/0b1deea18e494a14b7f4008c7cb9644f/dbe95101-4eda-4ed0-b2ac-5e03d25c0398') hrDatenteamCorona = pymsteams.connectorcard( 'https://hrhessen.webhook.office.com/webhookb2/7cea83e5-54d9-4ef1-b745-29a8c632ad00@daaae532-0750-4b35-8f3f-fdd6ba4c86f0/IncomingWebhook/cb2b0da4990948a4abf8c75faa97e0a7/dbe95101-4eda-4ed0-b2ac-5e03d25c0398' ) hrDatenteamCorona.title( 'Update Leitindikatoren zur Bestimmung des Pandemiegeschehens ') hrDatenteamCorona.text( 'letzte Aktualisierung: ' + list(data_dict.values())[0] + ' Uhr, Quelle: Hessisches Ministerium fuer Soziales und Integration') hiSection = pymsteams.cardsection() hiSection.text('Hospitalisierungsinzidenz') hiSection.addFact('aktuell', list(data_dict.values())[1]) hiSection.addFact('letzte Woche', list(data_dict.values())[2]) hrDatenteamCorona.addSection(hiSection) iaSection = pymsteams.cardsection() iaSection.text('Intensivbettenauslastung ' + list(data_dict.values())[3]) iaSection.addFact('aktuell', list(data_dict.values())[4]) iaSection.addFact('bestaetigt', list(data_dict.values())[5]) iaSection.addFact('Verdacht', list(data_dict.values())[6]) hrDatenteamCorona.addSection(iaSection) naSection = pymsteams.cardsection() naSection.text('Normalbettenauslastung ' + list(data_dict.values())[7]) naSection.addFact('aktuell', list(data_dict.values())[8]) naSection.addFact('bestaetigt', list(data_dict.values())[9]) naSection.addFact('Verdacht', list(data_dict.values())[10]) hrDatenteamCorona.addSection(naSection) ihSection = pymsteams.cardsection() ihSection.text('Impfstatus Hospitalisierte') ihSection.addFact('ungeimpft', str(list(data_dict.values())[11]) + ' %') ihSection.addFact('Impfstatus unbekannt', str(list(data_dict.values())[12]) + ' %') ihSection.addFact('geimpft', str(list(data_dict.values())[13]) + ' %') hrDatenteamCorona.addSection(ihSection) iqSection = pymsteams.cardsection() iqSection.text('Impfquote ' + list(data_dict.values())[14]) iqSection.addFact('gesamt', str(list(data_dict.values())[15]) + ' %') iqSection.addFact('nur Impffaehige', str(list(data_dict.values())[16]) + ' %') hrDatenteamCorona.addSection(iqSection) hrDatenteamCorona.send() print('Nachricht in MS-Teams Chat von "hr-Datenteam corona" geschickt')
def send_alarm(self, alarm): tmsg = pymsteams.connectorcard(config.notifications['msteams']['webhook_url']) description = alarm['info']['description'] if len(alarm['groupby']) > 0: description += '\n *Please note that the items below have been grouped by: %s*' % pprint(alarm['groupby']) tmsg.text(description) tmsg.color('red') try: for hit in alarm['hits']['hits']: tcs = pymsteams.cardsection() tcs.disableMarkdown() i = 0 title = hit['_id'] while i < len(alarm['groupby']): if i == 0: title = getValue('_source.%s' % alarm['groupby'][i], hit) else: title = '%s / %s' % (title, getValue('_source.%s' % alarm['groupby'][i], hit)) i += 1 tcs.activityTitle('Alarm on item: %s' % title) #tcs.activitySubtitle(alarm['info']['description']) for field in alarm['fields']: val = getValue('_source.%s' % field, hit) tcs.addFact(field, pprint(val)) tmsg.addSection(tcs) except Exception as e: self.logger.exception(e) pass tmsg.title('Alarm from %s [%s hits]' % (alarm['info']['name'], alarm['hits']['total'])) tmsg.send()
def send_message(self, message=None, **kwargs): """Send a message to the webhook.""" teams_message = pymsteams.connectorcard(self._webhook_url) title = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT) data = kwargs.get(ATTR_DATA) teams_message.title(title) teams_message.text(message) if data is not None: file_url = data.get(ATTR_FILE_URL) if file_url is not None: if not file_url.startswith("http"): _LOGGER.error("URL should start with http or https") return message_section = pymsteams.cardsection() message_section.addImage(file_url) teams_message.addSection(message_section) try: teams_message.send() except RuntimeError as err: _LOGGER.error("Could not send notification. Error: %s", err)
def send_notification_to_microsoft_teams(webhook_address: str, spec: Dict): """ Send push notification to Microsoft Teams using webhook. Just to manage all the instance """ message = pymsteams.connectorcard(webhook_address) if os.environ.get("IS_TESTING_CI") is not None: message.text( "Hi @channel, a new CI/CD test for the colab ssh pip package was initialized! Here was it configuration:" ) else: # pragma: no cover message.text( "Hi @channel, a new colab spot instance was created! Here was it configuration:" ) section = pymsteams.cardsection() section.addFact("CPU", spec['cpu']) section.addFact("RAM", spec['ram']) section.addFact("GPU", spec['gpu']) section.addFact("Hostname", spec['hostname']) section.addFact("Connection command", spec['ssh_command']) message.addSection(section) try: message.send() except Exception as exception: # pylint: disable=broad-except print(f"Error sending notification to Microsoft Teams: {exception}")
def Price_comparison_elektroncycles(old_data, new_data): x = old_data["Products"] old_data__ = [k["Name"] for k in x if k.get("Name")] old_data_length = len(old_data__) y = new_data["Products"] new_data__ = [k["Name"] for k in y if k.get("Name")] new_data_length = len(new_data__) for i in range(0, new_data_length): for j in range(0, old_data_length): if (new_data["Products"][i]["Name"] == old_data["Products"][j] ["Name"]): if (new_data["Products"][i]["Price"] != old_data["Products"][j]["Price"]): print("Price Changed") myTeamsMessage = pymsteams.connectorcard( "https://outlook.office.com/webhook/c773f8b0-dfb8-4ba1-bde6-3742af93d8d9@8c4858b5-f020-483a-b7ef-71ded6e81767/IncomingWebhook/4ac039be94c64aa28e53f448e7571982/57e1e599-de0e-4e8f-be89-4f86146ae25c" ) myMessageSection = pymsteams.cardsection() myTeamsMessage.title( "PRICE CHANGED (website:Elektron Cycles)") myTeamsMessage.text("```Name```:" + new_data["Products"][i]["Name"]) myMessageSection.text( "```old price```:" + str(old_data["Products"][j]["Price"]) + "```new price```:" + str(new_data["Products"][i]["Price"])) myTeamsMessage.addLinkButton( "Reference", new_data["Products"][i]["Reference"]) myTeamsMessage.addSection(myMessageSection) myMessageSection.addImage(new_data["Products"][i]["Image"]) myTeamsMessage.send()
def send_teams_test_message(): myTeamsMessage = pymsteams.connectorcard(config['TEAMS']['WEBHOOK_URL']) # create the section myMessageSection = pymsteams.cardsection() # Section Title myMessageSection.title("Section title") # Activity Elements myMessageSection.activityTitle("my activity title") myMessageSection.activitySubtitle("my activity subtitle") myMessageSection.activityImage("http://i.imgur.com/c4jt321l.png") myMessageSection.activityText("This is my activity Text") # Facts are key value pairs displayed in a list. myMessageSection.addFact("this", "is fine") myMessageSection.addFact("this is", "also fine") # Section Text myMessageSection.text("This is my section text") # Section Images myMessageSection.addImage("http://i.imgur.com/c4jt321l.png", ititle="This Is Fine") # Add your section to the connector card object before sending myTeamsMessage.addSection(myMessageSection) myTeamsMessage.summary("Test Message") myTeamsMessage.printme() result = myTeamsMessage.send() return result
def share_on_teams(tweet): #Creates a connector card object using the Microsoft Webhook URL teamsMessage = pymsteams.connectorcard(tweet.teamsUrl) # Add text to the message. teamsMessage.text("{} posted a new tweet!".format(tweet.userName)) #Create the section messageSection = pymsteams.cardsection() #Activity Elements messageSection.activityTitle("{} @{}".format(tweet.userName, tweet.screenName)) messageSection.activitySubtitle("Posted on {}".format(tweet.createdAt)) messageSection.activityImage(tweet.profilePic) messageSection.activityText(tweet.tweetText) #Section Text messageSection.text('<a href="{}">Direct link to tweet</a>'.format( tweet.twitterLink)) #Add section text to the teams message teamsMessage.addSection(messageSection) #Send the message to the channel teamsMessage.send()
def teams_send_msg_start(self): """ Fuction to send start tasks messages to defined Microsoft Teams chat channel with additional run information. """ try: # Create Microsoft Teams connection object ms_teams_connector = pymsteams.connectorcard(self.ms_teams_room) # Create Microsoft Teams message content ms_teams_connector.color('green') ms_teams_connector.title('Starting: ' + str(self.limit)) ms_teams_connector.text('Starting ' + str(self.playbook_name) + ' on: ' + str(self.limit)) # Create section card with more facts (key/value) ms_teams_card_obj = pymsteams.cardsection() ms_teams_card_obj.disableMarkdown() ms_teams_card_obj.title('Ansible Information') ms_teams_card_obj.addFact('Executed by', str(self.executor)) ms_teams_card_obj.addFact('Playbook', str(self.playbook_name)) ms_teams_card_obj.addFact('Limit(s)', str(self.limit)) ms_teams_card_obj.addFact('Tag(s)', str(self.tags)) ms_teams_card_obj.addFact('Extra-Vars', str(self.extra_vars)) # Add section to teams message ms_teams_connector.addSection(ms_teams_card_obj) # Send message to Microsoft Teams chat channel # (honor dry-run mode) if self.ms_teams_notify: ms_teams_connector.send() else: ms_teams_connector.printme() except: print '\n[CRITICAL]: Could not connect to Microsoft Teams.'
def send_teams_webhook_finish_failed(self, text: str, config, reset_links=False): if self.config.args.simulate: print( f"SIM: send Teams webhook for Round Finished Failed with text: {text}" ) return True if self.endpoint: message_card = msteams.connectorcard(self.endpoint) message_card.text(text) if reset_links: reset_section = msteams.cardsection() reset = msteams.potentialaction(f"Reset round (New qtbase)", "HttpPOST") reset.payload[ "target"] = "https://qt-cherry-pick-bot.herokuapp.com/reset-submodule-updates" reset.payload["body"] = yaml.dump( {"branch": config.args.branch}) msteams.connectorcard.addPotentialAction(reset_section, reset) retry = msteams.potentialaction( f"Retry current failed modules on '{config.args.branch}'", "HttpPOST") retry.payload[ "target"] = "https://qt-cherry-pick-bot.herokuapp.com/retry-submodule-updates" retry.payload["body"] = yaml.dump( {"branch": config.args.branch}) msteams.connectorcard.addPotentialAction(reset_section, retry) message_card.addSection(reset_section) failed_section = msteams.cardsection() failed_modules_text = "\n".join([ r.id for r in config.state_data.values() if r.progress == PROGRESS.DONE_FAILED_BLOCKING ]) failed_section.text( f"```\nFailed Modules on {config.args.branch}:\n{failed_modules_text}" ) message_card.addSection(failed_section) message_card.send() if message_card.last_http_status.status_code != 200: print( f"WARN: Unable to send alert to webhook for Round Failed Finished on {config.args.branch}" ) return False return True
def send_error_message(error): myTeamsMessage.title("Auto offboard script error") myTeamsMessage.summary("..") myMessageSection = pymsteams.cardsection() myMessageSection.title("Error details") myMessageSection.activityText("%s" % error) myTeamsMessage.addSection(myMessageSection) myTeamsMessage.send()
def send_teams_webhook_module_failed(self, repo, text_override: str = None, test_failures: str = None, pause_links: bool = False): if self.config.args.simulate: print(f"SIM: send Teams webhook for {repo.id} with text:" + ( text_override or f"Dependency update on *{repo.id}* failed in **{repo.branch}**" ) + '\n' + test_failures) return if self.endpoint: message_card = msteams.connectorcard(self.endpoint) message_card.color('#FF0000') message_card.text( text_override or f"Dependency update on *{repo.id}* failed in **{repo.branch}*" f"*") message_card.addSection(msteams.cardsection().linkButton( *gerrit_link_maker(self.config, repo))) if pause_links: pause_section = msteams.cardsection() pause = msteams.potentialaction( f"Pause Updates on '{repo.branch}' (This failure can be fixed)", "HttpPOST") pause.payload[ "target"] = "https://qt-cherry-pick-bot.herokuapp.com/pause-submodule-updates" pause.payload["body"] = yaml.dump({"branch": repo.branch}) msteams.connectorcard.addPotentialAction(pause_section, pause) resume = msteams.potentialaction( f"Resume Updates on '{repo.branch}'", "HttpPOST") resume.payload[ "target"] = "https://qt-cherry-pick-bot.herokuapp.com/resume-submodule-updates" resume.payload["body"] = yaml.dump({"branch": repo.branch}) msteams.connectorcard.addPotentialAction(pause_section, resume) message_card.addSection(pause_section) if test_failures: message_card.addSection( msteams.cardsection().text('```\nBuild/Test Log:\n' + test_failures)) message_card.send() if message_card.last_http_status.status_code != 200: print(f"WARN: Unable to send alert to webhook for {repo.id}") return False return True
def compose_sections(action, summary, **kwargs): sections = pymsteams.cardsection() sections.activityTitle(action) sections.activitySubtitle(summary) sections.activityImage('https://user-images.githubusercontent.com/63040751/79412387-53969200-7fe0-11ea-8e39-6da2e22bab6e.png') for key, value in kwargs.items(): sections.addFact(key, value) return sections
def send(self, text, title=None, image=None, imageTitle=None): self.check_connect() self.client.text(text) if title: self.client.title(title) if image: myMessageSection = pymsteams.cardsection() myMessageSection.addImage(image, ititle=imageTitle) self.client.addSection(myMessageSection) self.client.send() print("Message Send")
def send_message(users): myTeamsMessage.title("Auto offboard daily report") myTeamsMessage.summary("..") for k, v in users.items(): myMessageSection = pymsteams.cardsection() myMessageSection.title("User %s details" % k) myMessageSection.activityText("\n".join(["- %s" % x for x in v])) myTeamsMessage.addSection(myMessageSection) myTeamsMessage.send()
def deliver_to_msteams_channel(self, channel_url): notification = pymsteams.connectorcard(channel_url) notification.title(self.title) notification.summary(f"{self.title} - {self.subtitle}") section = pymsteams.cardsection() section.activityTitle(self.subtitle) section.activityImage(self.image) for key, value in self.data.items(): section.addFact(key, value) notification.addSection(section) notification.printme() notification.send()
def sendDownCode(errorHook, service, date, status): #channel URL teamsURL = config.errorHook myTeamsMessage = pymsteams.connectorcard(teamsURL) myTeamsMessage.title("TEST REPORT CODE {} in {}".format(status, service)) myTeamsMessage.text("Test run at " + str(date)) #section with the up services myMessageSection = pymsteams.cardsection() myMessageSection.activityTitle(service) myMessageSection.activityText(str(status)) myTeamsMessage.addSection(myMessageSection) myTeamsMessage.send()
def sendError(errorHook, service, date, error): #channel URL teamsURL = config.errorHook myTeamsMessage = pymsteams.connectorcard(teamsURL) myTeamsMessage.title("TEST REPORT ERROR FOR " + str(service)) myTeamsMessage.text("Test run at " + str(date)) #section with the up services myMessageSection = pymsteams.cardsection() myMessageSection.activityTitle(service) myMessageSection.activityText(str(error)) myTeamsMessage.addSection(myMessageSection) myTeamsMessage.send()
def done(self, analysis): # Teams connector message = pymsteams.connectorcard(self.url) # Compile and send message message.title("FAME Analysis Completed") message.summary( "New analysis ready for review at: {0}/analyses/{1}".format( self.fame_base_url, analysis['_id'])) target_section = pymsteams.cardsection() target_section.title("Targets") target_section.text(defang(', '.join(analysis._file['names']))) message.addSection(target_section) # May want to use addFact() on below sections for showing lists if analysis['modules'] is not None: module_section = pymsteams.cardsection() module_section.title("Analysis Modules") module_section.text(', '.join(analysis['modules'])) message.addSection(module_section) if len(analysis['extractions']) > 0: extraction_section = pymsteams.cardsection() extraction_section.title("Extracted Items") extraction_section.text("{0}".format(','.join( [x['label'] for x in analysis['extractions']]))) message.addSection(extraction_section) if len(analysis['probable_names']) > 0: classification_section = pymsteams.cardsection() classification_section.title("Probably Names") classification_section.text("{0}".format(','.join( analysis['probable_names']))) message.addSection(classification_section) message.addLinkButton( "View Analysis", "{0}/analyses/{1}".format(self.fame_base_url, analysis['_id'])) message.send()
def post_note(day: date): print("Checking your config") config = load_config() if config["msTeams"]["connectorURL"]: link = config["msTeams"]["connectorURL"] print(f"Using connectorURL from config: {link}") else: link = input("Please put in the connector link: ") if config["msTeams"]["name"]: name = config["msTeams"]["name"] print(f"Using name from config: {name}") else: name = input("Please enter your name: ") date_of_note = "Date: " + day.strftime("%m/%d/%Y") + " \n" print("Posting your note") myTeamsMessage = pymsteams.connectorcard(link) myTeamsMessage.text(name + "'s standup notes for " + date_of_note) # Create Section 1 Section1 = pymsteams.cardsection() Section1.activityTitle("What I did yesterday") Section1.activityText(get_text(get_note_name(day), 'y')) # Create Section 2 Section2 = pymsteams.cardsection() Section2.activityTitle("What I am doing today") Section2.activityText(get_text(get_note_name(day), 't')) # Create Section 3 Section3 = pymsteams.cardsection() Section3.activityTitle("Blockers") Section3.activityText(get_blockers(get_note_name(day))) # Add both Sections to the main card object myTeamsMessage.addSection(Section1) myTeamsMessage.addSection(Section2) myTeamsMessage.addSection(Section3) myTeamsMessage.send() print("Message sent")
def test_chaining(): card = pymsteams.cardsection() card.title("Foo").activityTitle("Bar").activitySubtitle("Baz") assert card.payload["title"] == "Foo" assert card.payload["activityTitle"] == "Bar" assert card.payload["activitySubtitle"] == "Baz" connector_card = pymsteams.connectorcard("https://example.org") connector_card.text("Big text").title("Cool title").summary( "Something happened") assert connector_card.payload["title"] == "Cool title" assert connector_card.payload["text"] == "Big text" assert connector_card.payload["summary"] == "Something happened"
def post_teams(slackhookurl: str, title: str, detail: str) -> None: #def post_teams(title: str, detail: str,graph_path: str) -> None: myTeamsMessage = pymsteams.connectorcard(slackhookurl) myTeamsMessage.title('AWSコスト通知') myTeamsMessage.text('リソースの使用料を確認してください') myMessageSection = pymsteams.cardsection() myMessageSection.activityTitle(title) myMessageSection.activityText(detail) myTeamsMessage.addSection(myMessageSection) myTeamsMessage.send()
def build_conversation(self, card, incident_id, task_id, teams_payload, teams_mrkdow): """ build the message card format used to post to teams webhooks :param card: :param incident_id: :param task_id: :param teams_payload: json formatted data :param teams_mrkdow: true/false to support markdown format :return: formatted card for transmission """ incident_url = build_incident_url( build_resilient_url(self.opts['host'], self.opts['port']), incident_id) type = 'Incident' # build url back to resilient if task_id: incident_url = "{}{}{}".format(incident_url, TASK_FRAGMENT, task_id) type = 'Task' # url back to resilient card.addLinkButton("Resilient {}".format(type), incident_url) if teams_payload.get("title"): card.title(teams_payload.get("title")) mrkdown = MarkdownParser() card.text(mrkdown.convert(teams_payload.get("summary", "-None-"))) for section in teams_payload.get("sections", []): cardsection = pymsteams.cardsection() if teams_mrkdow: cardsection.enableMarkdown() if section.get("title"): cardsection.title(section.get("title")) if section.get("text"): cardsection.text(section.get("text")) for fact in section.get("facts", []): cardsection.addFact(fact.get("name"), fact.get("value")) card.addSection(cardsection) return card
def createWebhook(self, job_title, level, advice, reason, img_url): # create the section myMessageSection = pymsteams.cardsection() # Section Title myMessageSection.title(job_title) # Activity Elements myMessageSection.activityTitle(level) myMessageSection.activitySubtitle(advice) myMessageSection.activityImage(img_url) myMessageSection.activityText(reason) self.myTeamsMessage.addSection(myMessageSection) self.myTeamsMessage.printme() self.myTeamsMessage.send()
def sendTeams(reportHook, date, services): #channel URL teamsURL = config.reportHook myTeamsMessage = pymsteams.connectorcard(teamsURL) myTeamsMessage.title("Test Report") myTeamsMessage.text("Test run at " + str(date)) #section with the up services myMessageSection = pymsteams.cardsection() myMessageSection.activityTitle("Up Services") myMessageSection.activityText("Service name and response code: ") for up in services: myMessageSection.addFact(up, "200") myTeamsMessage.addSection(myMessageSection) myTeamsMessage.send()
def create_teams_message(snsMessage): webHookUrl = os.environ["TEAMS_WEBHOOK_URL"] imageUrl = os.environ["TEAMS_IMAGE_URL"] result = pymsteams.connectorcard(webHookUrl) result.summary(snsMessage['Subject']) teamsSection = pymsteams.cardsection() teamsSection.activityTitle(snsMessage['Subject']) teamsSection.activitySubtitle(snsMessage['Message']) if imageUrl != None and imageUrl != '': teamsSection.activityImage(imageUrl) teamsSection.addFact("Timestamp", snsMessage['Timestamp']) teamsSection.addFact("MessageId", snsMessage['MessageId']) teamsSection.addFact("TopicArn", snsMessage['TopicArn']) teamsSection.addFact("Type", str(snsMessage['Type'])) result.addSection(teamsSection) return result
def createWebhook(self, job_title, level, advice, reason): # create the section myMessageSection = pymsteams.cardsection() # Section Title myMessageSection.title(job_title) # Activity Elements myMessageSection.activityTitle(level) myMessageSection.activitySubtitle(advice) myMessageSection.activityImage( "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSor4Y5twpPy0VFBFkVYqcsjZIc1DPSPUhkuA&usqp=CAU" ) myMessageSection.activityText(reason) self.myTeamsMessage.addSection(myMessageSection) self.myTeamsMessage.printme() self.myTeamsMessage.send()