-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
450 lines (399 loc) · 24.6 KB
/
Program.cs
File metadata and controls
450 lines (399 loc) · 24.6 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
442
443
444
445
446
447
448
449
450
using NetCord;
using NetCord.Gateway;
using NetCord.Rest;
using System;
using System.Threading.Tasks;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
namespace DiscordBotTTS
{
public class Program
{
private GatewayClient _client;
private RestClient _restClient;
private CommandHandler _ch;
public static void Main(string[] args)
=> new Program().MainAsync().GetAwaiter().GetResult();
public async Task MainAsync()
{
// Set up cleanup handlers for graceful shutdown
Console.CancelKeyPress += (sender, e) =>
{
Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - Ctrl+C received, shutting down gracefully...");
e.Cancel = true; // Prevent immediate termination
TTSModule.CleanupCoquiServer();
TTSModule.CleanupPocketTTSServer();
MumbleModule.Cleanup();
Environment.Exit(0);
};
AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
{
Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - Application exiting, cleaning up...");
TTSModule.CleanupCoquiServer();
TTSModule.CleanupPocketTTSServer();
MumbleModule.Cleanup();
};
try
{
Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - Starting bot initialization...");
_ = Steam.RunSteamTask();
_ = bool.TryParse(ConfigurationManager.AppSettings.Get("EnableMessageContent"), out bool useMessageContent);
var intents = useMessageContent ? GatewayIntents.AllNonPrivileged | GatewayIntents.MessageContent : GatewayIntents.AllNonPrivileged;
var botToken = ConfigurationManager.AppSettings.Get("BotToken");
if (string.IsNullOrEmpty(botToken))
{
Console.WriteLine("ERROR: Bot token is null or empty. Check your App.config file.");
return;
}
Console.WriteLine($"Bot token found, length: {botToken.Length}");
Console.WriteLine($"Intents: {intents}");
Console.WriteLine($"Message content enabled: {useMessageContent}");
// Initialize the TTS module
slashtts = new TTSModule();
var token = new BotToken(botToken);
_restClient = new RestClient(token);
// Set the RestClient for the slash command TTS module
slashtts.SetRestClient(_restClient);
_client = new GatewayClient(token, new GatewayClientConfiguration { Intents = intents });
_client.Ready += Client_Ready;
_client.InteractionCreate += async interaction =>
{
Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - Interaction received from {interaction.User.Username}");
if (interaction is SlashCommandInteraction slashCommand)
{
await SlashCommandHandler(slashCommand);
}
};
_ch = new CommandHandler(_client, _restClient);
await _ch.InstallCommandsAsync();
// Start Coqui TTS server if configured for server mode
TTSModule.LoadEngineSwitch();
await TTSModule.InitializeCoquiServerAsync();
// Start PocketTTS server if enabled
await TTSModule.InitializePocketTTSServerAsync();
// Initialize Mumble connection if enabled
await MumbleModule.InitializeAsync();
Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - Starting NetCord client...");
await _client.StartAsync();
Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - NetCord client started successfully!");
// Block this task until the program is closed.
await Task.Delay(-1);
}
catch (Exception ex)
{
Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - FATAL ERROR: {ex.Message}");
Console.WriteLine($"Stack trace: {ex.StackTrace}");
}
}
public async ValueTask Client_Ready(ReadyEventArgs eventArgs)
{
Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - Bot is READY!");
Console.WriteLine($"Logged in as: {eventArgs.User.Username} (ID: {eventArgs.User.Id})");
Console.WriteLine($"Connected to {_client.Cache.Guilds.Count} guilds");
foreach (var guild in _client.Cache.Guilds.Values)
{
Console.WriteLine($" - {guild.Name} (ID: {guild.Id})");
}
Dictionary<string, (string description, List<ApplicationCommandOptionProperties> options)> commands = new Dictionary<string, (string, List<ApplicationCommandOptionProperties>)>()
{
{"help", ("Gets command help", new List<ApplicationCommandOptionProperties>())},
{"link", ("Link Steam account to Discord", new List<ApplicationCommandOptionProperties>
{
new ApplicationCommandOptionProperties(ApplicationCommandOptionType.String, "steamid", "Your Steam ID") { Required = true },
new ApplicationCommandOptionProperties(ApplicationCommandOptionType.String, "voice", "TTS Voice (optional)") { Required = false },
new ApplicationCommandOptionProperties(ApplicationCommandOptionType.Integer, "rate", "Speech rate (-10 to 10)") { Required = false }
})},
{"unlink", ("Unlink Steam account from Discord", new List<ApplicationCommandOptionProperties>())},
{"verify", ("Verify your current link status", new List<ApplicationCommandOptionProperties>())},
{"join", ("Join voice channel", new List<ApplicationCommandOptionProperties>
{
new ApplicationCommandOptionProperties(ApplicationCommandOptionType.Channel, "channel", "Voice channel to join (optional)") { Required = false }
})},
{"leave", ("Leave voice channel", new List<ApplicationCommandOptionProperties>())},
{"voices", ("List available TTS voices", new List<ApplicationCommandOptionProperties>())},
{"changevoice", ("Change TTS voice", new List<ApplicationCommandOptionProperties>
{
new ApplicationCommandOptionProperties(ApplicationCommandOptionType.String, "voice", "Voice name") { Required = true }
})},
{"changerate", ("Change speech rate", new List<ApplicationCommandOptionProperties>
{
new ApplicationCommandOptionProperties(ApplicationCommandOptionType.Integer, "rate", "Speech rate (-10 to 10)") { Required = true }
})},
{"changeserver", ("Change server", new List<ApplicationCommandOptionProperties>())},
{"say", ("Send a TTS message directly from Discord", new List<ApplicationCommandOptionProperties>
{
new ApplicationCommandOptionProperties(ApplicationCommandOptionType.String, "message", "The message to speak") { Required = true }
})},
{"uploadvoice", ("Upload a custom PocketTTS voice (.wav file)", new List<ApplicationCommandOptionProperties>
{
new ApplicationCommandOptionProperties(ApplicationCommandOptionType.String, "name", "Name for the custom voice") { Required = true },
new ApplicationCommandOptionProperties(ApplicationCommandOptionType.Attachment, "file", "A .wav voice sample file") { Required = true },
new ApplicationCommandOptionProperties(ApplicationCommandOptionType.Boolean, "truncate", "Truncate long audio") { Required = false },
new ApplicationCommandOptionProperties(ApplicationCommandOptionType.Integer, "lsd_decode_steps", "Number of generation steps") { Required = false },
new ApplicationCommandOptionProperties(ApplicationCommandOptionType.String, "temperature", "Temperature for generation") { Required = false },
new ApplicationCommandOptionProperties(ApplicationCommandOptionType.String, "noise_clamp", "Noise clamp value") { Required = false },
new ApplicationCommandOptionProperties(ApplicationCommandOptionType.String, "eos_threshold", "EOS threshold") { Required = false },
new ApplicationCommandOptionProperties(ApplicationCommandOptionType.Integer, "frames_after_eos", "Frames to generate after EOS") { Required = false },
})},
{"renamevoice", ("Rename a custom PocketTTS voice", new List<ApplicationCommandOptionProperties>
{
new ApplicationCommandOptionProperties(ApplicationCommandOptionType.String, "oldname", "Current voice name") { Required = true },
new ApplicationCommandOptionProperties(ApplicationCommandOptionType.String, "newname", "New voice name") { Required = true }
})},
{"deletevoice", ("Delete a custom PocketTTS voice", new List<ApplicationCommandOptionProperties>
{
new ApplicationCommandOptionProperties(ApplicationCommandOptionType.String, "name", "Voice name to delete") { Required = true }
})},
{"customvoices", ("List all custom PocketTTS voices", new List<ApplicationCommandOptionProperties>())},
{"destination", ("Change where TTS audio is sent (discord/mumble/both)", new List<ApplicationCommandOptionProperties>
{
new ApplicationCommandOptionProperties(ApplicationCommandOptionType.String, "target", "Destination: discord, mumble, or both") { Required = true }
})},
{"mumblestatus", ("Show Mumble connection status", new List<ApplicationCommandOptionProperties>())},
{"mumblejoin", ("Move the bot to a Mumble channel", new List<ApplicationCommandOptionProperties>
{
new ApplicationCommandOptionProperties(ApplicationCommandOptionType.String, "channel", "Mumble channel name to join") { Required = true }
})}
};
List<SlashCommandProperties> builtCommands = new List<SlashCommandProperties>();
foreach ((var command, (var description, var options)) in commands)
{
var commandData = new SlashCommandProperties(command, description)
{
Options = options
};
builtCommands.Add(commandData);
}
Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - Registering {builtCommands.Count} slash commands...");
foreach (var guild in _client.Cache.Guilds.Values)
{
try
{
foreach (var prop in builtCommands)
{
await _restClient.CreateGuildApplicationCommandAsync(guild.Id, guild.Id, prop);
Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - Registered /{prop.Name} command for guild {guild.Name}");
}
}
catch (Exception ex)
{
Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - Error registering commands for guild {guild.Name}: {ex.Message}");
}
}
}
private TTSModule slashtts;
private async Task SlashCommandHandler(SlashCommandInteraction command)
{
Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - Slash command received: {command.Data.Name} from {command.User.Username}");
try
{
var textChannel = command.Channel as TextChannel;
var userId = command.User.Id;
var username = command.User.Username;
var guildId = command.GuildId.Value;
var commandName = command.Data.Name;
// Send immediate response to acknowledge the interaction
await command.SendResponseAsync(InteractionCallback.Message($"Processing {commandName} command..."));
// Handle special case commands that need slash-specific logic
if (commandName == "help")
{
await slashtts.Help(textChannel);
return;
}
// Handle join command with special voice channel parsing
if (commandName == "join")
{
var channelOption = command.Data.Options?.FirstOrDefault(o => o.Name == "channel")?.Value;
ulong? voiceChannelId = null;
if (channelOption != null && ulong.TryParse(channelOption.ToString(), out ulong channelId))
{
voiceChannelId = channelId;
}
await _ch.HandleTTSCommandAsync(commandName, textChannel, guildId, userId, username, null, voiceChannelId);
return;
}
// Handle link command with special parameter parsing
if (commandName == "link")
{
var steamIdStr = command.Data.Options?.FirstOrDefault(o => o.Name == "steamid")?.Value?.ToString();
var voice = command.Data.Options?.FirstOrDefault(o => o.Name == "voice")?.Value?.ToString() ?? "Microsoft David";
var rateObj = command.Data.Options?.FirstOrDefault(o => o.Name == "rate")?.Value;
var rate = rateObj != null ? Convert.ToInt32(rateObj) : 0;
if (steamIdStr != null && ulong.TryParse(steamIdStr, out ulong steamId))
{
// Create fake args array for the shared handler
string[] args = { "tts", "link", steamIdStr, voice, rate.ToString() };
await _ch.HandleTTSCommandAsync(commandName, textChannel, guildId, userId, username, args);
}
else
{
await textChannel.SendMessageAsync(new MessageProperties { Content = "Invalid Steam ID provided." });
}
return;
}
// Handle changevoice command with special parameter parsing
if (commandName == "changevoice")
{
var voice = command.Data.Options?.FirstOrDefault(o => o.Name == "voice")?.Value?.ToString();
if (voice != null)
{
// Create fake args array for the shared handler
string[] args = { "tts", "changevoice", voice };
await _ch.HandleTTSCommandAsync(commandName, textChannel, guildId, userId, username, args);
}
else
{
await textChannel.SendMessageAsync(new MessageProperties { Content = "Voice name is required." });
}
return;
}
// Handle changerate command with special parameter parsing
if (commandName == "changerate")
{
var rateObj = command.Data.Options?.FirstOrDefault(o => o.Name == "rate")?.Value;
if (rateObj != null)
{
var rate = Convert.ToInt32(rateObj);
// Create fake args array for the shared handler
string[] args = { "tts", "changerate", rate.ToString() };
await _ch.HandleTTSCommandAsync(commandName, textChannel, guildId, userId, username, args);
}
else
{
await textChannel.SendMessageAsync(new MessageProperties { Content = "Rate value is required." });
}
return;
}
// Handle commands that don't need special parameter parsing
switch (commandName)
{
case "voices":
case "unlink":
case "verify":
case "leave":
case "changeserver":
case "customvoices":
await _ch.HandleTTSCommandAsync(commandName, textChannel, guildId, userId, username);
break;
case "say":
var sayMessage = command.Data.Options?.FirstOrDefault(o => o.Name == "message")?.Value?.ToString();
if (sayMessage != null)
{
string[] args = { "tts", "say", sayMessage };
await _ch.HandleTTSCommandAsync(commandName, textChannel, guildId, userId, username, args);
}
else
{
await textChannel.SendMessageAsync(new MessageProperties { Content = "Message is required." });
}
break;
case "uploadvoice":
var voiceName = command.Data.Options?.FirstOrDefault(o => o.Name == "name")?.Value?.ToString();
var fileAttachmentId = command.Data.Options?.FirstOrDefault(o => o.Name == "file")?.Value?.ToString();
string uploadUrl = null;
string uploadFileName = null;
if (fileAttachmentId != null && command.Data.ResolvedData?.Attachments != null)
{
if (ulong.TryParse(fileAttachmentId, out ulong attId) && command.Data.ResolvedData.Attachments.TryGetValue(attId, out var resolvedAtt))
{
uploadUrl = resolvedAtt.Url;
uploadFileName = resolvedAtt.FileName;
}
}
if (voiceName != null)
{
// Build args array with optional export-voice flags
var uploadArgs = new List<string> { "tts", "uploadvoice", voiceName };
var truncateOpt = command.Data.Options?.FirstOrDefault(o => o.Name == "truncate")?.Value;
if (truncateOpt != null && Convert.ToBoolean(truncateOpt)) uploadArgs.Add("--truncate");
var lsdOpt = command.Data.Options?.FirstOrDefault(o => o.Name == "lsd_decode_steps")?.Value;
if (lsdOpt != null) { uploadArgs.Add("--lsd-decode-steps"); uploadArgs.Add(Convert.ToInt32(lsdOpt).ToString()); }
var tempOpt = command.Data.Options?.FirstOrDefault(o => o.Name == "temperature")?.Value?.ToString();
if (tempOpt != null) { uploadArgs.Add("--temperature"); uploadArgs.Add(tempOpt); }
var ncOpt = command.Data.Options?.FirstOrDefault(o => o.Name == "noise_clamp")?.Value?.ToString();
if (ncOpt != null) { uploadArgs.Add("--noise-clamp"); uploadArgs.Add(ncOpt); }
var etOpt = command.Data.Options?.FirstOrDefault(o => o.Name == "eos_threshold")?.Value?.ToString();
if (etOpt != null) { uploadArgs.Add("--eos-threshold"); uploadArgs.Add(etOpt); }
var faeOpt = command.Data.Options?.FirstOrDefault(o => o.Name == "frames_after_eos")?.Value;
if (faeOpt != null) { uploadArgs.Add("--frames-after-eos"); uploadArgs.Add(Convert.ToInt32(faeOpt).ToString()); }
await _ch.HandleTTSCommandAsync(commandName, textChannel, guildId, userId, username, uploadArgs.ToArray(),
attachmentUrl: uploadUrl, attachmentFileName: uploadFileName);
}
else
{
await textChannel.SendMessageAsync(new MessageProperties { Content = "Voice name is required." });
}
break;
case "renamevoice":
var oldName = command.Data.Options?.FirstOrDefault(o => o.Name == "oldname")?.Value?.ToString();
var newName = command.Data.Options?.FirstOrDefault(o => o.Name == "newname")?.Value?.ToString();
if (oldName != null && newName != null)
{
string[] args = { "tts", "renamevoice", oldName, newName };
await _ch.HandleTTSCommandAsync(commandName, textChannel, guildId, userId, username, args);
}
else
{
await textChannel.SendMessageAsync(new MessageProperties { Content = "Both old and new voice names are required." });
}
break;
case "deletevoice":
var deleteVoiceName = command.Data.Options?.FirstOrDefault(o => o.Name == "name")?.Value?.ToString();
if (deleteVoiceName != null)
{
string[] args = { "tts", "deletevoice", deleteVoiceName };
await _ch.HandleTTSCommandAsync(commandName, textChannel, guildId, userId, username, args);
}
else
{
await textChannel.SendMessageAsync(new MessageProperties { Content = "Voice name is required." });
}
break;
case "destination":
var destTarget = command.Data.Options?.FirstOrDefault(o => o.Name == "target")?.Value?.ToString();
if (destTarget != null)
{
string[] args = { "tts", "destination", destTarget };
await _ch.HandleTTSCommandAsync(commandName, textChannel, guildId, userId, username, args);
}
else
{
await textChannel.SendMessageAsync(new MessageProperties { Content = "Destination is required (discord, mumble, or both)." });
}
break;
case "mumblestatus":
await _ch.HandleTTSCommandAsync(commandName, textChannel, guildId, userId, username);
break;
case "mumblejoin":
var mumbleChannel = command.Data.Options?.FirstOrDefault(o => o.Name == "channel")?.Value?.ToString();
if (mumbleChannel != null)
{
string[] args = { "tts", "mumblejoin", mumbleChannel };
await _ch.HandleTTSCommandAsync(commandName, textChannel, guildId, userId, username, args);
}
else
{
await textChannel.SendMessageAsync(new MessageProperties { Content = "Mumble channel name is required." });
}
break;
default:
await textChannel.SendMessageAsync(new MessageProperties { Content = $"Unknown command: {commandName}" });
break;
}
}
catch (Exception ex)
{
Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - Error handling slash command: {ex.Message}");
try
{
if (command.Channel is TextChannel errorTextChannel)
{
await errorTextChannel.SendMessageAsync(new MessageProperties { Content = "An error occurred while processing the command." });
}
}
catch { }
}
}
}
}