Skip to content

Commit

Permalink
Merge branch 'universal' into 1224458014
Browse files Browse the repository at this point in the history
  • Loading branch information
TheRealKamisama committed Mar 31, 2023
2 parents 0789bf0 + 5ef7902 commit 62d587d
Show file tree
Hide file tree
Showing 13 changed files with 166 additions and 24 deletions.
5 changes: 4 additions & 1 deletion WFBot/Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public class Config : Configuration<Config>

public string localsha;

public int WMSearchCount = 3;
public int WMSearchCount = 5;

public int WFASearchCount = 5;

Expand All @@ -77,6 +77,9 @@ public class Config : Configuration<Config>
public bool UseKraber = true;
public bool CleanMemoryAfterImageRendering = false;
public bool UseImagePGO = false;
public bool AtAllBroadcast = false;
public string BotMarketUUID = "";
public bool BroadcastToAllGroup = false;

protected override void AfterUpdate()
{
Expand Down
27 changes: 25 additions & 2 deletions WFBot/Features/Common/WFNotificationHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Text;
using HtmlAgilityPack;
using Manganese.Array;
using Microsoft.AspNetCore.Mvc.Formatters;
using WFBot.Features.ImageRendering;
using WFBot.Features.Resource;
using WFBot.Features.Timers;
Expand All @@ -22,7 +23,8 @@ public class WFNotificationHandler
private readonly HashSet<string> sendedFissureSet = new HashSet<string>();
private readonly HashSet<DateTime> sendedStalkerSet = new HashSet<DateTime>();
private readonly HashSet<WarframeUpdate> sendedUpdateSet = new HashSet<WarframeUpdate>();
// 如果你把它改到5分钟以上 sentientoutpost会出错
private readonly HashSet<string> sendedCetusSet = new HashSet<string>();

private WFChineseAPI api => WFResources.WFChineseApi;
public List<WFAlert> AlertPool = new List<WFAlert>();
public List<WFInvasion> InvasionPool = new List<WFInvasion>();
Expand Down Expand Up @@ -68,6 +70,7 @@ private async Task InitWFNotificationAsync()
{
Trace.WriteLine($"WF 通知初始化出错: {e}");
}

}

[CalledByTimer(typeof(NotificationTimer))]
Expand All @@ -93,6 +96,26 @@ public void Update()
}
}

public async Task CheckCetusCycle()
{
if (Config.Instance.Miguel_Platform != MessagePlatform.Kook) return;
// 因为只有Kook可以这么频繁的发通知, 不用担心被封号...

var cetus = await api.GetCetusCycle();
if (cetus.IsDay && !sendedCetusSet.Contains(cetus.ID))
{
var eta = cetus.Expiry - DateTime.Now;
if (eta <= TimeSpan.FromMinutes(10))
{
var sb = new StringBuilder();
sb.AppendLine("距离希图斯的夜晚剩余不足10分钟, 夜灵即将出现.");
var messages = new RichMessages { new TextMessage { Content = sb.ToString() } };
MiguelNetwork.Broadcast(messages);
sendedCetusSet.Add(cetus.ID);
}
}
}

public async Task<List<WarframeUpdate>> GetWarframeUpdates()
{
var result = new List<WarframeUpdate>();
Expand Down Expand Up @@ -184,7 +207,7 @@ private void CheckPersistentEnemies()
var result = sb.ToString().Trim();
if (Config.Instance.EnableImageRendering)
{
AsyncContext.SetCommandIdentifier("WFBot通知");
AsyncContext.SetCommandIdentifier("WFBot通知");
MiguelNetwork.Broadcast(new RichMessages()
{

Expand Down
3 changes: 1 addition & 2 deletions WFBot/Features/ImageRendering/ImageRenderHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -579,8 +579,7 @@ public static Image<Rgba32> GetResource(string path)
var image = new Image<Rgba32>(50,50, new Rgba32(0,0,0));
image.Mutate(x => x.Fill(new Color(new Rgba32(206, 64, 202)), new RectangleF(0,0,25,25)));
image.Mutate(x => x.Fill(new Color(new Rgba32(206, 64, 202)), new RectangleF(25,25,25,25)));
image.Mutate(x => x.DrawText(CreateTextOptions(10), "错误", Color.White));
return RenderText("错误");
return image;
}
Cache[path] = Image.Load<Rgba32>(stream, new PngDecoder());
}
Expand Down
2 changes: 1 addition & 1 deletion WFBot/Features/ImageRendering/RichMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,6 @@ public class ImageMessage : RichMessage
public class AtMessage : RichMessage
{
public bool IsAll { get; set; }
public string QQ { get; set; }
public string UserID { get; set; }
}
}
1 change: 1 addition & 0 deletions WFBot/Features/Resource/WFResources.cs
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,7 @@ private static async Task<WFBotApi> GetWFBotTranslateApi()
var source = IsKraber? "https://wfbot.kraber.top:8888/Resources/TRKS-Team/WFBot_Lexicon@master/" : "https://cdn.jsdelivr.net/gh/TRKS-Team/WFBot_Lexicon@master/";

AddTask(ref api.RSale, "WFBot_Sale.json");
AddTask(ref api.RDict, "WFBot_Dict.json");

if (WFResourcesManager.WFResourceGitHubInfos.All(i => i.Category != nameof(WFTranslator)))
{
Expand Down
28 changes: 28 additions & 0 deletions WFBot/Features/Timers/BotMarketHeartbeatTimer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using GammaLibrary.Extensions;
using Humanizer;
using WFBot.Features.Timers.Base;
using WFBot.Orichalt;
using WFBot.Utils;

namespace WFBot.Features.Timers
{
class BotMarketHeartbeatTimer : WFBotTimer
{
public BotMarketHeartbeatTimer() : base(30.Minutes())
{

}

protected override void Tick()
{
if (Config.Instance.Miguel_Platform == MessagePlatform.Kook && !Config.Instance.BotMarketUUID.IsNullOrEmpty())
{
WebHelper.DownloadStringAsync("http://bot.gekj.net/api/v1/online.bot",
new List<KeyValuePair<string, string>>
{
new("uuid", Config.Instance.BotMarketUUID)
}).Wait();
}
}
}
}
3 changes: 3 additions & 0 deletions WFBot/Features/Utils/WFObjects.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1557,6 +1557,9 @@ public class WFBotApi
{
public Sale[] Sale => RSale.Value;
public WFResource<Sale[]> RSale;

public Dict[] Dict => RDict.Value;
public WFResource<Dict[]> RDict;
}

public class WFApi
Expand Down
6 changes: 3 additions & 3 deletions WFBot/Features/Utils/WFTranslator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public WFTranslator()
private void InitTranslators()
{
dictTranslator.Clear();
foreach (var dict in translateApi.Dict)
foreach (var dict in wfbotApi.Dict)
{
dictTranslator.AddEntry(dict.En, dict.Zh);
searchwordTranslator.Clear();
Expand Down Expand Up @@ -113,8 +113,8 @@ public string GetTranslateResult(string str)

/*var formatedDict = translateApi.Dict.Select(dict => new Dict
{En = dict.En.Format(), Id = dict.Id, Type = dict.Type, Zh = dict.Zh}).ToList();*/
var zhResults = translateApi.Dict.Where(dict => dict.Zh.Format() == str).ToList();
var enResults = translateApi.Dict.Where(dict => dict.En.Format() == str).ToList();
var zhResults = wfbotApi.Dict.Where(dict => dict.Zh.Format() == str).ToList();
var enResults = wfbotApi.Dict.Where(dict => dict.En.Format() == str).ToList();
if (!zhResults.Any() && !enResults.Any())
{
return "并没有查询到任何翻译,请检查输入.";
Expand Down
3 changes: 2 additions & 1 deletion WFBot/Orichalt/KookVerifyServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,9 @@ public void Init()
connected = true;
break;
}
catch (Exception)
catch (Exception e)
{
MiguelNetwork.SendDebugInfo($"Kook验证服务器连接出错: {e}");
}
}
};
Expand Down
66 changes: 57 additions & 9 deletions WFBot/Orichalt/MiguelNetwork.cs
Original file line number Diff line number Diff line change
Expand Up @@ -441,13 +441,18 @@ public static void Broadcast(RichMessages content)
}
Task.Factory.StartNew(async () =>
{
if (Config.Instance.AtAllBroadcast)
{
content.Insert(0, new AtMessage{IsAll = true});
}
var count = 0;
switch (Platform)
{
case MessagePlatform.MiraiHTTP:
case MessagePlatform.MiraiHTTPV1:
case MessagePlatform.OneBot:
foreach (var group in Config.Instance.WFGroupList)
var groups = Config.Instance.BroadcastToAllGroup ? GetAllGroups() : Config.Instance.WFGroupList;
foreach (var group in groups)
{
var sb = new StringBuilder();

Expand Down Expand Up @@ -481,21 +486,51 @@ public static void Broadcast(RichMessages content)
var channels = KookCore.KookClient.Guilds
.Select(g =>
g.TextChannels
.Where(t => t.Id == KookConfig.Instance.NotificationChannelDict[g.Id]))
.Where(t => KookConfig.Instance.NotificationChannelDict.ContainsKey(g.Id) && t.Id == KookConfig.Instance.NotificationChannelDict[g.Id]))
.SelectMany(l => l);
var cb = new CardBuilder();
cb.AddModule(new SectionModuleBuilder { Text = new PlainTextElementBuilder { Content = "[WFBot通知]" } });
cb = await BuildRichMessagesCard(content, cb);
foreach (var channel in channels)
{


// 这特么写的太屎了, 但是我真的想不出别的方法了, 妈的Kook.Net真傻逼啊
// 我找了大概一个小时的文档才弄明白该这么写, Kook.Net的文档也一坨, 我都去查Discord.Net了.
var isAll = content.Any(c => c is AtMessage { IsAll: true });
if (isAll)
{
await channel.SendTextAsync(MentionUtils.PlainTextMentionChannel(channel.Id));
}
await channel.SendCardAsync(cb.Build());



}
break;
}

}, TaskCreationOptions.LongRunning);

}
/// <summary>
/// 获取机器人所在的所有群号
/// </summary>
/// <returns></returns>
public static List<string> GetAllGroups()
{
switch (Platform)
{
case MessagePlatform.OneBot:
return OneBotCore.OneBotClient.GetGroupListAsync().Result.Select(g => g.Id.ToString()).ToList();
case MessagePlatform.MiraiHTTP:
return MiraiHTTPCore.Bot.GetGroupsAsync().Result.Select(g => g.Id).ToList();
case MessagePlatform.MiraiHTTPV1:
return MiraiHTTPV1Core.Mirai.GetGroupListAsync().Result.Select(g => g.Id.ToString()).ToList();
default:
throw new ArgumentOutOfRangeException();
}
}

//
// 以下的方法不应在本类外调用, 通用功能应该调用通用接口
Expand All @@ -511,7 +546,11 @@ private static void OneBotSendToGroup(GroupID group, string msg)
}
private static void OneBotSendToGroup(GroupID group, RichMessages msg)
{
OneBotCore.OneBotClient.SendGroupMessageAsync(group, msg.Select(x => x switch { ImageMessage image => SendingMessage.ByteArrayImage(image.Content), TextMessage t => new SendingMessage(t.Content) }).Aggregate((a, b) => a + b));
OneBotCore.OneBotClient.SendGroupMessageAsync(group, msg.Select(x => x switch {
AtMessage atMessage => atMessage.IsAll ? SendingMessage.AtAll() : SendingMessage.At(atMessage.UserID.ToLong()),
ImageMessage image => SendingMessage.ByteArrayImage(image.Content), TextMessage t => new SendingMessage(t.Content),
_ => new SendingMessage()
}).Aggregate((a, b) => a + b));

}
private static async Task OneBotSendToGroupWithAutoRevoke(GroupID group, string msg)
Expand Down Expand Up @@ -568,7 +607,7 @@ private static void MiraiHTTPSendToGroup(GroupID qq, RichMessages msg)
builder.AtAll();
break;
}
builder.At(at.QQ);
builder.At(at.UserID);
break;
}
}
Expand All @@ -581,10 +620,10 @@ private static void MiraiHTTPSendToGroupWithAutoRevoke(GroupID qq, string msg)
builder.Plain(msg);
if (MiraiConfig.Instance.AutoRevoke)
{
var message = MiraiHTTPCore.Bot.SendGroupMessageAsync(qq.ID, builder.Build()).Result;
var messageId = MiraiHTTPCore.Bot.SendGroupMessageAsync(qq.ID, builder.Build()).Result;
Task.Delay(TimeSpan.FromSeconds(MiraiConfig.Instance.RevokeTimeInSeconds)).ContinueWith(t =>
{
MiraiHTTPCore.Bot.RecallAsync(qq.ID.ToString(), message);
MiraiHTTPCore.Bot.RecallAsync(qq.ID.ToString(), messageId);
});

return;
Expand Down Expand Up @@ -613,7 +652,7 @@ private static void MiraiHTTPSendToGroupWithAutoRevoke(GroupID qq, RichMessages
builder.AtAll();
break;
}
builder.At(at.QQ);
builder.At(at.UserID);
break;
}
}
Expand Down Expand Up @@ -700,9 +739,18 @@ public static async Task<CardBuilder> BuildRichMessagesCard(RichMessages msg, Ca
cb.AddModule(cob);
break;
case TextMessage text:
var sb = new SectionModuleBuilder { Text = new PlainTextElementBuilder { Content = text.Content } };
var sb = new SectionModuleBuilder
{
Text = new PlainTextElementBuilder
{
Content = text.Content
}
};
cb.AddModule(sb);
break;
case AtMessage at:
// 目前@全体消息只在Broadcast那边处理
break;
}
}

Expand All @@ -712,7 +760,7 @@ public static async Task<CardBuilder> BuildRichMessagesCard(RichMessages msg, Ca
public static async Task ReplyKookChannelUser(KookContext context, RichMessages msg)
{
var cb = await BuildRichMessagesCard(msg);
await context.Channel.SendCardAsync(cb.Build(), ephemeralUser: context.Author);
await context.Channel.SendCardAsync(cb.Build());
}
}
}
1 change: 1 addition & 0 deletions WFBot/WFBotCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -605,6 +605,7 @@ private void InitTimer()
AddTimer<NotificationTimer>();
AddTimer<WFResourcesTimer>();
AddTimer<ImageRenderingPGOTimer>();
AddTimer<BotMarketHeartbeatTimer>();

void AddTimer<T>() where T : WFBotTimer
{
Expand Down
17 changes: 16 additions & 1 deletion WFBot/WebUI/Pages/Settings.razor
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,22 @@
</div>
</div>
</div>

<div class="mb-2">
<div class="form-check form-switch">
<input @bind="config.AtAllBroadcast" class="form-check-input" type="checkbox">
<label class="form-check-label">
在所有通知前@全体成员(需要机器人为管理员)
</label>
</div>
</div>
<div class="mb-2">
<div class="form-check form-switch">
<input @bind="config.BroadcastToAllGroup" class="form-check-input" type="checkbox">
<label class="form-check-label">
对机器人加入的所有群都发送通知(将会覆盖下面所填写的群号列表)
</label>
</div>
</div>
<h3 class="my-4">发送通知的群号</h3>

<textarea type="text" @bind="NotifyGroupList" class="form-control my-3" style="min-height: 300px">
Expand Down
28 changes: 24 additions & 4 deletions docs/docker.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,34 @@
```yaml
adapters:
- http
- ws
- ws
debug: false
enableVerify: true
verifyKey: 请修改我 # 修改为和下文对应的一个Token
verifyKey: '请修改我' ## 修改为一个与下文一样的Token
singleMode: false
cacheSize: 4096
persistenceFactory: 'built-in'
adapterSettings: {}
adapterSettings:
ws:
## websocket server 监听的本地地址
## 一般为 localhost 即可, 如果多网卡等情况,自定设置
host: 0.0.0.0

## websocket server 监听的端口
## 与 http server 可以重复, 由于协议与路径不同, 不会产生冲突
port: 8080

reservedSyncId: -1
http:
## http server 监听的本地地址
## 一般为 localhost 即可, 如果多网卡等情况,自定设置
host: 0.0.0.0

## http server 监听的端口
## 与 websocket server 可以重复, 由于协议与路径不同, 不会产生冲突
port: 8080

## 配置跨域, 默认允许来自所有域名
cors: [*]
```
5. 再次运行 `sudo docker-compose run --rm mirai` 观察到以下绿色输出
![](images/QQ%E6%88%AA%E5%9B%BE20220627214408.png)
Expand Down

0 comments on commit 62d587d

Please sign in to comment.