Skip to content

Instantly share code, notes, and snippets.

@gunyarakun
Last active August 29, 2015 14:16
Show Gist options
  • Save gunyarakun/f3ffe3d9a53bea5750f6 to your computer and use it in GitHub Desktop.
Save gunyarakun/f3ffe3d9a53bea5750f6 to your computer and use it in GitHub Desktop.
Simple Slack bot
#!/usr/bin/env python
# encoding: utf-8
import json
import urllib
import urllib2
token = 'xoxp-xxxxxxxx-xxxxxxxx-xxxxxxx-xxxxxx'
bot_name = 'gunyabot'
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):
post_data = {
'channel': self.channels[channel_name]['id'],
'text': text,
'username': self.bot_name,
}
self.request('chat.postMessage', post_data)
sc = SlackClient(token, bot_name)
print sc.post_message('zatsudan', u'なぜかSlackのbot作りに詳しくなるマン')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment