-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwitchConnect.py
More file actions
371 lines (331 loc) · 14.5 KB
/
TwitchConnect.py
File metadata and controls
371 lines (331 loc) · 14.5 KB
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
import socket
import time
import threading
from threading import Thread
import SettingsAndPreferences as settings
import TextInput as AI
import GenerateSentences as speak
import TwitchAPI as api
import UI
HOST = "irc.chat.twitch.tv"
PORT = 6667
s = socket.socket()
def parseMessage(tags):
msginfo = {}
for line in tags[1:].split(";"):
try:
(key, value) = line.split("=")
msginfo[key] = value
except:
pass
return msginfo
def send_message(rep, addprefix = True):
MSGPR = settings.findValue("MessagePrefix")
if MSGPR != "30" and addprefix:
prefix = MSGPR+" "
else:
prefix = ""
while len(prefix+rep)>=500: #hard cap
rep=rep[:-1]
s.send(bytes("PRIVMSG #" + SENDTO + " :" + prefix + rep + "\r\n", "UTF-8"))
def connectToTwitch():
s.connect((HOST, PORT))
s.send(bytes("PASS " + PASS + "\r\n", "UTF-8"))
s.send(bytes("NICK " + NICK + "\r\n", "UTF-8"))
s.send(bytes('CAP REQ :twitch.tv/tags\r\n', 'UTF-8'))
s.send(bytes('CAP REQ :twitch.tv/commands\r\n', 'UTF-8'))
s.send(bytes("JOIN #" + JOIN + " \r\n", "UTF-8"))
while True:
line = (s.recv(1024)).decode("utf-8","replace")
for text in line.split('\\r\\n'):
if text:
print(text)
if "End of /NAMES list" in line:
UI.go = False
break
class AddWords(Thread):
def __init__(self, message=None):
Thread.__init__(self)
self.message = message
def run(self):
if messageGenThread.is_alive():
messageGenThread.join()
if self.message:
if self.message==1:
AI.load()
else:
AI.add(self.message)
else:
settings.levelprint("No words received", 4)
class GenerateMessage(Thread):
def __init__(self, message=None):
Thread.__init__(self)
self.message = message
def run(self):
if wordAddingThread.is_alive():
wordAddingThread.join()
feed = []
if self.message:
#pregen
if self.message==1:
pregenAmount = int(settings.findValue("PregenAmount"))
pregenStart = 0.5-(0.05*min(max(0.2*int(settings.findValue("PregenStartupSpeed")),0),10))
pregenRefresh = (10.0/(min(max(0.2*int(settings.findValue("PregenRefreshSpeed")),1),10))-0.5)
if pregenAmount>99:
progress = 0
if pregenAmount-len(speak.pregen)<2:
progress = 100
while self.message==1:
if len(speak.pregen)>=pregenAmount:
del speak.pregen[0]
time.sleep(pregenRefresh)
else:
time.sleep(pregenStart)
if settings.findValue("NewGeneration")=="1":
speak.pregen.append(speak.GenerateSentence([],False))
else:
speak.pregen.append(speak.newGenerateSentence([], 10))
if int(100*len(speak.pregen)/pregenAmount)>progress:
progress=int(100*len(speak.pregen)/pregenAmount)
settings.levelprint("Pre-generating... "+str(progress)+"%",0)
return
try:
feed = self.message.lower().replace(settings.findValue("call"), "").strip().split()
except Exception as e:
feed = self.message.lower().strip().split()
print(e)
else:
feed = []
reply = ""
if speak.pregen:
reply = speak.findPregen(feed)
hasFeed = False
for w in feed:
if reply and w in reply.lower().split():
hasFeed = True
if not reply or (feed and not hasFeed):
reply = speak.GenerateSentence(feed)
send_message(reply)
if hasFeed:
settings.levelprint("PREGEN MESSAGE: " + reply, 1)
try:
speak.pregen.remove(reply)
except:
settings.levelprint("Couldn't remove from pregen",2)
else:
settings.levelprint("GENERATED MESSAGE: " + reply, 1)
class SubWatch(Thread):
def __init__(self, user, months, user2):
Thread.__init__(self)
self.user = user
self.months = months
self.user2 = user2
def run(self):
subtype = "Sub"
if self.months!="0":
subtype = "Resub"
if self.user2:
subtype = "Subgift"
subreply = settings.findValue(subtype+"Reply")
if subreply and subreply!="30" and settings.findValue("enableTalking"):
if subreply.find("()")>-1:
gen = speak.newGenerateSentence()
reply=subreply.replace("{}", self.user).replace("[]", self.months).replace("()", gen)
reply=reply.replace("{from}", self.user).replace("{to}", self.user2).strip()
send_message(reply)
settings.levelprint("SUB REPLY: " + reply, 1)
class FollowWatch(Thread):
def __init__(self):
Thread.__init__(self)
self.followers = api.totalFollowers()
def run(self):
followreply = settings.findValue("FollowReply")
while followreply!="30" and followreply:
try:
self.followers2 = api.totalFollowers()
if self.followers2>self.followers and followreply!="30" and settings.findValue("enableTalking")=="1":
followreply = settings.findValue("FollowReply")
gen = ""
if followreply.find("()")>-1:
gen = speak.newGenerateSentence()
time.sleep(1) #ensure the new username is in before fetching
reply=followreply.replace("{}", api.NewFollower(True)).replace("()", gen).strip()
send_message(reply)
settings.levelprint("FOLLOW REPLY: " + reply, 1)
self.followers = self.followers2
except Exception as e:
settings.levelprint("Couldn't update follower count", 0)
settings.levelprint(e, 0)
time.sleep(int(settings.findValue("FollowCheckCooldown")))
class SubcountWatch(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
while True:
try:
self.subs = api.totalSubs()
subfile = open(settings.folder+"/subgoal.txt","w")
subgoaltext = settings.findValue("SubGoal").replace("{}", str(self.subs))
subfile.write(subgoaltext)
subfile.close()
except Exception as e:
settings.levelprint("Couldn't update sub count", 0)
settings.levelprint(e, 0)
time.sleep(int(settings.findValue("FollowCheckCooldown")))
getinput = UI.getInput()
getinput.start()
wordAddingThread = AddWords(1)
wordAddingThread.setName('Word adding')
messagePreGen = GenerateMessage(1)
messagePreGen.setName('Message pre-generation')
messageGenThread = GenerateMessage()
messageGenThread.setName('Message generation')
wordAddingThread.start()
messagePreGen.start()
while not UI.go:
time.sleep(0.1)
NICK = settings.findValue("NICK")
JOIN = settings.findValue("JOIN")
SENDTO = settings.findValue("SENDTO")
PASS = settings.findValue("oauth")
connectToTwitch()
print("Talking set to "+settings.findValue("enableTalking"))
print("Learning set to "+settings.findValue("enableLearning"))
timeOfReply = 0
timeOfAuto = 0
timeOfCommand = 0
s.settimeout(10)
if settings.findValue("FollowReply")!="30":
followChecker = FollowWatch()
followChecker.setName('Follow checker')
followChecker.start()
subChecker = SubcountWatch()
subChecker.setName('Subcount checker')
subChecker.start()
print("All systems go")
message = ""
while True:
try:
for line in (s.recv(1024)).decode("utf-8","replace").split('\\r\\n'):
if line.strip()=="PING :tmi.twitch.tv":
s.send(bytes("PONG\r\n", "UTF-8"))
settings.levelprint("PING PONG", 0)
if settings.findValue("autosave")=="1":
AI.save()
settings.saveall()
continue
settings.levelprint(line.strip(),6)
if len(line)<5:
continue
parts = line.split(" :", 2)
if "tmi.twitch.tv" in parts[1] and len(parts)>2:
message = parts[2].strip()
else:
message = ""
settings.levelprint("Couldn't parse message", 0)
settings.levelprint(line, 0)
continue
msginfo = parseMessage(parts[0])
settings.levelprint(msginfo,4)
username = msginfo.get("display-name","")
if not username:
settings.levelprint("No display-name found", 6)
approved = False
if "subscriber" in msginfo.get("badges","") or "mod" in msginfo.get("badges",""):
approved = True
elif username.lower() in settings.userlist("approved users.txt"):
approved = True
if approved:
settings.levelprint(username+" is approved!", 6)
if msginfo.get("msg-id", ""):
settings.levelprint(msginfo["msg-id"]+" happened!", 0)
msgid = msginfo["msg-id"]
if "sub" in msgid and settings.findValue("enableTalking")=="1":
months = msginfo.get("msg-param-months","0")
user2 = msginfo.get("msg-param-recipient-display-name", None)
subChecker = SubWatch(username, months, user2)
subChecker.setName('Sub message')
subChecker.start()
msgtype = "WHISPER" if "WHISPER" in parts[1] else "-"
if not "PRIVMSG" in parts[1] and not "WHISPER" in parts[1] and message:
settings.levelprint("Non PRIVMSG message: "+message, 3)
else:
settings.levelprint(msgtype+" "+username+": "+message, 3)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('localhost', 55555)
color = msginfo.get("color", "")
emotes = msginfo.get("emotes", "")
sent = sock.sendto(bytes(username+' '+color+' '+emotes+' '+msgtype+' '+message, 'UTF-8'), server_address)
sock.close()
if not "PRIVMSG" in parts[1]:
continue
#update settings
cooldown = int(settings.findValue("cooldown"))
longerCooldown = int(settings.findValue("longerCooldown"))
autoCooldown = int(settings.findValue("autoCooldown"))
prefix = settings.findValue("MessagePrefix")
call = settings.findValue("call")
#commands
if message[0]=='!':
white = username.lower() in settings.userlist("whitelist.txt")
if white or abs(time.perf_counter()-timeOfCommand) > int(settings.findValue("commandCooldown")):
cmdparts = message.strip().split(" ", 1)
reply = settings.findValue(message)
if white:
try:
if cmdparts[1][0]!="!":
cmdparts[1] = "!"+cmdparts[1]
if cmdparts[0]=="!del":
reply = settings.findValue(cmdparts[1], None, True)
cmd = cmdparts[1].split("=")[0].strip()
val = cmdparts[1].split("=")[1].strip()
if len(cmdparts)>=2:
if cmdparts[0]=="!edit":
reply = settings.findValue(cmd, val, True)
if cmdparts[0]=="!add":
reply = settings.findValue(cmd, val)
except IndexError as e:
pass
if reply!="30":
settings.levelprint("COMMAND RESPONSE: " + reply, 1)
send_message(reply, False)
timeOfCommand = time.perf_counter()
#learning
elif username.lower() not in settings.userlist("ignore list.txt") and settings.findValue("enableLearning")=="1":
if wordAddingThread.is_alive():
settings.levelprint("Skipping because adding previous words", 6)
else:
wordAddingThread = AddWords(message)
wordAddingThread.start()
#talking
if settings.findValue("enableTalking")=="1" and (message.lower().find(call)>-1 or abs(time.perf_counter()-timeOfAuto) > autoCooldown and autoCooldown > 0):
if (abs(time.perf_counter()-timeOfReply)>cooldown and approved) or abs(time.perf_counter()-timeOfReply)>longerCooldown:
if messageGenThread.is_alive():
settings.levelprint("Skipping because generating another message", 6)
else:
if message.lower().find(call)>-1:
timeOfReply = time.perf_counter()
else:
timeOfAuto = time.perf_counter()
messageGenThread = GenerateMessage(message)
message = ""
messageGenThread.start()
except socket.timeout:
autoCooldown = int(settings.findValue("autoCooldown"))
if settings.findValue("enableTalking")=="1" and abs(time.perf_counter()-timeOfAuto) > autoCooldown and autoCooldown > 0:
if messageGenThread.is_alive():
settings.levelprint("Skipping because generating another message", 6)
else:
timeOfAuto = time.perf_counter()-min(3, int(settings.findValue("autoCooldown"))-3)
if message:
messageGenThread = GenerateMessage()
message = ""
else:
messageGenThread = GenerateMessage()
messageGenThread.start()
except ConnectionResetError:
s.shutdown(socket.SHUT_WR)
s.close()
settings.levelprint("Trying to reconnect", 0)
connectToTwitch()
settings.levelprint("Reconnected hopefully", 0)