Created
July 26, 2017 01:57
-
-
Save WhiteRaBot/913fb397bd4f1749edf105ab17c543e6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Import Slack Client | |
from slackclient import SlackClient | |
## Import Time | |
import time | |
#Set Bot Name | |
BOT_NAME = '' | |
#We will give the token in a moment | |
SLACK_BOT_TOKEN = "" | |
CHANNEL_ID = "" | |
BOT_ID = "" | |
AT_BOT = '<@' + BOT_ID + '>' | |
### OUR FIRST COMMAND #### | |
EXAMPLE_COMMAND = 'hello' | |
# This is for communicating with the Slack API | |
slack_client = SlackClient(SLACK_BOT_TOKEN) | |
### This is the command Parser that many start bots use for Slack | |
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 | |
return (output['text' | |
].split(AT_BOT)[1].strip().lower(), | |
output['channel']) | |
return (None, None) | |
def handle_command(command, channel): | |
""" | |
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 = 'Not sure what you mean. Use the *' + EXAMPLE_COMMAND \ | |
+ '* command with numbers, delimited by spaces.' | |
if command.startswith(EXAMPLE_COMMAND): | |
response = 'Greetings, and Congratulations' | |
slack_client.api_call('chat.postMessage', channel=channel, | |
text=response, as_user=True) | |
else: | |
response = 'Channel: ' + channel \ | |
+ 'I do not understand this command!!' | |
slack_client.api_call('chat.postMessage', channel=channel, | |
text=response, as_user=True) | |
## __main__ is default for the top level .py being run in all py programs | |
if __name__ == '__main__': | |
## Setting a delay for how quickly to check for commands | |
READ_WEBSOCKET_DELAY = 1 # 1 second delay between reading from firehose | |
if slack_client.rtm_connect(): | |
print ('Bot connected and running!') | |
while True: | |
(command, channel) = \ | |
parse_slack_output(slack_client.rtm_read()) | |
if command and channel: | |
handle_command(command, channel) | |
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