Last active
September 7, 2016 03:36
-
-
Save gunyarakun/40f190d9640fb6618abc5c80acbc5ce3 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
#!/usr/bin/env python | |
# encoding: utf-8 | |
import json | |
import urllib | |
import urllib2 | |
import codecs | |
import time | |
from bs4 import BeautifulSoup | |
from datetime import datetime | |
import sys | |
sys.stdin = codecs.getreader('utf-8')(sys.stdin) | |
sys.stdout = codecs.getwriter('utf-8')(sys.stdout) | |
token = 'xoxp-change-your-token' | |
bot_name = u'USD-JPY-san' | |
channel_name = 'bottest' | |
crawl_url = 'https://finance.yahoo.com/quote/usdjpy=x' | |
class SlackClient: | |
def __init__(self, token, bot_name='gunyabot'): | |
self.token = token | |
self.bot_name = bot_name | |
self.channels = self.get_channels() | |
@staticmethod | |
def encoded_dict(in_dict): | |
out_dict = {} | |
for k, v in in_dict.iteritems(): | |
if isinstance(v, unicode): | |
v = v.encode('utf8') | |
elif isinstance(v, str): | |
# Must be encoded in UTF-8 | |
v.decode('utf8') | |
out_dict[k] = v | |
return out_dict | |
def request(self, request='?', post_data={}, domain='slack.com'): | |
post_data['token'] = self.token | |
enc_post_data = urllib.urlencode(self.encoded_dict(post_data)) | |
url = 'https://{}/api/{}'.format(domain, request) | |
response = urllib2.urlopen(url, enc_post_data) | |
response_str = response.read() | |
response_obj = json.loads(response_str) | |
if not response_obj['ok']: | |
raise ValueError | |
return response_obj | |
def get_channels(self): | |
d = {} | |
for channel in self.request('channels.list')['channels']: | |
d[channel['name']] = channel | |
return d | |
def post_message(self, channel_name, text, attachments=[]): | |
post_data = { | |
'channel': self.channels[channel_name]['id'], | |
'text': text, | |
'username': self.bot_name, | |
'attachments': json.dumps(attachments), | |
} | |
return self.request('chat.postMessage', post_data) | |
sc = SlackClient(token, bot_name) | |
while True: | |
try: | |
now = datetime.now() | |
f = codecs.getreader('utf-8')(urllib.urlopen(crawl_url)) | |
html = f.read() | |
soup = BeautifulSoup(html) | |
usdjpy = soup.find_all('span', class_=['Fw(b)', 'D(ib)', 'Fz(36px)', 'Mb(-4px)'])[-2].string | |
if usdjpy: | |
print(usdjpy) | |
sc.post_message(channel_name, u'1 USD = {} JPY'.format(usdjpy)) | |
sys.stdout.flush() | |
except: | |
pass | |
time.sleep(86400) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment