This commit is contained in:
MelodyMaster
2025-06-12 11:28:05 +08:00
parent d843ad857a
commit 5ca29d24d6
5 changed files with 257 additions and 10 deletions

66
Command/Link.cs Normal file
View File

@ -0,0 +1,66 @@
using System;
using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using QQBot.Event;
using QQBot.SQL;
namespace QQBot
{
internal class Link
{
public static async Task HandleLinkCommand(JsonElement eventData, string messageText)
{
try
{
// 提取绑定码
var parts = messageText.Split(' ');
if (parts.Length < 2)
{
await Send.SendReply(eventData, "绑定格式错误,请使用: link [绑定码]");
return;
}
string bindCode = parts[1];
string qqNumber = eventData.GetProperty("user_id").GetString();
// 验证绑定码
var result = Mysql.ValidateBindCode(bindCode, qqNumber);
if (result.Success)
{
// 更新QQ号
if (Mysql.UpdateQQNumber(bindCode, qqNumber))
{
await Send.SendReply(eventData, "✅ 绑定成功!请重新登录服务器");
// 踢出玩家(如果在线)
KickPlayer(result.SteamId);
}
else
{
await Send.SendReply(eventData, "❌ 绑定更新失败");
}
}
else
{
await Send.SendReply(eventData, $"❌ {result.Message}");
}
}
catch (Exception ex)
{
Console.WriteLine($"处理link命令时出错: {ex}");
await Send.SendReply(eventData, "绑定过程中发生错误");
}
}
// 踢出玩家方法(需根据实际情况实现)
private static void KickPlayer(string steamId)
{
// 实际实现应通过游戏服务器API踢出玩家
Console.WriteLine($"通知游戏服务器踢出玩家: {steamId}");
}
}
}

View File

@ -1,9 +1,12 @@
using System;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using QQBot.Event;
@ -15,10 +18,16 @@ namespace QQBot.Event
public static async Task Start(string[] args)
{
Console.WriteLine("已启动千空之星QQ机器人API系统 ");
var builder = WebApplication.CreateBuilder(args);
// 添加 CORS 支持
// 添加 HttpClient 工厂支持
builder.Services.AddHttpClient();
// 添加 CORS 支持
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll", policyBuilder =>
@ -31,10 +40,10 @@ namespace QQBot.Event
var app = builder.Build();
// 使用 CORS 中间件
// 使用 CORS 中间件
app.UseCors("AllowAll");
// 注册发送文本接口
// 注册发送文本接口
app.Use(async (context, next) =>
{
context.Response.ContentType = "text/plain; charset=utf-8";
@ -68,7 +77,7 @@ namespace QQBot.Event
try
{
// 调用 Send.ReplyByMod 方法发送消息
// 调用 Send.ReplyByMod 方法发送消息
await Send.ReplyByMod(text, QQID, mod);
await context.Response.WriteAsync($"消息已发送至 {(mod == 1 ? "" : "")} ({QQID})");
}
@ -84,7 +93,7 @@ namespace QQBot.Event
await next();
});
// 注册发送图片接口
// 注册发送图片接口
app.Use(async (context, next) =>
{
context.Response.ContentType = "text/plain; charset=utf-8";
@ -122,7 +131,7 @@ namespace QQBot.Event
var imageData = await httpClient.GetByteArrayAsync(url);
Console.WriteLine($"图片大小: {imageData.Length} 字节,准备发送至 {(mod == 1 ? "" : "")} ({QQID})");
// 调用 Send.ImageByMod 方法发送图片
// 调用 Send.ImageByMod 方法发送图片
await Send.ImageByMod(imageData, QQID, mod);
await context.Response.WriteAsync($"图片已成功发送至 {(mod == 1 ? "" : "")} ({QQID})");
}
@ -138,7 +147,51 @@ namespace QQBot.Event
await next();
});
// 默认提示
// 注册获取 QQ 名称接口
app.MapGet("/QQName", async (HttpContext context, [FromServices] IHttpClientFactory httpClientFactory) =>
{
var qq = context.Request.Query["user_id"].ToString();
if (!long.TryParse(qq, out var qqId))
{
await context.Response.WriteAsJsonAsync(new { Nickname = "Invalid QQ format" });
return;
}
var client = httpClientFactory.CreateClient();
var requestContent = JsonContent.Create(new { user_id = qqId });
try
{
var response = await client.PostAsync("http://localhost:3000/get_stranger_info", requestContent);
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadFromJsonAsync<JsonElement>();
// 检查 retcode 是否为 0 表示成功
if (json.TryGetProperty("retcode", out var retCodeNode) && retCodeNode.GetInt32() == 0)
{
// 获取 data 对象中的 nickname
if (json.TryGetProperty("data", out var dataNode) &&
dataNode.TryGetProperty("nickname", out var nickNode))
{
var result = new { Nickname = nickNode.GetString() };
await context.Response.WriteAsJsonAsync(result);
return;
}
}
}
await context.Response.WriteAsJsonAsync(new { Nickname = "Unknown" });
}
catch (Exception ex)
{
await context.Response.WriteAsJsonAsync(new { Nickname = "Network error" });
}
});
// 默认提示
app.MapGet("/sendapi", async context =>
{
await context.Response.WriteAsync("请提供 text 和 QQID 参数");

43
Main.cs
View File

@ -5,21 +5,42 @@ using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Diagnostics;
using Microsoft.Extensions.DependencyInjection;
using QQBot;
using QQBot.Command;
using QQBot.Event;
using QQBot.SQL;
class Nebulamist
{
static async Task Main(string[] args)
{
Console.WriteLine("===!连接SQL数据库中!===");
Mysql.InitSql();
if (!Mysql.IsSql)
{
Console.WriteLine("!错误! SQL没有正确连接,插件不会启用!");
}
if (Mysql.IsSql)
{
Console.WriteLine("===!SQL数据已成功连接!===");
Console.WriteLine("===!正在启动机器人!===");
await Start(args); // 启动 Web 应用程序
}
}
static async Task Start(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// 添加 HttpClient 工厂支持
builder.Services.AddHttpClient();
var app = builder.Build();
// 创建 Web 应用构建器
var builder = WebApplication.CreateBuilder();
// 构建 Web 应用
var app = builder.Build();
// 使用中间件处理传入的请求
app.Use(async (context, next) =>
@ -99,6 +120,20 @@ class Nebulamist
break;
}
// 在消息段处理部分添加
if (messageText.StartsWith("link ", StringComparison.OrdinalIgnoreCase) ||
messageText.Equals("link", StringComparison.OrdinalIgnoreCase))
{
// Fix for CS7036: Add the missing "messageText" parameter when calling Link.HandleLinkCommand
if (messageText.StartsWith("link ", StringComparison.OrdinalIgnoreCase) ||
messageText.Equals("link", StringComparison.OrdinalIgnoreCase))
{
await Link.HandleLinkCommand(eventData, messageText);
return;
}
}
// 可以继续添加其他关键词处理逻辑
}
}
@ -126,5 +161,7 @@ class Nebulamist
await app.RunAsync("http://localhost:5000");
}
}

90
Mysql.cs Normal file
View File

@ -0,0 +1,90 @@
using MySql.Data.MySqlClient;
using static System.Net.Mime.MediaTypeNames;
namespace QQBot.SQL
{
public class Mysql
{
private static readonly string ConnectionString = "server=8.138.193.132;port=3306;user=slroot;password=root;database=sl;charset=utf8mb4;";
// 添加 IsSql 字段
public static bool IsSql { get; private set; }
private static MySqlConnection Connection { get; set; }
// 验证绑定码是否存在
public static async Task InitSql()
{
Connection = new MySqlConnection(ConnectionString);
try
{
IsSql = true;
Connection.Open();
Connection.Close();
}
catch (MySqlException ex)
{
Console.WriteLine(ex.Message);
IsSql = false;
}
}
public static BindResult ValidateBindCode(string code, string qqNumber)
{
var result = new BindResult();
using (var conn = new MySqlConnection(ConnectionString))
{
try
{
conn.Open();
var cmd = new MySqlCommand(
"SELECT uid, steam17id FROM binding WHERE bind_code = @code AND qq_number IS NULL",
conn);
cmd.Parameters.AddWithValue("@code", code);
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
result.Success = true;
result.Uid = reader["uid"].ToString();
result.SteamId = reader["steam17id"].ToString();
}
else
{
result.Message = "无效或已被使用的绑定码";
}
}
}
catch (Exception ex)
{
result.Message = $"数据库错误: {ex.Message}";
}
}
return result;
}
// 更新绑定码对应的QQ号
public static bool UpdateQQNumber(string code, string qq)
{
using (var conn = new MySqlConnection(ConnectionString))
{
conn.Open();
var cmd = new MySqlCommand("UPDATE binding SET qq_number = @qq WHERE bind_code = @code", conn);
cmd.Parameters.AddWithValue("@qq", qq);
cmd.Parameters.AddWithValue("@code", code);
return cmd.ExecuteNonQuery() > 0;
}
}
}
public class BindResult
{
public bool Success { get; set; }
public string Message { get; set; }
public string Uid { get; set; }
public string SteamId { get; set; }
}
}

View File

@ -9,6 +9,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="9.0.5" />
<PackageReference Include="MySql.Data" Version="9.3.0" />
<PackageReference Include="SkiaSharp" Version="3.119.0" />
<PackageReference Include="System.Diagnostics.PerformanceCounter" Version="10.0.0-preview.5.25277.114" />
<PackageReference Include="System.Management" Version="9.0.5" />