Created
March 6, 2010 09:18
-
-
Save mashiro/323605 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 urllib | |
| import socket | |
| from xml.etree import ElementTree | |
| def get_threadinfo(video): | |
| url = 'http://api.jk.nicovideo.jp/v1/channel.get' | |
| params = urllib.urlencode({'v': video}) | |
| f = urllib.urlopen(url, params) | |
| tree = ElementTree.parse(f) | |
| thread_id = tree.find('//thread_id').text | |
| host = tree.find('//ms').text | |
| port = int(tree.find('//ms_port').text) | |
| return thread_id, host, port | |
| def create_sendmessage(thread, res_from='-10', version='20061206'): | |
| e = ElementTree.Element( 'thread', { | |
| 'thread': str(thread), | |
| 'res_from': str(res_from), | |
| 'version': str(version), | |
| }) | |
| return ElementTree.tostring(e) + '\0' | |
| def recv_element(socket): | |
| s = '' | |
| while 1: | |
| c = socket.recv(1) | |
| if c == '\0': | |
| return s | |
| s += c | |
| def connect(thread_id, host, port, raw=False): | |
| s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
| s.connect((host, port)) | |
| s.sendall(create_sendmessage(thread_id)) | |
| while 1: | |
| xml = recv_element(s) | |
| e = ElementTree.fromstring(xml) | |
| if e.tag == 'chat': | |
| if raw: | |
| print xml | |
| else: | |
| print e.text | |
| def main(): | |
| from optparse import OptionParser | |
| parser = OptionParser(usage='%prog [-r] video', version='%prog 0.1') | |
| parser.add_option('-r', '--raw', action='store_true', default=False, dest='raw', help='raw output') | |
| options, args = parser.parse_args() | |
| if len(args) != 1: | |
| parser.error('incorrect number of arguments') | |
| thread_id, host, port = get_threadinfo(args[0]) | |
| connect(thread_id, host, port, options.raw) | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment