feat: 新增灵田 秘境结算持久化

main
LyMysterious 5 months ago
parent ea73d594c5
commit 7c6b2580d6

@ -2,6 +2,7 @@
using Furion; using Furion;
using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.HttpOverrides;
using NapCatRobotClient.Core.Helper; using NapCatRobotClient.Core.Helper;
using NapCatRobotClient.Service.BackGround;
using System.Net; using System.Net;
namespace NapCatRobotClient.API namespace NapCatRobotClient.API
@ -18,6 +19,9 @@ namespace NapCatRobotClient.API
builder.Services.AddEndpointsApiExplorer(); builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(); builder.Services.AddSwaggerGen();
builder.Services.AddHostedService<MijingBackGroundWorker>();
builder.Services.AddHostedService<LingTianBackGroundWorker>();
var app = builder.Build(); var app = builder.Build();
app.UseInject(string.Empty); app.UseInject(string.Empty);

@ -149,6 +149,7 @@
"😲🏹🇿🐦": "惊弓之鸟", "😲🏹🇿🐦": "惊弓之鸟",
"🐓✈️🥚🤛": "鸡飞蛋打", "🐓✈️🥚🤛": "鸡飞蛋打",
"🐴🌾🍊🏹": "马到成功", "🐴🌾🍊🏹": "马到成功",
"😋🥂🤹‍♂️😀": "吃喝玩乐" "😋🥂🤹‍♂️😀": "吃喝玩乐",
"📟🐝🗣🌧": "呼风唤雨"
} }
} }

@ -7,5 +7,9 @@
{ {
public const string GoodsKey = "GoodsInfo"; public const string GoodsKey = "GoodsInfo";
public const string MiJingKey = "MiJing:";
public const string LingTianKey = "LingTian:";
} }
} }

@ -1,4 +1,5 @@
using Flurl.Http; using Flurl.Http;
using Furion.Logging;
using NapCatRobotClient.Core.RobotAPI.Dto.Request; using NapCatRobotClient.Core.RobotAPI.Dto.Request;
namespace NapCatRobotClient.Core.RobotAPI namespace NapCatRobotClient.Core.RobotAPI
@ -26,13 +27,22 @@ namespace NapCatRobotClient.Core.RobotAPI
} }
private static async Task<string> Post(string parameters, string action) private static async Task<string> Post(string parameters, string action)
{
try
{ {
string url = App.Configuration["QQConfig:SendApiUrl"] + action; string url = App.Configuration["QQConfig:SendApiUrl"] + action;
string response = await url.WithHeader("Authorization", "Bearer " + App.Configuration["QQConfig:AccessToken"]) string response = await url.WithHeader("Authorization", "Bearer " + App.Configuration["QQConfig:AccessToken"])
.WithHeader("Content-Type", "application/json;charset=utf-8") .WithHeader("Content-Type", "application/json;charset=utf-8")
.AllowAnyHttpStatus()
.PostStringAsync(parameters) .PostStringAsync(parameters)
.ReceiveString(); .ReceiveString();
return response; return response;
} }
catch (Exception ex)
{
Log.Error($"RobotAPI 请求异常,请求参数:{parameters},请求地址:{action} {ex.Message},{ex.StackTrace}");
return default;
}
}
} }
} }

@ -0,0 +1,60 @@
using Furion.Logging;
using Microsoft.Extensions.Hosting;
using NapCatRobotClient.Core.RobotAPI.Dto.Request;
namespace NapCatRobotClient.Service.BackGround
{
/// <summary>
/// 灵田结算通知
/// </summary>
public class LingTianBackGroundWorker : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
string[] keys = RedisHelper.Client.Keys($"{RedisPrefix.LingTianKey}*");
foreach (string key in keys)
{
string json = RedisHelper.Client.Get(key);
if (string.IsNullOrEmpty(json)) continue;
TaskDetailInfo task = JsonConvert.DeserializeObject<TaskDetailInfo>(json);
if (task.TriggerTime <= DateTime.Now)
{
GroupSendMessageRequest request = new()
{
GroupId = task.GroupId,
Message = new()
{
new MessageItem()
{
Type = "text",
Data = new()
{
Text = $"【灵田结算通知】\r\n该结算奖励了"
}
},
new MessageItem()
{
Type = "at",
Data = new()
{
QQ = task.UserId
}
}
}
};
_ = RobotAPI.SendGroupText(request);
RedisHelper.Client.Del(key);
}
}
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
}
}
}

@ -0,0 +1,55 @@
using Furion.Logging;
using Microsoft.Extensions.Hosting;
using NapCatRobotClient.Core.RobotAPI.Dto.Request;
namespace NapCatRobotClient.Service.BackGround
{
/// <summary>
/// 秘境结算通知
/// </summary>
public class MijingBackGroundWorker : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
string[] keys = RedisHelper.Client.Keys($"{RedisPrefix.MiJingKey}*");
foreach (string key in keys)
{
string json = RedisHelper.Client.Get(key);
if (string.IsNullOrEmpty(json)) continue;
TaskDetailInfo task = JsonConvert.DeserializeObject<TaskDetailInfo>(json);
if (task.TriggerTime <= DateTime.Now)
{
GroupSendMessageRequest request = new ()
{
GroupId = task.GroupId,
Message =
[
new MessageItem
{
Type = "text",
Data = new() { Text = $"【秘境结算通知】\r\n探索已完成该结算奖励了{task.Minutes} 分钟)" }
},
new MessageItem
{
Type = "at",
Data = new() { QQ = task.UserId }
}
]
};
_ = RobotAPI.SendGroupText(request);
RedisHelper.Client.Del(key);
}
}
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
}
}
}

@ -0,0 +1,28 @@
namespace NapCatRobotClient.Service.Group.Dto
{
/// <summary>
/// 任务处理信息
/// </summary>
public class TaskDetailInfo
{
/// <summary>
/// 群ID
/// </summary>
public string GroupId { get; set; }
/// <summary>
/// 用户ID
/// </summary>
public string UserId { get; set; }
/// <summary>
/// 结束时间
/// </summary>
public DateTime TriggerTime { get; set; }
/// <summary>
/// 用时
/// </summary>
public double? Minutes { get; set; }
}
}

@ -7,12 +7,12 @@ namespace NapCatRobotClient.Service.Group.Service
/// <summary> /// <summary>
/// 修仙大群 /// 修仙大群
/// </summary> /// </summary>
private static List<string> XiuXianGroup = App.GetConfig<List<string>>("QQConfig:XiuXianGroupId"); private List<string> XiuXianGroup = App.GetConfig<List<string>>("QQConfig:XiuXianGroupId");
/// <summary> /// <summary>
/// 自动做任务群 /// 自动做任务群
/// </summary> /// </summary>
private static List<string> AutoTaskGroup = App.GetConfig<List<string>>("QQConfig:AutoTaskGroupId"); private List<string> AutoTaskGroup = App.GetConfig<List<string>>("QQConfig:AutoTaskGroupId");
/// <summary> /// <summary>
/// 处理群消息 /// 处理群消息

@ -25,11 +25,49 @@ namespace NapCatRobotClient.Service.Group.TextProcess
} }
string groupMsg = JArray.Parse(json["message"].ToString()).FirstOrDefault(o => o["type"].ToString() == "text" string groupMsg = JArray.Parse(json["message"].ToString()).FirstOrDefault(o => o["type"].ToString() == "text"
&& !string.IsNullOrWhiteSpace(o["data"]["text"].ToString()) && (o["data"]["text"].ToString().Contains("道友本次采集成果") || o["data"]["text"].ToString().Contains("道友成功收获药材")))?["data"]?["text"]?.ToString(); && !string.IsNullOrWhiteSpace(o["data"]["text"].ToString()) && (o["data"]["text"].ToString().Contains("道友的灵田还不能收取") || o["data"]["text"].ToString().Contains("道友本次采集成果") || o["data"]["text"].ToString().Contains("道友成功收获药材")))?["data"]?["text"]?.ToString();
if (string.IsNullOrWhiteSpace(groupMsg)) return false; if (string.IsNullOrWhiteSpace(groupMsg)) return false;
List<GoodsInfo> goods = new(); List<GoodsInfo> goods = new();
if (groupMsg.Contains("道友本次采集成果")) if (groupMsg.Contains("道友的灵田还不能收取"))
{
double ts = ConvertLastTime(groupMsg);
if (ts > 0)
{
ts += 0.01;
var atData = JArray.Parse(json["message"].ToString()).FirstOrDefault(o => o["type"].ToString() == "at");
if (atData is not null)
{
string at = atData["data"]["qq"].ToString();
ScheduleNextNotify(groupId, at, ts);
GroupSendMessageRequest request = new()
{
GroupId = groupId,
Message = new()
{
new MessageItem()
{
Type = "text",
Data = new()
{
Text = $"灵田结算预计在 【{DateTime.Now.AddHours(ts):yyyy-MM-dd HH:mm:ss}】 提醒您收取"
}
},
new MessageItem()
{
Type = "at",
Data = new()
{
QQ = at
}
}
}
};
await RobotAPI.SendGroupText(request);
}
}
}
else if (groupMsg.Contains("道友本次采集成果"))
{ {
goods = await NewCmd(groupMsg); goods = await NewCmd(groupMsg);
} }
@ -91,7 +129,7 @@ namespace NapCatRobotClient.Service.Group.TextProcess
var atData = JArray.Parse(json["message"].ToString()).FirstOrDefault(o => o["type"].ToString() == "at"); var atData = JArray.Parse(json["message"].ToString()).FirstOrDefault(o => o["type"].ToString() == "at");
if (atData is not null) if (atData is not null)
{ {
ScheduleNextNotify(groupId, atData["data"]["qq"].ToString()); ScheduleNextNotify(groupId, atData["data"]["qq"].ToString(), 47.01);
} }
} }
@ -104,6 +142,17 @@ namespace NapCatRobotClient.Service.Group.TextProcess
return await Task.FromResult(true); return await Task.FromResult(true);
} }
private static double ConvertLastTime(string text)
{
Match match = Regex.Match(text, @"([\d\.]+)\s*小时");
double hours = 0;
if (match.Success)
{
hours = double.Parse(match.Groups[1].Value);
}
return hours;
}
private static async Task<List<GoodsInfo>> OldCmd(string message) private static async Task<List<GoodsInfo>> OldCmd(string message)
{ {
List<GoodsInfo> goodsInfos = new(); List<GoodsInfo> goodsInfos = new();
@ -134,41 +183,19 @@ namespace NapCatRobotClient.Service.Group.TextProcess
return await Task.FromResult(goodsInfos); return await Task.FromResult(goodsInfos);
} }
private static void ScheduleNextNotify(string groupId, string userId) private static void ScheduleNextNotify(string groupId, string userId, double hours)
{ {
TimeSpan delay = TimeSpan.FromHours(47.01); DateTime now = DateTime.Now.AddHours(hours);
TimeSpan delay = TimeSpan.FromHours(hours + 0.09);
Log.Information($@"{DateTime.Now:yyyy-MM-dd HH:mm:ss} {userId} 触发下次灵田结算通知 ");
_ = Task.Run(async () => Log.Information($@"{DateTime.Now:yyyy-MM-dd HH:mm:ss} {userId} 触发下次灵田结算通知 结算时间:{now} ");
{
await Task.Delay(delay);
GroupSendMessageRequest request = new() RedisHelper.Client.Set($"{RedisPrefix.LingTianKey}{groupId}:{userId}", new TaskDetailInfo()
{ {
GroupId = groupId, GroupId = groupId,
Message = new() UserId = userId,
{ TriggerTime = now
new MessageItem() }, delay);
{
Type = "text",
Data = new()
{
Text = $"【灵田结算通知】\r\n该结算奖励了"
}
},
new MessageItem()
{
Type = "at",
Data = new()
{
QQ = userId
}
}
}
};
await RobotAPI.SendGroupText(request);
});
} }
} }
} }

@ -1,5 +1,4 @@
using Furion.Logging; using Furion.Logging;
using NapCatRobotClient.Core.RobotAPI.Dto.Request;
using System.Globalization; using System.Globalization;
namespace NapCatRobotClient.Service.Group.TextProcess namespace NapCatRobotClient.Service.Group.TextProcess
@ -51,40 +50,17 @@ namespace NapCatRobotClient.Service.Group.TextProcess
private static void ScheduleReminder(string groupId, string userId, double minutes) private static void ScheduleReminder(string groupId, string userId, double minutes)
{ {
DateTime now = DateTime.Now; DateTime now = DateTime.Now.AddMinutes(minutes);
TimeSpan delay = TimeSpan.FromMinutes(minutes); Log.Information($@"{now:yyyy-MM-dd HH:mm:ss} {userId} 触发秘境通知 {minutes}分钟 结束时间: {now:yyyy-MM-dd HH:mm:ss}");
Log.Information($@"{now:yyyy-MM-dd HH:mm:ss} {userId} 触发秘境通知 {minutes}分钟 结束时间: {now.AddMinutes(minutes):yyyy-MM-dd HH:mm:ss}"); RedisHelper.Client.Set($"{RedisPrefix.MiJingKey}{groupId}:{userId}", new TaskDetailInfo()
_ = Task.Run(async () =>
{
await Task.Delay(delay);
GroupSendMessageRequest request = new()
{ {
GroupId = groupId, GroupId = groupId,
Message = new() Minutes = minutes,
{ UserId = userId,
new MessageItem() TriggerTime = now
{ }, Convert.ToInt32((minutes + 3) * 60));
Type = "text",
Data = new()
{
Text = $"【秘境结算通知】\r\n探索已完成该结算奖励了{minutes} 分钟)"
}
},
new MessageItem()
{
Type = "at",
Data = new()
{
QQ = userId
}
}
}
};
await RobotAPI.SendGroupText(request);
});
} }
private static double ParseMinutes(string content) private static double ParseMinutes(string content)

Loading…
Cancel
Save