How To Build a Bot Using Slack And AWS

Original article can be found here (source): Artificial Intelligence on Medium

sample python code

“””
Slack chat-bot Lambda handler.
“””

import os
import logging
import urllib

# Grab the Bot OAuth token from the environment.
BOT_TOKEN = os.environ[“BOT_TOKEN”]

# Define the URL of the targeted Slack API resource.
# We’ll send our replies there.
SLACK_URL = “
https://slack.com/api/chat.postMessage

def lambda_handler(data, context):
“””Handle an incoming HTTP request from a Slack chat-bot.
“””
if “challenge” in data:
return data[“challenge”]
# Grab the Slack event data.
slack_event = data[‘event’]

# We need to discriminate between events generated by
# the users, which we want to process and handle,
# and those generated by the bot.
if “bot_id” in slack_event:
logging.warn(“Ignore bot event”)
else:
# Get the text of the message the user sent to the bot,
# and reverse it.
text = slack_event[“text”]
reversed_text = text[::-1]

# Get the ID of the channel where the message was posted.
channel_id = slack_event[“channel”]

# We need to send back three pieces of information:
# 1. The reversed text (text)
# 2. The channel id of the private, direct chat (channel)
# 3. The OAuth token required to communicate with
# the API (token)
# Then, create an associative array and URL-encode it,
# since the Slack API doesn’t not handle JSON (bummer).
data = urllib.parse.urlencode(
(
(“token”, BOT_TOKEN),
(“channel”, channel_id),
(“text”, “Hello! How are you doing “)
)
)
data = data.encode(“ascii”)

# Construct the HTTP request that will be sent to the Slack API.
request = urllib.request.Request(
SLACK_URL,
data=data,
method=”POST”
)
# Add a header mentioning that the text is URL-encoded.
request.add_header(
“Content-Type”,
“application/x-www-form-urlencoded”
)

# Fire off the request!
urllib.request.urlopen(request).read()

# Everything went fine.
return “200 OK”

We reference an environment variable for the bot OAuth token, so let’s define it under the Environment variables.

We now need to enable event subscription. The way the chat bot will work is the following:

  • Users send a direct chat message to the chat-bot
  • An event representing that message is published
  • If the bot is subscribed to that type of event, a HTTP POST request, containing information about that chat message, is dispatched to a Web resource living at a given URL.

let’s also create and assign an appropriate role to the function. Scroll down to the Execution role and role section and select Create a role new role from aws policies templates from the Role dropdown.

Back to API Gateway

Configure the resource so that it handles POST requests. Click on the Actions button again and select Create Method, then click on the new drop down field that has appeared and select POST. Finally, click on the tick icon.

Click Save. A pop-up notifying you that you are about to give the API Gateway permission to your new Lambda function will appear. Click OK.

Upon clicking OK, you will end up landing on the following screen:

Now it’s time to deploy the API and made available through a specific web URL. Click on Actions, and then Deploy API.

Click on Actions and then Deploy API

Enter a Stage name and Stage description of your choice and click on Deploy

Important: You need the URL of your event-handler resource, not the root resource! Expand the tree and click on the green POST link to get to it.

Copy the Link URL. Now we need to subscribe the bot to the right type of event

Go to the Event Subscriptions page and Enable Events:

Scroll down to the Subscribe to Bot Events section and click on the Add Bot User Event. Select message.im as the event type:

Save your changes and go back to the Slack team channel.

Conclusion

Thanks to those who already published articles on how to create a bot using Slack and AWS. This Article is updated version of all those. I hope this was useful. I’m working to add more intelligence to this bot. Stay Tuned!