Skip to content

Commit

Permalink
Merge pull request #550 from UnrealMultiple/cai_dev
Browse files Browse the repository at this point in the history
更新: CaiBot新增Ban事件上报、生成验证码命令、调试开关、状态信息
  • Loading branch information
ACaiCat authored Nov 3, 2024
2 parents 4bd5ae1 + cfefb2f commit ed6c603
Show file tree
Hide file tree
Showing 4 changed files with 137 additions and 28 deletions.
1 change: 0 additions & 1 deletion src/CaiBot/EconomicSupport.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using TerrariaApi.Server;
using TShockAPI;

namespace CaiBot;

Expand Down
3 changes: 2 additions & 1 deletion src/CaiBot/MessageHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public static class MessageHandle

public static async Task SendDateAsync(string message)
{
if (Program.LaunchParameters.ContainsKey("-caidebug"))
if (Plugin.DebugMode)
{
TShock.Log.ConsoleInfo($"[CaiAPI]发送BOT数据包:{message}");
}
Expand Down Expand Up @@ -85,6 +85,7 @@ public static async Task HandleMessageAsync(string receivedData)
Random rnd = new ();
Plugin.InitCode = rnd.Next(10000000, 99999999);
TShock.Log.ConsoleError($"[CaiBot]您的服务器绑定码为: {Plugin.InitCode}");
await Plugin.WebSocket.CloseAsync(WebSocketCloseStatus.Empty,"", new CancellationToken());
break;
case "hello":
TShock.Log.ConsoleInfo("[CaiAPI]CaiBOT连接成功...");
Expand Down
123 changes: 116 additions & 7 deletions src/CaiBot/Plugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using Terraria.Localization;
using TerrariaApi.Server;
using TShockAPI;
using TShockAPI.DB;


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

public Plugin(Main game) : base(game)
{
}

public static int InitCode = -1;

public static bool LocalMode;
public static bool DebugMode;
public static ClientWebSocket WebSocket = new();
public static Task WebSocketTask = Task.CompletedTask;
public static readonly CancellationTokenSource TokenSource = new ();
Expand All @@ -54,8 +56,11 @@ public Plugin(Main game) : base(game)

public override void Initialize()
{
// Commands.ChatCommands.Add(new Command( TestCommand,"test"));
Commands.ChatCommands.Add(new Command("CaiBot.Admin", this.CaiBotCommand,"caibot"));
Config.Read();
LocalMode = Terraria.Program.LaunchParameters.ContainsKey("-cailocalbot");
DebugMode = Terraria.Program.LaunchParameters.ContainsKey("-caidebug");
BanManager.OnBanPostAdd += this.OnBanInsert;
AppDomain.CurrentDomain.AssemblyResolve += this.CurrentDomain_AssemblyResolve;
On.OTAPI.Hooks.MessageBuffer.InvokeGetData += this.MessageBuffer_InvokeGetData;
On.OTAPI.Hooks.MessageBuffer.InvokeGetData += Login.MessageBuffer_InvokeGetData;
Expand All @@ -68,7 +73,7 @@ public override void Initialize()
try
{
WebSocket = new ClientWebSocket();
while (Config.config.Token == "")
while (string.IsNullOrEmpty(Config.config.Token))
{
await Task.Delay(TimeSpan.FromSeconds(10));
HttpClient client = new();
Expand All @@ -90,10 +95,11 @@ public override void Initialize()

}

if (Terraria.Program.LaunchParameters.ContainsKey("-cailocalbot"))
if (LocalMode)
{
await WebSocket.ConnectAsync(new Uri("ws://127.0.0.1:22334/bot/" + Config.config.Token),
CancellationToken.None);
TShock.Log.ConsoleWarn($"[CaiAPI]你正在使用CaiBot本地模式,请确保你已本地部署CaiBot!");
}
else
{
Expand All @@ -107,7 +113,7 @@ await WebSocket.ConnectAsync(new Uri("ws://api.terraria.ink:22334/bot/" + Config
var result = await WebSocket.ReceiveAsync(new ArraySegment<byte>(buffer),
CancellationToken.None);
var receivedData = Encoding.UTF8.GetString(buffer, 0, result.Count);
if (Terraria.Program.LaunchParameters.ContainsKey("-caidebug"))
if (DebugMode)
{
TShock.Log.ConsoleInfo($"[CaiAPI]收到BOT数据包: {receivedData}");
}
Expand All @@ -118,7 +124,7 @@ await WebSocket.ConnectAsync(new Uri("ws://api.terraria.ink:22334/bot/" + Config
catch (Exception ex)
{
TShock.Log.ConsoleInfo($"[CaiAPI]CaiBot断开连接...");
if (Terraria.Program.LaunchParameters.ContainsKey("-caidebug"))
if (DebugMode)
{
TShock.Log.ConsoleError(ex.ToString());
}
Expand Down Expand Up @@ -160,11 +166,15 @@ protected override void Dispose(bool disposing)
{
if (disposing)
{
var asm = Assembly.GetExecutingAssembly();
Commands.ChatCommands.RemoveAll(c => c.CommandDelegate.Method?.DeclaringType?.Assembly == asm);
AppDomain.CurrentDomain.AssemblyResolve -= this.CurrentDomain_AssemblyResolve;
On.OTAPI.Hooks.MessageBuffer.InvokeGetData -= this.MessageBuffer_InvokeGetData;
On.OTAPI.Hooks.MessageBuffer.InvokeGetData -= Login.MessageBuffer_InvokeGetData;
BanManager.OnBanPostAdd -= this.OnBanInsert;
ServerApi.Hooks.NetGetData.Deregister(this, Login.OnGetData);
ServerApi.Hooks.GamePostInitialize.Deregister(this, this.GenCode);
WebSocket.Dispose();
if (!WebSocketTask.IsCompleted)
{
TokenSource.Cancel();
Expand All @@ -173,6 +183,105 @@ protected override void Dispose(bool disposing)
}
base.Dispose(disposing);
}

private void CaiBotCommand(CommandArgs args)
{
var plr = args.Player;
void ShowHelpText()
{
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, plr, out var pageNumber))
{
return;
}

List<string> lines = new()
{
"/caibot debug CaiBot调试开关",
"/caibot code 生成并且展示验证码",
"/caibot info 显示CaiBot的一些信息"
};

PaginationTools.SendPage(
plr, pageNumber, lines,
new PaginationTools.Settings
{
HeaderFormat = GetString("帮助 ({0}/{1}):"),
FooterFormat = GetString("输入 {0}caibot help {{0}} 查看更多").SFormat(Commands.Specifier)
}
);
}

if (args.Parameters.Count == 0)
{
ShowHelpText();
return;
}


switch (args.Parameters[0].ToLowerInvariant())
{
// 帮助
case "help":
ShowHelpText();
return;

default:
ShowHelpText();
break;

case "信息":
case "info":
plr.SendInfoMessage($"[CaiBot信息]\n" +
$"插件版本: v{VersionNum}\n" +
$"WebSocket状态: {WebSocket.State}\n" +
$"绑定QQ群: {(Config.config.GroupNumber == 0L?"未绑定|未连接":Config.config.GroupNumber)}\n" +
$"本地模式: {LocalMode}\n" +
$"绑定状态: {Config.config.Token != ""}\n" +
$"Debug模式: {DebugMode}\n" +
$"Economic API支持: {EconomicSupport.GetCoinsSupport}\n"+
$"Economic RPG支持: {EconomicSupport.GetLevelNameSupport}\n"+
$"Economic Skill支持: {EconomicSupport.GetSkillSupport}\n"
);
break;
case "调试":
case "debug":
DebugMode = !DebugMode;
plr.SendInfoMessage($"[CaiBot]调试模式已{(DebugMode?"开启":"关闭")}!");
break;
case "验证码":
case "code":
if (!string.IsNullOrEmpty(Config.config.Token))
{
plr.SendInfoMessage($"[CaiBot]服务器已绑定无法生成验证码!");
return;
}
this.GenCode(null);
plr.SendInfoMessage($"[CaiBot]验证码已生成,请在后台查看喵~");
break;
}
}

private async void OnBanInsert(object? sender, BanEventArgs e)
{
if (e.Ban.Identifier.StartsWith(Identifier.Name.Prefix) || e.Ban.Identifier.StartsWith(Identifier.Account.Prefix))
{
var name = e.Ban.Identifier.Replace(Identifier.Name.Prefix, "").Replace(Identifier.Account.Prefix, "");
var expireTime = e.Ban.GetPrettyExpirationString();
var result = new RestObject
{
{ "type", "post_ban_add" },
{ "name", name },
{ "reason", e.Ban.Reason },
{ "admin", e.Ban.BanningUser },
{ "expire_time", expireTime=="Never"?"永久封禁":expireTime }
};
await MessageHandle.SendDateAsync(JsonConvert.SerializeObject(result));
}


}


private void GenCode(EventArgs args)
{
if (!string.IsNullOrEmpty(Config.config.Token))
Expand Down
38 changes: 19 additions & 19 deletions src/CaiBot/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,23 @@

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


## 使用方法(轻量版):

1. 将插件安装在ServerPlugins/

2. 重启服务器

3. 启动服务器后会显示授权码

4. 群内发送 添加服务器 <IP地址> <端口> <验证码>

5. 完成配置

## 更新日志

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

## 指令

```
暂无
```
| 语法 | 权限 | 说明 |
|----------------|:------------:|:------------:|
| /caibot debug | CaiBot.Admin | 调试模式开关 |
| /caibot code | CaiBot.Admin | 生成验证码 |
| /caibot info | CaiBot.Admin | 显示CaiBot状态信息 |

## 配置

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

----------

## 使用方法(轻量版):

1.将插件安装在ServerPlugins/

2.重启服务器

3.启动服务器后会显示授权码

4.群内发送 添加服务器 <IP地址> <端口> <验证码>

5.完成配置

----------

## 反馈

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

0 comments on commit ed6c603

Please sign in to comment.