· 4 years ago · Apr 08, 2021, 10:30 AM
1import re
2import socket
3import sys
4import random
5import requests
6import codecs
7import json
8import time
9
10HOST = "irc.twitch.tv"
11PORT = 6667
12CHAN = "#screamlark"
13NICK = "rprtr258"
14PASS = ""
15PASS = "oauth:token" # get here https://twitchapps.com/tmi/
16#with open('PASS.txt', 'r') as myfile:
17# PASS = myfile.read()
18
19def send_pong(msg):
20 con.send(bytes('PONG %s\r\n' % msg, 'UTF-8'))
21
22def send_message(msg):
23 con.send(bytes('PRIVMSG %s :%s\r\n' % (CHAN, msg), 'UTF-8'))
24 #print(NICK + ": " + msg)
25 #sys.stdout.flush()
26
27def send_nick(nick):
28 con.send(bytes('NICK {}\r\n'.format(nick).encode("utf-8")))
29
30def send_pass(password):
31 con.send(bytes('PASS %s\r\n' % password, 'UTF-8'))
32
33def join_channel(chan):
34 con.send(bytes('JOIN %s\r\n' % chan, 'UTF-8'))
35
36def part_channel(chan):
37 con.send(bytes('PART %s\r\n' % chan, 'UTF-8'))
38
39def get_sender(msg):
40 result = ""
41 for char in msg:
42 if char == "!":
43 break
44 if char != ":":
45 result += char
46 return result
47
48def get_message(msg):
49 result = ""
50 i = 3
51 length = len(msg)
52 while i < length:
53 result += msg[i] + " "
54 i += 1
55 result = result.lstrip(':')
56 return result
57
58con = socket.socket()
59con.connect((HOST, PORT))
60
61send_pass(PASS)
62send_nick(NICK)
63join_channel(CHAN)
64
65data = ""
66
67while True:
68 try:
69 data = data + con.recv(1024).decode('UTF-8')
70 data_split = re.split(r"[~\r\n]+", data)
71 data = data_split.pop()
72
73 for line in data_split:
74 line = str.rstrip(line)
75 line = str.split(line)
76
77 if len(line) >= 1:
78 if line[0] == 'PING':
79 send_pong(line[1])
80
81 if line[1] == 'PRIVMSG':
82 sender = get_sender(line[0])
83 message = get_message(line)
84 print(f"{sender}: {message}")
85 #parse_message(message)
86 sys.stdout.flush()
87
88 except socket.error as e:
89 print("Socket died")
90 print(e)
91 except socket.timeout:
92 print("Socket timeout")
93