This repository has been archived by the owner on Nov 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWorker.cs
190 lines (169 loc) · 5.08 KB
/
Worker.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
using DBotDDRefuge.Common;
using DBotDDRefuge.Common.Audio;
using DBotDDRefuge.Common.Handlers;
using DBotDDRefuge.Handlers;
using Discord;
using Discord.Interactions;
using Discord.WebSocket;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System.Reflection;
using Victoria;
namespace DBotDDRefuge;
/// <summary>
/// Worker
/// <para>參考:https://www.gss.com.tw/blog/net-core-worker-service </para>
/// </summary>
public class Worker : BackgroundService
{
private readonly IConfigurationRoot _configurationRoot;
private readonly IServiceProvider _serviceProvider;
private readonly ILogger<Worker> _logger;
private readonly IHttpClientFactory _httpClientFactory;
private readonly DiscordShardedClient _shardedClient;
private readonly InteractionService _interactionService;
private readonly LavaNode<XLavaPlayer> _lavaNode;
public Worker(
IConfigurationRoot configurationRoot,
IServiceProvider serviceProvider,
ILogger<Worker> logger,
IHttpClientFactory httpClientFactory,
DiscordShardedClient shardedClient,
InteractionService interactionService,
LavaNode<XLavaPlayer> lavaNode)
{
_configurationRoot = configurationRoot;
_serviceProvider = serviceProvider;
_logger = logger;
_httpClientFactory = httpClientFactory;
_shardedClient = shardedClient;
_interactionService = interactionService;
_lavaNode = lavaNode;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
if (!stoppingToken.IsCancellationRequested)
{
await RunAsync();
}
}
private async Task RunAsync()
{
string rawBotName = Assembly.GetEntryAssembly()?.GetName().Name ?? "機器人";
string rawToken = _configurationRoot["discord:token"];
bool enableLavalink = bool.TryParse(_configurationRoot["dataSource:lavalink:enable"], out bool tempBool1) && tempBool1;
if (!string.IsNullOrEmpty(rawToken))
{
_shardedClient.Log += Log;
_shardedClient.ShardReady += async (socketClient) =>
{
await _interactionService.RegisterCommandsGloballyAsync(true);
_logger.LogInformation("{BotName} - Shard 編號 {ShardID},已連接且已準備就緒!",
rawBotName,
socketClient.ShardId);
if (enableLavalink)
{
try
{
if (!_lavaNode.IsConnected)
{
await _lavaNode.ConnectAsync();
}
}
catch (Exception ex)
{
_logger.LogError("連接 Lavalink 失敗,錯誤訊息:{Exception}", ex);
}
}
else
{
_logger.LogInformation("未啟用 Lavalink,音樂撥放相關的斜線命令將無法使用。");
}
};
_shardedClient.SelectMenuExecuted += SelectMenuExecuted;
_interactionService.Log += Log;
await _serviceProvider.GetRequiredService<CommandHandler>().InitializeAsync();
await _shardedClient.LoginAsync(TokenType.Bot, rawToken);
await _shardedClient.StartAsync();
await Task.Delay(Timeout.Infinite);
}
else
{
// 強制讓程式中斷執行。
throw new Exception("Token 無效,請在 appsettings.json 檔案內設定 \"token\" 的值。");
}
}
private Task Log(LogMessage arg)
{
CustomFunction.WriteLog(_logger, arg);
return Task.CompletedTask;
}
private async Task SelectMenuExecuted(SocketMessageComponent arg)
{
try
{
string rawCustomID = arg.Data.CustomId;
if (!string.IsNullOrEmpty(rawCustomID))
{
switch (rawCustomID)
{
case "menu_calendar":
string? rawQueryType = arg.Data.Values.FirstOrDefault();
if (!string.IsNullOrEmpty(rawQueryType))
{
CustomInteractionHandler.GetICalendarEventAsync(
_httpClientFactory,
_logger,
arg,
rawQueryType);
}
else
{
_logger.LogError("發生錯誤,rawQueryType 是 Null 或空白。");
await arg.UpdateAsync(n =>
{
n.Content = $"{arg.User.Mention}" +
$"{Environment.NewLine}{Environment.NewLine}發生錯誤,您選擇的項目無效。";
n.Components = null;
});
}
break;
case "menu_activity":
string? rawActionType = arg.Data.Values.FirstOrDefault();
if (!string.IsNullOrEmpty(rawActionType))
{
CustomInteractionHandler.GetActivityEventAsync(
_httpClientFactory,
_logger,
_shardedClient,
arg,
rawActionType);
}
else
{
_logger.LogError("發生錯誤,rawActivityAction 是 Null 或空白。");
await arg.UpdateAsync(n =>
{
n.Content = $"{arg.User.Mention}" +
$"{Environment.NewLine}{Environment.NewLine}發生錯誤,您選擇的項目無效。";
n.Components = null;
});
}
break;
default:
break;
}
}
else
{
_logger.LogError("發生錯誤,從 SocketMessageComponent 取得的 CustomID 是 Null 或空白。");
}
}
catch (Exception ex)
{
_logger.LogError("發生錯誤,錯誤訊息:{Exception}", ex);
}
}
}