-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdvancedExample.cs
More file actions
460 lines (396 loc) · 14.9 KB
/
Copy pathAdvancedExample.cs
File metadata and controls
460 lines (396 loc) · 14.9 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
451
452
453
454
455
456
457
458
459
460
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PawSharp.API.Clients;
using PawSharp.API.Models;
using PawSharp.Client;
using PawSharp.Core.Entities;
using PawSharp.Core.Logging;
using PawSharp.Core.Metrics;
using PawSharp.Core.Models;
using PawSharp.Gateway.Events;
using PawSharp.Interactions;
namespace PawSharp.Examples;
/// <summary>
/// Comprehensive example demonstrating PawSharp features including:
/// - Bot initialization and configuration
/// - Event handling (messages, joins, presence)
/// - Command processing
/// - Caching
/// - Error handling
/// - Performance monitoring
/// </summary>
public class AdvancedExampleBot
{
private DiscordClient _client;
private readonly ILogger<AdvancedExampleBot> _logger;
private readonly PerformanceMetrics _metrics;
private readonly MemoryMetrics _memoryMetrics;
private readonly Dictionary<string, Func<Message, Task>> _commands;
private bool _isRunning;
public AdvancedExampleBot()
{
_metrics = new PerformanceMetrics();
_memoryMetrics = new MemoryMetrics();
_commands = new Dictionary<string, Func<Message, Task>>(StringComparer.OrdinalIgnoreCase);
_logger = null!; // Will be set in Initialize
}
/// <summary>
/// Initialize the bot with all required services.
/// </summary>
public async Task InitializeAsync(string botToken)
{
// Configure dependency injection
var services = new ServiceCollection();
services.AddLogging(builder =>
{
builder.AddPawSharpLogging(LogLevel.Information);
builder.AddConsole();
});
var options = new PawSharpOptions
{
Token = botToken,
ApiVersion = 10
};
services.AddSingleton(options);
services.AddSingleton<IEntityCache, EntityCache>();
services.AddSingleton(_metrics);
services.AddSingleton(_memoryMetrics);
services.AddHttpClient<IDiscordRestClient, DiscordRestClient>();
var provider = services.BuildServiceProvider();
var loggerFactory = provider.GetRequiredService<ILoggerFactory>();
_logger = loggerFactory.CreateLogger<AdvancedExampleBot>();
var httpClient = provider.GetRequiredService<HttpClient>();
var cache = provider.GetRequiredService<IEntityCache>();
var restClient = provider.GetRequiredService<IDiscordRestClient>();
_client = new DiscordClient(options, cache,
loggerFactory.CreateLogger<DiscordClient>(), restClient);
// Register event handlers
RegisterEventHandlers();
// Register commands
RegisterCommands();
// Register interactions
RegisterInteractions();
_logger.LogInformation("Bot initialized successfully");
}
/// <summary>
/// Connect to Discord and start the bot.
/// </summary>
public async Task RunAsync()
{
try
{
_logger.LogInformation("Connecting to Discord...");
await _client.ConnectAsync();
_isRunning = true;
_logger.LogInformation("Bot is running. Press Ctrl+C to stop.");
// Keep bot running
await Task.Delay(Timeout.Infinite);
}
catch (Exception ex)
{
_logger.LogCritical(ex, "Fatal error");
throw;
}
}
/// <summary>
/// Register gateway event handlers.
/// </summary>
private void RegisterEventHandlers()
{
// Bot is ready
_client.Gateway.OnReady += async (ready) =>
{
_logger.LogInformation("Bot logged in as {Username}#{Discriminator}",
ready.User.Username, ready.User.Discriminator ?? "0000");
_logger.LogInformation("Connected to {GuildCount} guilds",
ready.Guilds?.Count ?? 0);
};
// Message received
_client.Gateway.OnMessageCreate += async (message) =>
{
try
{
// Record metric
_metrics.RecordGatewayMessage("MESSAGE_CREATE");
// Ignore bot's own messages
if (message.Author?.Id == _client.Cache.GetUser(message.Author.Id)?.Id)
return;
_logger.LogInformation("Message from {Author} in {Channel}: {Content}",
message.Author?.Username, message.ChannelId, message.Content);
// Process commands if message starts with !
if (message.Content?.StartsWith("!") ?? false)
{
await ProcessCommandAsync(message);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error handling message");
}
};
// Member joined
_client.Gateway.OnGuildMemberAdd += async (member) =>
{
try
{
_metrics.RecordGatewayMessage("GUILD_MEMBER_ADD");
_logger.LogInformation("Member joined: {Username}", member.User?.Username);
// Send welcome message to system channel if available
if (member.Guild?.SystemChannelId.HasValue ?? false)
{
var channelId = member.Guild.SystemChannelId.Value;
var message = $"Welcome {member.User?.Username}!";
await _client.Rest.CreateMessageAsync(channelId,
new CreateMessageRequest { Content = message });
}
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to handle member join");
}
};
// Member left
_client.Gateway.OnGuildMemberRemove += async (user) =>
{
_logger.LogInformation("Member left: {Username}", user.Username);
_metrics.RecordGatewayMessage("GUILD_MEMBER_REMOVE");
};
// Presence updated
_client.Gateway.OnPresenceUpdate += async (presence) =>
{
_metrics.RecordGatewayMessage("PRESENCE_UPDATE");
if (presence.Status != null)
{
_logger.LogDebug("{Username} is now {Status}",
presence.User?.Username, presence.Status);
}
};
// Reconnecting
_client.Gateway.OnReconnecting += async (attempt, maxAttempts) =>
{
_logger.LogWarning("Reconnecting... Attempt {Attempt}/{MaxAttempts}",
attempt, maxAttempts);
};
// Reconnected
_client.Gateway.OnReconnected += async () =>
{
_logger.LogInformation("✓ Reconnected to Discord");
};
}
/// <summary>
/// Register bot commands.
/// </summary>
private void RegisterCommands()
{
// !ping - Check bot latency
_commands["ping"] = async (msg) =>
{
await _client.Rest.CreateMessageAsync(msg.ChannelId,
new CreateMessageRequest { Content = "Pong!" });
};
// !help - Show available commands
_commands["help"] = async (msg) =>
{
var commands = string.Join("\n", _commands.Keys.Select(k => $" !{k}"));
var response = $"Available commands:\n{commands}";
await _client.Rest.CreateMessageAsync(msg.ChannelId,
new CreateMessageRequest { Content = response });
};
// !stats - Show bot statistics
_commands["stats"] = async (msg) =>
{
var metrics = _metrics.GetSummary();
var memory = _memoryMetrics.GetSummary();
var stats = $@"Bot Statistics
API Requests: {metrics.TotalApiRequests}
Avg Response: {metrics.AverageApiDurationMs}ms
Error Rate: {metrics.ApiErrorRate:F2}%
Cache Hit Rate: {metrics.CacheHitRate:F2}%
Memory: {memory.CurrentMemoryMB:F2}MB
Peak Memory: {memory.PeakMemoryMB:F2}MB
Threads: {memory.Threads}
Uptime: {memory.UptimeSeconds}s";
await _client.Rest.CreateMessageAsync(msg.ChannelId,
new CreateMessageRequest { Content = stats });
};
// !user <id> - Get user info
_commands["user"] = async (msg) =>
{
var args = msg.Content?.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (args?.Length < 2 || !ulong.TryParse(args[1], out var userId))
{
await _client.Rest.CreateMessageAsync(msg.ChannelId,
new CreateMessageRequest { Content = "Usage: !user <user_id>" });
return;
}
try
{
// Check cache first
var user = _client.Cache.GetUser(userId);
user ??= await _client.Rest.GetUserAsync(userId);
if (user != null)
{
var userInfo = $@"User Info
Username: {user.Username}#{user.Discriminator}
ID: {user.Id}
Bot: {user.Bot}
Created: {user.CreatedAt:g}";
await _client.Rest.CreateMessageAsync(msg.ChannelId,
new CreateMessageRequest { Content = userInfo });
}
}
catch (PawSharp.API.Exceptions.DiscordApiException ex) when (ex.StatusCode == 404)
{
await _client.Rest.CreateMessageAsync(msg.ChannelId,
new CreateMessageRequest { Content = "User not found." });
}
catch (Exception ex)
{
_logger.LogError(ex, "Error fetching user");
await _client.Rest.CreateMessageAsync(msg.ChannelId,
new CreateMessageRequest { Content = "Error fetching user." });
}
};
// !echo <text> - Echo a message
_commands["echo"] = async (msg) =>
{
var text = msg.Content?[5..].Trim(); // Skip "!echo"
if (string.IsNullOrWhiteSpace(text))
{
await _client.Rest.CreateMessageAsync(msg.ChannelId,
new CreateMessageRequest { Content = "Usage: !echo <text>" });
return;
}
try
{
await _client.Rest.CreateMessageAsync(msg.ChannelId,
new CreateMessageRequest { Content = text });
}
catch (PawSharp.Core.Exceptions.ValidationException ex)
{
_logger.LogWarning("Message too long");
await _client.Rest.CreateMessageAsync(msg.ChannelId,
new CreateMessageRequest { Content = "Message is too long (max 2000 chars)." });
}
};
_logger.LogInformation("Registered {CommandCount} commands", _commands.Count);
}
/// <summary>
/// Register slash commands and component handlers.
/// </summary>
private void RegisterInteractions()
{
// Register slash command: /ping
_client.Interactions.RegisterCommand("ping", async (interaction) =>
{
var response = new InteractionResponse
{
Type = (int)InteractionResponseType.ChannelMessageWithSource,
Data = new InteractionCallbackData
{
Content = "Pong! 🏓"
}
};
await _client.Interactions.RespondAsync(interaction.Id, interaction.Token, response);
});
// Register slash command: /echo <text>
_client.Interactions.RegisterCommand("echo", async (interaction) =>
{
var text = interaction.Data?.Options?.FirstOrDefault()?.Value?.ToString();
if (string.IsNullOrWhiteSpace(text))
{
text = "You didn't provide any text to echo!";
}
var response = new InteractionResponse
{
Type = (int)InteractionResponseType.ChannelMessageWithSource,
Data = new InteractionCallbackData
{
Content = text
}
};
await _client.Interactions.RespondAsync(interaction.Id, interaction.Token, response);
});
// Register component handler for a button
_client.Interactions.RegisterComponent("test_button", async (interaction) =>
{
var response = new InteractionResponse
{
Type = (int)InteractionResponseType.ChannelMessageWithSource,
Data = new InteractionCallbackData
{
Content = "Button clicked! 🎉"
}
};
await _client.Interactions.RespondAsync(interaction.Id, interaction.Token, response);
});
_logger.LogInformation("Registered interaction handlers");
}
/// <summary>
/// Process a command from a message.
/// </summary>
private async Task ProcessCommandAsync(Message message)
{
try
{
var parts = message.Content?.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts?.Length == 0) return;
var command = parts[0][1..].ToLower(); // Remove ! prefix
if (_commands.TryGetValue(command, out var handler))
{
_logger.LogInformation("Executing command: {Command}", command);
await handler(message);
}
else
{
await _client.Rest.CreateMessageAsync(message.ChannelId,
new CreateMessageRequest { Content = $"Unknown command: !{command}" });
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error processing command");
}
}
/// <summary>
/// Stop the bot gracefully.
/// </summary>
public async Task StopAsync()
{
if (!_isRunning) return;
_logger.LogInformation("Shutting down...");
// Log final metrics
var metrics = _metrics.GetSummary();
_logger.LogInformation(
"Final stats - Requests: {Requests}, Avg: {Avg}ms, Cache: {Cache:F2}%",
metrics.TotalApiRequests,
metrics.AverageApiDurationMs,
metrics.CacheHitRate);
_isRunning = false;
}
/// <summary>
/// Main entry point.
/// </summary>
public static async Task Main(string[] args)
{
var token = Environment.GetEnvironmentVariable("DISCORD_BOT_TOKEN");
if (string.IsNullOrEmpty(token))
{
Console.WriteLine("Error: DISCORD_BOT_TOKEN environment variable not set");
return;
}
var bot = new AdvancedExampleBot();
await bot.InitializeAsync(token);
// Handle graceful shutdown
Console.CancelKeyPress += async (s, e) =>
{
e.Cancel = true;
await bot.StopAsync();
};
await bot.RunAsync();
}
}