Skip to content

Instantly share code, notes, and snippets.

@vvalorous
Forked from jnth/slack-blink1.py
Created March 26, 2018 23:36
Show Gist options
  • Save vvalorous/18d7595dfb7e423ef82997107ed4822d to your computer and use it in GitHub Desktop.
Save vvalorous/18d7595dfb7e423ef82997107ed4822d to your computer and use it in GitHub Desktop.
Interaction between Slack and Blink1.
#!/usr/bin/env python3.6
# coding: utf-8
"""Interaction between Slack and Blink1.
Use the Slack Real Time Messaging API to analyze message and turn on the
Blink1 device.
Based on this great blog article :
https://www.fullstackpython.com/blog/build-first-slack-bot-python.html
In Slack, create an app with a bot.
Start this script and send message to the corresponding bot like this :
@bot red
@bot #00ff00
"""
import os
import time
import webcolors
from slackclient import SlackClient
from blink1.blink1 import Blink1
# Define SLACK_BOT_ID and SLACK_BOT_TOKEN environnement varible.
BOT_ID = os.environ.get('SLACK_BOT_ID')
TOKEN = os.environ.get('SLACK_BOT_TOKEN')
AT_BOT = f"<@{BOT_ID}>"
# Init
sc = SlackClient(TOKEN)
b = Blink1()
def parse_slack_output(outputs):
"""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.
"""
if outputs and len(outputs) > 0:
for output in outputs:
if output and 'text' in output and AT_BOT in output['text']:
# return text after the @ mention and channel
return (output['text'].split(AT_BOT)[1].strip().lower(),
output['channel'])
return None, None
def send_message(message, channel):
"""Send a message in Slack."""
sc.api_call("chat.postMessage", channel=channel, text=message,
as_user=True)
def handle_blink(color, channel):
"""Handle command."""
# Is it a name of a hex ?
if color in webcolors.CSS3_NAMES_TO_HEX:
b.fade_to_color(200, color)
send_message("ok", channel)
return True
else:
if '#' in color and len(color) == 7:
rgb = webcolors.hex_to_rgb(color)
b.fade_to_rgb(200, *rgb)
send_message("ok", channel)
return True
elif '#' not in color and len(color) == 6:
rgb = webcolors.hex_to_rgb(f'#{color}')
b.fade_to_rgb(200, *rgb)
send_message("ok", channel)
return True
send_message("I do not understand the color.", channel)
print(f"Cannot understand color '{color}'")
return False
def main():
"""Main."""
if sc.rtm_connect():
print("Ready!")
while True:
color, channel = parse_slack_output(sc.rtm_read())
if color and channel:
handle_blink(color, channel)
time.sleep(1)
else:
print("Connection Failed")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment