Compare commits
3 Commits
2b7632344e
...
a5b1c31812
| Author | SHA1 | Date | |
|---|---|---|---|
| a5b1c31812 | |||
| 0d3ad913be | |||
| 4e7c846426 |
@@ -1,31 +1,18 @@
|
||||
using Debugger;
|
||||
using Grpc.Core;
|
||||
using Lagrange.Core.Common.Interface.Api;
|
||||
using Lagrange.Core.Message;
|
||||
using Shrink.Login;
|
||||
|
||||
namespace Shrink.API;
|
||||
|
||||
public class BotServiceImpl : BotService.BotServiceBase
|
||||
public class BotServiceImpl : APIService.APIServiceBase
|
||||
{
|
||||
public override Task<DataResponse> SendData(DataRequest request, ServerCallContext context)
|
||||
{
|
||||
// 模拟向 QQ 机器人处理数据的逻辑
|
||||
Console.WriteLine($"服务端接收到请求:Code={request.Code}, Str1={request.Str1}, Str2={request.Str2}, Num={request.Num}");
|
||||
|
||||
// 假设调用你的 QQ 机器人方法(这里简化为打印消息)
|
||||
string botResponse = $"QQ机器人已处理请求: {request.Str1} 和 {request.Str2}";
|
||||
|
||||
var chain = MessageBuilder.Friend(3209851541).Text($"Shrink已处理请求: {request.Str1} 和 {request.Str2}");
|
||||
QrCode.Instance.Client.SendMessage(chain.Build());
|
||||
var chain1 = MessageBuilder.Friend(3048536893).Text($"Shrink已处理请求: {request.Str1} 和 {request.Str2}");
|
||||
QrCode.Instance.Client.SendMessage(chain1.Build());
|
||||
var chain2 = MessageBuilder.Group(954600523).Text($"Shrink已处理请求: {request.Str1} 和 {request.Str2} 整数 {request.Num}");
|
||||
QrCode.Instance.Client.SendMessage(chain2.Build());
|
||||
// 返回响应
|
||||
return Task.FromResult(new DataResponse
|
||||
{
|
||||
Message = botResponse,
|
||||
Message = "114514",
|
||||
Success = true
|
||||
});
|
||||
}
|
||||
|
||||
@@ -4,15 +4,25 @@ option csharp_namespace = "Debugger";
|
||||
|
||||
package Debugger;
|
||||
|
||||
service BotService {
|
||||
service APIService {
|
||||
rpc SendData (DataRequest) returns (DataResponse);
|
||||
}
|
||||
|
||||
message DataRequest {
|
||||
string code = 1;
|
||||
string str1 = 2;
|
||||
string str2 = 3;
|
||||
int32 num = 4;
|
||||
enum msgType{
|
||||
public = 0;
|
||||
private = 1;
|
||||
}
|
||||
int32 uin = 1;
|
||||
enum logLevel{
|
||||
fatal = 0;
|
||||
error = 1;
|
||||
warn = 2;
|
||||
info = 3;
|
||||
verbose= 4;
|
||||
debug = 5;
|
||||
}
|
||||
string text = 2;
|
||||
}
|
||||
|
||||
message DataResponse {
|
||||
|
||||
@@ -1,156 +0,0 @@
|
||||
using System.Text.Json;
|
||||
using System.Xml;
|
||||
using Lagrange.Core;
|
||||
using Lagrange.Core.Common.Interface.Api;
|
||||
using Lagrange.Core.Message;
|
||||
using Shrink.Login;
|
||||
|
||||
namespace Shrink.Command;
|
||||
|
||||
public class Commands
|
||||
{
|
||||
private static Commands? _instance;
|
||||
private static readonly object Lock = new();
|
||||
private Commands() { }
|
||||
|
||||
public static Commands Instance
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_instance != null) return _instance;
|
||||
lock (Lock)
|
||||
{
|
||||
_instance ??= new Commands();
|
||||
}
|
||||
return _instance;
|
||||
}
|
||||
}
|
||||
|
||||
// 使用字典存储命令和群消息
|
||||
private Dictionary<string, string> _commandDict = new();
|
||||
private List<string> _corpus = new();
|
||||
private Dictionary<uint, string> _messageDict = new();
|
||||
private HashSet<uint> _adminSet = new();
|
||||
|
||||
// 文件初始化
|
||||
public async Task Init()
|
||||
{
|
||||
// 读取Admins.json
|
||||
if (File.Exists("Admins.json"))
|
||||
{
|
||||
_adminSet = new HashSet<uint>(JsonSerializer.Deserialize<List<uint>>(await File.ReadAllTextAsync("Admins.json")));
|
||||
}
|
||||
else
|
||||
{
|
||||
_adminSet.Add(3048536893); // 默认管理员
|
||||
await File.WriteAllTextAsync("Admins.json", JsonSerializer.Serialize(_adminSet.ToList()));
|
||||
}
|
||||
|
||||
// 读取JoinMessage.json
|
||||
if (File.Exists("JoinMessage.json"))
|
||||
{
|
||||
_messageDict = JsonSerializer.Deserialize<List<KeyValuePair<uint, string>>>(await File.ReadAllTextAsync("JoinMessage.json"))
|
||||
.ToDictionary(msg => msg.Key, msg => msg.Value);
|
||||
}
|
||||
else
|
||||
{
|
||||
_messageDict.Add(620902312, "欢迎");
|
||||
await File.WriteAllTextAsync("JoinMessage.json", JsonSerializer.Serialize(_messageDict.Select(kv => new KeyValuePair<uint, string>(kv.Key, kv.Value)).ToList()));
|
||||
}
|
||||
|
||||
// 读取Commands.json
|
||||
if (File.Exists("Commands.json"))
|
||||
{
|
||||
_commandDict = JsonSerializer.Deserialize<List<KeyValuePair<string, string>>>(await File.ReadAllTextAsync("Commands.json"))
|
||||
.ToDictionary(cmd => cmd.Key, cmd => cmd.Value);
|
||||
}
|
||||
else
|
||||
{
|
||||
_commandDict.Add("/ping", "Pong!");
|
||||
await File.WriteAllTextAsync("Commands.json", JsonSerializer.Serialize(_commandDict.Select(kv => new KeyValuePair<string, string>(kv.Key, kv.Value)).ToList()));
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SaveAdmin()
|
||||
{
|
||||
await File.WriteAllTextAsync("Admins.json", JsonSerializer.Serialize(_adminSet.ToList()));
|
||||
await Init();
|
||||
}
|
||||
|
||||
// bot管理员权限检查
|
||||
private void NoEnoughPermission(BotContext ctx, uint groupID)
|
||||
{
|
||||
var chain = MessageBuilder.Group(groupID).Text("权限不足");
|
||||
ctx.SendMessage(chain.Build());
|
||||
}
|
||||
|
||||
// 先Init后再运行
|
||||
public Task Run()
|
||||
{
|
||||
QrCode.Instance.Client.Invoker.OnGroupMemberIncreaseEvent += (context, @event) =>
|
||||
{
|
||||
var groupid = @event.GroupUin;
|
||||
if (_messageDict.ContainsKey(groupid))
|
||||
{
|
||||
var message = _messageDict[groupid];
|
||||
var chain = MessageBuilder.Group(groupid).Text(message);
|
||||
context.SendMessage(chain.Build());
|
||||
}
|
||||
};
|
||||
|
||||
QrCode.Instance.Client.Invoker.OnGroupMessageReceived += (content, @event) =>
|
||||
{
|
||||
var groupId = @event.Chain.GroupUin.Value;
|
||||
var senderId = @event.Chain.FriendUin;
|
||||
var text = @event.Chain.ToPreviewText();
|
||||
|
||||
// 执行命令
|
||||
if (_commandDict.ContainsKey(text))
|
||||
{
|
||||
var chain = MessageBuilder.Group(groupId).Text(_commandDict[text]);
|
||||
content.SendMessage(chain.Build());
|
||||
}
|
||||
|
||||
var today = DateTime.Today;
|
||||
var seed = today.Year ^ today.Month ^ today.Day ^ senderId;
|
||||
var random = new Random((int)seed);
|
||||
|
||||
switch (text)
|
||||
{
|
||||
case "/reload":
|
||||
_ = Init();
|
||||
var chain3 = MessageBuilder.Group(groupId).Text("重载完成!");
|
||||
content.SendMessage(chain3.Build());
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
if (text.Contains("/addadmin") && text.StartsWith("/addadmin"))
|
||||
{
|
||||
if (_adminSet.Contains(senderId))
|
||||
{
|
||||
var temp = uint.Parse(text.Remove(0, 9));
|
||||
if (_adminSet.Contains(temp))
|
||||
{
|
||||
var chain = MessageBuilder.Group(groupId).Text("已存在管理员: " + temp);
|
||||
content.SendMessage(chain.Build());
|
||||
}
|
||||
else
|
||||
{
|
||||
_adminSet.Add(temp);
|
||||
var chain = MessageBuilder.Group(groupId).Text("已添加管理员: " + temp);
|
||||
SaveAdmin();
|
||||
content.SendMessage(chain.Build());
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
NoEnoughPermission(content, groupId);
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
16
Event/BotEventHandler.cs
Normal file
16
Event/BotEventHandler.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
using Lagrange.Core.Event;
|
||||
using Shrink.Login;
|
||||
|
||||
namespace Shrink.Event;
|
||||
|
||||
public class BotEventHandler
|
||||
{
|
||||
public BotEventHandler()
|
||||
{
|
||||
Console.WriteLine("Bot EventHandler");
|
||||
}
|
||||
private static readonly Lazy<BotEventHandler> _instance = new(() => new BotEventHandler());
|
||||
public static BotEventHandler Instance => _instance.Value;
|
||||
private EventInvoker _invoker = BotService.Instance.Client!.Invoker;
|
||||
|
||||
}
|
||||
136
Login/BotService.cs
Normal file
136
Login/BotService.cs
Normal file
@@ -0,0 +1,136 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Debugger;
|
||||
using Grpc.Core;
|
||||
using Lagrange.Core;
|
||||
using Lagrange.Core.Common;
|
||||
using Lagrange.Core.Common.Interface;
|
||||
using Lagrange.Core.Common.Interface.Api;
|
||||
using Shrink.API;
|
||||
using Shrink.Utility;
|
||||
using Console = System.Console;
|
||||
|
||||
namespace Shrink.Login;
|
||||
|
||||
public class BotService
|
||||
{
|
||||
private static readonly Lazy<BotService> _instance = new(() => new BotService());
|
||||
public static BotService Instance => _instance.Value;
|
||||
|
||||
public BotContext? Client;
|
||||
private bool _isOnline;
|
||||
private static string KeystoreFilePath => "Keystore.json";
|
||||
private static string DeviceInfoFilePath => "DeviceInfo.json";
|
||||
|
||||
|
||||
private static BotDeviceInfo GetDeviceInfo() =>
|
||||
ReadOrCreateJsonFile(DeviceInfoFilePath, BotDeviceInfo.GenerateInfo);
|
||||
|
||||
// 登录方法
|
||||
public async Task Login()
|
||||
{
|
||||
const int port = 50051;
|
||||
var server = new Server
|
||||
{
|
||||
Services = { APIService.BindService(new BotServiceImpl()) },
|
||||
Ports = { new ServerPort("localhost", port, ServerCredentials.Insecure) }
|
||||
};
|
||||
|
||||
var deviceInfo = File.Exists(DeviceInfoFilePath)
|
||||
? ReadJsonFromFile<BotDeviceInfo>(DeviceInfoFilePath)
|
||||
: GetDeviceInfo();
|
||||
|
||||
var keyStore = File.Exists(KeystoreFilePath)
|
||||
? ReadJsonFromFile<BotKeystore>(KeystoreFilePath)
|
||||
: new BotKeystore();
|
||||
|
||||
Client = BotFactory.Create(new BotConfig
|
||||
{
|
||||
UseIPv6Network = false,
|
||||
GetOptimumServer = true,
|
||||
AutoReconnect = true,
|
||||
Protocol = Protocols.Linux
|
||||
}, deviceInfo, keyStore);
|
||||
|
||||
// Log模式
|
||||
Client.Invoker.OnBotLogEvent += (_, @event) =>
|
||||
{
|
||||
@event.Level.ChangeColorByTitle();
|
||||
Console.WriteLine(@event.ToString());
|
||||
};
|
||||
|
||||
// bot信息保存
|
||||
Client.Invoker.OnBotOnlineEvent += (_, @event) =>
|
||||
{
|
||||
Console.WriteLine(@event.ToString());
|
||||
_isOnline = true;
|
||||
server.Start();
|
||||
Console.WriteLine($"gRPC server listening on port {port}");
|
||||
};
|
||||
Client.Invoker.OnBotOfflineEvent += async (_, @event) =>
|
||||
{
|
||||
Console.WriteLine(@event.ToString());
|
||||
await server.ShutdownAsync();
|
||||
_isOnline = false;
|
||||
};
|
||||
|
||||
if (File.Exists(KeystoreFilePath))
|
||||
{
|
||||
await Client.LoginByPassword();
|
||||
if (!_isOnline)
|
||||
{
|
||||
Console.WriteLine("账密登录失败,请尝试二维码登录。");
|
||||
var qrCode = await Client.FetchQrCode();
|
||||
if (qrCode != null)
|
||||
{
|
||||
await File.WriteAllBytesAsync("qr.png", qrCode.Value.QrCode);
|
||||
await Client.LoginByQrCode();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await File.WriteAllTextAsync(KeystoreFilePath, JsonSerializer.Serialize(Client.UpdateKeystore()));
|
||||
await File.WriteAllTextAsync(DeviceInfoFilePath, JsonSerializer.Serialize(Client.UpdateDeviceInfo()));
|
||||
}
|
||||
|
||||
private static T ReadJsonFromFile<T>(string filePath)
|
||||
{
|
||||
try
|
||||
{
|
||||
var json = File.ReadAllText(filePath);
|
||||
return JsonSerializer.Deserialize<T>(json,
|
||||
new JsonSerializerOptions { ReferenceHandler = ReferenceHandler.Preserve })!;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"读取文件出错: {filePath}: {ex.Message}");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static T ReadOrCreateJsonFile<T>(string filePath, Func<T> createFunc)
|
||||
{
|
||||
if (File.Exists(filePath))
|
||||
{
|
||||
return ReadJsonFromFile<T>(filePath);
|
||||
}
|
||||
|
||||
var newData = createFunc();
|
||||
WriteJsonToFile(filePath, newData);
|
||||
return newData;
|
||||
}
|
||||
|
||||
private static void WriteJsonToFile<T>(string filePath, T data)
|
||||
{
|
||||
try
|
||||
{
|
||||
var json = JsonSerializer.Serialize(data);
|
||||
File.WriteAllText(filePath, json);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"写入文件出错: {filePath}: {ex.Message}");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
106
Login/QrCode.cs
106
Login/QrCode.cs
@@ -1,106 +0,0 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Lagrange.Core;
|
||||
using Lagrange.Core.Common;
|
||||
using Lagrange.Core.Common.Interface;
|
||||
using Lagrange.Core.Common.Interface.Api;
|
||||
using Lagrange.Core.Event.EventArg;
|
||||
using Shrink.Utility;
|
||||
using Console = System.Console;
|
||||
|
||||
namespace Shrink.Login;
|
||||
|
||||
public class QrCode
|
||||
{
|
||||
private static QrCode? _instance;
|
||||
|
||||
private static readonly object Lock = new();
|
||||
|
||||
public static QrCode Instance
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_instance != null) return _instance;
|
||||
lock (Lock)
|
||||
{
|
||||
_instance ??= new QrCode();
|
||||
}
|
||||
return _instance;
|
||||
}
|
||||
}
|
||||
|
||||
public BotContext? Client;
|
||||
public static void SaveKeystore(BotKeystore keystore) =>
|
||||
File.WriteAllText("Keystore.json", JsonSerializer.Serialize(keystore));
|
||||
|
||||
public static BotDeviceInfo GetDeviceInfo()
|
||||
{
|
||||
if (File.Exists("DeviceInfo.json"))
|
||||
{
|
||||
var info = JsonSerializer.Deserialize<BotDeviceInfo>(File.ReadAllText("DeviceInfo.json"));
|
||||
if (info != null) return info;
|
||||
|
||||
info = BotDeviceInfo.GenerateInfo();
|
||||
File.WriteAllText("DeviceInfo.json", JsonSerializer.Serialize(info));
|
||||
return info;
|
||||
}
|
||||
|
||||
var deviceInfo = BotDeviceInfo.GenerateInfo();
|
||||
File.WriteAllText("DeviceInfo.json", JsonSerializer.Serialize(deviceInfo));
|
||||
return deviceInfo;
|
||||
}
|
||||
public static BotKeystore? LoadKeystore()
|
||||
{
|
||||
try
|
||||
{
|
||||
var text = File.ReadAllText("Keystore.json");
|
||||
return JsonSerializer.Deserialize<BotKeystore>(text, new JsonSerializerOptions()
|
||||
{
|
||||
ReferenceHandler = ReferenceHandler.Preserve
|
||||
});
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
// 登录方法
|
||||
public async Task Login()
|
||||
{
|
||||
#region bot实例化
|
||||
|
||||
var deviceInfo = GetDeviceInfo();
|
||||
var keyStore = LoadKeystore() ?? new BotKeystore();
|
||||
|
||||
Client = BotFactory.Create(new BotConfig
|
||||
{
|
||||
UseIPv6Network = false,
|
||||
GetOptimumServer = true,
|
||||
AutoReconnect = true,
|
||||
Protocol = Protocols.Linux
|
||||
}, deviceInfo, keyStore);
|
||||
|
||||
#endregion
|
||||
|
||||
// Log模式
|
||||
Client.Invoker.OnBotLogEvent += (_, @event) =>
|
||||
{
|
||||
@event.Level.ChangeColorByTitle();
|
||||
Console.WriteLine(@event.ToString());
|
||||
};
|
||||
|
||||
// bot信息保存,但存在bug未修复
|
||||
Client.Invoker.OnBotOnlineEvent += (_, @event) =>
|
||||
{
|
||||
Console.WriteLine(@event.ToString());
|
||||
SaveKeystore(Client.UpdateKeystore());
|
||||
};
|
||||
// 二维码生成,启动后在根目录下生成qr.png
|
||||
var qrCode = await Client.FetchQrCode();
|
||||
if (qrCode != null)
|
||||
{
|
||||
await File.WriteAllBytesAsync("qr.png", qrCode.Value.QrCode);
|
||||
await Client.LoginByQrCode();
|
||||
}
|
||||
}
|
||||
}
|
||||
64
Program.cs
64
Program.cs
@@ -1,8 +1,4 @@
|
||||
using Debugger;
|
||||
using Grpc.Core;
|
||||
using Shrink.API;
|
||||
using Shrink.Command;
|
||||
using Shrink.Login;
|
||||
using BotService = Shrink.Login.BotService;
|
||||
|
||||
namespace Shrink;
|
||||
|
||||
@@ -10,62 +6,6 @@ public static class Program
|
||||
{
|
||||
public static async Task Main()
|
||||
{
|
||||
/*var originalAssemblyPath = "Lagrange.Core.dll";
|
||||
var tempAssemblyPath = "ModifiedExternalAssembly.dll";
|
||||
var oldUrl = "自己找";
|
||||
var newUrl = "自己找";
|
||||
|
||||
ModifyAssembly(originalAssemblyPath, tempAssemblyPath, oldUrl, newUrl);*/
|
||||
const int port = 50051;
|
||||
|
||||
var server = new Server
|
||||
{
|
||||
Services = { BotService.BindService(new BotServiceImpl()) },
|
||||
Ports = { new ServerPort("localhost", port, ServerCredentials.Insecure) }
|
||||
};
|
||||
|
||||
server.Start();
|
||||
|
||||
Console.WriteLine($"gRPC server listening on port {port}");
|
||||
|
||||
await QrCode.Instance.Login();
|
||||
await Commands.Instance.Init();
|
||||
await Commands.Instance.Run();
|
||||
//await server.ShutdownAsync();
|
||||
await BotService.Instance.Login();
|
||||
}
|
||||
/*private static void ModifyAssembly(string originalAssemblyPath, string tempAssemblyPath, string oldUrl, string newUrl)
|
||||
{
|
||||
var assembly = AssemblyDefinition.ReadAssembly(originalAssemblyPath);
|
||||
var module = assembly.MainModule;
|
||||
|
||||
// 查找LinuxSigner类型
|
||||
var linuxSignerType = module.Types.FirstOrDefault(t => t.Name == "LinuxSigner");
|
||||
if (linuxSignerType == null)
|
||||
{
|
||||
Console.WriteLine("无LinuxSigner类型");
|
||||
return;
|
||||
}
|
||||
|
||||
// 查找构造函数
|
||||
var constructor = linuxSignerType.Methods.FirstOrDefault(m => m.IsConstructor);
|
||||
if (constructor == null)
|
||||
{
|
||||
Console.WriteLine("无构造函数");
|
||||
return;
|
||||
}
|
||||
|
||||
var ilProcessor = constructor.Body.GetILProcessor();
|
||||
foreach (var instruction in constructor.Body.Instructions)
|
||||
{
|
||||
// 检查是否是加载字符串操作
|
||||
if (instruction.OpCode == OpCodes.Ldstr && instruction.Operand is string str && str == oldUrl)
|
||||
{
|
||||
instruction.Operand = newUrl; // 替换为新URL
|
||||
Console.WriteLine($"替换: {oldUrl}为{newUrl}");
|
||||
}
|
||||
}
|
||||
|
||||
assembly.Write(tempAssemblyPath);
|
||||
Console.WriteLine($"已将修改后的程序集保存在{tempAssemblyPath}");
|
||||
}*/
|
||||
}
|
||||
Reference in New Issue
Block a user