Last active
October 17, 2015 14:43
-
-
Save bcbwilla/421fbbdfa5ca06021ab5 to your computer and use it in GitHub Desktop.
This file contains 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
""" OCN forum link unfurler bot for Slack """ | |
import json | |
import time | |
import re | |
import requests | |
from slackclient import SlackClient | |
from bs4 import BeautifulSoup | |
def get_token(filename): | |
""" get Slack API token from config file """ | |
with open('conf.txt', "r") as f: | |
return f.read().rstrip() | |
def get_urls(text): | |
""" get urls from message text """ | |
m = 'oc.tc/forums/' | |
return filter(lambda x: m in x and not x.endswith('s/'), text.split()) | |
def get_post_data(url): | |
""" get post information for url unfurling """ | |
r = requests.get(url) | |
if r.status_code != 200: | |
print "Can't open url" | |
return | |
post_id = url.split('#')[1] if '#' in url else None | |
soup = BeautifulSoup(r.content) | |
d = {} | |
try: | |
d['title_link'] = url | |
d['title'] = soup.title.string.split('-')[0].strip() | |
page_header = soup.find('div', {'class': 'page-header', 'style':'margin: 0px;'}) | |
page_header = page_header.h3.text.split('\n') | |
thread_title = page_header[1] | |
thread_author = page_header[4] | |
if post_id: | |
post = soup.find('div', {'class': '', 'id': post_id}) | |
else: | |
post = soup.find('div', id=re.compile(r'[0-9]+')) | |
author = post.a['href'].strip('/') | |
d['author_name'] = author | |
d['author_link'] = 'https://www.oc.tc/' + author | |
d['author_icon'] = post.img['src'].replace('32@2x.png', '16@2x.png') | |
d['text'] = post.find('div', {'class': 'converted post-content'}).contents[1].find(text=True) | |
d['fallback'] = '%s: %s' % (d['author_name'], d['text']) | |
except (AttributeError, IndexError) as e: | |
print "Can't read html:", e | |
return | |
return d | |
def main(): | |
""" run main loop to listen for messages """ | |
token = get_token('conf.yaml') | |
if not token: | |
print "Can't get Slack token" | |
return | |
sc = SlackClient(token) | |
if sc.rtm_connect(): | |
while True: | |
events = sc.rtm_read() | |
for event in events: | |
if 'type' in event and event['type'] == 'message' and 'attachments' not in event.keys(): | |
for url in get_urls(event['text']): | |
url = url.strip('<').strip('>') | |
d = get_post_data(url) | |
if d: | |
content = { | |
'type': 'message', | |
'channel': event['channel'], | |
'username': 'bot', | |
'text': '', | |
'attachments': json.dumps([d]), | |
} | |
sc.api_call('chat.postMessage', **content) | |
time.sleep(1) | |
else: | |
print "Can't connect to Slack." | |
if __name__=='__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment