/ PowerShell

Telegram Notifications with Powershell

I recently had the need for a basic notification service as part of my Gigafiber Availability check script. I decided on Telegram for a few reasons, I'd already used it before, it's very simple to use the API, and it's free.

To get started you'll want to download the application to your phone. (apple/android)
Next, sign up for an account.

Then on the top right hit search and type in @BotFather, select the result.

In your chat with BotFather type /newbot, it'll ask for a name, come up with one ending in bot. If your name was unique BotFather will reply with your API token code. You'll want to hold onto this for later.

Now open a chat with your bot by going back to the home page, hitting search on the top right, and searching for @YourBotName. Hit Start, or type /start.
Note: You always have to start the conversation with a bot, it cannot initiate chats.

Now we need to grab your private chat ID, open up a browser and go to https://api.telegram.org/bot<bottokenhere>/getUpdates. You should see a line that has your "/start" message. On this line look for Chat, then ID. This is the ID for your private chat. Record this for later.

Now open up a text editor or ISE and paste in the below script.

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

$botToken = ''
$chatID = ''
$messageText = ''

$telegramURI = ("https://api.telegram.org/bot" + $botToken + "/sendMessage")
$telegramJson = ConvertTo-Json -Compress @{chat_id = $chatID; text=$messageText}
$telegramResponse = Invoke-RestMethod -Uri $telegramURI -Method Post -ContentType 'application/json;charset=utf-8' -Body $telegramJson

Fill out the variables botToken and chatID with the values you received earlier and messageText with whatever you'd like your message to be.

Now execute the script. Did it work? If so, great. If not double check your token and chatID or try a more basic message. The response to your API call is recorded in the variable telegramResponse, a successful response should have Ok: True and a non-empty result.

The script can certainly be improved, this is the bare minimum for something that can easily be copy/pasted into your own scripts. If it's critical your message get sent, you may want to implement error handing to check the response from Telegram.

If you'd like to implement additional functionality the full api documentation for Telegram bots can be found (here).

Telegram Notifications with Powershell
Share this