ニコ生アラートAPIから番組通知を取得する
Page not found · GitHubに整理したコードぶち込みました.
pythonでニコ生アラートAPIにログインする - miettal diaryの続きです.
通知を受け取る方法もニコ生アラート(本家)の仕様とは (ニコナマアラートホンケノシヨウとは) [単語記事] - ニコニコ大百科にまとめられています.
通知を受け取る方法がXMLSocketになっていて,XMLSocketはHttpと違い通信は切らずに,XMLデータを\0で挟んで何回も送ることができます.
import socket # # 省略 # host port threadについては前回のエントリを参照 host = res_data.getalertstatus.ms.addr port = int(res_data.getalertstatus.ms.port) thread = res_data.getalertstatus.ms.thread sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) sock.sendall(('<thread thread="%s" version="20061206" res_form="-1"/>'+chr(0)) % thread) print ('<thread thread="%s" version="20061206" res_form="-1"/>' % thread) msg = "" while True : rcvmsg = sock.recv(1024) for ch in rcvmsg: if ch == chr(0) : print msg msg = "" else : msg += ch sock.close()
output
<thread thread="xxxxxxxxxx" version="20061206" res_form="-1"/> <thread resultcode="0" thread="xxxxxxxxxx" last_res="xxxxxxxx" ticket="0xXXXXXXX" revision="1" server_time="1325016509"/> <chat thread="xxxxxxxxxx" no="xxxxxxxx" date="1325016509" user_id="xxx" premium="2">xxxxxxxx,xxxxxxxxx,xxxxxxxx</chat> <chat thread="xxxxxxxxxx" no="xxxxxxxx" date="1325016514" user_id="xxx" premium="2">xxxxxxxx,xxxxxxxxx,xxxxxxx</chat> <chat thread="xxxxxxxxxx" no="xxxxxxxx" date="1325016517" user_id="xxx" premium="2">xxxxxxxx,xxxxxxxxx,xxxxxxx</chat> <chat thread="xxxxxxxxxx" no="xxxxxxxx" date="1325016517" user_id="xxx" premium="2">xxxxxxxx,xxxxxxxxx,xxxxxxxx</chat> <chat thread="xxxxxxxxxx" no="xxxxxxxx" date="1325016519" user_id="xxx" premium="2">xxxxxxxx,xxxxxxxxx,xxxxxxxx</chat> <chat thread="xxxxxxxxxx" no="xxxxxxxx" date="1325016519" user_id="xxx" premium="2">xxxxxxxx,xxxxxxxxx,xxxxxxxx</chat> <chat thread="xxxxxxxxxx" no="xxxxxxxx" date="1325016521" user_id="xxx" premium="2">xxxxxxxx,xxxxxxxxx,xxxxxxx</chat> <chat thread="xxxxxxxxxx" no="xxxxxxxx" date="1325016530" user_id="xxx" premium="2">xxxxxxxx,xxxxxxxxx,xxxxxxxx</chat> <chat thread="xxxxxxxxxx" no="xxxxxxxx" date="1325016533" user_id="xxx" premium="2">xxxxxxxx,xxxxxxxxx,xxxxxxxx</chat> <chat thread="xxxxxxxxxx" no="xxxxxxxx" date="1325016533" user_id="xxx" premium="2">xxxxxxxx,xxxxxxxxx,xxxxxxx</chat> <chat thread="xxxxxxxxxx" no="xxxxxxxx" date="1325016534" user_id="xxx" premium="2">xxxxxxxx,xxxxxxxxx,xxxxxxxx</chat> ...