To send messages to the Microsoft teams channel, we will use the requests module.
import requests import json response = requests.post(url, headers=headers, data=json.dumps(payload))
'url' will be the webhook URL of the channel which can be fetched as below.
In your Teams application, click on the 'Apps'. Search for 'webhook'.
Click on the 'Incoming Webhook'. On the next screen, click on the 'Add to a team' button.
On the next screen, search for the team and channel you want to add the webhook app and then click 'Set up a connector' button at the bottom.
Enter the name of the connector and select the icon image and click 'create'. A webhook URL will be generated. Copy this URL.
Webhook URL should be in similar to the below URL:
url = "https://outlook.office.com/webhook/" \
"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx/" \
"IncomingWebhook/xxxxxxxxxxxxxxxxx/" \
"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx"
Sending a simple text message:
To send a plain text message, create a payload JSON with 'text' as key.
payload = {
"text": "Sample Alert Text"
}
Create headers JSON and add the 'Content-Type' header in it.
headers = {
'Content-Type': 'application/json'
}
Putting it all together:
import requests
import json
url = "https://outlook.office.com/webhook/" \
"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx@xxxxxx-xxx-xxx-xxx-xxxxx/" \
"IncomingWebhook/xxxxxxxxxxxxxxxx/" \
"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx"
payload = {
"text": "Sample alert text"
}
headers = {
'Content-Type': 'application/json'
}
response = requests.post(url, headers=headers, data=json.dumps(payload))
print(response.text.encode('utf8'))
Make sure the requests
module is installed in your virtual environment. Execute the above code.
python ms_teams_alert.py
You should receive an alert on your channel.
Host your Django Application for free on PythonAnyWhere. If you want full control of your application and server, you should consider DigitalOcean. Create an account with this link and get $100 credits.