Last active
August 29, 2015 14:06
-
-
Save jupemara/6533be55f7e1138f7987 to your computer and use it in GitHub Desktop.
Talking Chatwork
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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
""" | |
This script posts a message to the specified chatwork room. | |
""" | |
import optparse | |
import urllib | |
import urllib2 | |
DEFAULT = { | |
'api_endpoint': 'https://api.chatwork.com/v1/', | |
'api_token': None, | |
'room_id': None, | |
'message': None | |
} | |
def get_args(): | |
usage = ( | |
'Post a message to the specified chatwork group.' | |
) | |
parser = optparse.OptionParser(usage=usage) | |
parser.add_option( | |
'--api-endpoint', '-E', | |
type='string', default=DEFAULT['api_endpoint'], | |
dest='api_endpoint', | |
help='Chatwork api endpoint.' | |
) | |
parser.add_option( | |
'--api-token', '-A', | |
type='string', default=DEFAULT['api_token'], | |
dest='api_token', | |
help='Chatwork api token.' | |
) | |
parser.add_option( | |
'--room-id', '-r', | |
type='int', default=DEFAULT['room_id'], | |
dest='room_id', | |
help='Chatwork room id.' | |
) | |
parser.add_option( | |
'--message', '-m', | |
type='string', default=DEFAULT['message'], | |
help='Posted message.' | |
) | |
return parser.parse_args()[0] | |
class ChatworkAPIException(BaseException): | |
def __init__(self, message): | |
super(ChatworkAPIException, self).__init__(message) | |
class ChatworkRoomMessage(object): | |
def __init__(self, endpoint, room_id, token): | |
self.endpoint = ( | |
'{base_endpoint}rooms/{room_id}/messages' | |
''.format( | |
base_endpoint=endpoint, | |
room_id=room_id | |
) | |
) | |
self.token = token | |
self.headers = { | |
'X-ChatWorkToken': self.token | |
} | |
def post_message(self, message): | |
data = { | |
'body': message | |
} | |
data = urllib.urlencode(data) | |
print data | |
request = urllib2.Request( | |
self.endpoint, | |
data=data, | |
headers=self.headers | |
) | |
try: | |
response = urllib2.urlopen(request) | |
return response | |
except Exception as exception: | |
raise ChatworkAPIException( | |
exception.__str__() | |
) | |
def main(): | |
options = get_args() | |
chatwork = ChatworkRoomMessage( | |
endpoint=options.api_endpoint, | |
room_id=options.room_id, | |
token=options.api_token | |
) | |
chatwork.post_message(options.message) | |
if __name__ == '__main__': | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment