-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchatbotMock.py
More file actions
441 lines (367 loc) · 14.7 KB
/
chatbotMock.py
File metadata and controls
441 lines (367 loc) · 14.7 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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
import importlib
import sys
import os
import time
sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))
import requests
import json
from threading import Thread
import random
# noinspection PyPep8Naming,PyUnusedLocal
class Parent(object):
mocking = False
viewer_list = {}
stop = False
cooldowns = {}
user_cooldowns = {}
MixerChat = None
websocket = None
currency_name = "LyonBucks"
mixitupbot = "http://localhost:8911/api"
subscribers = {}
API_Key = None
stream_online = False
currency_id = None
ranks = {}
@classmethod
def SendStreamMessage(cls, msg):
cls.MixerChat.send_msg(msg)
cls.stop = True
@classmethod
def SendStreamWhisper(cls, user, msg):
username = cls.viewer_list[user]["username"]
cls.MixerChat.send_whisper(username, msg)
cls.stop = True
@classmethod
def get_currency_id(cls):
if cls.currency_id is None:
resp = requests.get(cls.mixitupbot + "/currency", timeout=1)
if resp.status_code == 200:
currency = filter(lambda x: x["Name"] == cls.currency_name, resp.json())[0]
cls.currency_id = currency["ID"]
cls.ranks = {rank["Name"]: rank["MinimumPoints"] for rank in currency["Ranks"]}
return cls.currency_id
@classmethod
def Log(cls, script_name, log):
print "log from " + script_name + ": " + log
@classmethod
def RemovePoints(cls, user_id, username, amount):
if cls.mocking:
return True
try:
resp = requests.patch(
cls.mixitupbot + '/users/%i/currency/%s/adjust' % (user_id, cls.get_currency_id()),
json={"Amount": -amount}, timeout=0.5)
return resp.status_code == 200
except requests.exceptions.Timeout:
return False
@classmethod
def AddPoints(cls, user_id, username, amount):
if cls.mocking:
return True
try:
resp = requests.patch(
cls.mixitupbot + '/users/%i/currency/%s/adjust' % (user_id, cls.get_currency_id()),
json={"amount": amount}, timeout=0.5)
return resp.status_code == 200
except requests.exceptions.Timeout:
return False
@classmethod
def AddPointsAll(cls, points_dict): # TODO: check if users are in viewerlist
if cls.mocking:
return []
try:
resp = requests.post(
cls.mixitupbot + '/currency/%i/give' % cls.get_currency_id(),
json=[{"Amount": amount, "UsernameOrID": user} for user, amount in points_dict.iteritems()], timeout=1.5)
if resp.status_code == 200:
return []
else:
return [cls.viewer_list[user] for user in points_dict]
except requests.exceptions.Timeout:
return [False for i in xrange(len(points_dict))]
@classmethod
def AddPointsAllAsync(cls, points_dict, callback):
thread = Thread(target=cls.AddPointsAllAsync_, args=(points_dict, callback))
thread.daemon = True
thread.run()
@classmethod
def AddPointsAllAsync_(cls, points_dict, callback):
resp = cls.AddPointsAll(points_dict)
callback(resp)
@classmethod
def GetTopCurrency(cls, top):
try:
resp = requests.get(cls.mixitupbot + '/currency/%i/top?count=%i' % (cls.get_currency_id(), top), timeout=0.5)
data = resp.json()
except requests.exceptions.Timeout:
return []
try:
return {user["ID"]:filter(lambda x: x["ID"] == cls.get_currency_id(), user["Currencyamounts"])[0]["Amount"] for user in data}
except IndexError:
return []
@classmethod
def GetRank(cls, user):
points = cls.GetPoints(user)
max_min_amount = 0
high_rank = ""
for rank, min_amount in cls.ranks.iteritems():
if points > min_amount > max_min_amount:
high_rank = rank
max_min_amount = min_amount
return high_rank
@classmethod
def GetRanksAll(cls, users):
print "not yet implemented"
pass
@classmethod
def GetHours(cls, user_id):
try:
data = requests.get(cls.mixitupbot + "/users/" + str(user_id), timeout=0.5).json()
except requests.exceptions.Timeout:
return 0
if resp.status_code == 200:
return data["ViewingMinutes"] / 60
else:
return 0
@classmethod
def GetHoursAll(cls, users):
print "not yet implemented"
try:
resp = requests.post(cls.mixitupbot + '/users', json=users, timeout=1)
except requests.exceptions.Timeout:
return 0
return { data["ID"]: data["ViewingMinutes"]/60 for data in resp.json()}
@classmethod
def GetCurrencyUsers(cls, users):
print "not yet implemented"
pass
@classmethod
def GetPoints(cls, user_id):
try:
resp = requests.get(cls.mixitupbot + "/users/" + str(user_id), timeout=0.5)
except requests.exceptions.Timeout:
return 0
if resp.status_code == 200:
try:
return filter(lambda x: x["ID"] == cls.get_currency_id(), resp.json()["Currencyamounts"])[0]["Amount"]
except IndexError:
return 0
else:
return 0
@classmethod
def GetPointsAll(cls, users):
try:
resp = requests.post(cls.mixitupbot + '/users', json=users, timeout=1)
except requests.exceptions.Timeout:
return 0
try:
return [filter(lambda x: x["ID"] == cls.get_currency_id(), data["Currencyamounts"])[0]["Amount"]
for data in resp.json()]
except IndexError:
return 0
@classmethod
def IsLive(cls):
return cls.stream_online
@classmethod
def GetDisplayName(cls, user_id):
return cls.viewer_list.get(user_id,{"username":str(user_id)})["username"]
@classmethod
def GetDisplayNames(cls, user_ids):
return [cls.viewer_list[user_id]["username"] for user_id in user_ids]
@classmethod
def GetActiveUsers(cls): # TODO: filter active
return [user_data["username"] for user_data in cls.viewer_list.itervalues()]
@classmethod
def GetViewerList(cls):
return [user_data["username"] for user_data in cls.viewer_list.itervalues()]
# to make the mock work
@classmethod
def add_viewer(cls, user_id, user_data):
cls.viewer_list[user_id] = user_data
@classmethod
def GetCurrencyName(cls):
return cls.currency_name
@classmethod
def GetChannelName(cls):
if cls.mocking:
return "mi_thom"
return cls.MixerChat.config["channel"]
@classmethod
def IsOnUserCooldown(cls, scriptname, commandname, user):
return time.time() < cls.user_cooldowns.get(scriptname + commandname, {}).get(user, 0)
@classmethod
def IsOnCooldown(cls, scriptname, commandname):
return time.time() < cls.cooldowns.get(scriptname + commandname, 0)
@classmethod
def AddUserCooldown(cls, scriptname, commandname, user, seconds):
if scriptname + commandname not in cls.user_cooldowns:
cls.user_cooldowns[scriptname + commandname] = {}
cls.user_cooldowns[scriptname + commandname][user] = time.time() + seconds
@classmethod
def AddCooldown(cls, scriptname, commandname, seconds):
cls.cooldowns[scriptname + commandname] = time.time() + seconds
@classmethod
def GetCooldownDuration(cls, scriptname, commandname):
return round((cls.cooldowns.get(scriptname + commandname, 0) - time.time())*100)/100
@classmethod
def GetUserCooldownDuration(cls, scriptname, commandname, user):
return round((cls.user_cooldowns.get(scriptname + commandname, {}).get(user, 0) - time.time())*100)/100
functions = {"Everyone": lambda x, y: True,
"Regular": lambda x, y: Parent.GetHours(x) / 60 >= 5,
"Subscriber": lambda x, y: "Subscriber" in Parent.viewer_list[x]["roles"],
"GameWisp Subscriber": lambda x, y: False,
"Moderator": lambda x, y: "Moderator" in Parent.viewer_list[x]["roles"] or
"ChannelEditor" in Parent.viewer_list[x]["roles"] or
"Owner" in Parent.viewer_list[x]["roles"],
"Editor": lambda x, y: "ChannelEditor" in Parent.viewer_list[x]["roles"] or
"Owner" in Parent.viewer_list[x]["roles"],
"User_Specific": lambda x, y: y == Parent.viewer_list[x]["username"],
"Min_Rank": lambda x, y: Parent.GetPoints(x) >= Parent.ranks[y],
"Min_Points": lambda x, y: Parent.GetPoints(x) >= y,
"Min_Hours": lambda x, y: Parent.GetHours(x) >= y,
"Caster": lambda x, y: True}
@classmethod
def HasPermission(cls, user, permission, extra):
if cls.mocking:
return random.choice([True, True, True, False])
return cls.functions[permission](user, extra)
@classmethod
def BroadcastWsEvent(cls, eventname, jsondata):
for client_id, client in Parent.subscribers.get(eventname, {}).iteritems():
cls.websocket.send_message(client, json.dumps({"event": eventname, "data": jsondata}))
@classmethod
def GetRequest(cls, url, headers):
resp = requests.get(url, headers=headers, timeout=1)
return json.dumps({"status": resp.status_code,
"response": resp.text})
@classmethod
def PostRequest(cls, url, headers, content, isJsonContent=True):
if isJsonContent:
resp = requests.post(url, headers=headers, json=content, timeout=0.5)
else:
resp = requests.post(url, headers=headers, data=content, timeout=0.5)
return json.dumps({"status": resp.status_code, "response": resp.text})
@classmethod
def DeleteRequest(cls, url, headers):
resp = requests.delete(url, headers=headers, timeout=0.5)
return json.dumps({"status": resp.status_code, "response": resp.text})
@classmethod
def PutRequest(cls, url, headers, content, isJsonContent=True):
if isJsonContent:
resp = requests.put(url, headers=headers, json=content, timeout=0.5)
else:
resp = requests.put(url, headers=headers, data=content, timeout=0.5)
return json.dumps({"status": resp.status_code, "response": resp.text})
@classmethod
def GetRandom(cls, mini, maxi):
return random.randint(mini, maxi)
@staticmethod
def on_message(client, server, message):
data = json.loads(message)
if data.get("api_key", None) == Parent.API_Key:
for event in data.get("events", {}):
if event in Parent.subscribers:
Parent.subscribers[event][client["id"]] = client
else:
Parent.subscribers[event] = {client["id"]: client}
@classmethod
def GetStreamingService(cls):
return "Mixer"
@staticmethod
def on_client_connect(client, server):
print "client connected" + str(client)
@staticmethod
def on_client_disconnect(client, server):
for event in Parent.subscribers:
if client["id"] in Parent.subscribers[event]:
del Parent.subscribers[event][client["id"]]
def concat(msg1, msg2):
return msg1 + msg2["text"]
# noinspection PyPep8Naming
class Data(object):
def __init__(self, user, username, jsond, raw):
self.Message = reduce(concat, jsond["data"].get("message", {}).get("message", ""), "")
self.User = user
self.UserName = username
self.Whisper = "whisper" in jsond["data"].get("message", {}).get("meta", {})
self.RawData = raw
self.ServiceType = "Mixer"
def IsChatMessage(self):
return self.Message != ""
def IsWhisper(self):
return self.Whisper
@staticmethod
def IsFromDiscord(): # discord might be implemented
return False
@staticmethod
def IsFromTwitch(): # no twitch will be implemented
return False
@staticmethod
def IsFromYoutube(): # no youtube will be implemented
return False
@staticmethod
def IsFromMixer(): # at the moment only Mixer will be implemented
return True
def GetParamCount(self):
return len(self.Message.split())
def GetParam(self, index):
return self.Message.split()[index]
class Currency(object): # this should be read only!
def __init__(self, userid, username, points, minutes_watched, rank):
self.__UserId = userid
self.__UserName = username
self.__Points = points
self.__TimeWatched = minutes_watched
self.__Rank = rank
@property
def UserId(self):
return self.__UserId
@property
def UserName(self):
return self.__UserName
@property
def Points(sefl):
return self.__Points
@property
def TimeWatched(self):
return self.__TimeWatched
@property
def Rank(self):
return self.__Rank
def start(script_name, folder=None):
import json
class MixerMock(object):
def send_msg(self, msg):
print msg
def send_whisper(self, target, msg):
print '/w', target, msg
Parent.MixerChat = MixerMock()
Parent.mocking = True
Parent.stream_online = True
Parent.add_viewer(Parent.GetChannelName(), {'username': Parent.GetChannelName()})
def gather_input(last_user):
user = raw_input("username? ")
if len(user) > 0:
Parent.add_viewer('id:'+user, {'username': user})
jsond={'data': {'message': {'message': [{'text': raw_input("msg: ")}]}}}
messages.append(Data("id:" + user, user, jsond, json.dumps(jsond)))
elif last_user is not None:
jsond = {'data': {'message': {'message': [{'text': raw_input("msg: ")}]}}}
messages.append(Data("id:" + last_user, last_user, jsond, json.dumps(jsond)))
return user or last_user
sys.path.append(os.path.join(os.path.dirname(__file__), folder or script_name))
if not script_name.endswith("_StreamlabsSystem"):
script_name += "_StreamlabsSystem"
script = importlib.import_module(script_name)
script.Parent = Parent
script.Init()
messages = []
last_user = None
while True:
script.Tick()
last_user = gather_input(last_user)
if len(messages) > 0:
script.Execute(messages.pop())
if __name__ == "__main__":
start(*raw_input().split())