Creating a simple Slack chat bot with PHP

Creating a simple Slack chat bot with PHP

To create the bot, we are going to use Slack’s Outgoing Webhooks integration. With it, we can create any page and whenever a message is sent into a specific Slack channel or in any Slack channel your page will be called with information about the sender of the message, the message itself and other useful metadata. When a request is made to your page, you can return JSON with the property text in it and the bot will send back a response directly in the channel in which the message occurred.

Whenever you initialize Outgoing Webhooks for a team you will be given a few settings. The bot can listen for messages on a specific channel, or in all channels. If the bot listens for requests on all channels, you need to provide a trigger word mandatorily. The message in the channel needs to start with the trigger word for your page/script to be called by Slack. You can also customize the bot by providing it with a name and a picture.  You have to enter the URL which will be called when a message is sent in the channel and which matches the trigger word(s), if any.

Now, let us create a file responding to the given URL in the Outgoing Webhooks settings.

Let us make a simple help function which returns a list of what the bot is capable of. We can actually provide Markdown in the bot’s response text. To do this, we simply enter the Markdown itself in the message and when returning a response, we simply provide another property called mrkdwn.

We then check if the parameter text is sent with the request – and if so, we remove everything from the command up to the first : sign. We do this because we expect a text such as botName: command

Then, if what is left of the text is equal to help – we know that the person wants to see the help command.

The same goes with the kittens command.

We send a request to the Cat API to get an actual image which would be previewable in Slack and simply send the URL back into the channel. We then simply check if the command is kittens and call the kittens function:

So, we end up with a simple bot which can be refactored and customized in great details to serve any purpose.

Author Surjit Sidhu

Surjit SidhuSurjit is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling.

Leave a Reply

Be the First to Comment!

avatar

wpDiscuz