Skip to content

Commit cfefb2f

Browse files
committed
更新: CaiBot新增Ban事件上报、生成验证码命令、调试开关、状态信息
1 parent 652babd commit cfefb2f

File tree

4 files changed

+137
-28
lines changed

4 files changed

+137
-28
lines changed

src/CaiBot/EconomicSupport.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
using System.Reflection.Emit;
33
using System.Runtime.CompilerServices;
44
using TerrariaApi.Server;
5-
using TShockAPI;
65

76
namespace CaiBot;
87

src/CaiBot/MessageHandler.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ public static class MessageHandle
2121

2222
public static async Task SendDateAsync(string message)
2323
{
24-
if (Program.LaunchParameters.ContainsKey("-caidebug"))
24+
if (Plugin.DebugMode)
2525
{
2626
TShock.Log.ConsoleInfo($"[CaiAPI]发送BOT数据包:{message}");
2727
}
@@ -85,6 +85,7 @@ public static async Task HandleMessageAsync(string receivedData)
8585
Random rnd = new ();
8686
Plugin.InitCode = rnd.Next(10000000, 99999999);
8787
TShock.Log.ConsoleError($"[CaiBot]您的服务器绑定码为: {Plugin.InitCode}");
88+
await Plugin.WebSocket.CloseAsync(WebSocketCloseStatus.Empty,"", new CancellationToken());
8889
break;
8990
case "hello":
9091
TShock.Log.ConsoleInfo("[CaiAPI]CaiBOT连接成功...");

src/CaiBot/Plugin.cs

Lines changed: 116 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
using Terraria.Localization;
1010
using TerrariaApi.Server;
1111
using TShockAPI;
12+
using TShockAPI.DB;
1213

1314

1415
namespace CaiBot;
@@ -19,15 +20,16 @@ public class Plugin : TerrariaPlugin
1920
public override string Author => "Cai,羽学,西江";
2021
public override string Description => "CaiBot机器人的适配插件";
2122
public override string Name => "CaiBotPlugin";
22-
public static readonly Version VersionNum = new(2024, 10, 20 , 1); //日期+版本号(0,1,2...)
23+
public static readonly Version VersionNum = new(2024, 11, 3 , 1); //日期+版本号(0,1,2...)
2324
public override Version Version => VersionNum;
2425

2526
public Plugin(Main game) : base(game)
2627
{
2728
}
2829

2930
public static int InitCode = -1;
30-
31+
public static bool LocalMode;
32+
public static bool DebugMode;
3133
public static ClientWebSocket WebSocket = new();
3234
public static Task WebSocketTask = Task.CompletedTask;
3335
public static readonly CancellationTokenSource TokenSource = new ();
@@ -54,8 +56,11 @@ public Plugin(Main game) : base(game)
5456

5557
public override void Initialize()
5658
{
57-
// Commands.ChatCommands.Add(new Command( TestCommand,"test"));
59+
Commands.ChatCommands.Add(new Command("CaiBot.Admin", this.CaiBotCommand,"caibot"));
5860
Config.Read();
61+
LocalMode = Terraria.Program.LaunchParameters.ContainsKey("-cailocalbot");
62+
DebugMode = Terraria.Program.LaunchParameters.ContainsKey("-caidebug");
63+
BanManager.OnBanPostAdd += this.OnBanInsert;
5964
AppDomain.CurrentDomain.AssemblyResolve += this.CurrentDomain_AssemblyResolve;
6065
On.OTAPI.Hooks.MessageBuffer.InvokeGetData += this.MessageBuffer_InvokeGetData;
6166
On.OTAPI.Hooks.MessageBuffer.InvokeGetData += Login.MessageBuffer_InvokeGetData;
@@ -68,7 +73,7 @@ public override void Initialize()
6873
try
6974
{
7075
WebSocket = new ClientWebSocket();
71-
while (Config.config.Token == "")
76+
while (string.IsNullOrEmpty(Config.config.Token))
7277
{
7378
await Task.Delay(TimeSpan.FromSeconds(10));
7479
HttpClient client = new();
@@ -90,10 +95,11 @@ public override void Initialize()
9095

9196
}
9297

93-
if (Terraria.Program.LaunchParameters.ContainsKey("-cailocalbot"))
98+
if (LocalMode)
9499
{
95100
await WebSocket.ConnectAsync(new Uri("ws://127.0.0.1:22334/bot/" + Config.config.Token),
96101
CancellationToken.None);
102+
TShock.Log.ConsoleWarn($"[CaiAPI]你正在使用CaiBot本地模式,请确保你已本地部署CaiBot!");
97103
}
98104
else
99105
{
@@ -107,7 +113,7 @@ await WebSocket.ConnectAsync(new Uri("ws://api.terraria.ink:22334/bot/" + Config
107113
var result = await WebSocket.ReceiveAsync(new ArraySegment<byte>(buffer),
108114
CancellationToken.None);
109115
var receivedData = Encoding.UTF8.GetString(buffer, 0, result.Count);
110-
if (Terraria.Program.LaunchParameters.ContainsKey("-caidebug"))
116+
if (DebugMode)
111117
{
112118
TShock.Log.ConsoleInfo($"[CaiAPI]收到BOT数据包: {receivedData}");
113119
}
@@ -118,7 +124,7 @@ await WebSocket.ConnectAsync(new Uri("ws://api.terraria.ink:22334/bot/" + Config
118124
catch (Exception ex)
119125
{
120126
TShock.Log.ConsoleInfo($"[CaiAPI]CaiBot断开连接...");
121-
if (Terraria.Program.LaunchParameters.ContainsKey("-caidebug"))
127+
if (DebugMode)
122128
{
123129
TShock.Log.ConsoleError(ex.ToString());
124130
}
@@ -160,11 +166,15 @@ protected override void Dispose(bool disposing)
160166
{
161167
if (disposing)
162168
{
169+
var asm = Assembly.GetExecutingAssembly();
170+
Commands.ChatCommands.RemoveAll(c => c.CommandDelegate.Method?.DeclaringType?.Assembly == asm);
163171
AppDomain.CurrentDomain.AssemblyResolve -= this.CurrentDomain_AssemblyResolve;
164172
On.OTAPI.Hooks.MessageBuffer.InvokeGetData -= this.MessageBuffer_InvokeGetData;
165173
On.OTAPI.Hooks.MessageBuffer.InvokeGetData -= Login.MessageBuffer_InvokeGetData;
174+
BanManager.OnBanPostAdd -= this.OnBanInsert;
166175
ServerApi.Hooks.NetGetData.Deregister(this, Login.OnGetData);
167176
ServerApi.Hooks.GamePostInitialize.Deregister(this, this.GenCode);
177+
WebSocket.Dispose();
168178
if (!WebSocketTask.IsCompleted)
169179
{
170180
TokenSource.Cancel();
@@ -173,6 +183,105 @@ protected override void Dispose(bool disposing)
173183
}
174184
base.Dispose(disposing);
175185
}
186+
187+
private void CaiBotCommand(CommandArgs args)
188+
{
189+
var plr = args.Player;
190+
void ShowHelpText()
191+
{
192+
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, plr, out var pageNumber))
193+
{
194+
return;
195+
}
196+
197+
List<string> lines = new()
198+
{
199+
"/caibot debug CaiBot调试开关",
200+
"/caibot code 生成并且展示验证码",
201+
"/caibot info 显示CaiBot的一些信息"
202+
};
203+
204+
PaginationTools.SendPage(
205+
plr, pageNumber, lines,
206+
new PaginationTools.Settings
207+
{
208+
HeaderFormat = GetString("帮助 ({0}/{1}):"),
209+
FooterFormat = GetString("输入 {0}caibot help {{0}} 查看更多").SFormat(Commands.Specifier)
210+
}
211+
);
212+
}
213+
214+
if (args.Parameters.Count == 0)
215+
{
216+
ShowHelpText();
217+
return;
218+
}
219+
220+
221+
switch (args.Parameters[0].ToLowerInvariant())
222+
{
223+
// 帮助
224+
case "help":
225+
ShowHelpText();
226+
return;
227+
228+
default:
229+
ShowHelpText();
230+
break;
231+
232+
case "信息":
233+
case "info":
234+
plr.SendInfoMessage($"[CaiBot信息]\n" +
235+
$"插件版本: v{VersionNum}\n" +
236+
$"WebSocket状态: {WebSocket.State}\n" +
237+
$"绑定QQ群: {(Config.config.GroupNumber == 0L?"未绑定|未连接":Config.config.GroupNumber)}\n" +
238+
$"本地模式: {LocalMode}\n" +
239+
$"绑定状态: {Config.config.Token != ""}\n" +
240+
$"Debug模式: {DebugMode}\n" +
241+
$"Economic API支持: {EconomicSupport.GetCoinsSupport}\n"+
242+
$"Economic RPG支持: {EconomicSupport.GetLevelNameSupport}\n"+
243+
$"Economic Skill支持: {EconomicSupport.GetSkillSupport}\n"
244+
);
245+
break;
246+
case "调试":
247+
case "debug":
248+
DebugMode = !DebugMode;
249+
plr.SendInfoMessage($"[CaiBot]调试模式已{(DebugMode?"开启":"关闭")}!");
250+
break;
251+
case "验证码":
252+
case "code":
253+
if (!string.IsNullOrEmpty(Config.config.Token))
254+
{
255+
plr.SendInfoMessage($"[CaiBot]服务器已绑定无法生成验证码!");
256+
return;
257+
}
258+
this.GenCode(null);
259+
plr.SendInfoMessage($"[CaiBot]验证码已生成,请在后台查看喵~");
260+
break;
261+
}
262+
}
263+
264+
private async void OnBanInsert(object? sender, BanEventArgs e)
265+
{
266+
if (e.Ban.Identifier.StartsWith(Identifier.Name.Prefix) || e.Ban.Identifier.StartsWith(Identifier.Account.Prefix))
267+
{
268+
var name = e.Ban.Identifier.Replace(Identifier.Name.Prefix, "").Replace(Identifier.Account.Prefix, "");
269+
var expireTime = e.Ban.GetPrettyExpirationString();
270+
var result = new RestObject
271+
{
272+
{ "type", "post_ban_add" },
273+
{ "name", name },
274+
{ "reason", e.Ban.Reason },
275+
{ "admin", e.Ban.BanningUser },
276+
{ "expire_time", expireTime=="Never"?"永久封禁":expireTime }
277+
};
278+
await MessageHandle.SendDateAsync(JsonConvert.SerializeObject(result));
279+
}
280+
281+
282+
}
283+
284+
176285
private void GenCode(EventArgs args)
177286
{
178287
if (!string.IsNullOrEmpty(Config.config.Token))

src/CaiBot/README.md

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,23 @@
1010

1111
- [ACaiCat/CaiBotDocument](https://github.com/ACaiCat/CaiBotDocument)
1212

13+
14+
## 使用方法(轻量版):
15+
16+
1. 将插件安装在ServerPlugins/
17+
18+
2. 重启服务器
19+
20+
3. 启动服务器后会显示授权码
21+
22+
4. 群内发送 添加服务器 <IP地址> <端口> <验证码>
23+
24+
5. 完成配置
25+
1326
## 更新日志
1427

1528
```
29+
v2024.11.3.1 新增Ban事件上报、生成验证码命令、调试开关、状态信息
1630
v2024.10.20.1 修复`查看地图`命令小、中世界的图片尺寸偏大的问题
1731
v2024.10.19.1 重写白名单登录,修复卡死WebSocket的问题
1832
v2024.10.12.3 修复卡号Bug
@@ -37,9 +51,11 @@ v1.1 修复前置加载失败的问题
3751

3852
## 指令
3953

40-
```
41-
暂无
42-
```
54+
| 语法 | 权限 | 说明 |
55+
|----------------|:------------:|:------------:|
56+
| /caibot debug | CaiBot.Admin | 调试模式开关 |
57+
| /caibot code | CaiBot.Admin | 生成验证码 |
58+
| /caibot info | CaiBot.Admin | 显示CaiBot状态信息 |
4359

4460
## 配置
4561

@@ -53,22 +69,6 @@ v1.1 修复前置加载失败的问题
5369
}
5470
```
5571

56-
----------
57-
58-
## 使用方法(轻量版):
59-
60-
1.将插件安装在ServerPlugins/
61-
62-
2.重启服务器
63-
64-
3.启动服务器后会显示授权码
65-
66-
4.群内发送 添加服务器 <IP地址> <端口> <验证码>
67-
68-
5.完成配置
69-
70-
----------
71-
7272
## 反馈
7373

7474
- 优先发issued -> 共同维护的插件库:https://github.com/UnrealMultiple/TShockPlugin

0 commit comments

Comments
 (0)