Skip to content

Instantly share code, notes, and snippets.

@chappy84 chappy84/Dockerfile
Last active Sep 5, 2018

Embed
What would you like to do?
Velominati Slack Bot - Names the rule that someone is quoting in slack (Quickly hacked together script)
FROM python:2-alpine3.7
ARG slack_api_token
ENV SLACK_API_TOKEN $slack_api_token
WORKDIR /local/bot
COPY velominati-slack-bot.py ./
RUN apk update && \
apk add build-base libxml2 libxml2-dev libxslt libxslt-dev && \
pip install lxml slackclient && \
apk del build-base libxml2-dev libxslt-dev
CMD python velominati-slack-bot.py
from lxml import etree
from lxml import html
from HTMLParser import HTMLParser
from slackclient import SlackClient
import os
import re
import requests
import socket
import time
import websocket
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)
def strip_tags(htmlString):
s = MLStripper()
s.feed(htmlString)
return s.get_data()
slackToken = os.environ.get("SLACK_API_TOKEN")
sc = SlackClient(slackToken)
rulesLink = "http://www.velominati.com/the-rules/"
ruleMessageMatch = re.compile('[#]?Rule(?:\s*|\s+#)?([0-9]{1,2})', re.I)
ruleReferencesMatch = re.compile('(.+?\.)\s*[0-9\,]+\s*')
rulesPage = requests.get(
rulesLink,
headers={
'User-Agent': 'VelominatiSlackBot/0.0.1'
}
)
rulesTree = html.fromstring(rulesPage.content)
ruleElements = rulesTree.xpath(
'.//ol[contains(@class,"ruleitem")]/li[contains(@class,"ruleitem")]//div[contains(@class, "vm_rule_title")]'
)
ruleTitles = []
for element in ruleElements:
ruleTitle = strip_tags(etree.tostring(element, pretty_print=True))
if ruleReferencesMatch.search(ruleTitle):
ruleTitle = ruleReferencesMatch.sub('\g<1>', ruleTitle)
ruleTitles.append(ruleTitle.rstrip(" \n."))
if sc.rtm_connect():
while True:
try:
events = sc.rtm_read()
except (socket.error, websocket._exceptions.WebSocketConnectionClosedException) as error:
print('Connection closed, re-connecting...')
if not sc.rtm_connect():
print('Connection failed, something\'s amiss!')
break
events = sc.rtm_read()
for event in events:
if (
'channel' in event and
'text' in event and
event.get('type') == 'message'
):
message = event['text']
if ruleMessageMatch.search(message):
matches = ruleMessageMatch.findall(message)
for match in matches:
ruleNumber = match.lstrip('0')
if len(ruleNumber):
ruleNumber = int(ruleNumber)
if len(ruleTitles) >= ruleNumber:
sc.api_call(
'chat.postMessage',
channel=event['channel'],
text="<%s#%s|#%s>: %s" % (
rulesLink,
ruleNumber,
ruleNumber,
ruleTitles[ruleNumber - 1]
),
as_user='true:',
unfurl_links=False
)
time.sleep(1)
else:
print('Connection failed, invalid token?')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.