-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBotService.cs
67 lines (59 loc) · 2.49 KB
/
BotService.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
using Discord;
using Discord.Commands;
using Discord.Interactions;
using Discord.WebSocket;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
namespace Portal;
public class BotService(DiscordSocketClient discordSocketClient,
InteractionService interactionService,
InteractionHandler interactionHandler,
CommandService commandService,
CommandHandler commandHandler,
IConfiguration configuration) : IHostedService
{
public async Task StartAsync(CancellationToken cancellationToken)
{
CustomBotLogger customBotLogger = new();
await interactionHandler.InitializeAsync();
await commandHandler.InstallCommandsAsync();
interactionService.Log += customBotLogger.BotLogger;
commandService.Log += customBotLogger.BotLogger;
discordSocketClient.Log += customBotLogger.BotLogger;
discordSocketClient.Ready += async () =>
{
_ = Task.Run(async () =>
{
// Setting up slash commands and context commands
ulong guildId = Convert.ToUInt64(configuration["Bot:GuildId"]);
var guild = discordSocketClient.GetGuild(guildId);
await guild.BulkOverwriteApplicationCommandAsync(new ApplicationCommandProperties[]
{
AddContextCommand().Build()
});
await interactionService.RegisterCommandsToGuildAsync(guildId);
}, cancellationToken);
await Task.CompletedTask;
};
// Starting discord socket client
await discordSocketClient.LoginAsync(TokenType.Bot, configuration["DISCORD_BOT_TOKEN"]);
await discordSocketClient.StartAsync();
// Setting bot's activity
await discordSocketClient.SetGameAsync(configuration["RichPresence:CustomMessage"],
null, ActivityType.CustomStatus);
}
public async Task StopAsync(CancellationToken cancellationToken)
{
// Stops the discord socket client instance and logs out (graceful shutdown).
await discordSocketClient.LogoutAsync();
await discordSocketClient.StopAsync();
}
private MessageCommandBuilder AddContextCommand()
{
// Create a context command named "Open Portal"
var guildMessageCommand = new MessageCommandBuilder()
.WithName("Open Portal")
.WithContextTypes(InteractionContextType.Guild, InteractionContextType.PrivateChannel);
return guildMessageCommand;
}
}