def create_api():

	auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
	auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
	api = tweepy.API(auth , wait_on_rate_limit = True, wait_on_rate_limit_notify = True)

	try:
		api.verify_credentials()
		logging.info('API credentials successfully verified')

	except:
		logging.warning('API credentials unsuccessfully verified')

	tweets = api.search(
		# Modify query results here
		q= 'this OR that -filter:retweets -bad_words',
		lang='ja',
		result_type='recent',
		count=40)

	myTeamsMessage = pymsteams.connectorcard(OUTLOOK_WEBHOOK)

	for tweet in tweets:

		try:
			# Create a URL for easy clicking within chat
			# Twitter URLs follow this format- https://twitter.com/[USERNAME]/status/[TWEET ID]
			url = str('https://twitter.com/' + tweet.user.screen_name + '/status/' + str(tweet.id))
			myTeamsMessage = pymsteams.connectorcard(OUTLOOK_WEBHOOK)
			myTeamsMessage.addLinkButton(url, url)
			myTeamsMessage.text(
				# Create format of text message
				'Username: '******'\n' + '\n' +
				'Screen Name: ' + tweet.user.screen_name + '\n' + '\n' +
				'Sent time: ' + str(tweet.created_at + datetime.timedelta(hours=9)) + '\n' + '\n' +
				'URL: '+ url + '\n' + '\n' +
				'Body: ' + tweet.text + '\n' + '\n'

				)
			logging.info('Tweet # ' + str(tweet.id) + ' created')

			myTeamsMessage.send()
			logging.info('Tweet # '+ str(tweet.id) + ' sent')

			tweet_list = []

			for tweet.id:
				tweet_list.append(tweet.id)
Exemplo n.º 2
0
def send_text(message: str, title: str, webhook: str) -> None:
    """Send the message to the specified Microsoft Teams channel."""
    ms_message = pymsteams.connectorcard(webhook)
    ms_message.title(title)
    ms_message.text(f'<pre>\n{message}\n</pre>')

    ms_message.send()
Exemplo n.º 3
0
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
Exemplo n.º 4
0
def test_send_potential_action():
    """
        This sends a message with a potential action
    """

    myTeamsMessage = pymsteams.connectorcard(os.getenv("MS_TEAMS_WEBHOOK"))
    myTeamsMessage.text("This message should have three potential actions.")
    myTeamsMessage.title("Action Message Title")

    myTeamsPotentialAction1 = pymsteams.potentialaction(_name="Add a comment")
    myTeamsPotentialAction1.addInput("TextInput", "comment", "Add a comment",
                                     False)
    myTeamsPotentialAction1.addAction(
        "HttpPost", "Add Comment",
        "https://jsonplaceholder.typicode.com/posts")

    myTeamsPotentialAction2 = pymsteams.potentialaction(_name="Get Users")
    myTeamsPotentialAction2.addInput("DateInput", "dueDate", "Enter due date")
    myTeamsPotentialAction2.addAction(
        "HttpPost", "save", "https://jsonplaceholder.typicode.com/posts")

    myTeamsPotentialAction3 = pymsteams.potentialaction(_name="Change Status")
    myTeamsPotentialAction3.choices.addChoices("In progress", "0")
    myTeamsPotentialAction3.choices.addChoices("Active", "1")
    myTeamsPotentialAction3.addInput("MultichoiceInput", "list",
                                     "Select a status", False)
    myTeamsPotentialAction3.addAction(
        "HttpPost", "Save", "https://jsonplaceholder.typicode.com/posts")

    myTeamsMessage.addPotentialAction(myTeamsPotentialAction1)
    myTeamsMessage.addPotentialAction(myTeamsPotentialAction2)
    myTeamsMessage.addPotentialAction(myTeamsPotentialAction3)
    myTeamsMessage.summary("Message Summary")
    myTeamsMessage.send()
Exemplo n.º 5
0
async def notify(log_level: int = None) -> None:
    """Notify our users periodically of the number of red metrics."""
    logging.getLogger().setLevel(log_level or logging.ERROR)

    sleep_duration = int(os.environ.get('NOTIFIER_SLEEP_DURATION', 60))
    server_host = os.environ.get('SERVER_HOST', 'localhost')
    server_port = os.environ.get('SERVER_PORT', '5001')
    webhook = os.environ.get('TEAMS_WEBHOOK')

    while True:
        async with aiohttp.ClientSession(raise_for_status=True, trust_env=True) as session:
            response = await session.get(f"http://{server_host}:{server_port}/api/v3/reports")
            json = await response.json()

            reds_in_reports = reds_per_report(json)

            notification = "Number of red metrics in each report:"
            for report in reds_in_reports:
                notification += "\n\r - " + report[0] + ": " + str(report[1])

            if webhook:
                logging.info("Sending notification to configured webhook")
                my_teams_message = pymsteams.connectorcard(webhook)
                my_teams_message.text(notification)
                my_teams_message.send()
            else:
                logging.warning("No webhook configured; please set the environment variable TEAMS_WEBHOOK")

            logging.info("Sleeping %.1f seconds...", sleep_duration)
            await asyncio.sleep(sleep_duration)
Exemplo n.º 6
0
def send_msteams_message(state, timestamp, message="", dry_run=True):
    """Post error message to Teams."""
    # if platform.system() == "Windows":
    if not send_to_teams:
        if state:
            print("Automated WSV alert canceled (beta)")
            print(f"{timestamp}: WSV is running normaly.")
        else:
            print("Automated WSV Alert (beta)")
            print(
                f"{timestamp}: The automated WSV checking script has failed.{message}"
            )
    else:
        my_teams_message = pymsteams.connectorcard(
            os.environ.get['TEAMS_WEBHOOK'])
        if state:
            my_teams_message.title("Automated WSV alert canceled (beta)")
            my_teams_message.text(f"{timestamp}: WSV is running normaly.")
        else:
            my_teams_message.title("Automated WSV Alert (beta)")
            my_teams_message.text(
                f"{timestamp}: The automated WSV checking script has failed.{message}"
            )
            if "North_Europe" in message:
                my_teams_message.addLinkButton(
                    "Check WSV in North Europe!",
                    "https://www.websupervisor.net")
            if "Australia" in message:
                my_teams_message.addLinkButton(
                    "Check WSV in Australia!", "https://aus.websupervisor.net")
        my_teams_message.send()
Exemplo n.º 7
0
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")
Exemplo n.º 8
0
def sendtoteams(request):
    # Get the JSON from Request
    data = request.get_json()

    #Get Message Value (Depends on the form_param you define), user dashboard link

    title = data['form_params']['Title']
    message = data['form_params']['Message']
    msteamswebhook = data['data']['msteamswebhook']
    user_dash = data['data']['link']
    link_text = data['data']['linktext']

    # You must create the connectorcard object with the Microsoft Webhook URL
    myTeamsMessage = pymsteams.connectorcard(msteamswebhook)

    # Add title to the message.
    myTeamsMessage.title(title)

    # Add text to the message.
    myTeamsMessage.text(message)

    # Add Link Button
    myTeamsMessage.addLinkButton(link_text, user_dash)

    # send the message.
    myTeamsMessage.send()

    #if False not in response:
    return '{"looker": {"success": true}}'
Exemplo n.º 9
0
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)
Exemplo n.º 10
0
def send_message(text):

    if clients['msteams'] is True:

        print("msteams active")

        from config import msteams_webhook

        msteams = pymsteams.connectorcard(msteams_webhook)

        if clients['msteams'] is True:

            msteams.text(text)
            msteams.send()

    if clients['telegram'] is True:

        print("telegram active")

        from config import tg_token, tg_chat_id

        message = 'https://api.telegram.org/bot' + tg_token + '/sendMessage?chat_id=' + tg_chat_id + '&parse_mode=Markdown&text=' + text

        response = requests.get(message)

        return response.json()
Exemplo n.º 11
0
    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 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()
Exemplo n.º 13
0
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}")
Exemplo n.º 14
0
def selftest_function(opts):
    """
    Placeholder for selftest function. An example use would be to test package api connectivity.
    Suggested return values are be unimplemented, success, or failure.
    """
    options = opts.get("fn_teams", {})

    # determine if self test is enabled
    if not options.get(SELF_TEST):
        return {
            "state": "unimplemented",
            "reason": "{} not found in app.config".format((SELF_TEST))
        }
    else:
        webhook = options.get(SELF_TEST)

        try:
            card = pymsteams.connectorcard(webhook, http_proxy=opts['proxy_http'] if opts.get('proxy_http') else None,
                                           https_proxy=opts['proxy_https'] if opts.get('proxy_https') else None,
                                           http_timeout=60)

            card.title("Resilient SelfTest")
            card.text(datetime.ctime(datetime.now()))
            card.send()

            return {
                "state": "success",
                "reason": None
            }
        except Exception as err:
            log.error(err.message)
            return {
                "state": "failure",
                "reason": err.message if err.message else None
            }
Exemplo n.º 15
0
    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()
Exemplo n.º 16
0
def test_bad_webhook_call():
    with pytest.raises(pymsteams.TeamsWebhookException):
        #myTeamsMessage = pymsteams.connectorcard(os.getenv("MS_TEAMS_WEBHOOK"))
        myTeamsMessage = pymsteams.connectorcard("https://httpstat.us/500")
        myTeamsMessage.text("This is a simple text message.")
        myTeamsMessage.title("Simple Message Title")
        myTeamsMessage.send()
Exemplo n.º 17
0
    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)
Exemplo n.º 18
0
   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.'
Exemplo n.º 19
0
def send_teams_notification_traffic(rtr, interface, util, thresold):
    myTeamsMessage = pymsteams.connectorcard("<change-me>")
    myTeamsMessage.addSection(
        generate_teams_notification(rtr, interface, util, thresold))
    summary_text = 'summary_text'
    myTeamsMessage.summary(summary_text)
    myTeamsMessage.printme()
    myTeamsMessage.send()
Exemplo n.º 20
0
 def api_notifications(self, summary, last_test_data, previous_test):
     text = '# **Test Execution Summary**\n\n'
     text += self.create_api_test_summary(summary) + '_____'
     text += self.create_api_test_thresholds_info(last_test_data, self.args['comparison_metric']) + '_____'
     text += self.create_api_test_comparison_info(last_test_data, previous_test, self.args['comparison_metric'])
     ms_teams = pymsteams.connectorcard(self.args['ms_teams_web_hook'])
     ms_teams.text(text)
     ms_teams.send()
Exemplo n.º 21
0
 def ui_notifications(self, summary, last_test_data):
     text = '# **Test Execution Summary**\n\n'
     text += self.create_ui_test_summary(summary) + '_____'
     text += self.create_ui_test_thresholds_info(last_test_data) + '_____'
     text += self.create_ui_failed_pages_info(last_test_data)
     ms_teams = pymsteams.connectorcard(self.args['ms_teams_web_hook'])
     ms_teams.text(text)
     ms_teams.send()
Exemplo n.º 22
0
def main():
    hook_address = os.environ["MSTEAMS_HOOK_ADDRESS"]
    if len(hook_address) == 0:
        raise RuntimeError("Env variable missing")

    myTeamsMessage = pymsteams.connectorcard(hook_address)
    myTeamsMessage.text("It's coffee time!")
    myTeamsMessage.send()
Exemplo n.º 23
0
def sleeve(df):
#df.to_html()

myTeamsMessage = pymsteams.connectorcard("my webhook url ")
myTeamsMessage.title(“List Of Booking Status”)
#myTeamsMessage.text(“Test Mail”)
myTeamsMessage.text(df.to_string())
myTeamsMessage.send()
 def send_message(self, webhook, title, message, link):
     print(f'Teams Webhook: {webhook}')
     connectorcard = pymsteams.connectorcard(webhook)
     connectorcard.title(title)
     connectorcard.text(message)
     connectorcard.addLinkButton(link, link)
     print(f'|{title}| {message} [{link}]')
     connectorcard.send()
Exemplo n.º 25
0
def send_teams_report(report):
    try:
        teams_message = pymsteams.connectorcard(TEAMS_CHANNEL_WEBHOOK)
        teams_message.text(report)
        teams_message.send()
        print("[*] Report has been sent to Microsoft Teams!")
    except:
        print("[!] Sending to Microsoft Teams failed!")
Exemplo n.º 26
0
def send_msg_to_ms_teams(webhook_url, msg):
    """
    Send a message to a webhook (generated for a specific MS channel)
    For info on creating webhooks, see https://docs.microsoft.com/en-us/\
    microsoftteams/platform/webhooks-and-connectors/how-to/add-incoming-webhook
    """
    tms_msg = pymsteams.connectorcard(webhook_url)
    tms_msg.test(msg)
    tm_msg.send()
Exemplo n.º 27
0
    def _format_message(cls, alert, publication, webhook_url):
        """Format the message to be sent to Teams

        Args:
            alert (Alert): The alert
            publication (dict): Alert relevant to the triggered rule
            webhook_url (str): The webhook_url to send the card too

        Returns:
            pymsteams.connectorcard: The message to be sent to Teams
                The card will look like (by Default):
                    StreamAlert Rule Triggered: rule_name
                    Rule Description:
                    This will be the docstring from the rule, sent as the rule_description

                    Record:
                      key   value
                      key   value
                      ...
        """
        # Presentation defaults
        default_title = "StreamAlert Rule Triggered: {}".format(
            alert.rule_name)
        default_description = alert.rule_description
        default_color = "E81123"  # Red in Hexstring format

        # Special field that Publishers can use to customize the message
        title = publication.get("@teams.title", default_title)
        description = publication.get("@teams.description",
                                      default_description)
        card_color = publication.get("@teams.card_color", default_color)
        with_record = publication.get("@teams.with_record", True)

        # Instantiate the card with the url
        teams_card = pymsteams.connectorcard(webhook_url)

        # Set the cards title, text and color
        teams_card.title(title)
        teams_card.text(description)
        teams_card.color(card_color)

        # Add the Alert Section
        teams_card.addSection(cls._generate_alert_section(alert))

        if with_record:
            # Add the record Section
            teams_card.addSection(cls._generate_record_section(alert.record))

        if "@teams.additional_card_sections" in publication:
            teams_card = cls._add_additional_sections(
                teams_card, publication["@teams.additional_card_sections"])

        if "@teams.buttons" in publication:
            teams_card = cls._add_buttons(teams_card,
                                          publication["@teams.buttons"])

        return teams_card
Exemplo n.º 28
0
def send_to_teams(message):
    """
    Send a message to teams using a webhook.
    [Tutorial](www.create_the_webhoook.com)
    """
    teams_webhook = config.teams_webhook
    teams_message = pymsteams.connectorcard(teams_webhook)
    teams_message.text(message)
    teams_message.send()
Exemplo n.º 29
0
def send_notification(destination: str, text: str) -> None:
    """Send notification to Microsoft Teams using a Webhook."""
    logging.info("Sending notification to configured teams webhook")
    my_teams_message = pymsteams.connectorcard(destination)
    my_teams_message.text(text)
    try:
        my_teams_message.send()
    except Exception as reason:  # pylint: disable=broad-except
        logging.error("Could not deliver notification: %s", reason)
def send_notification_to_web_hook(web_hook_url: str,
                                  event_object: VeeamEvent) -> bool:
    logger_inst = logging.getLogger()
    logger_inst.debug('web_hook_url: ' + str(web_hook_url))
    logger_inst.debug('threat: ' + str(event_object))
    if uri_validator(web_hook_url) is not True:
        logger_inst.error('Malformed url: ' + str(web_hook_url))
        return False
    team_connection = pymsteams.connectorcard(web_hook_url)
    text = None
    if event_object.job_type_name is not None:
        if event_object.result_text == 'success':
            text = 'A Veeam ' + event_object.job_type_name + ' **"' + str(
                event_object.job_name
            ) + '"** has finished **successfully** at ' + str(
                event_object.end_time)[:-7]
            team_connection.color(
                '005f4b')  # it's a brand color named "Veeam Sapphire", btw
        elif event_object.result_text == 'warning':
            text = 'A Veeam ' + event_object.job_type_name + ' **"' + str(
                event_object.job_name
            ) + '"** has finished with **warning** and result: \n\n"' + str(
                event_object.reason) + '" at ' + str(
                    event_object.end_time)[:-7]
            team_connection.color('ffff00')  # just Yellow
        elif event_object.result_text == 'failed':
            text = 'A Veeam ' + event_object.job_type_name + ' **"' + str(
                event_object.job_name
            ) + '"** has **failed** with a result: \n\n"' + str(
                event_object.reason) + '" at ' + str(
                    event_object.end_time)[:-7]
            team_connection.color('ba0200')  # "Veeam Accent Red"
    else:
        if event_object.result_text == 'success':
            # There is no need to notify about system events when everything is good
            return True
        elif event_object.result_text == 'warning':
            text = 'A Veeam Task **"' + event_object.job_name + '"** has finished with **warning** and result: \n\n"' + str(
                event_object.reason).replace('\n\n', ' ') + '" at ' + str(
                    event_object.end_time)[:-7]
            team_connection.color('ffff00')  # just Yellow
        elif event_object.result_text == 'failed':
            text = 'A Veeam Task **"' + event_object.job_name + '"** has **failed** with a result: \n\n"' + str(
                event_object.reason).replace('\n\n', ' ') + '" at ' + str(
                    event_object.end_time)[:-7]
            team_connection.color('ba0200')  # "Veeam Accent Red"
    if text is None:
        return False
    team_connection.text(text)
    try:
        result = team_connection.send()
    except Exception as error:
        logger_inst.error(
            'Unable to send notification to MS Teams due to the following error: \n'
            + str(error))
        return False
    return result
Exemplo n.º 31
0
    def post_receive(self, alert):

        if alert.repeat:
            return

        if MS_TEAMS_SUMMARY_FMT:
            try:
                template = Template(MS_TEAMS_SUMMARY_FMT)
            except Exception as e:
                LOG.error('MS Teams: ERROR - Template init failed: %s', e)
                return

            try:
                template_vars = {
                    'alert': alert,
                    'config': app.config
                }
                summary = template.render(**template_vars)
            except Exception as e:
                LOG.error('MS Teams: ERROR - Template render failed: %s', e)
                return
        else:
            summary = ('<b>[{status}] {environment} {service} {severity} - <i>{event} on {resource}</i></b>').format(
                status=alert.status.capitalize(),
                environment=alert.environment.upper(),
                service=','.join(alert.service),
                severity=alert.severity.capitalize(),
                event=alert.event,
                resource=alert.resource
            )
            url = "%s/#/alert/%s" % (DASHBOARD_URL, alert.id)
            
        if alert.severity == 'critical':
            color = "D8122A"
        elif alert.severity == 'major':
            color = "EA680F"
        elif alert.severity == 'minor':
            color = "FFBE1E"
        elif alert.severity == 'warning':
            color = "BA2222"
        else:
            color = "00AA5A"

        LOG.debug('MS Teams payload: %s', summary)

        try:
            msTeamsMessage = pymsteams.connectorcard(MS_TEAMS_WEBHOOK_URL)
            msTeamsMessage.title(summary)
            msTeamsMessage.text(alert.text)
            msTeamsMessage.addLinkButton("Open in Alerta", url)
            msTeamsMessage.color(color)
            msTeamsMessage.send()
        except Exception as e:
            raise RuntimeError("MS Teams: ERROR - %s", e)