/
RelayBot.cs
421 lines (333 loc) · 18 KB
/
RelayBot.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
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
/*
Copyright 2011 MCForge
Dual-licensed under the Educational Community License, Version 2.0 and
the GNU General Public License, Version 3 (the "Licenses"); you may
not use this file except in compliance with the Licenses. You may
obtain a copy of the Licenses at
http://www.opensource.org/licenses/ecl2.php
http://www.gnu.org/licenses/gpl-3.0.html
Unless required by applicable law or agreed to in writing,
software distributed under the Licenses are distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
or implied. See the Licenses for the specific language governing
permissions and limitations under the Licenses.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using MCGalaxy.Commands;
using MCGalaxy.DB;
using MCGalaxy.Events.ServerEvents;
namespace MCGalaxy.Modules.Relay {
public class RelayUser { public string ID, Nick; }
/// <summary> Manages a connection to an external communication service </summary>
public abstract class RelayBot {
/// <summary> List of commands that cannot be used by relay bot controllers. </summary>
public List<string> BannedCommands;
/// <summary> List of channels to send public chat messages to </summary>
public string[] Channels;
/// <summary> List of channels to send staff only messages to </summary>
public string[] OpChannels;
/// <summary> List of user IDs that all chat from is ignored </summary>
public string[] IgnoredUsers;
readonly Player fakeGuest = new Player("RelayBot");
readonly Player fakeStaff = new Player("RelayBot");
DateTime lastWho, lastOpWho;
protected bool resetting;
protected byte retries;
/// <summary> The name of the service this relay bot communicates with </summary>
/// <example> IRC, Discord </example>
public abstract string RelayName { get; }
/// <summary> Whether this relay bot is currently enabled </summary>
public abstract bool Enabled { get; }
/// <summary> Wehther this relay bot is connected to the external communication service </summary>
public abstract bool Connected { get; }
/// <summary> List of users allowed to run in-game commands from the external communication service </summary>
public PlayerList Controllers;
/// <summary> Sends a message to all channels setup for general public chat </summary>
public void SendPublicMessage(string message) {
foreach (string chan in Channels) {
SendMessage(chan, message);
}
}
/// <summary> Sends a message to all channels setup for staff chat only </summary>
public void SendStaffMessage(string message) {
foreach (string chan in OpChannels) {
SendMessage(chan, message);
}
}
/// <summary> Sends a message to the given channel </summary>
/// <remarks> Channels can specify either group chat or direct messages </remarks>
public void SendMessage(string channel, string message) {
if (!Enabled || !Connected) return;
DoSendMessage(channel, ConvertMessage(message));
}
/// <summary> Formats a message for displaying on the external communication service </summary>
/// <example> IRC converts colors such as &0 into IRC color codes </example>
protected virtual string ConvertMessage(string message) {
message = EmotesHandler.Replace(message);
message = ChatTokens.ApplyCustom(message);
return message;
}
/// <summary> Sends a chat message to the given channel </summary>
/// <remarks> The message has already been formatted using ConvertMessage </remarks>
protected abstract void DoSendMessage(string channel, string message);
/// <summary> Attempts to connect to the external communication service </summary>
/// <remarks> Does nothing if disabled, already connected, or the server is shutting down </remarks>
public void Connect() {
if (!Enabled || Connected || Server.shuttingDown) return;
Logger.Log(LogType.RelayActivity, "Connecting to {0}...", RelayName);
try {
UpdateConfig();
DoConnect();
} catch (Exception e) {
Logger.Log(LogType.RelayActivity, "Failed to connect to {0}!", RelayName);
Logger.LogError(e);
}
}
/// <summary> Attempts to disconnect from the external communication service </summary>
/// <remarks> Does nothing if not connected </remarks>
public void Disconnect(string reason) {
if (!Connected) return;
DoDisconnect(reason);
Logger.Log(LogType.RelayActivity, "Disconnected from {0}!", RelayName);
}
public void Reset() {
resetting = true;
retries = 0;
Disconnect(RelayName + " Bot resetting...");
if (Enabled) Connect();
}
protected void OnReady() {
Logger.Log(LogType.RelayActivity, "Connected to {0}!", RelayName);
resetting = false;
retries = 0;
}
protected void AutoReconnect() {
if (resetting || retries >= 3) return;
retries++;
Connect();
}
protected abstract void DoConnect();
protected abstract void DoDisconnect(string reason);
/// <summary> Loads the list of controller users from disc </summary>
public abstract void LoadControllers();
/// <summary> Reloads all configuration (including controllers list) </summary>
public virtual void ReloadConfig() {
UpdateConfig();
LoadControllers();
}
protected abstract void UpdateConfig();
protected void LoadBannedCommands() {
BannedCommands = new List<string>() { "IRCBot", "DiscordBot", "OpRules", "IRCControllers", "DiscordControllers" };
if (!File.Exists("text/irccmdblacklist.txt")) {
File.WriteAllLines("text/irccmdblacklist.txt", new string[] {
"# Here you can put commands that cannot be used from the IRC bot.",
"# Lines starting with \"#\" are ignored." });
}
foreach (string line in File.ReadAllLines("text/irccmdblacklist.txt")) {
if (!line.IsCommentLine()) BannedCommands.Add(line);
}
}
protected void HookEvents() {
OnChatEvent.Register(OnChat, Priority.Low);
OnChatSysEvent.Register(OnChatSys, Priority.Low);
OnChatFromEvent.Register(OnChatFrom, Priority.Low);
OnShuttingDownEvent.Register(OnShutdown, Priority.Low);
}
protected void UnhookEvents() {
OnChatEvent.Unregister(OnChat);
OnChatSysEvent.Unregister(OnChatSys);
OnChatFromEvent.Unregister(OnChatFrom);
OnShuttingDownEvent.Unregister(OnShutdown);
}
static bool FilterIRC(Player pl, object arg) {
return !pl.Ignores.IRC && !pl.Ignores.IRCNicks.Contains((string)arg);
} static ChatMessageFilter filterIRC = FilterIRC;
public static void MessageInGame(string srcNick, string message) {
Chat.Message(ChatScope.Global, message, srcNick, filterIRC);
}
string Unescape(Player p, string msg) {
return msg
.Replace("λFULL", UnescapeFull(p))
.Replace("λNICK", UnescapeNick(p));
}
protected virtual string UnescapeFull(Player p) {
return Server.Config.IRCShowPlayerTitles ? p.FullName : p.group.Prefix + p.ColoredName;
}
protected virtual string UnescapeNick(Player p) { return p.ColoredName; }
protected virtual string PrepareMessage(string msg) { return msg; }
void MessageToRelay(ChatScope scope, string msg, object arg, ChatMessageFilter filter) {
ChatMessageFilter scopeFilter = Chat.scopeFilters[(int)scope];
fakeGuest.group = Group.DefaultRank;
if (scopeFilter(fakeGuest, arg) && (filter == null || filter(fakeGuest, arg))) {
SendPublicMessage(msg); return;
}
fakeStaff.group = Group.Find(Server.Config.IRCControllerRank);
if (fakeStaff.group == null) fakeStaff.group = Group.NobodyRank;
if (scopeFilter(fakeStaff, arg) && (filter == null || filter(fakeStaff, arg))) {
SendStaffMessage(msg);
}
}
void OnChatSys(ChatScope scope, string msg, object arg,
ref ChatMessageFilter filter, bool relay) {
if (!relay) return;
msg = PrepareMessage(msg);
MessageToRelay(scope, msg, arg, filter);
}
void OnChatFrom(ChatScope scope, Player source, string msg,
object arg, ref ChatMessageFilter filter, bool relay) {
if (!relay) return;
msg = PrepareMessage(msg);
MessageToRelay(scope, Unescape(source, msg), arg, filter);
}
void OnChat(ChatScope scope, Player source, string msg,
object arg, ref ChatMessageFilter filter, bool relay) {
if (!relay) return;
msg = PrepareMessage(msg);
MessageToRelay(scope, Unescape(source, msg), arg, filter);
}
void OnShutdown(bool restarting, string message) {
Disconnect(restarting ? "Server is restarting" : "Server is shutting down");
}
/// <summary> Simplifies some fancy characters (e.g. simplifies ” to ") </summary>
protected void SimplifyCharacters(StringBuilder sb) {
// simplify fancy quotes
sb.Replace("“", "\"");
sb.Replace("”", "\"");
sb.Replace("‘", "'");
sb.Replace("’", "'");
}
protected abstract string ParseMessage(string message);
/// <summary> Handles a direct message written by the given user </summary>
protected void HandleDirectMessage(RelayUser user, string channel, string message) {
if (IgnoredUsers.CaselessContains(user.ID)) return;
message = ParseMessage(message);
string[] parts = message.SplitSpaces(2);
string cmdName = parts[0].ToLower();
string cmdArgs = parts.Length > 1 ? parts[1] : "";
if (HandleListPlayers(user, channel, cmdName, false)) return;
Command.Search(ref cmdName, ref cmdArgs);
string error;
if (!CanUseCommand(user, cmdName, out error)) {
if (error != null) SendMessage(channel, error);
return;
}
ExecuteCommand(user, channel, cmdName, cmdArgs);
}
/// <summary> Handles a message written by the given user on the given channel </summary>
protected void HandleChannelMessage(RelayUser user, string channel, string message) {
if (IgnoredUsers.CaselessContains(user.ID)) return;
message = ParseMessage(message);
message = message.TrimEnd();
if (message.Length == 0) return;
string[] parts = message.SplitSpaces(3);
string rawCmd = parts[0].ToLower();
bool opchat = OpChannels.CaselessContains(channel);
if (HandleListPlayers(user, channel, rawCmd, opchat)) return;
if (rawCmd.CaselessEq(Server.Config.IRCCommandPrefix)) {
if (!HandleCommand(user, channel, message, parts)) return;
}
if (opchat) {
Logger.Log(LogType.RelayChat, "(OPs): ({0}) {1}: {2}", RelayName, user.Nick, message);
Chat.MessageOps(string.Format("To Ops &f-&I({0}) {1}&f- {2}", RelayName, user.Nick,
Server.Config.ProfanityFiltering ? ProfanityFilter.Parse(message) : message));
} else if (Channels.CaselessContains(channel)) {
// ignore message if it is not from a configured channel
Logger.Log(LogType.RelayChat, "({0}) {1}: {2}", RelayName, user.Nick, message);
MessageInGame(user.Nick, string.Format("&I({0}) {1}: &f{2}", RelayName, user.Nick,
Server.Config.ProfanityFiltering ? ProfanityFilter.Parse(message) : message));
}
}
bool HandleListPlayers(RelayUser user, string channel, string cmd, bool opchat) {
bool isWho = cmd == ".who" || cmd == ".players" || cmd == "!players";
DateTime last = opchat ? lastOpWho : lastWho;
if (!isWho || (DateTime.UtcNow - last).TotalSeconds <= 5) return false;
try {
RelayPlayer p = new RelayPlayer(channel, user, this);
p.group = Group.DefaultRank;
MessagePlayers(p);
} catch (Exception e) {
Logger.LogError(e);
}
if (opchat) lastOpWho = DateTime.UtcNow;
else lastWho = DateTime.UtcNow;
return true;
}
/// <summary> Outputs the list of online players to the given user </summary>
protected virtual void MessagePlayers(RelayPlayer p) {
Command.Find("Players").Use(p, "", p.DefaultCmdData);
}
bool HandleCommand(RelayUser user, string channel, string message, string[] parts) {
string cmdName = parts.Length > 1 ? parts[1].ToLower() : "";
string cmdArgs = parts.Length > 2 ? parts[2] : "";
Command.Search(ref cmdName, ref cmdArgs);
string error;
if (!CanUseCommand(user, cmdName, out error)) {
if (error != null) SendMessage(channel, error);
return false;
}
return ExecuteCommand(user, channel, cmdName, cmdArgs);
}
bool ExecuteCommand(RelayUser user, string channel, string cmdName, string cmdArgs) {
Command cmd = Command.Find(cmdName);
Player p = new RelayPlayer(channel, user, this);
if (cmd == null) { p.Message("Unknown command!"); return false; }
string logCmd = cmdArgs.Length == 0 ? cmdName : cmdName + " " + cmdArgs;
Logger.Log(LogType.CommandUsage, "/{0} (by {1} from {2})", logCmd, user.Nick, RelayName);
try {
if (!p.CanUse(cmd)) {
CommandPerms.Find(cmd.name).MessageCannotUse(p);
return false;
}
if (!cmd.SuperUseable) {
p.Message(cmd.name + " can only be used in-game.");
return false;
}
cmd.Use(p, cmdArgs);
} catch (Exception ex) {
p.Message("CMD Error: " + ex);
Logger.LogError(ex);
}
return true;
}
/// <summary> Returns whether the given relay user is allowed to execute the given command </summary>
protected bool CanUseCommand(RelayUser user, string cmd, out string error) {
error = null;
// Intentionally show no message to non-controller users to avoid spam
if (!Controllers.Contains(user.ID)) return false;
// Make sure controller is actually allowed to execute commands right now
if (!CheckController(user.ID, ref error)) return false;
if (BannedCommands.CaselessContains(cmd)) {
error = "You are not allowed to use this command from " + RelayName + ".";
return false;
}
return true;
}
/// <summary> Returns whether the given controller is currently allowed to execute commands </summary>
/// <remarks> e.g. a user may have to login before they are allowed to execute commands </remarks>
protected abstract bool CheckController(string userID, ref string error);
protected sealed class RelayPlayer : Player {
public readonly string ChannelID;
public readonly RelayUser User;
public readonly RelayBot Bot;
public RelayPlayer(string channel, RelayUser user, RelayBot bot) : base(bot.RelayName) {
group = Group.Find(Server.Config.IRCControllerRank);
if (group == null) group = Group.NobodyRank;
ChannelID = channel;
User = user;
color = "&a";
Bot = bot;
if (user != null) {
string nick = "(" + bot.RelayName + user.Nick + ")";
DatabaseID = NameConverter.InvalidNameID(nick);
}
SuperName = bot.RelayName;
}
public override void Message(byte type, string message) {
Bot.SendMessage(ChannelID, message);
}
}
}
}