In this article, we will go through building a runbook with Powershell and Telegram to allow us to interact with the script with just a message.
If you haven’t read it yet, have a look at Automating Telegram Messages with Powershell – In there, I build a simple script that helps me interact with users members of a Telegram group. That article has the core of what I’m about to show you now and will also explain how to get a Telegram Bot setup.
So in this specific example, we will build a very simple runbook with Powershell that will integrate with Telegram: this will allow us to “talk” to our powershell script with just a Telegram message. What’s cool about the below, is that you can keep adding “switches” to increase the amount of tasks the script can perform. What’s even cooler is that the script below will allow you to run powershell with a Telegram message and get the output on your phone! In other words, I can tell the script to run whatever command I want. 🙂
Here’s an example of me messaging the Telegram bot with “run get-childitem -path c:\users” and the result (screenshot taken from the web interface of Telegream, but it’s the same on your phone):
The script leverages a “Switch” to handle multiple IFs and specifically, it’ll will follow this flow:
- Check for any new Message in the Telegram conversation, in a loop.
- Note: To be safe, when the script starts up, it’ll ignore the last message sent, and will be listening for any new message right after that.
- To perform this, I used the Message Timestamp that is in Telegram’s json ($LastMessage.message.date).
- If a new Message has been received, check with a Switch if the message contains either “run *” and “quit_script”.
- If it contains “run *” (example: run Get-ChildItem -Path C:\), it’ll split the string received and run the command in powershell.
- If the message is “quit_script”, it’ll exit the script running on the computer.
- If it doesn’t contain anything like that (example: Hello), it’ll tell the user that the script doesn’t understand that command.