LoginSignup
12
19

More than 3 years have passed since last update.

Twitchのコメントを取得して解析するプログラム

Posted at

今回(と言っても結構前に作ったやつだけど)、Twitchのコメントを取得して特定の言葉が何回出てきたかカウントするプログラムを作りました。
実行にはTwitch APIが必要です、ここから作れます。

import socket
import logging
import re
from emoji import demojize


server = 'irc.chat.twitch.tv'
port = 80
nickname = 'your twitch id'
token = 'your api id'
channel = '# channel id you want to get comments'
formatter = '%(asctime)s - %(message)s'
logging.basicConfig(level=logging.DEBUG, format=formatter)

def main():
    sock = socket.socket()
    sock.connect((server, port))
    sock.send(f"PASS {token}\r\n".encode('utf-8'))
    sock.send(f"NICK {nickname}\r\n".encode('utf-8'))
    sock.send(f"JOIN {channel}\r\n".encode('utf-8'))
    word_counter = 0
    patterns = [some word]
    try:
        while True:
            resp = sock.recv(2048).decode('utf-8')
            word_list = []
            if resp.startswith('PING'):
                # sock.send("PONG :tmi.twitch.tv\n".encode('utf-8'))
                sock.send("PONG\n".encode('utf-8'))
            elif len(resp) > 0:
                resp = demojize(resp)
                index = resp.rfind(' :')
                chat = resp[index:] 
                for pattern in patterns:
                    word = re.findall(pattern,chat)
                    [word_list.append(i) for i in word if len(word) >0]
                if len(word_list) >0:
                    logging.info(chat)
                    word_counter += len(word_list)
                    print(word_list)
                    print(word_counter)

    except KeyboardInterrupt:
        sock.close()
        exit()

if __name__ == '__main__':
    main()

あなたのツイッチのID(nickname)とAPI(token)、カウントしたいワード(複数可能 patterns)、コメントを取得したい配信者の名前を#の後に続けて入力(channel)して実行します。
実行後はワードが含まれるコメントと今までのカウント数が出ます。
 
今回はただカウント数だけ知りたかっただけでしたが、CSVに出力したり、時間と一緒に取得してグラフを作ってみるのもいいし、色々汎用性がありそうです。

12
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
19