Posting Messages To Microsoft Teams With Code
[C#, .NET, Microsoft Teams]
Microsoft Teams makes use of an API, the Microsoft Graph API, that is leveraged to push data into, and pull data out of various Microsoft Products, chiefly Office 365.
The premise in Teams is communications happens in the context of channels
, that are child entities of teams
.
To communicate with a channel
, you require a webhook
. By default, channels do not have webhooks.
Channels
& webhooks
can be added by owners of the teams, or administrators.
This is done in the settings of the team.
This opens the following dialog, allowing specification of multiple connectors.
Identify Incoming Webhook
and click Configure
In the resulting screen you can configure the following
- A name (which is mandatory)
- An image (to give the integrating application a distinctive look)
You will need to scroll down to save
Once you save you will get the following screen
The URL there is the webhook
.
You will need this for any application or script that interfaces with Teams. It is pretty long, but there is an icon that will copy it to the clipboard.
If you need to access the webhook, or change the name, click the Connectors
menu again.
This time click Configured
The resultant screen will show you a link with the existing configured connectors.
Click that link to access the setup
Once the webhooks are generated you can post messages to the approproate channels using a HTTP request
using whatever technique - Powershell
, Curl
, HTTPie
or other such.
Bash on macOS or Linux
curl -H 'Content-Type: application/json' -d '{"text": "Hello World"}' <YOUR WEBHOOK URL>
Command Prompt Or Bash on Windows
curl.exe -H "Content-Type:application/json" -d "{'text':'Hello World'}" <YOUR WEBHOOK URL>
Note for windows the .exe
is important otherwise the shell will consider curl
as an alias for invoke-webrequest
You can install curl directly here. Alternatively you can use Chocolatey package manager if you are on windows. In which case you run this command from your favourite shell
choco install curl
For Linux, curl is usually installed by default.
Powershell
Invoke-RestMethod -Method post -ContentType 'Application/Json' -Body '{"text":"Hello World!"}' -Uri <YOUR WEBHOOK URL>
Resources
Happy hacking!