Notify msteams throws error (import requests, no named module) - but it´s allready installed

CMK version: Raw 2.0.p19
OS version: Ubuntu 20.04.4 LTS
Installed MKP: MSTeams-1.5.mkp from @ricardoftribeiro

Hi, hope someone could help. I´ve installed the MKP above, setting up the notification rule, restarting site and testing notification. Notification get failed, error message follows:

Error message:

> ImportError: No module named requests Traceback (most recent call last): -- File "/omd/sites/azure/local/share/check_mk/notifications/msteams", line 6, in <module> -- import requests -- ImportError: No module named requests

Output of: “sudo pip3 install requests”:

> Requirement already satisfied: requests in /usr/lib/python3/dist-packages (2.22.0)

Output of: “sudo apt install python3-requests”:

> python3-requests is already the newest version (2.22.0-2ubuntu1)

The requests must exists inside the site Python.
Can you try a “su azure” and then “pip3 install requests”.
Now the notification plugin should work.

1 Like

Requests is already included in the site’s Python 3 installation.

I assume that this notification script still tries to use Python 2. Have a look at its first line. It should read

#!/usr/bin/env python3

If not, the script needs to be migrated to Python 3.

2 Likes

:pensive:

> #!/usr/bin/env python

Installation done:

> OMD[azure]:~$ pip3 install requests
> Collecting requests
>   Downloading requests-2.27.1-py2.py3-none-any.whl (63 kB)
>      |████████████████████████████████| 63 kB 23 kB/s
> Collecting charset-normalizer~=2.0.0; python_version >= "3"
>   Downloading charset_normalizer-2.0.12-py3-none-any.whl (39 kB)
> Collecting urllib3<1.27,>=1.21.1
>   Downloading urllib3-1.26.9-py2.py3-none-any.whl (138 kB)
>      |████████████████████████████████| 138 kB 51.1 MB/s
> Collecting certifi>=2017.4.17
>   Downloading certifi-2021.10.8-py2.py3-none-any.whl (149 kB)
>      |████████████████████████████████| 149 kB 49.3 MB/s
> Collecting idna<4,>=2.5; python_version >= "3"
>   Downloading idna-3.3-py3-none-any.whl (61 kB)
>      |████████████████████████████████| 61 kB 8.7 MB/s
> Installing collected packages: charset-normalizer, urllib3, certifi, idna, requests
> Successfully installed certifi-2021.10.8 charset-normalizer-2.0.12 idna-3.3 requests-2.27.1 urllib3-1.26.9

fired up new alert →

same result:
Traceback (most recent call last): – File “/omd/sites/azure/local/share/check_mk/notifications/msteams”, line 6, in – import requests – ImportError: No module named requests

i’m not a developer, is it possible to change the first line and give it a try?

ah no, throws other errors… bad idea…

@ricardoftribeiro: is it possible for you, to migrate your script to python3?

Try 2to3 for the migration.

1 Like

migration runs without problems. should i change first line from python to python3 now?

It looks like the shebang is not replaced with the correct one. Yes you need to change it to python3.

Inside a CMK 2.0 site only python3 is available.
For the “pip3 install …” @r.sander was completely right that the requests is already included. Only if you need modules that are not already existing, then you need to install it with “pip3 install …”.

If this is changed and you start the script directly inside your site, you should get the message Webhook URL not set.

ok, i will give it a try…

Yes you need to change it to python3.

done

If this is changed and you start the script directly inside your site, you should get the message Webhook URL not set .

exact, that´s the output

new day, new try, new error :sweat_smile: (changed to python3, → replay notify via webgui → notifications)

> Traceback (most recent call last): -- File "/omd/sites/azure/local/share/check_mk/notifications/msteams", line 10, in <module> -- context = dict([ (var[7:], value.decode("utf-8")) -- File "/omd/sites/azure/local/share/check_mk/notifications/msteams", line 10, in <listcomp> -- context = dict([ (var[7:], value.decode("utf-8")) -- AttributeError: 'str' object has no attribute 'decode'

notify.log

46  2022-04-27 09:20:58,710 [20] [cmk.base.notify] ----------------------------------------------------------------------
    47  2022-04-27 09:20:58,710 [20] [cmk.base.notify] Analysing notification (XXX-PKR) context with 36 variables
    48  2022-04-27 09:20:58,711 [20] [cmk.base.notify] Global rule ''...
    49  2022-04-27 09:20:58,711 [20] [cmk.base.notify]  -> matches!
    50  2022-04-27 09:20:58,711 [20] [cmk.base.notify]    - adding notification of monitoring via msteams
    51  2022-04-27 09:20:58,712 [15] [cmk.base.notify] Global rule 'Notify all contacts of a host/service via HTML email'...
    52  2022-04-27 09:20:58,712 [15] [cmk.base.notify]  -> does not match: The host's name 'XXX-PKR' is on the list of excluded hosts
    53  2022-04-27 09:20:58,712 [15] [cmk.base.notify] Global rule 'Only one notify during a service problem'...
    54  2022-04-27 09:20:58,712 [15] [cmk.base.notify]  -> does not match: This rule requires membership in a service group, but this is a host notification
    55  2022-04-27 09:20:58,713 [20] [cmk.base.notify] Executing 1 notifications:
    56  2022-04-27 09:20:58,713 [20] [cmk.base.notify]   * would notify monitoring via msteams, parameters: url_prefix, webhook, bulk: no

SOLVED: like @r.sander helped in other thread. Issue with python-requests

same solution… thanks for your help @andreas-doehler und @r.sander !

1 Like

would you share your ported and working version :)? (I don’t need it right now but others might appreciate it)

1 Like

of course…

#!/usr/bin/env python3
# MS-Teams
# Author : ricardoftribeiro@gmail.com @krfribeiro

import os, sys
import requests
import json
import re

context = dict([ (var[7:], value)
                  for (var, value) in os.environ.items()
                  if var.startswith("NOTIFY_")])

map_states = {
        "OK":           ("ok.png","2eb886" ),
        "WARNING":      ("warning.png","daa038" ),
        "CRITICAL":     ("critical.png","a30200" ),
        "UNKNOWN":      ("unknown.png","cccccc" ),
        "DOWN":         ("critical.png","a30200" ),
        "UP":           ("ok.png","2eb886" ),
}

regexp = re.compile(r'CRITICAL|WARNING|UNKNOWN|OK|DOWN|UP')

if 'PARAMETER_WEBHOOK' in context:
        msteams_path = context["PARAMETER_WEBHOOK"]
else:
        sys.stderr.write("Webhook URL not set\n")
        sys.exit(2)

if 'PARAMETER_URL_PREFIX' in context:
    baseURL=re.sub('/$','',context['PARAMETER_URL_PREFIX'])
else:
    baseURL="https://" + context['MONITORING_HOST'] + "/" + context['OMD_SITE']

icons_path = "https://github.com/krfribeiro/check_mk/raw/master/local/share/check_mk/web/images/"

headers = {"Content-type": "application/json", "Accept": "text/plain"}
message = context['NOTIFICATIONTYPE']  + ' | Hostname : ' + context['HOSTNAME'] + " "
authorText = ""

if context['WHAT'] == 'SERVICE':
    message += "| Service: " + context['SERVICEDESC']
    context['DETAILS_OUTPUT'] = context['SERVICEOUTPUT']
    infoURL = baseURL + context['SERVICEURL']
    if context['NOTIFICATIONAUTHOR'] != '':
        authorText += "Triggered by **" + context['NOTIFICATIONAUTHOR'] + "** - *" + context['NOTIFICATIONCOMMEN>    if context['NOTIFICATIONTYPE'] == 'DOWNTIMESTART':
        icon = "downtime.png"
        colour = "439FE0"
        message += " - Downtime started"
    elif context['NOTIFICATIONTYPE'] == 'DOWNTIMEEND':
        icon = "downtime.png"
        colour = "33cccc"
        message += " - Downtime ended"
    elif context['NOTIFICATIONTYPE'] == 'ACKNOWLEDGEMENT':
        icon = "acknowledge.png"
        colour = "8f006b"
        message += " | " + context['SERVICEACKCOMMENT']
    elif regexp.search(context['SERVICESTATE']):
        icon, colour = map_states.get(context['SERVICESTATE'])
        message += " is " + context['SERVICESTATE']
    else:
        icon = "cmk.png"
else:
    message += "is " + context['HOSTSTATE']
    context['DETAILS_OUTPUT'] = context['HOSTOUTPUT']
    infoURL = baseURL + context['HOSTURL']
    if context['NOTIFICATIONAUTHOR'] != '':
        authorText += "Triggered by **" + context['NOTIFICATIONAUTHOR'] + "** - *" + context['NOTIFICATIONCOMMEN>    if context['NOTIFICATIONTYPE'] == 'DOWNTIMESTART':
        icon = "downtime.png"
        colour = "439FE0"
        message += " - Downtime started"
    elif context['NOTIFICATIONTYPE'] == 'DOWNTIMEEND':
        icon = "downtime.png"
        colour = "33cccc"
        message += " - Downtime ended"
    elif context['NOTIFICATIONTYPE'] == 'ACKNOWLEDGEMENT':
        icon = "acknowledge.png"
        colour = "8f006b"
        message += " | " + context['HOSTACKCOMMENT']
    elif regexp.search(context['HOSTSTATE']):
        icon, colour = map_states.get(context['HOSTSTATE'])
    else:
        icon = "cmk.png"

sections = {
        "activitySubtitle": authorText,
        "activityImage": icons_path + icon,
        "facts": [{
            "name": "Detail",
            "value": context['DETAILS_OUTPUT']
        }, {
            "name": "Affected groups",
            "value": context['HOSTGROUPNAMES']
        }],
        "markdown": "True"
    }


data = {
    "@type": "MessageCard",
    "@context": "http://schema.org/extensions",
        "title": message,
    "themeColor": colour,
    "summary": message,
    "sections": [sections],
    "potentialAction": [{
        "@type": "OpenUri",
        "name": "Alarm Details",
        "targets": [{
            "os": "default",
            "uri": infoURL
        }]
    }]
}

conn = requests.post(msteams_path, data = json.dumps(data))

if conn.status_code == 200:
        sys.exit(0)
else:
        sys.stderr.write(conn.text)
        sys.exit(2)
1 Like

Hi,

a new version of the plugin is under review.
But already available on git

Get the files in place :

Please give me your feedback.
Cheers,

2 Likes

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed. Contact an admin if you think this should be re-opened.