MSTeams Notification
To send a notification to a Microsoft Teams channel using a WebHook in Python, you can use the `requests` library to make an HTTP POST request to the WebHook URL provided by Teams. Here's a basic example of how you can do this:
Steps to set up Teams WebHook:
1. Go to the channel where you want to send the message.
2. Click on the `...` (More options) next to the channel name.
3. Select `Connectors`.
4. Search for and add the `Incoming Webhook`.
5. Set it up by giving it a name and an icon (optional), and it will generate a WebHook URL.
6. Copy that URL; you'll use it in your Python code.
Python Code:
import requests
import json
def send_teams_message(webhook_url, message):
# Payload to send to Teams
payload = {
"text": message
}
# Send the HTTP request to the Teams WebHook
headers = {'Content-Type': 'application/json'}
response = requests.post(webhook_url, data=json.dumps(payload), headers=headers)
if response.status_code == 200:
print("Message sent successfully!")
else:
print(f"Failed to send message. Status code: {response.status_code}, Response: {response.text}")
# Example usage:
webhook_url = 'https://outlook.office.com/webhook/your-webhook-url-here'
message = 'This is a test notification from Python!'
send_teams_message(webhook_url, message)
Explanation:
- webhook_url: The WebHook URL generated by Teams.
- message: The content of the message you want to send to the Teams channel.
- The message is sent as a JSON payload in the POST request.
You can enhance this by customizing the payload to include additional details like a title, theme, etc., using Teams' message card format if needed.
Make sure you have the `requests` library installed. You can install it via pip:
pip install requests