forked from Deleeete/klbot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPLJJModule.cs
More file actions
99 lines (93 loc) · 3.38 KB
/
Copy pathPLJJModule.cs
File metadata and controls
99 lines (93 loc) · 3.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
using klbotlib.Modules.ModuleUtils;
using System.Text.Json.Serialization;
namespace klbotlib.Modules;
/// 图像模块
public class PLJJModule : SingleTypeModule<MessagePlain>
{
private readonly HttpHelper _httpHelper = new();
[JsonInclude]
private readonly int _maxRetryCount = 3;
[JsonInclude]
private readonly List<string> _urlList = [];
[JsonInclude]
private DateTime _lastActivateTime = DateTime.UnixEpoch;
/// <inheritdoc/>
public sealed override bool UseSignature => false;
/// <inheritdoc/>
public sealed override string FriendlyName => "漂亮姐姐模块";
/// <inheritdoc/>
public sealed override string HelpInfo => "发送“早安”触发每日漂亮姐姐图片";
/// <inheritdoc/>
public override async Task<Message?> Processor(MessageContext context, MessagePlain msg)
{
if (msg.Text.Trim() == "早安" && DateTime.Now.Date != _lastActivateTime.Date)
{
_lastActivateTime = DateTime.Now;
await Messaging.ReplyMessage(context, "早安!");
(bool success, string url) = await GetRandomUrl("图片", context, silent: true);
return success ? new MessageImage(url, true) : (Message)$"已重试{_maxRetryCount}次。运气太差,放弃获取";
}
return null;
}
/// <summary>
/// 随机返回一条图库内的URL
/// </summary>
/// <returns>(是否成功,图片URL)</returns>
public async Task<(bool, string)> GetRandomUrl(string enhanceWord, MessageContext originContext, bool silent = false)
{
int trials = 0;
//预检查URL可用性
while (true)
{
int index = Random.Shared.Next(_urlList.Count);
string url = _urlList[index];
if (trials > _maxRetryCount)
return (false, string.Empty);
var urlStatus = await VerifyUrl(url);
switch (urlStatus)
{
case UrlStatus.Ok:
return (true, url);
case UrlStatus.Timeout:
_urlList.RemoveAt(index);
if (!silent)
await Messaging.ReplyMessage(originContext, $"[{trials}]发现缓慢{enhanceWord},已踢出。将重新获取");
trials++;
continue;
case UrlStatus.Error:
_urlList.RemoveAt(index);
if (!silent)
await Messaging.ReplyMessage(originContext, $"[{trials}]发现无效{enhanceWord},已踢出。将重新获取");
trials++;
continue;
default:
throw new Exception($"[{trials}]未知URL status [{urlStatus}]");
}
}
}
private async Task<UrlStatus> VerifyUrl(string url)
{
try
{
var response = await _httpHelper.GetAsync(url);
_ = response.EnsureSuccessStatusCode();
return UrlStatus.Ok;
}
catch (Exception ex)
{
if (ex is TimeoutException)
{
ModuleLog($"URL<{url}>超时,已踢出");
return UrlStatus.Timeout;
}
ModuleLog($"URL<{url}>不可用:{ex.Message}");
return UrlStatus.Error;
}
}
private enum UrlStatus
{
Ok,
Timeout,
Error
}
}