-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbeaverbot.py
178 lines (151 loc) · 5 KB
/
beaverbot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# noinspection PyUnresolvedReferences
import cfgzam as cfg
import time, logging, random, json, requests, socket, re
from messages import Message
import song_requests as sr
from irctools import chat, ping
# noinspection PyUnresolvedReferences
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
handler = logging.FileHandler("beaver.log", mode="w")
formatter = logging.Formatter(
"""%(asctime)s - %(name)s - %(levelname)s - %(message)s"""
)
handler.setFormatter(formatter)
logger.addHandler(handler)
s = None # only here to make the linter happy
def connect(HOST, PORT):
global s
s = None
try:
s.close()
except:
pass
s = socket.socket()
try:
s.connect((HOST, PORT))
except ConnectionAbortedError:
logger.info("Connection Failed")
def login(sock, PASS, NICK, CHAN):
sock.send("PASS {}\r\n".format(PASS).encode("utf-8"))
sock.send("NICK {}\r\n".format(NICK).encode("utf-8"))
test = sock.recv(1024).decode("utf-8")
logger.info(test)
sock.send("JOIN {}\r\n".format(CHAN).encode("utf-8"))
test = sock.recv(1024).decode("utf-8")
logger.info(test)
sock.send("CAP REQ :twitch.tv/tags\r\n".encode("utf-8"))
test = sock.recv(1024).decode("utf-8")
logger.info(test)
sock.send("CAP REQ :twitch.tv/commands\r\n".encode("utf-8"))
test = sock.recv(1024).decode("utf-8")
logger.info(test)
def exponential_backoff():
global s
count = 1
while True:
try:
connect(cfg.HOST, cfg.PORT)
login(s, cfg.PASS, cfg.NICK, cfg.CHAN)
return True
except ConnectionResetError:
time.sleep(count)
count = count * 2
def splitmessages(response: str):
messages = response.splitlines()
return messages
command_switch = {
"!clearplaylist": lambda: sr.clear_playlist(s, messagedict),
"!requeue": lambda: sr.requeue(s, messagedict),
"!modqueue": lambda: sr.mod_queue(s, messagedict),
"!song": lambda: sr.now_playing(s, messagedict),
}
# message type RECONNECT
def reconnect(HOST, PORT, PASS, NICK, CHAN):
global s
s.close()
connect(HOST, PORT)
login(s, PASS, NICK, CHAN)
# message type HOSTTARGET
def host(sock, message):
target = message["host target"]
if target == "-":
return False
else:
return chat(
s,
f"If the host broke on your end, here is the link: https://twitch.tv/{target}",
cfg.CHAN,
)
# message type PRIVMSG
def PRIVMSG(mtesting, messagedict):
userid = messagedict["user-id"]
username = messagedict["user-id"]
if "custom-reward-id" in messagedict.keys():
reward_switch = {
"16f48209-c3b9-4a32-9143-109a2802a162": lambda: sr.song_requests(
s, messagedict, cfg.URL
)
}
mtesting = reward_switch.get(messagedict["custom-reward-id"], lambda: False)()
elif messagedict["message"].startswith("!"):
word_list = messagedict["message"].split(" ")
command = word_list[0]
mtesting = command_switch.get(command, lambda: False)()
return mtesting
# message type: userstate, clearchat, clearmsg, notice, roomstate, usernotice, whisper
def the_rest():
return False
message_switch = {
"WHISPER": lambda: the_rest(),
"PRIVMSG": lambda: PRIVMSG(mtesting, messagedict),
"USERNOTICE": lambda: the_rest(),
"USERSTATE": lambda: the_rest(),
"CLEARCHAT": lambda: the_rest(),
"CLEARMSG": lambda: the_rest(),
"HOSTTARGET": lambda: host(s, messagedict),
"NOTICE": lambda: the_rest(),
"ROOMSTATE": lambda: the_rest(),
"PING": lambda: ping(s),
"RECONNECT": lambda: reconnect(cfg.HOST, cfg.PORT, cfg.PASS, cfg.NICK, cfg.CHAN),
}
if __name__ == "__main__":
connect(cfg.HOST, cfg.PORT)
login(s, cfg.PASS, cfg.NICK, cfg.CHAN)
chan = cfg.CHAN[1:]
t = time.time()
timer, timeq = time.time(), time.time()
timecheck = False
cd = 15
while True:
try:
response = s.recv(8192).decode("utf-8")
except ConnectionResetError:
print("timed out, attempting reconnect")
exponential_backoff()
continue
except:
continue
if response == "":
continue
messagelist = splitmessages(response)
for message in messagelist:
try:
mtesting = False
try:
messagedict = Message(message).dict
except:
logging.exception(response)
continue
if messagedict["action"] == "BAD MESSAGE":
print("bad message")
continue
else:
mtesting = message_switch.get(
messagedict["action"], lambda: False
)()
if mtesting:
time.sleep(1 / (100 / 30))
except:
print(message)
logger.exception("Error processing message:" + message)