Powershell-SlackBot: Harnessing the Power of the Slack Real-Time Messaging API

This project is a PowerShell implementation of a Chat Bot for Slack that utilises the Slack Real Time Messaging (RTM) API. This code is intended to provide a simple framework for anyone that wants to write a Chat Bot for a single Slack Team that is able to respond to Channel and Direct Messages. It would also be simple to extend the code to permit the Bot to respond to any other events exposed via the RTM API.

Requirements

This script uses the .NET class: System.Net.WebSockets.WebSocket. As such the code has to be run on Windows 8 / Server 2012 or newer operating systems.

Getting Started

To get started with this project, you’ll first need to create a Bot under Custom Integrations > Bots in your Slack account. Once you have done that, you’ll need to obtain the API token for your Bot, which can be passed to the Invoke-SlackBot cmdlet as a parameter or read from an XML file created via $Token | Export-CliXML.

If you’re running PowerShell 5, you can install the SlackBot module from the PowerShell Gallery using the following command:

Install-Module -Name SlackBot

Alternatively, you can download or clone the module folder from the GitHub repository and copy it to your modules directory. Then, you can load the module with the following command:

Import-Module SlackBot

Once you have the module loaded, you can start the Bot by executing the following command:

Invoke-SlackBot -token "yourtoken"

The bot will generate a log file by default in your User Profile directory (C:\Users\youruser) under \Logs, and all log messages will also appear in the console as either PowerShell standard Verbose, Warning or Error output.

The bot is currently configured to respond to any Direct Messages, or any conversation that includes @botname (whatever you named your Bot) as any word of the message.

Extending the script

There are two obvious places to extend the script:

  1. Add additional conditions in the Switch($words) statement and any code that you want executed when those conditions are matched. Currently, it splits the message into an Array of $words, but you may want to instead match the full .text response of the message.

  2. Add additional conditions in the Switch($RTM) statement to match other RTM API events. See the RTM API documentation for a full list of events.

Contributions

The author welcomes contributions to this project. If you have any ideas or improvements, feel free to submit a pull request or open an issue on the GitHub repository.