-
Notifications
You must be signed in to change notification settings - Fork 0
/
StreamlabsSocketMirror_StreamlabsSystem.py
255 lines (231 loc) · 9.06 KB
/
StreamlabsSocketMirror_StreamlabsSystem.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
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
#---------------------------------------
# Import Libraries
#---------------------------------------
import logging
from logging.handlers import TimedRotatingFileHandler
import clr
import re
import os
import codecs
import json
import uuid
clr.AddReference("SocketIOClientDotNet.dll")
clr.AddReference("Newtonsoft.Json.dll")
from System import Uri, Action
from Quobject.SocketIoClientDotNet import Client as SocketIO
from Newtonsoft.Json.JsonConvert import SerializeObject as JSONDump
#---------------------------------------
# [Required] Script Information
#---------------------------------------
ScriptName = 'StreamlabsSocketMirror'
Website = 'https://github.com/nossebro/StreamlabsSocketMirror'
Creator = 'nossebro'
Version = '0.0.1'
Description = 'Mirrors events from the Streamlabs socket, and sends them to the local SLCB socket'
#---------------------------------------
# Script Variables
#---------------------------------------
ScriptSettings = None
StreamlabsSocketAPI = None
Logger = None
SettingsFile = os.path.join(os.path.dirname(__file__), "Settings.json")
UIConfigFile = os.path.join(os.path.dirname(__file__), "UI_Config.json")
#---------------------------------------
# Script Classes
#---------------------------------------
class StreamlabsLogHandler(logging.StreamHandler):
def emit(self, record):
try:
message = self.format(record)
Parent.Log(ScriptName, message)
self.flush()
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
class Settings(object):
def __init__(self, settingsfile=None):
defaults = self.DefaultSettings(UIConfigFile)
try:
with codecs.open(settingsfile, encoding="utf-8-sig", mode="r") as f:
settings = json.load(f, encoding="utf-8")
self.__dict__ = MergeLists(defaults, settings)
except:
self.__dict__ = defaults
def DefaultSettings(self, settingsfile=None):
defaults = dict()
with codecs.open(settingsfile, encoding="utf-8-sig", mode="r") as f:
ui = json.load(f, encoding="utf-8")
for key in ui:
try:
defaults[key] = ui[key]['value']
except:
if key != "output_file":
Parent.Log(ScriptName, "DefaultSettings(): Could not find key {0} in settings".format(key))
return defaults
def Reload(self, jsondata):
self.__dict__ = MergeLists(self.DefaultSettings(UIConfigFile), json.loads(jsondata, encoding="utf-8"))
#---------------------------------------
# Script Functions
#---------------------------------------
def GetLogger():
log = logging.getLogger(ScriptName)
log.setLevel(logging.DEBUG)
sl = StreamlabsLogHandler()
sl.setFormatter(logging.Formatter("%(funcName)s(): %(message)s"))
sl.setLevel(logging.INFO)
log.addHandler(sl)
fl = TimedRotatingFileHandler(filename=os.path.join(os.path.dirname(__file__), "info"), when="w0", backupCount=8, encoding="utf-8")
fl.suffix = "%Y%m%d"
fl.setFormatter(logging.Formatter("%(asctime)s %(funcName)s(): %(levelname)s: %(message)s"))
fl.setLevel(logging.INFO)
log.addHandler(fl)
if ScriptSettings.DebugMode:
dfl = TimedRotatingFileHandler(filename=os.path.join(os.path.dirname(__file__), "debug"), when="h", backupCount=24, encoding="utf-8")
dfl.suffix = "%Y%m%d%H%M%S"
dfl.setFormatter(logging.Formatter("%(asctime)s %(funcName)s(): %(levelname)s: %(message)s"))
dfl.setLevel(logging.DEBUG)
log.addHandler(dfl)
log.debug("Logger initialized")
return log
def MergeLists(x = dict(), y = dict()):
for attr in x:
if attr not in y:
y.append(attr)
return y
#---------------------------------------
# Chatbot Initialize Function
#---------------------------------------
def Init():
global ScriptSettings
ScriptSettings = Settings(SettingsFile)
global Logger
Logger = GetLogger()
Parent.BroadcastWsEvent('{0}_UPDATE_SETTINGS'.format(ScriptName.upper()), json.dumps(ScriptSettings.__dict__))
Logger.debug(json.dumps(ScriptSettings.__dict__), True)
global StreamlabsSocketAPI
url = Uri("https://sockets.streamlabs.com")
options = SocketIO.IO.Options(AutoConnect=False, QueryString="token={0}".format(ScriptSettings.SLSocketToken))
StreamlabsSocketAPI = SocketIO.IO.Socket(url, options)
StreamlabsSocketAPI.On("event", Action[object](StreamlabsSocketAPIEvent))
StreamlabsSocketAPI.On(SocketIO.Socket.EVENT_CONNECT, Action[object](StreamlabsSocketAPIConnected))
StreamlabsSocketAPI.On(SocketIO.Socket.EVENT_CONNECT_ERROR, Action[object](StreamlabsSocketAPIError))
StreamlabsSocketAPI.On(SocketIO.Socket.EVENT_CONNECT_TIMEOUT, Action[object](StreamlabsSocketAPIError))
StreamlabsSocketAPI.On(SocketIO.Socket.EVENT_DISCONNECT, Action[object](StreamlabsSocketAPIDisconnected))
StreamlabsSocketAPI.On(SocketIO.Socket.EVENT_ERROR, Action[object](StreamlabsSocketAPIError))
StreamlabsSocketAPI.On(SocketIO.Socket.EVENT_MESSAGE, Action[object](StreamlabsSocketAPIMessage))
StreamlabsSocketAPI.On(SocketIO.Socket.EVENT_RECONNECT_ERROR, Action[object](StreamlabsSocketAPIError))
StreamlabsSocketAPI.On(SocketIO.Socket.EVENT_RECONNECT_FAILED, Action[object](StreamlabsSocketAPIError))
if ScriptSettings.SLSocketToken:
StreamlabsSocketAPI.Connect()
else:
Logger.warning("Streamlabs Socket Token not configured")
#---------------------------------------
# Chatbot Script Unload Function
#---------------------------------------
def Unload():
global StreamlabsSocketAPI
global Logger
if StreamlabsSocketAPI:
StreamlabsSocketAPI.Close()
StreamlabsSocketAPI = None
Logger.debug("StreamlabsSocketAPI Disconnected")
if Logger:
Logger.handlers.Clear()
Logger = None
#---------------------------------------
# Chatbot Save Settings Function
#---------------------------------------
def ReloadSettings(jsondata):
ScriptSettings.Reload(jsondata)
Logger.debug("Settings reloaded")
Parent.BroadcastWsEvent('{0}_UPDATE_SETTINGS'.format(ScriptName.upper()), json.dumps(ScriptSettings.__dict__))
Logger.debug(json.dumps(ScriptSettings.__dict__), True)
#---------------------------------------
# Chatbot Execute Function
#---------------------------------------
def Execute(data):
pass
#---------------------------------------
# Chatbot Tick Function
#---------------------------------------
def Tick():
pass
#---------------------------------------
# StreamlabsSocketAPI Connect Function
#---------------------------------------
def StreamlabsSocketAPIConnected(data):
Logger.debug("Connected")
#---------------------------------------
# StreamlabsSocketAPI Disconnect Function
#---------------------------------------
def StreamlabsSocketAPIDisconnected(data):
global Logger
Logger.debug("Disconnected: {0}".format(data))
#---------------------------------------
# StreamlabsSocketAPI Error Function
#---------------------------------------
def StreamlabsSocketAPIError(data):
global Logger
Logger.error(data.Message)
Logger.exception(data)
#---------------------------------------
# StreamlabsSocketAPI Message Function
#---------------------------------------
def StreamlabsSocketAPIMessage(data):
Logger.info("Message: {0}".format(json.dumps(json.loads(JSONDump(data)))))
#---------------------------------------
# StreamlabsSocketAPI Event Function
#---------------------------------------
def StreamlabsSocketAPIEvent(data):
event = json.loads(JSONDump(data).encode(encoding="UTF-8", errors="backslashreplace"))
if ScriptSettings.MirrorAll:
Logger.debug("Send original event to Local Socket")
Parent.BroadcastWsEvent("STREAMLABS", json.dumps(event))
if not "message" in event:
Logger.debug("No message in event: {0}".format(json.dumps(event)))
return
if not "for" in event and "type" in event and event["type"] == "donation":
Logger.debug("No \"for\" attribute in event: {0}".format(json.dumps(event)))
event["for"] = "streamlabs"
if isinstance(event["message"], dict):
event["message"] = json.loads( "[ {0} ]".format(json.dumps(event["message"])))
for message in event["message"]:
if "isTest" in message:
if not ScriptSettings.SLTestMode:
Logger.warning("Received test event, resend disabled in configuration")
Logger.debug(json.dumps(event))
continue
if "repeat" in message:
if not ScriptSettings.SLRepeat:
Logger.warning("Received repeated event, resend disabled in configuration")
Logger.debug(json.dumps(event))
continue
if event["for"] == "streamlabs":
if event["type"] == "donation":
Logger.info(message)
elif event["type"] == "loyalty_store_redemption":
Logger.info(message)
elif event["type"] == "merch":
Logger.info(message)
elif event["type"] == "prime_sub_gift":
Logger.info(message)
else:
Logger.warning("Unrecognised event for {0}: {1}".format(event["for"], json.dumps(event)))
elif event["for"] == "twitch_account":
if event["type"] == "bits":
Logger.info(message)
elif event["type"] == "follow":
Logger.info(message)
elif event["type"] == "host":
Logger.info(message)
elif event["type"] == "raid":
Logger.info(message)
elif event["type"] == "subscription":
Logger.info(message)
elif event["type"] == "resub":
Logger.info(message)
else:
Logger.warning("Unrecognised event for {0}: {1}".format(event["for"], json.dumps(event)))
else:
Logger.warning("Unrecognised event for {0}: {1}".format(event["for"], json.dumps(event)))