/// <summary> /// 获取指定用户最后一次出刀的类型 /// </summary> /// <param name="uid">uid</param> /// <param name="attackType">出刀类型</param> /// <returns> /// <para>刀号</para> /// <para><see langword="0"/> 没有出刀记录</para> /// <para><see langword="-1"/> 数据库错误</para> /// </returns> public int GetLastAttack(long uid, out AttackType attackType) { try { using SqlSugarClient dbClient = SugarUtils.CreateSqlSugarClient(DBPath); //获取最后一刀的类型出刀者UID var lastAttack = dbClient.Queryable <GuildBattle>() .AS(BattleTableName) .Where(member => member.Uid == uid) .OrderBy(attack => attack.Aid, OrderByType.Desc) .Select(attack => new { lastType = attack.Attack, attack.Aid }) .First(); attackType = lastAttack?.lastType ?? AttackType.Illeage; return(lastAttack?.Aid ?? 0); } catch (Exception e) { ConsoleLog.Error("Database error", ConsoleLog.ErrorLogBuilder(e)); attackType = AttackType.Illeage; return(-1); } }
/// <summary> /// 更新成员状态 /// </summary> /// <param name="uid">成员UID</param> /// <param name="newFlag">新的状态</param> /// <param name="newInfo">新的消息</param> /// <returns> /// <para><see langword="true"/> 写入成功</para> /// <para><see langword="false"/> 数据库错误</para> /// </returns> public bool UpdateMemberStatus(long uid, FlagType newFlag, string newInfo) { try { using SqlSugarClient dbClient = SugarUtils.CreateSqlSugarClient(DBPath); //更新成员信息 MemberInfo memberInfo = new MemberInfo() { Flag = newFlag, Info = newInfo, Time = Utils.GetNowTimeStamp(), }; return(dbClient.Updateable(memberInfo) .UpdateColumns(i => new{ i.Flag, i.Info, i.Time }) .Where(i => i.Gid == GuildEventArgs.SourceGroup.Id && i.Uid == uid) .ExecuteCommandHasChange()); } catch (Exception e) { ConsoleLog.Error("Database error", ConsoleLog.ErrorLogBuilder(e)); return(false); } }
async void RunThread() { bool repeat = true; while (repeat) { try { repeat = false; ConsoleLog.Info("Discord", "开始尝试登陆"); await Client.LoginAsync(TokenType.Bot, _token); await Client.StartAsync(); } catch (Exception e) { repeat = true; ConsoleLog.Error("Discord", ConsoleLog.ErrorLogBuilder(e)); ConsoleLog.Info("Discord", "已断开连接,五秒后将重新登陆"); Thread.Sleep(5000); } } }
/// <summary> /// 下载图片保存到本地 /// </summary> /// <param name="url">目标URL</param> /// <param name="receivePath">接收文件的地址</param> private void DownloadFileFromURL(string url, string receivePath) { try { int progressPercentage = 0; long bytesReceived = 0; DateTime flashTime = DateTime.Now; Console.WriteLine("开始从网络下载文件"); WebClient client = new WebClient(); //文件下载 client.DownloadProgressChanged += (sender, args) => { if (progressPercentage != args.ProgressPercentage) { progressPercentage = args.ProgressPercentage; ConsoleLog .Debug("Download Pic", $"Downloading {args.ProgressPercentage}% " + $"({(args.BytesReceived - bytesReceived) / 1024.0 / (DateTime.Now - flashTime).TotalSeconds}KB/s) "); flashTime = DateTime.Now; bytesReceived = args.BytesReceived; } }; //文件下载完成 client.DownloadFileCompleted += (sender, args) => { ConsoleLog.Info("Hso", "下载数据成功,发送图片"); QQGroup.SendGroupMessage(CQApi.CQCode_Image(receivePath)); ConsoleLog.Debug("file", Path.GetFileName(receivePath)); }; client.DownloadFileAsync(new Uri(url), receivePath); } catch (Exception e) { ConsoleLog.Error("色图下载失败", $"网络下载数据错误\n{ConsoleLog.ErrorLogBuilder(e)}"); } }
/// <summary> /// 查询今日余刀 /// 用于查刀和催刀 /// </summary> /// <returns>余刀表</returns> public Dictionary <long, int> GetTodayAtkCount() { try { using SqlSugarClient dbClient = SugarUtils.CreateSqlSugarClient(DBPath); return(dbClient.Queryable <GuildBattle>() .AS(BattleTableName) .Where(attack => attack.Time > Utils.GetUpdateStamp()) .GroupBy(member => member.Uid) .Select(member => new { member.Uid, times = SqlFunc.AggregateCount(member.Uid) }) .ToList() .ToDictionary(member => member.Uid, member => member.times)); } catch (Exception e) { ConsoleLog.Error("Database error", ConsoleLog.ErrorLogBuilder(e)); return(null); } }
/// <summary> /// 从比利比利源查询排名 /// </summary> private Task BiliWikiRank(string guildName) { string response; //获取响应 try { //获取查询结果 ConsoleLog.Info("NET", $"尝试查询{guildName}会站排名"); QQGroup.SendGroupMessage("查询中..."); response = HTTPUtils .GetHttpResponse($"https://tools-wiki.biligame.com/pcr/getTableInfo?type=search&search={HttpUtility.UrlEncode(guildName)}&page=0"); } catch (Exception e) { QQGroup.SendGroupMessage("哇哦~发生了网络错误,请联系机器人所在服务器管理员"); ConsoleLog.Error("网络发生错误", ConsoleLog.ErrorLogBuilder(e)); //阻止下一步处理 return(Task.CompletedTask); } //JSON数据处理 try { if (string.IsNullOrEmpty(response)) { QQGroup.SendGroupMessage("发生了未知错误,请请向开发者反馈问题"); ConsoleLog.Error("JSON数据读取错误", "从网络获取的文本为空"); return(Task.CompletedTask); } ConsoleLog.Debug("获取JSON成功", response); JArray responseJArray = JArray.Parse(response); //对返回值进行判断 if (responseJArray.Count == 0) { QQGroup.SendGroupMessage("未找到任意公会\n请检查是否查询的错误的公会名或公会排名在70000之后"); ConsoleLog.Info("JSON处理成功", "所查询列表为空"); return(Task.CompletedTask); } if (responseJArray.Count > 1) { QQGroup.SendGroupMessage("查询到多个公会,可能存在重名或关键词错误"); } if (responseJArray[0] is JObject rankData) { string rank = rankData["rank"]?.ToString(); string totalScore = rankData["damage"]?.ToString(); string leaderName = rankData["leader_name"]?.ToString(); ConsoleLog.Info("JSON处理成功", "向用户发送数据"); QQGroup.SendGroupMessage("查询成功!\n" + $"公会:{guildName}\n" + $"排名:{rank}\n" + $"总分数:{totalScore}\n" + $"会长:{leaderName}\n" + "如果查询到的信息有误,有可能关键词错误或公会排名在70000之后"); } } catch (Exception e) { QQGroup.SendGroupMessage("发生了未知错误,请请向开发者反馈问题"); ConsoleLog.Error("JSON数据读取错误", $"从网络获取的JSON格式无法解析{ConsoleLog.ErrorLogBuilder(e)}"); return(Task.CompletedTask); } return(Task.CompletedTask); }
public static async void Login(SoraMessage e) { await Task.Run(() => Library.Bilibili.Bilibili.QRCodeLoginRequest( async(bitmap) => { if (e.IsGroupMessage) { await e.ReplyToOriginal("登录任务已建立,请前往私聊等待登录二维码的发送"); } else { await e.ReplyToOriginal("登录任务已建立,请等待登录二维码的发送"); } var qr = new MemoryImage(bitmap); var path = qr.ToBase64File(); await e.SendPrivateMessage(CQCode.CQImage(path), "\n请使用Bilibili客户端扫码登录"); }, async() => await e.SendPrivateMessage("检测到扫描事件,请在客户端中确认登录"), async(cookie) => { if (int.TryParse(cookie.Split(";").Where(x => x.StartsWith("DedeUserID=")).First()[11..], out var id)) { await e.SendPrivateMessage("登录成功\n数据储存中……"); var data = await Database.FindAsync <UserData>(x => x.QQ == e.Sender.Id || x.Bilibili == id); if (data != null) { data.QQ = e.Sender.Id; data.Bilibili = id; data.BilibiliCookie = cookie; await Database.UpdateAsync(data).ContinueWith(async x => { if (x.Result > 0) { await e.SendPrivateMessage("记录数据已更新"); } else if (x.IsFaulted && x.Exception != null) { await e.SendPrivateMessage(new StringBuilder() .AppendLine("记录数据因异常导致更新失败,错误信息:") .Append(ConsoleLog.ErrorLogBuilder(x.Exception)) .ToString()); } else { await e.SendPrivateMessage("记录数据因未知原因导致更新失败,请稍后重试"); } }); } else { data = new() { QQ = e.Sender.Id, Bilibili = id, BilibiliCookie = cookie }; await Database.InsertAsync(data).ContinueWith(async x => { if (x.Result > 0) { await e.SendPrivateMessage("记录数据已添加"); } else if (x.IsFaulted && x.Exception != null) { await e.SendPrivateMessage(new StringBuilder() .AppendLine("记录数据因异常导致更新失败,错误信息:") .Append(ConsoleLog.ErrorLogBuilder(x.Exception)) .ToString()); } else { await e.SendPrivateMessage("记录数据因未知原因导致更新失败,请稍后重试"); } }); } }
/// <summary> /// <para>从色图源获取色图</para> /// <para>不会支持R18的哦</para> /// </summary> /// <param name="hso">hso配置实例</param> private async Task GiveMeSetu(Hso hso) { string localPicPath; JObject response; ConsoleLog.Debug("源", hso.Source); //本地模式 if (hso.Source == SetuSourceType.Local) { string[] picNames = Directory.GetFiles(IOUtils.GetHsoPath()); if (picNames.Length == 0) { await QQGroup.SendGroupMessage("机器人管理者没有在服务器上塞色图\r\n你去找他要啦!"); return; } Random randFile = new Random(); localPicPath = $"{picNames[randFile.Next(0, picNames.Length - 1)]}"; ConsoleLog.Debug("发送图片", localPicPath); await QQGroup.SendGroupMessage(hso.CardImage ?CQCode.CQCardImage(localPicPath) : CQCode.CQImage(localPicPath)); return; } //网络部分 try { ConsoleLog.Info("NET", "尝试获取色图"); await QQGroup.SendGroupMessage("正在获取色图中..."); string apiKey; string serverUrl; //源切换 switch (hso.Source) { case SetuSourceType.Mix: Random randSource = new Random(); if (randSource.Next(1, 100) > 50) { serverUrl = "https://api.lolicon.app/setu/"; apiKey = hso.LoliconApiKey ?? string.Empty; } else { serverUrl = "https://api.yukari.one/setu/"; apiKey = hso.YukariApiKey ?? string.Empty; } break; case SetuSourceType.Yukari: serverUrl = "https://api.yukari.one/setu/"; apiKey = hso.YukariApiKey ?? string.Empty; break; case SetuSourceType.Lolicon: serverUrl = "https://api.yukari.one/setu/"; apiKey = hso.YukariApiKey ?? string.Empty; break; default: await QQGroup.SendGroupMessage("发生了未知错误"); ConsoleLog.Error("Hso", "发生了未知错误"); return; } //向服务器发送请求 ReqResponse reqResponse = await Requests.GetAsync(serverUrl, new ReqParams { Timeout = 3000, Params = new Dictionary <string, string> { { "apikey", apiKey } } }); if (reqResponse.StatusCode != HttpStatusCode.OK) { ConsoleLog.Error("Net", $"{serverUrl} return code {(int)reqResponse.StatusCode}"); await HsoEventArgs.SourceGroup.SendGroupMessage($"哇哦~发生了网络错误[{reqResponse.StatusCode}],请联系机器人所在服务器管理员"); return; } response = reqResponse.Json(); ConsoleLog.Debug("Get Json", response); } catch (Exception e) { //网络错误 await QQGroup.SendGroupMessage("哇哦~发生了网络错误,请联系机器人所在服务器管理员"); ConsoleLog.Error("网络发生错误", ConsoleLog.ErrorLogBuilder(e.InnerException)); return; } //json处理 try { if ((int)response["code"] == 0) { //图片链接 string picUrl = response["data"]?[0]?["url"]?.ToString() ?? ""; ConsoleLog.Debug("获取到图片", picUrl); //本地图片存储路径 localPicPath = $"{IOUtils.GetHsoPath()}/{Path.GetFileName(picUrl)}".Replace('\\', '/'); if (File.Exists(localPicPath)) //检查是否已缓存过图片 { await QQGroup.SendGroupMessage(hso.CardImage ?CQCode.CQCardImage(localPicPath) : CQCode.CQImage(localPicPath)); } else { //文件名处理(mirai发送网络图片时pixivcat会返回403暂时无法使用代理发送图片 //QQGroup.SendGroupMessage(CQApi.Mirai_UrlImage(picUrl)); //检查是否有设置代理 if (!string.IsNullOrEmpty(hso.PximyProxy)) { string[] fileNameArgs = Regex.Split(Path.GetFileName(picUrl), "_p"); StringBuilder proxyUrlBuilder = new StringBuilder(); proxyUrlBuilder.Append(hso.PximyProxy); //图片Pid部分 proxyUrlBuilder.Append(hso.PximyProxy.EndsWith("/") ? $"{fileNameArgs[0]}" : $"/{fileNameArgs[0]}"); //图片Index部分 proxyUrlBuilder.Append(fileNameArgs[1].Split('.')[0].Equals("0") ? string.Empty : $"/{fileNameArgs[1].Split('.')[0]}"); ConsoleLog.Debug("Get Proxy Url", proxyUrlBuilder); DownloadFileFromURL(proxyUrlBuilder.ToString(), localPicPath, hso.UseCache, hso.CardImage); } else { DownloadFileFromURL(picUrl, localPicPath, hso.UseCache, hso.CardImage); } } return; } if (((int)response["code"] == 401 || (int)response["code"] == 429) && hso.Source == SetuSourceType.Lolicon) { ConsoleLog.Warning("API Token 失效", $"code:{response["code"]}"); } else { ConsoleLog.Warning("没有找到图片信息", "服务器拒绝提供信息"); } await QQGroup.SendGroupMessage("哇奧色图不见了\n请联系机器人服务器管理员"); } catch (Exception e) { ConsoleLog.Error("色图下载失败", $"网络下载数据错误\n{ConsoleLog.ErrorLogBuilder(e)}"); } }
/// <summary> /// 下载图片保存到本地 /// </summary> /// <param name="url">目标URL</param> /// <param name="receivePath">接收文件的地址</param> /// <param name="useCache">是否启用本地缓存</param> /// <param name="cardImg">使用装逼大图</param> private void DownloadFileFromURL(string url, string receivePath, bool useCache, bool cardImg) { try { int progressPercentage = 0; long bytesReceived = 0; DateTime flashTime = DateTime.Now; Console.WriteLine(@"开始从网络下载文件"); WebClient client = new WebClient(); //文件下载 client.DownloadProgressChanged += (sender, args) => { if (progressPercentage == args.ProgressPercentage) { return; } progressPercentage = args.ProgressPercentage; ConsoleLog .Debug("Download Pic", $"Downloading {args.ProgressPercentage}% " + $"({(args.BytesReceived - bytesReceived) / 1024.0 / ((DateTime.Now - flashTime).TotalMilliseconds / 1000)}KB/s) "); flashTime = DateTime.Now; bytesReceived = args.BytesReceived; }; //文件下载完成 client.DownloadFileCompleted += async(sender, args) => { ConsoleLog.Info("Hso", "下载数据成功,发送图片"); var(code, _) = await QQGroup.SendGroupMessage(cardImg ?CQCode.CQCardImage(receivePath) : CQCode.CQImage(receivePath)); ConsoleLog.Debug("file", Path.GetFileName(receivePath)); if (code == APIStatusType.OK) { ConsoleLog.Info("Hso", "色图发送成功"); } else { ConsoleLog.Error("Hso", $"色图发送失败 code={(int) code}"); await QQGroup.SendGroupMessage($"哇奧色图不见了\r\n色图发送失败了\r\nAPI ERROR [{code}]"); } //检查是否出现空文件 if (code == APIStatusType.OK || !File.Exists(receivePath)) { return; } FileInfo file = new FileInfo(receivePath); ConsoleLog.Debug("File Size Check", file.Length); if (file.Length != 0) { return; } ConsoleLog.Error("Hso", "色图下载失败"); //删除下载失败的文件 try { file.Delete(); } catch (Exception e) { ConsoleLog.Error("IO", ConsoleLog.ErrorLogBuilder(e)); } }; client.DownloadDataCompleted += async(sender, args) => { ConsoleLog.Info("Hso", "下载数据成功,发送图片"); try { StringBuilder ImgBase64Str = new StringBuilder(); ImgBase64Str.Append("base64://"); ImgBase64Str.Append(Convert.ToBase64String(args.Result)); var(code, _) = await QQGroup.SendGroupMessage(cardImg ?CQCode.CQCardImage(ImgBase64Str.ToString()) : CQCode.CQImage(ImgBase64Str.ToString())); if (code == APIStatusType.OK) { ConsoleLog.Info("Hso", "色图发送成功"); } else { ConsoleLog.Error("Hso", $"色图发送失败 code={(int) code}"); await QQGroup.SendGroupMessage($"哇奧色图不见了\r\n色图发送失败了\r\nAPI ERROR [{code}]"); } ConsoleLog.Debug("base64 length", ImgBase64Str.Length); } catch (Exception e) { Console.WriteLine(e); } }; if (useCache) { client.DownloadFileAsync(new Uri(url), receivePath); } else { client.DownloadDataAsync(new Uri(url)); } } catch (Exception e) { ConsoleLog.Error("色图下载失败", $"网络下载数据错误\n{ConsoleLog.ErrorLogBuilder(e)}"); } }
private static Task GetDynamic(CQApi cqApi, long biliUser, List <long> groupId, SubscriptionDBHelper dbHelper) { string message; Dynamic biliDynamic; //获取动态文本 try { JObject cardData = DynamicAPIs.GetBiliDynamicJson((ulong)biliUser, out CardType cardType); switch (cardType) { //检查动态类型 case CardType.PlainText: PlainTextCard plainTextCard = new PlainTextCard(cardData) { ContentType = ContentType.CQCode }; message = plainTextCard.ToString(); biliDynamic = plainTextCard; break; case CardType.TextAndPic: TextAndPicCard textAndPicCard = new TextAndPicCard(cardData) { ContentType = ContentType.CQCode }; message = textAndPicCard.ToString(); biliDynamic = textAndPicCard; break; default: ConsoleLog.Debug("动态获取", $"ID:{biliUser}的动态获取成功,动态类型未知"); return(Task.CompletedTask); } } catch (Exception e) { ConsoleLog.Error("获取动态更新时发生错误", ConsoleLog.ErrorLogBuilder(e)); return(Task.CompletedTask); } //获取用户信息 UserInfo sender = biliDynamic.GetUserInfo(); ConsoleLog.Info("动态获取", $"{sender.UserName}的动态获取成功"); //检查是否是最新的 List <long> targetGroups = new List <long>(); foreach (long group in groupId) { //检查是否已经发送过消息 if (!dbHelper.IsLatest(group, sender.Uid, biliDynamic.UpdateTime)) { targetGroups.Add(group); } } //没有群需要发送消息 if (targetGroups.Count == 0) { ConsoleLog.Info("动态获取", $"{sender.UserName}的动态已是最新"); return(Task.CompletedTask); } //向未发生消息的群发送消息 string messageToSend = MsgBuilder(sender, message, biliDynamic); foreach (long targetGroup in targetGroups) { ConsoleLog.Info("动态获取", $"向群{targetGroup}发送动态信息"); cqApi.SendGroupMessage(targetGroup, messageToSend); dbHelper.Update(targetGroup, sender.Uid, biliDynamic.UpdateTime); } return(Task.CompletedTask); }
/// <summary> /// <para>从色图源获取色图</para> /// <para>不会支持R18的哦</para> /// </summary> /// <param name="setuSource">源类型</param> /// <param name="loliconToken">lolicon token</param> /// <param name="yukariToken">yukari token</param> private Task GiveMeSetu(SetuSourceType setuSource, string loliconToken = null, string yukariToken = null) { string localPicPath; string response; StringBuilder urlBuilder = new StringBuilder(); ConsoleLog.Debug("源", setuSource); //源选择 switch (setuSource) { //混合源 case SetuSourceType.Mix: Random randSource = new Random(); if (randSource.Next(1, 100) > 50) { urlBuilder.Append("https://api.lolicon.app/setu/"); if (!string.IsNullOrEmpty(loliconToken)) { urlBuilder.Append($"?token={loliconToken}"); } ConsoleLog.Debug("色图源", "Lolicon"); } else { urlBuilder.Append("https://api.yukari.one/setu/"); if (!string.IsNullOrEmpty(yukariToken)) { urlBuilder.Append($"?token={yukariToken}"); } ConsoleLog.Debug("色图源", "Yukari"); } break; //lolicon case SetuSourceType.Lolicon: urlBuilder.Append("https://api.lolicon.app/setu/"); if (!string.IsNullOrEmpty(loliconToken)) { urlBuilder.Append($"?token={loliconToken}"); } ConsoleLog.Debug("色图源", "Lolicon"); break; //Yukari case SetuSourceType.Yukari: urlBuilder.Append("https://api.yukari.one/setu/"); if (!string.IsNullOrEmpty(yukariToken)) { urlBuilder.Append($"?token={yukariToken}"); } ConsoleLog.Debug("色图源", "Yukari"); break; case SetuSourceType.Local: string[] picNames = Directory.GetFiles(IOUtils.GetHsoPath()); Random randFile = new Random(); localPicPath = $"{picNames[randFile.Next(0, picNames.Length - 1)]}"; ConsoleLog.Debug("发送图片", localPicPath); QQGroup.SendGroupMessage(CQApi.CQCode_Image(localPicPath)); return(Task.CompletedTask); } //网络部分 try { ConsoleLog.Info("NET", "尝试获取色图"); QQGroup.SendGroupMessage("正在获取色图中..."); response = HTTPUtils.GetHttpResponse(urlBuilder.ToString()); ConsoleLog.Debug("Get Json", response); if (string.IsNullOrEmpty(response))//没有获取到任何返回 { ConsoleLog.Error("网络错误", "获取到的响应数据为空"); HsoEventArgs.FromGroup.SendGroupMessage("哇哦~发生了网络错误,请联系机器人所在服务器管理员"); return(Task.CompletedTask); } } catch (Exception e) { //网络错误 QQGroup.SendGroupMessage("哇哦~发生了网络错误,请联系机器人所在服务器管理员"); ConsoleLog.Error("网络发生错误", ConsoleLog.ErrorLogBuilder(e)); return(Task.CompletedTask); } //json处理 try { JObject picJson = JObject.Parse(response); if ((int)picJson["code"] == 0) { //图片链接 string picUrl = picJson["data"]?[0]?["url"]?.ToString() ?? ""; ConsoleLog.Debug("获取到图片", picUrl); //本地图片存储路径 localPicPath = $"{IOUtils.GetHsoPath()}/{Path.GetFileName(picUrl)}"; if (File.Exists(localPicPath)) //检查是否已缓存过图片 { QQGroup.SendGroupMessage(CQApi.CQCode_Image(localPicPath)); } else { //文件名处理(mirai发送网络图片时pixivcat会返回403暂时无法使用代理发送图片 //QQGroup.SendGroupMessage(CQApi.Mirai_UrlImage(picUrl)); DownloadFileFromURL(picUrl, localPicPath); } return(Task.CompletedTask); } if (((int)picJson["code"] == 401 || (int)picJson["code"] == 429) && setuSource == SetuSourceType.Lolicon) { ConsoleLog.Warning("API Token 失效", $"code:{picJson["code"]}"); } else { ConsoleLog.Warning("没有找到图片信息", "服务器拒绝提供信息"); } QQGroup.SendGroupMessage("哇奧色图不见了\n请联系机器人服务器管理员"); return(Task.CompletedTask); } catch (Exception e) { ConsoleLog.Error("色图下载失败", $"网络下载数据错误\n{ConsoleLog.ErrorLogBuilder(e)}"); return(Task.CompletedTask); } }
public async Task Login() { var msg = await ReplyAsync("请求已接受,请稍后……"); var dm = await Context.User.GetOrCreateDMChannelAsync(); IUserMessage qr = null; IUserMessage dmmsg = null; Library.Bilibili.Bilibili.QRCodeLoginRequest( async(bitmap) => { using var stream = new MemoryStream(); bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png); stream.Seek(0, SeekOrigin.Begin); qr = await dm.SendFileAsync(stream, "1.jpg"); bitmap.Dispose(); stream.Dispose(); dmmsg = await dm.SendMessageAsync("请在5分钟内使用Bilibili客户端扫描二维码进行登录"); await msg.ModifyAsync(x => x.Content = "登陆事件已建立,请前往私聊继续操作"); }, async() => { await dmmsg.ModifyAsync(x => x.Content = "已检测到扫描事件,请在Bilibili客户端中确认登录"); }, async(cookie) => { await qr?.DeleteAsync(); if (int.TryParse(cookie.Split(";").Where(x => x.StartsWith("DedeUserID=")).First()[11..], out var id)) { var t = await Database.Data.Table <UserData>().ToListAsync(); var data = t.Where(x => x.Discord == Convert.ToInt64(Context.User.Id) || x.Bilibili == id).FirstOrDefault(); if (data != null) { data.Discord = Convert.ToInt64(Context.User.Id); data.Bilibili = id; data.BilibiliCookie = cookie; await Database.Data.UpdateAsync(data).ContinueWith(async x => { if (x.Result > 0) { await dmmsg.ModifyAsync(x => x.Content = ":white_check_mark: 登录成功,用户数据已保存"); } else if (x.IsFaulted && x.Exception != null) { await dmmsg.ModifyAsync(y => y.Content = ":x: " + new StringBuilder() .AppendLine("记录数据因异常导致更新失败,错误信息:") .Append(ConsoleLog.ErrorLogBuilder(x.Exception)) .ToString()); } else { await dmmsg.ModifyAsync(x => x.Content = ":x: 记录数据因未知原因导致更新失败,请稍后重试"); } }); } else { data = new() { Discord = Convert.ToInt64(Context.User.Id), Bilibili = id, BilibiliCookie = cookie }; await Database.Data.InsertAsync(data).ContinueWith(async x => { if (x.Result > 0) { await dmmsg.ModifyAsync(x => x.Content = ":white_check_mark: 登录成功,用户数据已保存"); } else if (x.IsFaulted && x.Exception != null) { await dmmsg.ModifyAsync(y => y.Content = ":x: " + new StringBuilder() .AppendLine("记录数据因异常导致更新失败,错误信息:") .Append(ConsoleLog.ErrorLogBuilder(x.Exception)) .ToString()); } else { await dmmsg.ModifyAsync(x => x.Content = ":x: 记录数据因未知原因导致更新失败,请稍后重试"); } }); } await dmmsg.ModifyAsync(x => x.Content = ":white_check_mark: 登录成功,用户数据已保存"); }
// private async void GetGuildRank(string[] commandArgs) // { // //TODO 修改为可切换源的分发方法 // } /// <summary> /// 从比利比利源查询排名 /// </summary> private async Task <bool> BiliWikiRank(string guildName) { JArray response; //获取响应 try { //获取查询结果 ConsoleLog.Info("NET", $"尝试查询[{guildName}]会站排名"); await QQGroup.SendGroupMessage($"正在查询公会[{guildName}]的排名..."); ReqResponse reqResponse = await Requests.GetAsync("https://tools-wiki.biligame.com/pcr/getTableInfo", new ReqParams { Timeout = 3000, Params = new Dictionary <string, string> { { "type", "search" }, { "search", guildName }, { "page", "0" } } }); //判断响应 if (reqResponse.StatusCode != HttpStatusCode.OK) { await QQGroup.SendGroupMessage($"哇哦~发生了网络错误,请联系机器人所在服务器管理员\r\n{reqResponse.StatusCode}({(int)reqResponse.StatusCode})"); ConsoleLog.Error("网络发生错误", $"Code[{(int)reqResponse.StatusCode}]"); //阻止下一步处理 return(false); } //读取返回值 response = new JArray(reqResponse.Text); ConsoleLog.Info("获取JSON成功", response); } catch (Exception e) { await QQGroup.SendGroupMessage("哇哦~发生了网络错误,请联系机器人所在服务器管理员"); ConsoleLog.Error("网络发生错误", ConsoleLog.ErrorLogBuilder(e)); //阻止下一步处理 return(false); } //JSON数据处理 try { //对返回值进行判断 if (response.Count == 0) { await QQGroup.SendGroupMessage("未找到任意公会\n请检查是否查询的错误的公会名或公会排名在70000之后"); ConsoleLog.Info("JSON处理成功", "所查询列表为空"); return(false); } JArray dataArray = JArray.Parse(response.First?.ToString() ?? "[]"); JObject rankData = dataArray[0].ToObject <JObject>(); if (dataArray.Count > 1) { await QQGroup.SendGroupMessage("查询到多个公会,可能存在重名或关键词错误"); } if (rankData == null || rankData.Count == 0) { await QQGroup.SendGroupMessage("发生了未知错误,请请向开发者反馈问题"); ConsoleLog.Error("JSON数据读取错误", "从网络获取的文本为空"); return(false); } string rank = rankData["rank"]?.ToString(); string totalScore = rankData["damage"]?.ToString(); string leaderName = rankData["leader_name"]?.ToString(); ConsoleLog.Info("JSON处理成功", "向用户发送数据"); await QQGroup.SendGroupMessage("查询成功!\n" + $"公会:{guildName}\n" + $"排名:{rank}\n" + $"总分数:{totalScore}\n" + $"会长:{leaderName}\n" + "如果查询到的信息有误,有可能关键词错误或公会排名在70000之后"); return(true); } catch (Exception e) { await QQGroup.SendGroupMessage("发生了未知错误,请请向开发者反馈问题"); ConsoleLog.Error("JSON数据读取错误", $"从网络获取的JSON格式无法解析{ConsoleLog.ErrorLogBuilder(e)}"); return(false); } }
private static Task GetDynamic(SoraApi soraApi, long biliUser, List <long> groupId, SubscriptionDBHelper dbHelper) { string textMessage; Dynamic biliDynamic; List <string> imgList = new List <string>(); //获取动态文本 try { JObject cardData = DynamicAPIs.GetBiliDynamicJson((ulong)biliUser, out CardType cardType); switch (cardType) { //检查动态类型 case CardType.PlainText: PlainTextCard plainTextCard = new PlainTextCard(cardData); textMessage = plainTextCard.ToString(); biliDynamic = plainTextCard; break; case CardType.TextAndPic: TextAndPicCard textAndPicCard = new TextAndPicCard(cardData); imgList.AddRange(textAndPicCard.ImgList); textMessage = textAndPicCard.ToString(); biliDynamic = textAndPicCard; break; default: ConsoleLog.Warning("动态获取", $"ID:{biliUser}的动态获取成功,动态类型未知"); return(Task.CompletedTask); } } catch (Exception e) { ConsoleLog.Error("获取动态更新时发生错误", ConsoleLog.ErrorLogBuilder(e)); return(Task.CompletedTask); } //获取用户信息 BiliUserInfo sender = biliDynamic.GetUserInfo(); ConsoleLog.Debug("动态获取", $"{sender.UserName}的动态获取成功"); //检查是否是最新的 List <long> targetGroups = new List <long>(); foreach (long group in groupId) { //检查是否已经发送过消息 if (!dbHelper.IsLatest(group, sender.Uid, biliDynamic.UpdateTime)) { targetGroups.Add(group); } } //没有群需要发送消息 if (targetGroups.Count == 0) { ConsoleLog.Debug("动态获取", $"{sender.UserName}的动态已是最新"); return(Task.CompletedTask); } //构建消息 List <CQCode> msgList = new List <CQCode>(); StringBuilder sb = new StringBuilder(); sb.Append("获取到了来自 "); sb.Append(sender.UserName); sb.Append(" 的动态:\r\n"); sb.Append(textMessage); msgList.Add(CQCode.CQText(sb.ToString())); //添加图片 imgList.ForEach(imgUrl => msgList.Add(CQCode.CQImage(imgUrl))); sb.Clear(); sb.Append("\r\n更新时间:"); sb.Append(biliDynamic.UpdateTime); msgList.Add(CQCode.CQText(sb.ToString())); //向未发生消息的群发送消息 foreach (long targetGroup in targetGroups) { ConsoleLog.Info("动态获取", $"获取到{sender.UserName}的最新动态,向群{targetGroup}发送动态信息"); soraApi.SendGroupMessage(targetGroup, msgList); if (!dbHelper.Update(targetGroup, sender.Uid, biliDynamic.UpdateTime)) { ConsoleLog.Error("数据库", "更新动态记录时发生了数据库错误"); } } return(Task.CompletedTask); }
/// <summary> /// <para>从色图源获取色图</para> /// <para>不会支持R18的哦</para> /// </summary> /// <param name="hso">hso配置实例</param> private static async Task GeneaterHso(Hso hso, Sora.Entities.Group group) { string localPicPath; ConsoleLog.Debug("源", hso.Source); //本地模式 if (hso.Source == SetuSourceType.Local) { string[] picNames = Directory.GetFiles(IOUtils.GetHsoPath()); if (picNames.Length == 0) { await group.SendGroupMessage("机器人管理者没有在服务器上塞色图\r\n你去找他要啦!"); return; } Random randFile = new(); localPicPath = $"{picNames[randFile.Next(0, picNames.Length - 1)]}"; ConsoleLog.Debug("发送图片", localPicPath); await group.SendGroupMessage(hso.CardImage ?CQCode.CQCardImage(localPicPath) : CQCode.CQImage(localPicPath)); return; } //网络部分 try { ConsoleLog.Info("NET", "尝试获取色图"); string apiKey; string serverUrl; //源切换 switch (hso.Source) { case SetuSourceType.Mix: Random randSource = new(); if (randSource.Next(1, 100) > 50) { serverUrl = "https://api.lolicon.app/setu/"; apiKey = hso.LoliconApiKey ?? string.Empty; } else { serverUrl = "https://api.yukari.one/setu/"; apiKey = hso.YukariApiKey ?? string.Empty; } break; case SetuSourceType.Yukari: serverUrl = "https://api.yukari.one/setu/"; apiKey = hso.YukariApiKey ?? string.Empty; break; case SetuSourceType.Lolicon: serverUrl = "https://api.yukari.one/setu/"; apiKey = hso.LoliconApiKey ?? string.Empty; break; default: await group.SendGroupMessage("发生了未知错误"); ConsoleLog.Error("Hso", "发生了未知错误"); return; } //向服务器发送请求 var json = await HttpHelper.HttpGetAsync($"{serverUrl}?apikey={apiKey}&r18={hso.R18}"); var result = JsonConvert.DeserializeObject <HsoResponseModel>(json); if (result != null && result.Code == 0) { await group.SendGroupMessage(GetResult(result)); await group.SendGroupMessage(CQCode.CQImage(result.Data.First().Url)); } else { await group.SendGroupMessage("发生了未知错误"); } ConsoleLog.Debug("Get Json", json); } catch (Exception e) { //网络错误 await group.SendGroupMessage("网络错误,暂时没有请求到~"); ConsoleLog.Error("网络发生错误", ConsoleLog.ErrorLogBuilder(e.InnerException)); return; } //https://dotnet.microsoft.com/download/dotnet/current/runtime }