Skip to content

Instantly share code, notes, and snippets.

@PaulTR
Created December 6, 2016 21:59
Show Gist options
  • Save PaulTR/a536c079d9ec6b8e3d7dc19034d4f658 to your computer and use it in GitHub Desktop.
Save PaulTR/a536c079d9ec6b8e3d7dc19034d4f658 to your computer and use it in GitHub Desktop.
import os
import time
import requests
from slackclient import SlackClient
# add bot id and slack bot token
BOT_ID =
SLACK_BOT_TOKEN =
# constants
AT_BOT = "<@" + BOT_ID + ">"
VERSION = "version"
# instantiate Slack & Twilio clients
slack_client = SlackClient(SLACK_BOT_TOKEN)
def handle_command(command, channel, user):
"""
Receives commands directed at the bot and determines if they
are valid commands. If so, then acts on the commands. If not,
returns back what it needs for clarification.
"""
response = "Wat"
headers={'Accept': 'text/plain'}
args = command.split();
if command.startswith(VERSION):
response = requests.get('http://foaas.com/version', headers=headers).text
else:
if len(args) == 1:
response = requests.get('http://foaas.com/' + args[0] + "/" + user, headers=headers).text
if len(args) == 2:
response = requests.get('http://foaas.com/' + args[0] + "/" + args[1] + "/" + user, headers=headers).text
if len(args) == 3:
response = requests.get('http://foaas.com/' + args[0] + "/" + args[1] + "/" + args[2] + "/" + user, headers=headers).text
slack_client.api_call("chat.postMessage", channel=channel,
text=response, as_user=True)
def parse_slack_output(slack_rtm_output):
"""
The Slack Real Time Messaging API is an events firehose.
this parsing function returns None unless a message is
directed at the Bot, based on its ID.
"""
output_list = slack_rtm_output
if output_list and len(output_list) > 0:
for output in output_list:
if output and 'text' in output and AT_BOT in output['text']:
# return text after the @ mention, whitespace removed
payload = {'token': SLACK_BOT_TOKEN, 'user': output['user']}
r = requests.get('https://slack.com/api/users.info', params=payload)
username = r.json()['user']['name']
return output['text'].split(AT_BOT)[1].strip().lower(), \
output['channel'], username
return None, None, None
if __name__ == "__main__":
READ_WEBSOCKET_DELAY = 1 # 1 second delay between reading from firehose
if slack_client.rtm_connect():
print("StarterBot connected and running!")
while True:
command, channel, user = parse_slack_output(slack_client.rtm_read())
if command and channel and user:
handle_command(command, channel, user)
time.sleep(READ_WEBSOCKET_DELAY)
else:
print("Connection failed. Invalid Slack token or bot ID?")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment