forked from iPeer/DiscordBot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
280 lines (238 loc) · 11.7 KB
/
Program.cs
File metadata and controls
280 lines (238 loc) · 11.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord;
using Newtonsoft.Json;
using System.IO;
using DiscordBot.Config;
using DiscordBot.Commands;
using DiscordBot.Logging;
using DiscordBot.Utilities;
using DiscordBot.Fun;
namespace DiscordBot
{
class Program
{
public bool IS_RUNNING = false;
public DateTime STARTUP_TIME;
public DiscordClient client;
public BotConfig _config;
public static Program Instance { get; private set; }
public Logger Logger { get; private set; }
public CommandManager commandManager { get; private set; }
public ServerLogManager serverLogManager { get; private set; }
public MessageLogger messageLogger { get; private set; }
public FunManager funManager { get; private set; }
static void Main(string[] args)
{
Program p = new Program();
}
public TimeSpan getUptime()
{
return (TimeSpan)(DateTime.Now - this.STARTUP_TIME);
}
public Program()
{
Instance = this;
if (Directory.GetFiles(Path.Combine(Utils.getApplicationEXEFolderPath(), "logs")).Length > 0)
Logger.ArchiveAndRemoveOldLogs();
this.STARTUP_TIME = DateTime.Now;
this.Logger = new Logger("Program");
this.Logger.Log("Checking for config directories and creating them if they don't exist.");
// Set up config
Directory.CreateDirectory("config/");
if (!File.Exists("config/config.cfg"))
File.WriteAllText("config/config.cfg", JsonConvert.SerializeObject(new BotConfig(), Formatting.Indented));
_config = JsonConvert.DeserializeObject<BotConfig>(File.ReadAllText("config/config.cfg"));
if (_config.botAPIToken.Equals("YOUR.TOKEN.HERE"))
{
Console.WriteLine("NO BOT TOKEN IS SET IN THE CONFIG, CANNOT RUN.");
Console.WriteLine("PLEASE SET UP YOUR config/config.cfg FILE BEFROE RUNNING THE BOT AGAIN.");
}
else
{
this.Logger.Log("Initialising ServerLogManager");
this.serverLogManager = new ServerLogManager();
this.Logger.Log("Setting up DM logger");
this.messageLogger = new MessageLogger(Path.Combine(Utils.getApplicationEXEFolderPath(), "logs", "DMs"));
this.Logger.Log("Initialising CommandManager");
// Set up command manager
this.commandManager = new CommandManager();
this.Logger.Log("Initialising FunManager");
this.funManager = new FunManager();
this.Logger.Log("Starting DiscordClient");
this.client = new DiscordClient(new DiscordConfigBuilder()
{
MessageCacheSize = 10,
ConnectionTimeout = 60000,
LogLevel = LogSeverity.Warning,
LogHandler = LogDebugMessage
});
this.IS_RUNNING = true;
this.client.MessageReceived += (s, e) => MessageReceived(s, e, false);
this.client.JoinedServer += JoinedServer;
this.client.ServerAvailable += ServerAvailable;
this.client.ServerUnavailable += ServerUnavailable;
this.client.LeftServer += ServerUnavailable;
this.client.UserJoined += (s, e) => UserJoinedOrLeft(s, e, true);
this.client.UserLeft += (s, e) => UserJoinedOrLeft(s, e, false);
this.client.UserUpdated += UserUpdated;
/*this.client.MessageSent += MessageSent;
this.client.MessageAcknowledged += MessageSent;*/ // <-- This and the one above it do NOTHING. They're not even implemented in the library
this.client.MessageUpdated += MessageUpdated;
this.client.ExecuteAndWait(async () =>
{
await this.client.Connect(_config.botAPIToken, TokenType.Bot); // Updated to Discord.NET 0.9.5
Console.WriteLine("Connected host is {0}", this.client.GatewaySocket.Host);
#if RELEASE
await Task.Delay(150000).ConfigureAwait(false);
#else
await Task.Delay(1000).ConfigureAwait(false);
#endif
});
this.Logger.Log("No longer connected, terminating process.", LogLevel.WARNING);
this.funManager.onBotTerminating();
}
}
private void MessageUpdated(object sender, MessageUpdatedEventArgs e)
{
try
{
bool isDM = /*e.Server == null*/e.Channel.IsPrivate;
this.funManager.onMessageUpdated(e);
if (isDM)
{ // Private messages
this.messageLogger.Log(e.Channel, "{0} [{1}] updated message '{2}' to '{3}'", e.User.Name, e.User.Id, e.Before.Text, e.After.Text);
}
else
{
this.serverLogManager.getLoggerForServerID(e.Server.Id).Log(e.Channel, "{0} [{1}] updated message '{2}' to '{3}' in channel '{4}' [{5}] on server '{6}' [{7}]", e.User.Name, e.User.Id, e.Before.Text, e.After.Text, e.Channel.Name, e.Channel.Id, e.Server.Name, e.Server.Id);
}
#if DEBUG
this.Logger.Log("MessageUpdateCommandFiring: Enabled: {2}, Graced: {0} ({3} vs {4}), Text: {1}", (DateTime.Now - e.Before.Timestamp).TotalSeconds <= this._config.updatedMessageCommandGraceSeconds, e.After.Text, this._config.fireOnUpdatedMessages, DateTime.Now.ToString(), e.Before.Timestamp.ToString());
#endif
if (this._config.fireOnUpdatedMessages)
{
if ((DateTime.UtcNow - e.Before.Timestamp).TotalSeconds <= this._config.updatedMessageCommandGraceSeconds)
{
MessageEventArgs a = new MessageEventArgs(e.After);
this.MessageReceived(null, a, true);
}
}
}
catch (Exception _e)
{
Utils.LogException("MessageUpdated", _e);
}
}
private void MessageSent(object sender, MessageEventArgs e)
{
// This is only used to log replies in private messages to the correct place
Console.WriteLine("Message sent ping");
Utils.sendToDebugChannel("{0} // {1}: {2}", e.User.Name, e.User.Id, e.Message.Text);
}
private void UserUpdated(object sender, UserUpdatedEventArgs e)
{
try
{
this.funManager.onUserUpdate(e);
if (!this._config.logUserUpdates) { return; }
MessageLogger sl = this.serverLogManager.getLoggerForServer(e.Server);
string logMsg = String.Format("Update on user '{0}' [{1}] from server '{3}' [{4}]: {2}", e.Before.Name, e.Before.Id, String.Format("{0} -> {1}, {2} -> {3}, {4} -> {5}, {6} -> {7}", e.Before.Name, e.After.Name, e.Before.Nickname, e.After.Nickname, e.Before.CurrentGame.GetValueOrDefault().Name, e.After.CurrentGame.GetValueOrDefault().Name, e.Before.Status.ToString(), e.After.Status.ToString()), e.Server.Name, e.Server.Id);
sl.Log(logMsg);
}
catch (Exception _e)
{
Utils.LogException("UserUpdated", _e);
}
}
private void UserJoinedOrLeft(object sender, UserEventArgs e, bool isJoin)
{
if (isJoin)
this.funManager.onUserJoined(e);
else
this.funManager.onUserLeft(e);
MessageLogger sl = this.serverLogManager.getLoggerForServer(e.Server);
string logMsg = String.Format("{2} -> '{0}' [{1}]", e.User.Name, e.User.Id, isJoin?"JOIN":"LEAVE");
sl.Log(logMsg);
}
private void ServerUnavailable(object sender, ServerEventArgs e) // Fires if the bot is no longer authorised to be on the server (I think) - We also use it to handle when the bot leaves a server
{
this.funManager.onServerLeft(e);
MessageLogger sl = this.serverLogManager.getLoggerForServer(e.Server);
string logMsg = String.Format("Server unavailable: '{0}' [{1}]", e.Server.Name, e.Server.Id);
sl.Log(logMsg);
this.Logger.Log(logMsg);
this.serverLogManager.removeLoggerForServer(e.Server.Id);
}
private void ServerAvailable(object sender, ServerEventArgs e)
{
this.funManager.onServerJoined(e);
MessageLogger sl = this.serverLogManager.createLoggerForServer(e.Server);
string logMsg = String.Format("Server available: '{0}' [{1}]", e.Server.Name, e.Server.Id);
sl.Log(logMsg);
this.Logger.Log(logMsg);
}
private void JoinedServer(object sender, ServerEventArgs e)
{
this.funManager.onServerJoined(e);
MessageLogger sl = this.serverLogManager.createLoggerForServer(e.Server);
string logMsg = String.Format("Joined server '{0}' [{1}]", e.Server.Name, e.Server.Id);
sl.Log(logMsg);
this.Logger.Log(logMsg);
}
private void LogDebugMessage(object sender, LogMessageEventArgs e)
{
/*if (this._config.USE_DEBUG_CHANNEL && this.client.Servers.Any())
{
if (!e.Message.Contains(this._config.DEBUG_CHANNEL_NAME))
{
try
{
Server debug_server = this.client.Servers.First(s => s.Name.Equals(this._config.DEBUG_CHANNEL_SERVER_NAME));
Channel debug_channel = debug_server.TextChannels.First(c => c.Name.Equals(this._config.DEBUG_CHANNEL_NAME));
debug_channel.SendMessage(String.Format("[{0}] {1}", e.Severity, e.Message));
}
catch { Console.WriteLine("Cannot send messages to debug channel because it wasn't found."); }
}
}*/
this.Logger.Log("[{0}] {1} / {2}", e.Severity, "", e.Message);
}
private void MessageReceived(object sender, MessageEventArgs e, bool silent = true)
{
if (e.Message.Text.Length == 0) { return; } // Fix for ArgumentOutOfRangeException on messages which are just images
try
{
this.funManager.onMessageReceived(e);
bool isDM = /*e.Server == null*/e.Channel.IsPrivate;
if (!silent)
{
if (isDM)
{ // Private messages
this.messageLogger.Log(e.Channel, "{0} [{1}]: {2}", e.User.Name, e.User.Id, e.Message.Text);
}
else
{
this.serverLogManager.getLoggerForServerID(e.Server.Id).Log(e.Channel, "{0} [{1}]: {2}", e.User.Name, e.User.Id, e.Message.Text);
#if DEBUG
this.Logger.Log("[{0}] {1} [{4}]@{3}: {2}", e.Server, e.User, e.Message.Text, e.Channel, e.User.Id);
#endif
}
}
if (e.User.Name.Equals(this.client.CurrentUser.Name)) { return; }
this.commandManager.invokeMatchingPhraseCommands(e);
if (this._config.commandTriggerCharacters.Contains(e.Message.Text.Substring(0, 1)))
{
string command = e.Message.Text.Substring(1).Split(' ')[0];
this.commandManager.invokeCommandsFromName(command, e, isDM);
}
}
catch (Exception _e)
{
Utils.LogException("MessageReceived", _e);
}
}
}
}