public static void GuildBattleResponse(object Sender, CQGroupMessageEventArgs GBattleEventArgs, PCRGuildCmdType commandType) //功能响应 { if (GBattleEventArgs == null) { throw new ArgumentNullException(nameof(GBattleEventArgs)); } Group qqGroup = GBattleEventArgs.FromGroup; QQ senderQQ = GBattleEventArgs.FromQQ; GroupMemberInfo memberInfo = GBattleEventArgs.CQApi.GetGroupMemberInfo(qqGroup.Id, senderQQ.Id); //index=0为命令本身,其余为参数 string[] commandArgs = GBattleEventArgs.Message.Text.Split(' '); //数据库实例 GuildBattleMgrDBHelper guildBattleDB = new GuildBattleMgrDBHelper(Sender, GBattleEventArgs); //查找是否存在这个公会 if (!guildBattleDB.GuildExists()) { ConsoleLog.Debug("GuildExists", "guild not found"); qqGroup.SendGroupMessage(CQApi.CQCode_At(senderQQ.Id), "\r\n此群未被登记为公会", "\r\n请使用以下指令创建公会", $"\r\n{PCRGuildHandle.GetCommandHelp(commandType)}"); return; } //TODO 自动更新boss数据 switch (commandType) { case PCRGuildCmdType.BattleStart: //检查执行者权限 if (memberInfo.MemberType == QQGroupMemberType.Member) { //执行者为普通群员时拒绝执行指令 qqGroup.SendGroupMessage(CQApi.CQCode_At(senderQQ.Id), "此指令只允许管理者执行"); ConsoleLog.Warning($"会战[群:{qqGroup.Id}]", $"群成员{memberInfo.Nick}正在尝试执行指令{commandType}"); return; } ConsoleLog.Info($"会战[群:{qqGroup.Id}]", $"开始处理指令{commandType}"); int result = guildBattleDB.StartBattle(); //判断返回值 switch (result) { case -1: //已经执行过开始命令 qqGroup.SendGroupMessage(CQApi.CQCode_At(senderQQ.Id), "\r\n出刀统计已经开始了嗷", "\r\n请检查是否未结束上期会战的出刀统计"); break; case 0: qqGroup.SendGroupMessage(CQApi.CQCode_AtAll(), "\r\n新的一期会战开始啦!"); break; default: qqGroup.SendGroupMessage(CQApi.CQCode_At(senderQQ.Id), "\r\nERROR", "\r\n遇到未知错误,请联系当前机器人维护者"); break; } break; default: throw new NotImplementedException(); } }
public virtual void ResetAnimations() { ConsoleLog.Debug("reset_animations not enabled at this level"); }
/// <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 }
/// <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); }
protected virtual void ChatInputHandler(object sender, ChatEventArgs e) { ConsoleLog.Debug("ChatInputHandler proc not overridden"); }
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="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)}"); } }
protected virtual void SitHandler(object sender, AvatarSitResponseEventArgs e) { ConsoleLog.Debug("SitHandler proc not overridden"); }
protected virtual void MessageHandler(object sender, InstantMessageEventArgs e) { ConsoleLog.Debug("MessageHandler proc not overridden"); }
protected virtual void PermissionsHandler(object sender, ScriptQuestionEventArgs e) { ConsoleLog.Debug("PermissionsHandler proc not overridden"); }
protected virtual void AvatarAnimationHandler(object sender, AvatarAnimationEventArgs e) { ConsoleLog.Debug("AvatarAnimationHandler proc not overridden"); }
//private async Task selectStaticDescription() //{ // await JSRuntime._selectDescription("forecast-page"); //} private async Task getSettings() { logger.Debug($"CALLED"); _effectiveParams = await EffectiveParams.CreateByGettingUserSettings(JSRuntime, dailyData); }
static async void _GetIllustDetail(int id, Action <object[]> Reply, Action <object[]> SendMessage, bool slient = false) { try { var detail = await Illust.Get(id); if (detail == null) { if (!slient) { Reply?.Invoke(new object[] { $"数据(pid:{id})获取失败,请稍后再试" }); } return; } ArrayList msg = new(); if (detail.IsUgoira) { var ugoira = await detail.GetUgoira(); if (ugoira == null) { if (!slient) { Reply?.Invoke(new object[] { $"动图数据(pid:{id})获取失败" }); } } else { if (!slient) { Reply?.Invoke(new object[] { $"动图数据(pid:{id})获取成功,正在进行压缩..." }); } var img = await ugoira.LimitGifScale(500, 500); var file = await img.SaveGifToTempFile(); msg.Add(CQCode.CQImage(file)); } } else { foreach (var img in detail.Images) { var cache = await DownloadManager.GetCache(img.Medium); if (string.IsNullOrEmpty(cache)) { var url = ImageUrls.ToPixivCat(img.Medium); cache = await DownloadManager.GetCache(url); if (string.IsNullOrEmpty(cache)) { cache = await DownloadManager.Download(url); if (string.IsNullOrEmpty(cache)) { cache = await DownloadManager.Download(img.Medium, detail.Url); if (string.IsNullOrEmpty(cache)) { msg.Add("[图像缓存失败]"); continue; } } } } ImageUtils.LimitImageScale(cache, 1500, 1500); msg.Add(CQCode.CQImage(cache)); } } msg.Add(detail.ToString()); SendMessage?.Invoke(msg.ToArray()); } catch (Exception ex) { ConsoleLog.Debug("QQ Command - Pixiv", ex.GetFormatString(true)); if (!slient) { Reply?.Invoke(new object[] { $"处理作品(pid:{id})时发生异常错误,任务已终止" }); } } }
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="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); } }
protected JsonConfig process_prop(JsonConfig reply, string arg, string arg_value_default) { string arg_type = GetCommandArgTypes(arg).First(); if (arg_type != "") { if (arg_value_default != null) { Type Dtype = reply.GetType(); PropertyInfo prop = Dtype.GetProperty(arg, BindingFlags.Public | BindingFlags.Instance); if (prop != null) { if (prop.CanWrite == true) { if (arg_type == "Number") { if (int.TryParse(arg_value_default, out int result) == true) { prop.SetValue(reply, result, null); } } else if (arg_type == "Text") { prop.SetValue(reply, arg_value_default, null); } else if (arg_type == "True|False") { if (bool.TryParse(arg_value_default, out bool result) == true) { prop.SetValue(reply, result, null); } } else if (arg_type == "Collection") { prop.SetValue(reply, arg_value_default.Split(','), null); } else if (arg_type == "BigNumber") { if (ulong.TryParse(arg_value_default, out ulong result) == true) { prop.SetValue(reply, result, null); } } else { ConsoleLog.Debug("unsupported arg_type: " + arg_type + " for " + arg + ""); } } else { ConsoleLog.Warn("Unable to write to " + arg + ""); } } else { ConsoleLog.Crit("unknown prop " + arg + ""); } } } else { ConsoleLog.Debug("unknown arg_type for " + arg + ""); } return(reply); }
/// <summary> /// 通知事件处理和分发 /// </summary> /// <param name="messageJson">消息</param> /// <param name="connection">连接GUID</param> private async void NoticeAdapter(JObject messageJson, Guid connection) { switch (GetNoticeType(messageJson)) { //群文件上传 case "group_upload": ApiFileUploadEventArgs fileUpload = messageJson.ToObject <ApiFileUploadEventArgs>(); if (fileUpload == null) { break; } ConsoleLog.Debug("Sora", $"Group notice[Upload file] file[{fileUpload.Upload.Name}] from group[{fileUpload.GroupId}({fileUpload.UserId})]"); //执行回调函数 if (OnFileUpload == null) { break; } await OnFileUpload(typeof(EventInterface), new FileUploadEventArgs(connection, "group_upload", fileUpload)); break; //群管理员变动 case "group_admin": ApiAdminChangeEventArgs adminChange = messageJson.ToObject <ApiAdminChangeEventArgs>(); if (adminChange == null) { break; } ConsoleLog.Debug("Sora", $"Group amdin change[{adminChange.SubType}] from group[{adminChange.GroupId}] by[{adminChange.UserId}]"); //执行回调函数 if (OnGroupAdminChange == null) { break; } await OnGroupAdminChange(typeof(EventInterface), new GroupAdminChangeEventArgs(connection, "group_upload", adminChange)); break; //群成员变动 case "group_decrease": case "group_increase": ApiGroupMemberChangeEventArgs groupMemberChange = messageJson.ToObject <ApiGroupMemberChangeEventArgs>(); if (groupMemberChange == null) { break; } ConsoleLog.Debug("Sora", $"{groupMemberChange.NoticeType} type[{groupMemberChange.SubType}] member {groupMemberChange.GroupId}[{groupMemberChange.UserId}]"); //执行回调函数 if (OnGroupMemberChange == null) { break; } await OnGroupMemberChange(typeof(EventInterface), new GroupMemberChangeEventArgs(connection, "group_member_change", groupMemberChange)); break; //群禁言 case "group_ban": ApiGroupMuteEventArgs groupMute = messageJson.ToObject <ApiGroupMuteEventArgs>(); if (groupMute == null) { break; } ConsoleLog.Debug("Sora", $"Group[{groupMute.GroupId}] {groupMute.ActionType} member[{groupMute.UserId}]{groupMute.Duration}"); //执行回调函数 if (OnGroupMemberMute == null) { break; } await OnGroupMemberMute(typeof(EventInterface), new GroupMuteEventArgs(connection, "group_ban", groupMute)); break; //好友添加 case "friend_add": ApiFriendAddEventArgs friendAdd = messageJson.ToObject <ApiFriendAddEventArgs>(); if (friendAdd == null) { break; } ConsoleLog.Debug("Sora", $"Friend add user[{friendAdd.UserId}]"); //执行回调函数 if (OnFriendAdd == null) { break; } await OnFriendAdd(typeof(EventInterface), new FriendAddEventArgs(connection, "friend_add", friendAdd)); break; //群消息撤回 case "group_recall": ApiGroupRecallEventArgs groupRecall = messageJson.ToObject <ApiGroupRecallEventArgs>(); if (groupRecall == null) { break; } ConsoleLog.Debug("Sora", $"Group[{groupRecall.GroupId}] recall by [{groupRecall.OperatorId}],msg id={groupRecall.MessageId} sender={groupRecall.UserId}"); //执行回调函数 if (OnGroupRecall == null) { break; } await OnGroupRecall(typeof(EventInterface), new GroupRecallEventArgs(connection, "group_recall", groupRecall)); break; //好友消息撤回 case "friend_recall": ApiFriendRecallEventArgs friendRecall = messageJson.ToObject <ApiFriendRecallEventArgs>(); if (friendRecall == null) { break; } ConsoleLog.Debug("Sora", $"Friend[{friendRecall.UserId}] recall msg id={friendRecall.MessageId}"); //执行回调函数 if (OnFriendRecall == null) { break; } await OnFriendRecall(typeof(EventInterface), new FriendRecallEventArgs(connection, "friend_recall", friendRecall)); break; //群名片变更 //此事件仅在Go上存在 case "group_card": ApiGroupCardUpdateEventArgs groupCardUpdate = messageJson.ToObject <ApiGroupCardUpdateEventArgs>(); if (groupCardUpdate == null) { break; } ConsoleLog.Debug("Sora", $"Group[{groupCardUpdate.GroupId}] member[{groupCardUpdate.UserId}] card update [{groupCardUpdate.OldCard} => {groupCardUpdate.NewCard}]"); if (OnGroupCardUpdate == null) { break; } await OnGroupCardUpdate(typeof(EventInterface), new GroupCardUpdateEventArgs(connection, "group_card", groupCardUpdate)); break; case "offline_file": ApiOfflineFileEventArgs offlineFile = messageJson.ToObject <ApiOfflineFileEventArgs>(); if (offlineFile == null) { break; } ConsoleLog.Debug("Sora", $"Get offline file from[{offlineFile.UserId}] file name = {offlineFile.Info.Name}"); if (OnOfflineFileEvent == null) { break; } await OnOfflineFileEvent(typeof(EventInterface), new OfflineFileEventArgs(connection, "offline_file", offlineFile)); break; //通知类事件 case "notify": switch (GetNotifyType(messageJson)) { case "poke": //戳一戳 ApiPokeOrLuckyEventArgs pokeEvent = messageJson.ToObject <ApiPokeOrLuckyEventArgs>(); if (pokeEvent == null) { break; } ConsoleLog.Debug("Sora", $"Group[{pokeEvent.GroupId}] poke from [{pokeEvent.UserId}] to [{pokeEvent.TargetId}]"); if (OnGroupPoke == null) { break; } await OnGroupPoke(typeof(EventInterface), new GroupPokeEventArgs(connection, "poke", pokeEvent)); break; case "lucky_king": //运气王 ApiPokeOrLuckyEventArgs luckyEvent = messageJson.ToObject <ApiPokeOrLuckyEventArgs>(); if (luckyEvent == null) { break; } ConsoleLog.Debug("Sora", $"Group[{luckyEvent.GroupId}] lucky king user[{luckyEvent.TargetId}]"); if (OnLuckyKingEvent == null) { break; } await OnLuckyKingEvent(typeof(EventInterface), new LuckyKingEventArgs(connection, "lucky_king", luckyEvent)); break; case "honor": ApiHonorEventArgs honorEvent = messageJson.ToObject <ApiHonorEventArgs>(); if (honorEvent == null) { break; } ConsoleLog.Debug("Sora", $"Group[{honorEvent.GroupId}] member honor change [{honorEvent.HonorType}]"); if (OnHonorEvent == null) { break; } await OnHonorEvent(typeof(EventInterface), new HonorEventArgs(connection, "honor", honorEvent)); break; default: ConsoleLog.Warning("Sora", $"未知Notify事件类型[{GetNotifyType(messageJson)}]"); break; } break; default: ConsoleLog.Debug("Sora", $"unknown notice \n{messageJson}"); ConsoleLog.Warning("Sora", $"接收到未知事件[{GetNoticeType(messageJson)}]"); break; } }
protected JsonConfig MakeDefault() { string[] args = this.GetCommandsList(); JsonConfig reply = new JsonConfig(); foreach (string arg in args) { string arg_type = GetCommandArgTypes(arg).First(); string arg_value_default = null; if (arg_type != "") { string[] ArgHints = GetCommandArgHints(arg); if (ArgHints.Length > 0) { arg_value_default = ArgHints[0]; arg_value_default = arg_value_default.Replace("[", ""); arg_value_default = arg_value_default.Replace("]", ""); arg_value_default = arg_value_default.Replace("\"", ""); } else { ConsoleLog.Debug("[Notice] No args hint found for " + arg + ""); } } if (arg_value_default != null) { Type Dtype = reply.GetType(); PropertyInfo prop = Dtype.GetProperty(arg, BindingFlags.Public | BindingFlags.Instance); if (prop != null) { if (prop.CanWrite == true) { if (arg_type == "Number") { if (int.TryParse(arg_value_default, out int result) == true) { prop.SetValue(reply, result, null); } } else if (arg_type == "Text") { prop.SetValue(reply, arg_value_default, null); } else if (arg_type == "True|False") { if (bool.TryParse(arg_value_default, out bool result) == true) { prop.SetValue(reply, result, null); } } else if (arg_type == "Collection") { prop.SetValue(reply, arg_value_default.Split(','), null); } else if (arg_type == "BigNumber") { if (ulong.TryParse(arg_value_default, out ulong result) == true) { prop.SetValue(reply, result, null); } } else { ConsoleLog.Debug("unknown arg_type: " + arg_type + " for " + arg + ""); } } else { ConsoleLog.Warn("Unable to write to " + arg + ""); } } else { ConsoleLog.Crit("unknown prop " + arg + ""); } } } return(reply); }
/// <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)}"); } }
/// <summary> /// 加入公会 /// </summary> private async void JoinGuild() { //检查公会是否存在 if (DBHelper.GuildExists() != 1) { await SourceGroup.SendGroupMessage("该群未创建公会"); return; } //处理需要加入的成员列表 List <long> joinList = new List <long>(); switch (BotUtils.CheckForLength(CommandArgs, 1)) { case LenType.Illegal: joinList.Add(Sender); break; case LenType.Extra: case LenType.Legitimate: joinList.AddRange(MessageEventArgs.Message.GetAllAtList()); if (joinList.Count == 0) { await SourceGroup.SendGroupMessage("没有At任何成员"); return; } break; } //检查列表中是否有机器人 if (joinList.Any(member => member == MessageEventArgs.LoginUid)) { joinList.Remove(MessageEventArgs.LoginUid); await SourceGroup.SendGroupMessage("不要在成员中At机器人啊kora"); if (joinList.Count == 0) { return; } } ConsoleLog.Debug("Guild Mgr", $"Get join list count={joinList.Count}"); //从API获取成员信息 ConsoleLog.Debug("Guild Mgr", "Get group member infos"); var(apiStatus, groupMemberList) = await SourceGroup.GetGroupMemberList(); if (apiStatus != APIStatusType.OK) { ConsoleLog.Error("API error", $"api ret code {(int) apiStatus}"); await SourceGroup.SendGroupMessage(CQCode.CQAt(Sender), "\r\nAPI调用错误请重试"); return; } //加入待加入的成员 Dictionary <long, int> databaseRet = new Dictionary <long, int>(); foreach (long member in joinList) { //获取群成员名 string memberName = groupMemberList.Any(memberInfo => memberInfo.UserId == member) ? groupMemberList.Where(memberInfo => memberInfo.UserId == member) .Select(memberInfo => string.IsNullOrEmpty(memberInfo.Card) ? memberInfo.Nick : memberInfo.Card) .First() : "N/A"; //添加成员 databaseRet.Add(member, DBHelper.JoinGuild(member, SourceGroup, memberName)); } //构建格式化信息 List <CQCode> responseMsg = new List <CQCode>(); if (databaseRet.Any(ret => ret.Value == 0))//成员成功加入 { responseMsg.Add(CQCode.CQText("以下成员已加入:")); foreach (long member in databaseRet.Where(member => member.Value == 0) .Select(member => member.Key) .ToList()) { responseMsg.Add(CQCode.CQText("\r\n")); responseMsg.Add(CQCode.CQAt(member)); } } if (databaseRet.Any(ret => ret.Value == 1))//成员已存在 { if (responseMsg.Count != 0) { responseMsg.Add(CQCode.CQText("\r\n")); } responseMsg.Add(CQCode.CQText("以下成员已在公会中,仅更新信息:")); foreach (long member in databaseRet.Where(member => member.Value == 1) .Select(member => member.Key) .ToList()) { responseMsg.Add(CQCode.CQText("\r\n")); responseMsg.Add(CQCode.CQAt(member)); } } if (databaseRet.Any(ret => ret.Value == -1))//数据库错误 { if (responseMsg.Count != 0) { responseMsg.Add(CQCode.CQText("\r\n")); } responseMsg.Add(CQCode.CQText("以下成员在加入时发生错误:")); foreach (long member in databaseRet.Where(member => member.Value == -1) .Select(member => member.Key) .ToList()) { responseMsg.Add(CQCode.CQText("\r\n")); responseMsg.Add(CQCode.CQAt(member)); } } //发送信息 await SourceGroup.SendGroupMessage(responseMsg); }
/// <summary> /// 启动WS服务端 /// </summary> public async ValueTask StartServer() { if (!serverReady) { return; } //检查是否已有服务器被启动 if (serverExitis) { throw new SoraServerIsRuningException(); } //启动服务器 Server.Start(socket => { //接收事件处理 //获取请求头数据 if (!socket.ConnectionInfo.Headers.TryGetValue("X-Self-ID", out string selfId) || //bot UID !socket.ConnectionInfo.Headers.TryGetValue("X-Client-Role", out string role)) //Client Type { return; } //请求路径检查 bool isLost = role switch { "Universal" => !socket.ConnectionInfo.Path.Trim('/').Equals(Config.UniversalPath), _ => true }; if (isLost) { socket.Close(); ConsoleLog.Warning("Sora", $"关闭与未知客户端的连接[{socket.ConnectionInfo.ClientIpAddress}:{socket.ConnectionInfo.ClientPort}],请检查是否设置正确的监听地址"); return; } //打开连接 socket.OnOpen = () => { //获取Token if (socket.ConnectionInfo.Headers.TryGetValue("Authorization", out string token)) { //验证Token if (!token.Equals(this.Config.AccessToken)) { return; } } //向客户端发送Ping socket.SendPing(new byte[] { 1, 2, 5 }); //事件回调 ConnManager.OpenConnection(role, selfId, socket); ConsoleLog.Info("Sora", $"已连接客户端[{socket.ConnectionInfo.ClientIpAddress}:{socket.ConnectionInfo.ClientPort}]"); }; //关闭连接 socket.OnClose = () => { //移除原连接信息 if (ConnManager.ConnectionExitis(socket.ConnectionInfo.Id)) { ConnManager.CloseConnection(role, selfId, socket); } ConsoleLog.Info("Sora", $"客户端连接被关闭[{socket.ConnectionInfo.ClientIpAddress}:{socket.ConnectionInfo.ClientPort}]"); }; //上报接收 socket.OnMessage = (message) => { //处理接收的数据 // ReSharper disable once SimplifyLinqExpressionUseAll if (!ConnManager.ConnectionExitis(socket.ConnectionInfo.Id)) { return; } //进入事件处理和分发 Task.Run(() => { this.Event .Adapter(JObject.Parse(message), socket.ConnectionInfo.Id); }); }; }); ConsoleLog.Info("Sora", $"Sora WebSocket服务器正在运行[{Config.Location}:{Config.Port}]"); ConsoleLog.Info("Sora", $"Sora 服务端框架版本:{Assembly.GetExecutingAssembly().GetName().Version}"); //启动心跳包超时检查计时器 this.HeartBeatTimer = new Timer(ConnManager.HeartBeatCheck, null, new TimeSpan(0, 0, 0, (int)Config.HeartBeatTimeOut, 0), new TimeSpan(0, 0, 0, (int)Config.HeartBeatTimeOut, 0)); serverExitis = true; ConsoleLog.Debug("Sora", "开发交流群:1081190562"); await Task.Delay(-1); }
/// <summary> /// 退会 /// </summary> private async void QuitGuild() { //检查公会是否存在 if (DBHelper.GuildExists() != 1) { await SourceGroup.SendGroupMessage("该群未创建公会"); return; } //获取成员参数 List <long> quitList = new List <long>(); switch (BotUtils.CheckForLength(CommandArgs, 1)) { case LenType.Illegal: quitList.Add(Sender); break; case LenType.Legitimate: //只有单一成员时需判断uid参数 quitList.AddRange(MessageEventArgs.Message.GetAllAtList()); if (quitList.Count == 0) { if (long.TryParse(CommandArgs[1], out long uid)) { quitList.Add(uid); } else { await SourceGroup.SendGroupMessage("没有At任何成员"); return; } } break; case LenType.Extra: quitList.AddRange(MessageEventArgs.Message.GetAllAtList()); if (quitList.Count == 0) { await SourceGroup.SendGroupMessage("没有At任何成员"); return; } break; } //检查列表中是否有机器人 if (quitList.Any(member => member == MessageEventArgs.LoginUid)) { quitList.Remove(MessageEventArgs.LoginUid); await SourceGroup.SendGroupMessage("不要在成员中At机器人啊kora"); if (quitList.Count == 0) { return; } } ConsoleLog.Debug("Guild Mgr", $"Get quit list count={quitList.Count}"); Dictionary <long, int> databaseRet = new Dictionary <long, int>(); //删除退会成员 foreach (long member in quitList) { databaseRet.Add(member, DBHelper.QuitGuild(member, SourceGroup)); } //构建格式化信息 List <CQCode> responseMsg = new List <CQCode>(); if (databaseRet.Any(ret => ret.Value == 0)) { responseMsg.Add(CQCode.CQText("以下成员已退出:")); foreach (long member in databaseRet.Where(member => member.Value == 0) .Select(member => member.Key) .ToList()) { responseMsg.Add(CQCode.CQText("\r\n")); responseMsg.Add(CQCode.CQAt(member)); } } if (databaseRet.Any(ret => ret.Value == 1)) { if (responseMsg.Count != 0) { responseMsg.Add(CQCode.CQText("\r\n")); } responseMsg.Add(CQCode.CQText("以下成员并不在公会中:")); foreach (long member in databaseRet.Where(member => member.Value == 1) .Select(member => member.Key) .ToList()) { responseMsg.Add(CQCode.CQText("\r\n")); responseMsg.Add(CQCode.CQAt(member)); } } if (databaseRet.Any(ret => ret.Value == -1)) { if (responseMsg.Count != 0) { responseMsg.Add(CQCode.CQText("\r\n")); } responseMsg.Add(CQCode.CQText("以下成员在退出时发生错误:")); foreach (long member in databaseRet.Where(member => member.Value == -1) .Select(member => member.Key) .ToList()) { responseMsg.Add(CQCode.CQText("\r\n")); responseMsg.Add(CQCode.CQAt(member)); } } //发送信息 await SourceGroup.SendGroupMessage(responseMsg); }
protected virtual void LoginHandler(object o, LoginProgressEventArgs e) { ConsoleLog.Debug("LoginHandler proc not overridden"); }
protected override void ChatInputHandler(object sender, ChatEventArgs e) { base.ChatInputHandler(sender, e); if (e.Type == ChatType.OwnerSay) { if (allow_RLV == true) { if (e.Message.StartsWith("@") == true) { string message_text = e.Message.Substring(1); bool permissive_allow = true; if (permissive_allow == true) { string[] requested_commands = message_text.Split(','); foreach (string R in requested_commands) { List <string> args = new List <string>(); string command = ""; string[] build = R.Split('='); string[] build2 = build[0].Split(':'); if (build2.Length == 2) { string[] build3 = build2[1].Split(';'); foreach (string build_arg in build3) { args.Add(build_arg); } } command = build2[0]; if (build.Length == 2) { args.Add(build[1]); } if (blacklist_recvim.Contains(command) == false) { if (Notify.ContainsKey("#") == true) { foreach (int channel in Notify["#"]) { Client.Self.Chat("/" + message_text, channel, ChatType.Normal); } } if (Notify.ContainsKey(command) == true) { foreach (int channel in Notify[command]) { Client.Self.Chat("/" + message_text, channel, ChatType.Normal); } } RLVinterface.SetCallerDetails(e.SourceID, e.FromName); RLVinterface.Call(command, args.ToArray()); } else { ConsoleLog.Debug("RLV API -> blacklisted [" + command + "]"); } } } } } } }
protected virtual void CoreCommandLib(UUID fromUUID, bool from_master, string command, string arg, string signing_code) { ConsoleLog.Debug("CoreCommandLib proc not overridden"); }
/// <summary> /// 创建POST方式的HTTP请求 /// </summary> /// <param name="url">URL</param> /// <param name="parameters">PSOT数据</param> /// <param name="userAgent">UA</param> /// <param name="ContentType">内容类型</param> /// <param name="referer">referer</param> /// <param name="timeout">超时</param> /// <param name="cookies">cookies</param> /// <param name="CustomSource">自定义的来源</param> /// <returns>HttpWebResponse</returns> public static HttpWebResponse CreatePostHttpResponse(string url, JObject parameters, ref CookieContainer cookies, string userAgent = "Windows", string ContentType = "application/x-www-form-urlencoded", string referer = null, int timeout = 3000, string CustomSource = null) { Dictionary <String, String> UAList = new Dictionary <String, String> { { "Windows", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36" }, { "IOS", "Mozilla/5.0 (iPhone; CPU iPhone OS 8_3 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12F70 Safari/600.1.4" }, { "Andorid", "Mozilla/5.0 (Linux; Android 4.2.1; M040 Build/JOP40D) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.59 Mobile Safari/537.36" } }; HttpWebRequest request = null; //如果是发送HTTPS请求 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { request = WebRequest.Create(url) as HttpWebRequest; } else { request = WebRequest.Create(url) as HttpWebRequest; } request.Method = "POST"; request.ContentType = ContentType; //设置代理UserAgent和超时 request.UserAgent = UAList[userAgent]; request.Timeout = timeout; request.CookieContainer = cookies; request.Referer = referer ?? string.Empty; //镜华查询在不知道什么时候加了一个这个字段否则就403 if (CustomSource != null) { request.Headers.Set("Custom-Source", CustomSource); } //发送POST数据 if (!(parameters == null || parameters.Count == 0)) { string buffer = JsonConvert.SerializeObject(parameters); byte[] data = Encoding.UTF8.GetBytes(buffer); using (Stream stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } } foreach (string requestHeader in request.Headers) { ConsoleLog.Debug("HTTP-Headers", $"{requestHeader}={request.Headers.GetValues(requestHeader)?[0]}"); } return(request.GetResponse() as HttpWebResponse); }
protected virtual void BotStartHandler() { ConsoleLog.Debug("BotStartHandler proc not overridden"); }
static async Task Main() { //IOC Dependcy.Provider = new ServiceCollection() .AddScoped <ILianChatServices, LianChatServices>() .AddScoped <ILianKeyWordsServices, LianKeyWordsServices>() .AddScoped <ISignLogsServices, SignLogsServices>() .AddScoped <ISignUserServices, SignUserServices>() .AddScoped <ISpeakerServices, SpeakerServices>() .AddScoped <IRebortInterface, RebortService>() .AddScoped <ILianInterface, LianService>() .AddScoped <IModuleInterface, ModuleService>() .BuildServiceProvider(); var Instance = Dependcy.Provider.GetService <IRebortInterface>(); //修改控制台标题 Console.Title = "Qiushui.Bot"; ConsoleLog.Info("Qiushui.Bot初始化", "Qiushui.Bot初始化..."); //初始化配置文件 ConsoleLog.Info("Qiushui.Bot初始化", "初始化服务器全局配置..."); Config config = new(0); config.GlobalConfigFileInit(); config.LoadGlobalConfig(out GlobalConfig globalConfig, false); ConsoleLog.SetLogLevel(Fleck.LogLevel.Info); //显示Log等级 ConsoleLog.Debug("Log Level", globalConfig.LogLevel); //初始化字符编码 Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); //指令匹配初始化 CommandHelper.KeywordResourseInit(); // ConsoleLog.Info("Qiushui.Bot初始化", "初始化指令匹配集..."); ConsoleLog.Info("Qiushui.Bot初始化", "启动反向WebSocket服务器..."); //初始化服务器 SoraWSServer server = new(new ServerConfig { Location = globalConfig.Location, Port = globalConfig.Port, AccessToken = globalConfig.AccessToken, UniversalPath = globalConfig.UniversalPath, ApiPath = globalConfig.ApiPath, EventPath = globalConfig.EventPath, HeartBeatTimeOut = globalConfig.HeartBeatTimeOut, ApiTimeOut = globalConfig.ApiTimeOut }); server.Event.OnClientConnect += Instance.Initalization; server.Event.OnGroupMessage += Instance.GroupMessageParse; server.Event.OnPrivateMessage += Instance.PrivateMessageParse; server.Event.OnGroupPoke += Instance.GroupPokeEventParse; server.Event.OnFriendAdd += Instance.FriendAddParse; server.Event.OnGroupMemberChange += Instance.GroupMemberChangeParse; server.Event.OnGroupRecall += Instance.GroupRecallParse; //更多事件按需处理 //关闭连接事件处理 //server.ConnManager.OnCloseConnectionAsync += TimerEventParse.StopTimer; //server.ConnManager.OnHeartBeatTimeOut += TimerEventParse.StopTimer; await server.StartServer(); }