-
Notifications
You must be signed in to change notification settings - Fork 0
/
BotCommands.cs
272 lines (240 loc) · 9.92 KB
/
BotCommands.cs
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using UnityEngine;
using RoR2;
using RoR2.Stats;
using UnityEngine.Networking;
using R2API.Utils;
using Debug = UnityEngine.Debug;
using Path = System.IO.Path;
using Seq.Api;
using Newtonsoft.Json.Linq;
using Serilog.Formatting.Compact.Reader;
using System.Reactive.Linq;
namespace BotCMDs
{
[BepInDependency("com.bepis.r2api")]
[NetworkCompatibility(CompatibilityLevel.NoNeedForSync)] // Makes it so that the client doesn't need to run this mod to connect to the server
[BepInPlugin("com.Rayss.BotCommands", "BotCommands", "0.4.0")]
[R2APISubmoduleDependency(nameof(CommandHelper))]
public partial class BotCommands : BaseUnityPlugin
{
// Config
private static ConfigEntry<string> Servername { get; set; }
private static string _serverName;
private static ConfigEntry<string> Seqserver { get; set; }
private static string _seqserver;
private static ConfigEntry<string> Seqapi { get; set; }
private static string _seqapi;
private static ConfigEntry<string> Seqfilter { get; set; }
private static string _seqfilter;
// Create custom log source
private static ManualLogSource Log = new ManualLogSource("BotCommands");
Queue<string> Consolequeue = new Queue<string>();
[System.Diagnostics.CodeAnalysis.SuppressMessage("Code Quality", "IDE0051:Remove unused private members")]
private void Awake()
{
// Register custom log source
BepInEx.Logging.Logger.Sources.Add(Log);
// Register commands with console
R2API.Utils.CommandHelper.AddToConsoleWhenReady();
// Path is the current path of the .DLL
var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); // Unused?
Servername = Config.Bind<string>(
"Config",
"Server Name",
"Server1",
"Enter the name of your server for stats tracking"
);
_serverName = Servername.Value;
Seqserver = Config.Bind<string>(
"Config",
"Seq Server Address",
"http://example.com",
"Enter the value of your Seq.net server address"
);
_seqserver = Seqserver.Value;
Seqapi = Config.Bind<string>(
"Config",
"Seq API Key",
"",
"Enter the value of your Seq.net API Key"
);
_seqapi = Seqapi.Value;
Seqfilter = Config.Bind<string>(
"Config",
"Seq Filter",
"Contains(Channel,'670373469845979136') or Contains(Channel, '665998238171660320')", // Default uses two channels, which can be used as Admin + Regular command channels
"Enter the value of your Seq filter"
);
_seqfilter = Seqfilter.Value;
Log.LogInfo("Created by Rayss and InfernalPlacebo.");
#if DEBUG
Log.LogWarning("You are using a debug build!");
#endif
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Code Quality", "IDE0051:Remove unused private members")]
private void Start()
{
StartHooks();
SeqLogRead(_seqserver, _seqapi, _seqfilter);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Code Quality", "IDE0051:Remove unused private members")]
private void Update()
{
if (Consolequeue.Count > 0)
{
var consoleUser = new RoR2.Console.CmdSender();
RoR2.Console.instance.SubmitCmd(consoleUser, Consolequeue.Dequeue());
}
}
private async void SeqLogRead(string server, string apiKey, string filter)
{
#if DEBUG
Log.LogWarning(filter);
#endif
var connection = new SeqConnection(server, apiKey);
string strict = null;
if (filter != null)
{
var converted = await connection.Expressions.ToStrictAsync(filter);
strict = converted.StrictExpression;
}
var stream = await connection.Events.StreamAsync<JObject>(filter: strict);
stream.Select(jObject => LogEventReader.ReadFromJObject(jObject))
.Subscribe(evt => {
string command = evt.RenderMessage();
command = command.Trim(new char[] {'"'});
Consolequeue.Enqueue(command);
});
await stream;
}
private static void StartHooks()
{
// On run end
On.RoR2.RunReport.Generate += (orig, run, resulttype) =>
{
RunReport valid = orig(run, resulttype);
foreach (var user in NetworkUser.readOnlyInstancesList)
{
GetStats(user);
}
return valid;
};
// On player leave
On.RoR2.Networking.GameNetworkManager.OnServerDisconnect += (orig, run, conn) =>
{
if (Run.instance)
{
NetworkUser user = FindNetworkUserForConnectionServer(conn);
GetStats(user);
}
orig(run, conn);
};
// On scene change (unloaded, new scene not yet loaded)
On.RoR2.FadeToBlackManager.OnSceneUnloaded += (orig, run) =>
{
orig(run);
if (!Run.instance) return;
LogTime();
LogStagesCleared();
};
}
private static void LogTime()
{
if (!Run.instance)
{
throw new ConCommandException("No run is currently in progress.");
}
Debug.Log("Run time is " + Run.instance.GetRunStopwatch().ToString());
}
private static void LogStagesCleared()
{
if (!Run.instance)
{
throw new ConCommandException("No run is currently in progress.");
}
Debug.Log("Stages cleared: " + Run.instance.NetworkstageClearCount.ToString());
}
private static void GetStats(NetworkUser user)
{
try // Done to prevent users with no masterobject (spectators) from causing a NullReferenceException
{
// Unity variables
var playerMasterObject = user.masterObject;
var steamId = Convert.ToInt64(user.id.steamId.ToString());
var component = playerMasterObject.GetComponent<PlayerStatsComponent>();
var statSheet = component?.currentStats;
var sendToDynamo = new Dictionary<string, string>();
// Creates the array of the run report
var array = new string[statSheet.fields.Length];
// Iterates through the run report to add to a dictionary
for (var i = 0; i < array.Length; i++)
{
array[i] = $"[\"{statSheet.fields[i].name}\"]={statSheet.fields[i].ToString()}";
if (statSheet.fields[i].ToString() == "0")
{
}
else
{
sendToDynamo[statSheet.fields[i].name] = statSheet.fields[i].ToString();
}
}
// Adds server and SteamID to dictionary
sendToDynamo["Server"] = _serverName;
sendToDynamo["SteamID"] = steamId.ToString();
// Splits the dictionary into a string that can be used as an argument
var result = string.Join(" ", sendToDynamo.Select(kvp => $"{kvp.Key},{kvp.Value}"));
// Use ProcessStartInfo class
var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
#if DEBUG
var startInfo = new ProcessStartInfo
{
CreateNoWindow = false,
UseShellExecute = true,
FileName = path + @"\BotCommands_Dynamo.exe",
WindowStyle = ProcessWindowStyle.Normal,
Arguments = result
};
#else
var startInfo = new ProcessStartInfo
{
CreateNoWindow = true,
UseShellExecute = false,
FileName = path + @"\BotCommands_Dynamo.exe",
WindowStyle = ProcessWindowStyle.Hidden,
Arguments = result
};
#endif
try
{
// Start the process with the info we specified.
using (var exeProcess = Process.Start(startInfo))
{
Log.LogInfo("BotCommands: Updating stats database!");
}
}
catch (Exception ex)
{
Log.LogError($"BotCommands: {ex.Message}");
}
}
catch (Exception ex)
{
Log.LogError($"BotCommands: {ex.Message}");
}
}
// Borrowed from R2DSEssentials.Util.Networking
private static NetworkUser FindNetworkUserForConnectionServer(NetworkConnection connection)
{
return NetworkUser.readOnlyInstancesList.FirstOrDefault(networkUser =>
networkUser.connectionToClient == connection);
}
}
}