Example #1
0
        public static string GetFriendJson(long robotQQ)
        {
            string url  = "https://qun.qq.com/cgi-bin/qun_mgr/get_friend_list";
            string data = Marshal.PtrToStringAnsi(CQP.Api_GetCookies(robotQQ.ToString())) + Marshal.PtrToStringAnsi(CQP.Api_GetGroupPsKey(robotQQ.ToString()));

            data = data.Trim().Replace(" ", "").Trim();

            if (data.Length < 1)
            {
                return("");
            }
            string[]        ck     = data.Split(';');
            Uri             u      = new Uri(url);
            CookieContainer cookie = new CookieContainer();
            long            bkn    = 1000;

            for (int i = 0; i < ck.Length; i++)
            {
                CqApi  cq  = new CqApi();
                string key = ck[i].Split('=')[0];
                if (key.Trim() == "skey")
                {
                    bkn = cq.GetBkn(ck[i].Split('=')[1]);
                }
                string value = ck[i].Split('=')[1];
                Cookie ckie  = new Cookie(key, value);
                cookie.Add(u, ckie);
            }
            data = "bkn=" + bkn.ToString();
            MessageBox.Show(url + data + cookie.ToString());
            string result = IBoxs.Tool.Http.HttpTool.CPost(url, data, cookie);

            return(data);
        }
Example #2
0
            private static StrangerInfo UpdatePrivateInfo(long id)
            {
                StrangerInfo obj;

                try
                {
                    obj = CqApi.GetStrangerInfo(id.ToString()).Data;
                }
                catch
                {
                    obj = InitInfo();
                }

                return(obj ?? InitInfo());

                StrangerInfo InitInfo()
                {
                    var groupInfoV2 = new StrangerInfo
                    {
                        Nickname = id.ToString(),
                        UserId   = id,
                        Age      = "-1",
                        Sex      = "unknown",
                    };

                    return(groupInfoV2);
                }
            }
Example #3
0
        private CommonMessageResponse AddCount(CommonMessage cm)
        {
            string user = cm.UserId, group = cm.GroupId;

            try
            {
                Logger.Warn("发现好图,存了");
                if (!UserCount.ContainsKey(user))
                {
                    UserCount.Add(user, 2);
                }
                UserCount[user]--;
                if (UserCount[user] != 0)
                {
                    return(new CommonMessageResponse("?", cm, true));
                }
                else
                {
                    UserCount[user] = 2;
                    CqApi.SetGroupBan(group, user, (int)(0.5 * 60 * 60));
                    return(new CommonMessageResponse("?", cm, true));
                }
            }
            finally
            {
                SaveSettings(UserCount);
            }
        }
Example #4
0
 /// <summary>
 /// 刷新计时器
 /// </summary>
 public static void RefreshTimers()
 {
     Debug("刷新计时器");
     Task.Run(() =>
     {
         try
         {
             //释放所有计时器
             foreach (var item in Timers)
             {
                 item.Value.Dispose();
             }
             Timers.Clear();
             foreach (var item in AppConfig.groupConfigs)
             {
                 foreach (var _item in item.Value.GroupTimers.Values.Where(a => a.isOn))
                 {
                     var groupTimer = _item;
                     var key        = $"{item.Key}:{groupTimer.name}";
                     //生成计时器
                     Timers.Add(key, new Timer(
                                    _ =>
                     {
                         CqApi.SendGroupMessage(item.Key, groupTimer.Content);
                     }, null, groupTimer.inteval, groupTimer.inteval
                                    ));
                 }
             }
         }
         catch (Exception e)
         {
             Debug(e.Message, "计时器刷新");
         }
     });
 }
Example #5
0
        public static void SendMessage(CommonMessageResponse resp)
        {
            var msg = (resp.EnableAt && resp.MessageType != MessageType.Private ? new At(resp.UserId) + " " : "") +
                      resp.Message;
            var info = SessionInfo[resp.Identity] == null
                ? $"{resp.Identity.Type}{resp.Identity.Id}"
                : SessionInfo[resp.Identity].Name;
            string status;

            switch (resp.MessageType)
            {
            case MessageType.Group:
                status = CqApi.SendGroupMessageAsync(resp.GroupId, msg).Status;
                break;

            case MessageType.Discuss:
                status = CqApi.SendDiscussMessageAsync(resp.DiscussId, msg).Status;
                break;

            case MessageType.Private:
                status = CqApi.SendPrivateMessageAsync(resp.UserId, msg).Status;
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            Message(string.Format("({0}) 我: {{status: {1}}}\r\n  {2}", info, status, CqCode.DecodeToString(msg)));
        }
Example #6
0
            private static GroupInfoV2 UpdateGroupInfo(long id)
            {
                GroupInfoV2 obj;

                try
                {
                    obj = CqApi.GetGroupInfoV2(id.ToString()).Data;
                }
                catch
                {
                    obj = InitInfo();
                }

                return(obj ?? InitInfo());

                GroupInfoV2 InitInfo()
                {
                    var groupInfoV2 = new GroupInfoV2
                    {
                        GroupName = "群" + id,
                        GroupId   = long.Parse(id.ToString()),
                        Admins    = new List <GroupInfoV2Admins>(),
                    };

                    return(groupInfoV2);
                }
            }
Example #7
0
        private static void UpdateGroupList(int i)
        {
            List <GroupInfo>            list    = CqApi.GetGroupList().Data;
            List <GroupMemberGroupInfo> newList = new List <GroupMemberGroupInfo>();

            foreach (var groupInfo in list)
            {
                try
                {
                    GroupInfoV2 v2 = CqApi.GetGroupInfoV2(groupInfo.GroupId.ToString()).Data;
                    v2.Members = CqApi.GetGroupMemberList(v2.GroupId.ToString()).Data /*.Where(q => q.Role == "member")*/.ToList();
                    if (i % 6 == 0)
                    {
                        foreach (var groupMember in v2.Members)
                        {
                            var user = newList.FirstOrDefault(m => m.UserId == groupMember.UserId);
                            if (user == null)
                            {
                                newList.Add(new GroupMemberGroupInfo(groupMember.UserId));
                            }
                            user = newList.FirstOrDefault(m => m.UserId == groupMember.UserId);
                            if (!user.GroupIdList.Contains(groupInfo.GroupId))
                            {
                                user.GroupIdList.Add(groupInfo.GroupId);
                            }
                        }
                    }
                    CoolQDispatcher.SessionInfo.AddOrUpdateGroup(v2);
                    Logger.Success($"{groupInfo.GroupName} ({groupInfo.GroupId}): 管理{v2.Admins.Count}人, 成员{v2.Members.Count}人.");
                }
                catch (Exception)
                {
                    Logger.Error($"{groupInfo.GroupName} ({groupInfo.GroupId}) 加载失败。");
                }
            }

            string[] oldGroups  = CoolQDispatcher.SessionInfo.Sessions.Select(k => k.Value.Id).ToArray();
            string[] newGroups  = list.Select(k => k.GroupId.ToString()).ToArray();
            string[] noUseGroup = oldGroups.Where(k => !newGroups.Contains(k)).ToArray();
            foreach (var groupId in noUseGroup)
            {
                try
                {
                    CoolQDispatcher.SessionInfo.RemoveGroup(groupId);
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            if (i % 6 == 0)
            {
                CoolQDispatcher.GroupMemberGroupInfo = newList;
            }
        }
Example #8
0
        public override CommonMessageResponse Message_Received(CommonMessage messageObj)
        {
            if (messageObj.GroupId == "133605766")
            {
                return(null);
            }
            if (messageObj.GroupId == null)
            {
                return(null);
            }
            if (messageObj.ArgString.Trim() == "")
            {
                return(new CommonMessageResponse("要睡多少小时呀??", messageObj, true));
            }

            double sleepTime;

            if (SleepTime > 12)
            {
                sleepTime = 12;
            }
            else if (SleepTime < 0.5)
            {
                sleepTime = 0.5;
            }
            else if (SleepTime > 0)
            {
                sleepTime = SleepTime;
            }
            else
            {
                return(new CommonMessageResponse("穿越是不可以的……", messageObj, true));
            }

            DateTime dt = new DateTime();

            dt = dt.AddHours(sleepTime);
            int s = (int)(dt.Ticks / 10000000);

            CqApi.SetGroupBan(messageObj.GroupId, messageObj.UserId, s);
            string msg = "祝你一觉睡到" + DateTime.Now.AddHours(sleepTime).ToString("HH:mm") + " :D";

            return(new CommonMessageResponse(msg, messageObj, true));
        }
Example #9
0
        public override CommonMessageResponse Message_Received(CommonMessage messageObj)
        {
            // 查黄图
            if (messageObj.Group == null || messageObj.GroupId != "133605766")
            {
                return(null);
            }
            var imgList = CqCode.GetImageInfo(messageObj.Message);

            if (imgList == null)
            {
                return(null);
            }
            List <string>    urlList   = new List <string>();
            List <CosObject> cacheList = new List <CosObject>();

            foreach (var item in imgList)
            {
                if (Md5List.Keys.Contains(item.Md5))
                {
                    cacheList.Add(Md5List[item.Md5]);
                }
                else if (item.Size > 1000 * 60) //60KB
                {
                    urlList.Add(item.Url);
                }
            }

            if (urlList.Count == 0 && cacheList.Count == 0)
            {
                return(null);
            }

            Logger.Warn("发现了" + (urlList.Count + cacheList.Count) + "张图");

            CosAnalyzer model = new CosAnalyzer
            {
                result_list = new List <CosObject>()
            };

            if (urlList.Count != 0)
            {
                string str = Newtonsoft.Json.JsonConvert.SerializeObject(new
                {
                    appid    = "1252749411",
                    url_list = urlList.ToArray()
                });

                var abc = WebRequestUtil.CreatePostHttpResponse(
                    "http://service.image.myqcloud.com/detection/porn_detect", str, authorization: Signature.Get());
                var respStr = WebRequestUtil.GetResponseString(abc);

                model = Newtonsoft.Json.JsonConvert.DeserializeObject <CosAnalyzer>(respStr);
            }

            model.result_list.AddRange(cacheList);
            int i = 0;

            foreach (var item in model.result_list)
            {
                if (i < imgList.Length && !Md5List.Keys.Contains(imgList[i].Md5))
                {
                    Md5List.Add(imgList[i].Md5, item);
                }
                i++;

                switch (item.data.result)
                {
                case 0 when item.data.normal_score > item.data.hot_score &&
                    item.data.normal_score > item.data.porn_score && item.data.confidence > 40:
                    continue;

                case 1:
                case 2:
                    CqApi.SetGroupBan(messageObj.GroupId, messageObj.UserId, 24 * 60 * 60);
                    return(new CommonMessageResponse("...", messageObj));

                default:
                    break;
                }

                if (item.data.porn_score >= item.data.hot_score && item.data.porn_score > 65)
                {
                    return(AddCount(messageObj));
                }

                if (item.data.hot_score >= item.data.porn_score && item.data.hot_score > item.data.normal_score &&
                    item.data.hot_score > 80)
                {
                    return(AddCount(messageObj));
                }

                break;
            }

            return(null);

            //if (user != "2241521134") return null;
        }
Example #10
0
        private static void HandleMessage(CommonMessage cm)
        {
            bool cmdFlag   = false;
            long groupId   = Convert.ToInt64(cm.GroupId);
            long userId    = Convert.ToInt64(cm.UserId);
            long discussId = Convert.ToInt64(cm.DiscussId);
            var  type      = cm.MessageType;

            string group, sender, message = cm.Message;

            if (cm.MessageType == MessageType.Private)
            {
                group  = "私聊";
                sender = SessionInfo[cm.Identity].Name;
            }
            else if (cm.MessageType == MessageType.Discuss)
            {
                group  = SessionInfo[cm.Identity].Name;
                sender = cm.UserId;
            }
            else
            {
                var userInfo = SessionInfo[cm.Identity]?.GroupInfo?.Members?.FirstOrDefault(i => i.UserId == userId) ??
                               CqApi.GetGroupMemberInfo(cm.GroupId, cm.UserId).Data;
                group  = SessionInfo?[cm.Identity]?.Name;
                sender = string.IsNullOrEmpty(userInfo.Card)
                    ? userInfo.Nickname
                    : userInfo.Card;
            }

            Message($"({group}) {sender}:\r\n  {CqCode.DecodeToString(message)}");

            if (cm.Message.Substring(0, 1) == CommandFlag)
            {
                if (cm.Message.IndexOf(CommandFlag + "root ", StringComparison.InvariantCulture) == 0)
                {
                    if (cm.UserId != "2241521134")
                    {
                        SendMessage(new CommonMessageResponse(LoliReply.FakeRoot, cm));
                    }
                    else
                    {
                        cm.FullCommand     = cm.Message.Substring(6, cm.Message.Length - 6);
                        cm.PermissionLevel = PermissionLevel.Root;
                        cmdFlag            = true;
                        HandleMessageCmd(cm);
                    }
                }
                else if (message.IndexOf(CommandFlag + "sudo ", StringComparison.InvariantCulture) == 0 &&
                         type == MessageType.Group)
                {
                    if (SessionInfo[cm.Identity].GroupInfo.Admins.Count(q => q.UserId == userId) == 0)
                    {
                        SendMessage(new CommonMessageResponse(LoliReply.FakeAdmin, cm));
                    }
                    else
                    {
                        cm.FullCommand     = message.Substring(6, message.Length - 6);
                        cm.PermissionLevel = PermissionLevel.Admin;
                        cmdFlag            = true;
                        HandleMessageCmd(cm);
                    }
                }
                else
                {
                    // auto
                    if (SessionInfo[cm.Identity].GroupInfo?.Admins.Count(q => q.UserId == userId) != 0)
                    {
                        cm.PermissionLevel = PermissionLevel.Admin;
                    }
                    if (cm.UserId == "2241521134")
                    {
                        cm.PermissionLevel = PermissionLevel.Root;
                    }

                    cm.FullCommand = message.Substring(1, message.Length - 1);
                    cmdFlag        = true;
                    HandleMessageCmd(cm);
                }
            }
            if (!cmdFlag)
            {
                SessionReceived?.Invoke(null, new SessionReceivedEventArgs
                {
                    MessageObj = cm
                });
            }

            HandleMesasgeApp(cm);
            Thread.Sleep(Rnd.Next(MinTime, MaxTime));
        }
Example #11
0
        /// <summary>
        /// 核心识别by sahuang
        /// </summary>
        private void RunDetector(object pathList)
        {
            var list = (List <string>)pathList;

            foreach (var fullPath in list)
            {
                try
                {
                    //Thread.Sleep(6000);
                    //continue;
                    if (_proc != null)
                    {
                        if (!_proc.HasExited)
                        {
                            _proc.Kill();
                        }
                        _proc = null;
                    }

                    _proc = new Process
                    {
                        StartInfo =
                        {
                            FileName  = "python3", // python3 dragon-detection.py "root"
                            Arguments =
                                $"{Path.Combine(Domain.CurrentDirectory, "dragon", "dragon-detection.py")} \"{fullPath}\"",
                            CreateNoWindow         = true,
                            UseShellExecute        = false,
                            WindowStyle            = ProcessWindowStyle.Hidden,
                            RedirectStandardOutput = true, // 重定向标准输出
                            RedirectStandardError  = true  // 重定向错误输出
                                                           //StartInfo.StandardOutputEncoding = Encoding.UTF8;
                        }
                    };

                    _proc.OutputDataReceived += ProcOutputReceived;
                    _proc.ErrorDataReceived  += ProcErrorReceived;

                    Logger.Origin("正在调用中");
                    _proc.Start();
                    _proc.BeginOutputReadLine();
                    _proc.BeginErrorReadLine();

                    _proc.WaitForExit();
                    ProcExited();
                }
                catch (Exception ex)
                {
                    Logger.Exception(ex);
                }
                finally
                {
                    _totalCount--;
                }
            }

            if (_currentCount <= 0)
            {
                return;
            }

            //CqApi.SetGroupBan(group, user, rnd.Next(1, 100 * dragonCount + 1) * 60);
            if (_group != "133605766")
            {
                CqApi.SendGroupMessageAsync(_group, new At(_user) + " 你龙了?");
            }
            else
            {
                CqApi.DeleteMessage(_messageId);
            }
            if (_currentCount <= 1)
            {
                return;
            }
            Thread.Sleep(8000);
            CqApi.SetGroupBan(_group, _user, Rnd.Next(1, 100 * _currentCount + 1) * 60);
            //CqApi.SendGroupMessageAsync(group, "而且有好多张,送你" + dragonCount + "倍套餐!!");
        }
Example #12
0
        public override CommonMessageResponse Message_Received(CommonMessage messageObj)
        {
            string sessionId   = null;
            var    sessionType = MessageType.Private;

            if (messageObj.PermissionLevel != PermissionLevel.Root)
            {
                return(new CommonMessageResponse(LoliReply.RootOnly, messageObj));
            }
            if (Message == null)
            {
                return(new CommonMessageResponse("你要说什么……", messageObj));
            }
            if (GroupId != null && DiscussId != null)
            {
                return(new CommonMessageResponse("不能同时选择群和讨论组……", messageObj));
            }

            string innerMessage = Decode(Message);

            if (UseAllGroup)
            {
                sessionType = MessageType.Group;
                List <GroupInfo> list       = CqApi.GetGroupList().Data;
                List <string>    failedList = new List <string>();
                string           ok         = $"◈◈ {DateTime.Now:M月d日 H:mm}公告 ◈◈{Environment.NewLine}";
                string           msg        = ok + innerMessage;
                if (list?.Count > 0)
                {
                    foreach (var groupInfo in list)
                    {
                        try
                        {
                            sessionId = groupInfo.GroupId.ToString();
                            SendMessage(new CommonMessageResponse(msg, new Identity(sessionId, sessionType)));
                            Thread.Sleep(3000);
                        }
                        catch
                        {
                            failedList.Add($"({groupInfo.GroupId}) {groupInfo.GroupName}");
                        }
                    }
                }
                else
                {
                    return(new CommonMessageResponse("无有效群。", messageObj));
                }

                SaveLogs(msg, "announcement");
                if (failedList.Count == 0)
                {
                    return(new CommonMessageResponse("已成功发送至" + list.Count + "个群。", messageObj));
                }
                else
                {
                    return(new CommonMessageResponse(string.Format("有以下{0}个群未成功发送: {1}{2}", failedList.Count,
                                                                   Environment.NewLine, string.Join(Environment.NewLine, failedList)), messageObj));
                }
            }
            if (DiscussId != null)
            {
                sessionId   = DiscussId;
                sessionType = MessageType.Discuss;
            }
            else if (GroupId != null)
            {
                sessionId   = GroupId;
                sessionType = MessageType.Group;
            }
            if (UserId != null)
            {
                sessionId = UserId;
            }

            if (DiscussId == null && GroupId == null && UserId == null)
            {
                return(new CommonMessageResponse(Decode(messageObj.ArgString), messageObj));
            }

            SendMessage(new CommonMessageResponse(innerMessage, new Identity(sessionId, sessionType)));
            return(null);
        }
Example #13
0
        public override CommonMessageResponse Message_Received(CommonMessage messageObj)
        {
            _cm = messageObj;
            if (List)
            {
                if (_cm.PermissionLevel == PermissionLevel.Root)
                {
                    BllUserRole   bllUserRole = new BllUserRole();
                    List <string> strs        = new List <string>();
                    foreach (var item in _matchList)
                    {
                        var    userInfo = bllUserRole.GetUserRoleByQq(long.Parse(item.Qq))[0];
                        string osuName  = userInfo.CurrentUname;
                        string id       = item.SetId;
                        string status;

                        if (item.TargetQq == null)
                        {
                            status = "等待匹配";
                        }
                        else
                        {
                            var    info = bllUserRole.GetUserRoleByQq(long.Parse(item.TargetQq))[0];
                            string name = info.CurrentUname;
                            status = $"已经和{name}匹配";
                        }

                        if (id == null)
                        {
                            strs.Add(osuName + ": 闲置中。");
                        }
                        else
                        {
                            strs.Add($"{osuName}  地图号: s/{id} {status}");
                        }
                    }

                    return(new CommonMessageResponse(string.Join("\r\n", strs), _cm));
                }
                else
                {
                    return(new CommonMessageResponse(LoliReply.RootOnly, _cm));
                }
            }

            if (_cm.MessageType != MessageType.Private)
            {
                return(new CommonMessageResponse(LoliReply.PrivateOnly, _cm));
            }

            try
            {
                using (_session = new Session(DefaultTimeout, _cm.Identity, _cm.UserId))
                {
                    BllUserRole        bllUserRole = new BllUserRole();
                    List <TblUserRole> userInfo    = bllUserRole.GetUserRoleByQq(long.Parse(messageObj.UserId));
                    if (userInfo.Count == 0)
                    {
                        return(new CommonMessageResponse("这个功能是需要绑定osu id的,请使用/setid完成绑定", messageObj, true));
                    }

                    _osuId = userInfo[0].UserId.ToString();

                    try
                    {
                        // Init
                        if (!_matchList.Select(q => q.Qq).Contains(_cm.UserId))
                        {
                            const string intro = @"这是一个利用我进行自动化管理的M4M平台,只需将图的链接给我,你无需自己各处求摸。
我会地合理地从库中挑选,并与你和另一人互相推荐,以达成自动匹配M4M的目的。
每个人只能给我一张图,第二张图会覆盖第一张图,所以有什么图需摸要记得更新哦!
最重要的一点:这仅仅是一个平台,真正的交流还需面对面进行。";
                            SendMessage(new CommonMessageResponse(intro, _cm));

                            _matchList.Add(new MatchInfo(_cm.UserId));
                            SaveMatchList(); //apply

                            Thread.Sleep(8000);
                        }

                        // Load
                        _myInfo             = _matchList.FirstOrDefault(q => q.Qq == _cm.UserId);
                        _myInfo.IsOperating = true;
                        _myInfo.LastUse     = DateTime.Now;
                        if (PluginManager.ApplicationList.FirstOrDefault(o => o.GetType() == typeof(M4MMatchNotice)) is M4MMatchNotice plugin)
                        {
                            if (M4MMatchNotice.Tipped.ContainsKey(_myInfo.Qq))
                            {
                                M4MMatchNotice.Tipped[_myInfo.Qq] = DateTime.Now;
                            }
                            else
                            {
                                M4MMatchNotice.Tipped.TryAdd(_myInfo.Qq, DateTime.Now);
                            }
                            plugin.SaveSettings();
                        }
                        // Confirm
                        if (Confirm)
                        {
                            if (_myInfo.TargetQq == null)
                            {
                                return(new CommonMessageResponse("你尚且还没有正在进行的匹配。", _cm));
                            }

                            var oInfo = _matchList.FirstOrDefault(q => q.Qq == _myInfo.TargetQq);
                            if (DateTime.Now - oInfo.LastConfirmedTime < new TimeSpan(3, 0, 0))
                            {
                                return(new CommonMessageResponse("你已在三小时之内发出过核对确认,请稍后再试。", _cm));
                            }
                            oInfo.RequestBeConfirmed();
                            SaveMatchList(); //apply

                            string nick = CqApi.GetStrangerInfo(oInfo.Qq).Data?.Nickname ?? "玩家";
                            SendMessage(new CommonMessageResponse($"你已经确认了{nick}({oInfo.Qq})的摸,请及时完成自己的摸!", _cm));

                            string nick2 = CqApi.GetStrangerInfo(_myInfo.Qq).Data?.Nickname ?? "玩家";
                            SendMessage(new CommonMessageResponse($"{nick2}({_myInfo.Qq})已经确认查收了你的摸。",
                                                                  new Identity(oInfo.Qq, MessageType.Private)));

                            if (oInfo.LastConfirmedTime == null || _myInfo.LastConfirmedTime == null)
                            {
                                return(null);
                            }
                            Thread.Sleep(2000);
                            oInfo.FinishedSet.Add(_myInfo.SetId);
                            _myInfo.FinishedSet.Add(oInfo.SetId);
                            oInfo.Finish();
                            _myInfo.Finish();
                            SendMessage(new CommonMessageResponse(
                                            $"你与{nick}({oInfo.Qq})的M4M ({oInfo.SetUrl}) 已完成,合作愉快!",
                                            new Identity(_myInfo.Qq, MessageType.Private)));
                            SendMessage(new CommonMessageResponse(
                                            $"你与{nick2}({_myInfo.Qq})的M4M ({_myInfo.SetUrl}) 已完成,合作愉快!",
                                            new Identity(oInfo.Qq, MessageType.Private)));
                            SaveMatchList(); //apply
                            return(null);
                        }
                        // Finish
                        else if (Finish)
                        {
                            var oInfo = _matchList.FirstOrDefault(q => q.Qq == _myInfo.TargetQq);
                            if (DateTime.Now - _myInfo.LastNoticeTime < new TimeSpan(3, 0, 0))
                            {
                                return(new CommonMessageResponse("你已在三小时之内发出过完成提醒,请稍后再试。", _cm));
                            }
                            _myInfo.RequestFinishMatch();
                            SaveMatchList(); //apply

                            string nick2 = CqApi.GetStrangerInfo(_myInfo.Qq).Data?.Nickname ?? "玩家";
                            SendMessage(new CommonMessageResponse(
                                            $"{nick2}({_myInfo.Qq})已经摸完了你的图:\r\n" +
                                            $"{oInfo.SetUrl}\r\n" +
                                            $"正在等待你的摸。\r\n" +
                                            $"请检查他的modding情况,回复 \"/m4m -确认\" 查收。\r\n" +
                                            $"若对方没有摸完,请不要查收。若有疑问请相互交流。",
                                            new Identity(oInfo.Qq, MessageType.Private)));
                            return(new CommonMessageResponse("已发送完成请求。", _cm));
                        }
                        // Cancel
                        else if (Cancel)
                        {
                            var oInfo = _matchList.FirstOrDefault(q => q.Qq == _myInfo.TargetQq);

                            if (oInfo.MatchTime == null)
                            {
                                oInfo.MatchTime = DateTime.Now; // 临时补救
                            }
                            if (DateTime.Now - oInfo.MatchTime < new TimeSpan(7, 0, 0, 0))
                            {
                                return(new CommonMessageResponse("取消失败,仅匹配持续一周以上才可取消。", _cm));
                            }

                            string nick  = CqApi.GetStrangerInfo(oInfo.Qq).Data?.Nickname ?? "玩家";
                            string nick2 = CqApi.GetStrangerInfo(_myInfo.Qq).Data?.Nickname ?? "玩家";

                            oInfo.FinishedSet.Add(_myInfo.SetId);
                            _myInfo.FinishedSet.Add(oInfo.SetId);
                            oInfo.Finish();
                            _myInfo.Finish();
                            SendMessage(new CommonMessageResponse(
                                            $"你与{nick}({oInfo.Qq})的M4M ({oInfo.SetUrl}) 已强制取消。",
                                            new Identity(_myInfo.Qq, MessageType.Private)));
                            SendMessage(new CommonMessageResponse(
                                            $"你与{nick2}({_myInfo.Qq})的M4M ({_myInfo.SetUrl}) 已强制取消。",
                                            new Identity(oInfo.Qq, MessageType.Private)));
                            SaveMatchList(); //apply
                            return(null);
                        }

                        // No set after load
                        if (_myInfo.Set == null)
                        {
                            return(SessionNoMap());
                        }

                        // Matched Main
                        string info;
                        if (_myInfo.TargetQq != null)
                        {
                            var    oInfo = _matchList.FirstOrDefault(q => q.Qq == _myInfo.TargetQq);
                            string nick  = CqApi.GetStrangerInfo(oInfo.Qq).Data?.Nickname ?? "玩家";
                            info = $"你已经成功和{nick}({oInfo.Qq})匹配\r\n" +
                                   $"· 你的信息:\r\n" +
                                   $"    地图地址:{_myInfo.SetUrl}\r\n" +
                                   $"    备注:{_myInfo.Mark}\r\n" +
                                   $"· 他的信息:\r\n" +
                                   $"    地图地址:{oInfo.SetUrl} \r\n" +
                                   $"    备注:{oInfo.Mark}\r\n" +
                                   $"当你摸图完成时,请使用 \"/m4m -完成\" 提醒对方审阅。\r\n" +
                                   $"当对方向你提出审阅请求后,请使用 \"/m4m -确认\" 完成审阅。\r\n" +
                                   $"若匹配持续超过一周,可使用  \"/m4m -取消\" 强制取消,且下次不会匹配到此图。";
                            return(new CommonMessageResponse(info, _cm));
                        }

                        // Main
                        info = $"· 你的信息:\r\n" +
                               $"    地图地址:{_myInfo.SetUrl} \r\n" +
                               $"    备注:{_myInfo.Mark}\r\n" +
                               $"· 从下面的选项中选择一个你想进行的操作:\r\n" +
                               $">【1】删除已发布的地图。\r\n" +
                               $">【2】管理摸图偏好(当前:{_myInfo.GetPreferenceString()})。\r\n" +
                               $">【3】开始进行m4m匹配。";

                        SendMessage(new CommonMessageResponse(info, _cm));
                        CommonMessage cmMain = SessionCondition("1", "2", "3");
                        switch (cmMain.Message)
                        {
                        case "1":
                            SendMessage(new CommonMessageResponse("删除现有地图,确认吗?\r\n" +
                                                                  "【1】是 【2】否", _cm));
                            CommonMessage cmPub = SessionCondition("1", "2");
                            if (cmPub.Message == "1")
                            {
                                _myInfo.RemoveSet();
                                SaveMatchList();     //apply
                                return(new CommonMessageResponse("删除成功。使用/m4m重新发布地图。", _cm));
                            }
                            else
                            {
                                return(new CommonMessageResponse("你已取消操作。", _cm));
                            }

                        case "2":
                            if (SessionMode(out var sessionNoMap))
                            {
                                return(sessionNoMap);
                            }
                            return(null);

                        case "3":     // core
                            MatchInfo[] fullList = _matchList.Where(i =>
                                                                    i.Qq != _myInfo.Qq && i.TargetQq == null && i.Set != null && !i.IsOperating &&
                                                                    DateTime.Now - i.LastUse < new TimeSpan(7, 0, 0, 0)).ToArray();
                            if (fullList.Length == 0)
                            {
                                return(new CommonMessageResponse("目前没有可匹配的用户,也有可能是可匹配的用户同时在浏览m4m菜单。请等待他人匹配或稍后重试。", _cm));
                            }

                            MatchInfo[] canModList = fullList.Where(i =>
                                                                    i.Preference.Have(_myInfo.Modes) == 1 &&
                                                                    _myInfo.Preference.Have(i.Modes) == 1 &&
                                                                    !i.FinishedSet.Contains(_myInfo.SetId) &&
                                                                    !_myInfo.FinishedSet.Contains(i.SetId)).ToArray();
                            if (canModList.Length == 0)
                            {
                                return(new CommonMessageResponse("目前没有与你情况相符合的用户,请等待他人匹配或稍后重试。", _cm));
                            }

                            MatchInfo[] bestList = new MatchInfo[0];
                            int         count    = 0;
                            while (bestList.Length == 0 && count < 120)
                            {
                                bestList = canModList.Where(i =>
                                                            Math.Abs(_myInfo.GetPreferanceTotalLength(i) -
                                                                     i.GetPreferanceTotalLength(_myInfo)) < count).ToArray();
                                count += 10;
                                Thread.Sleep(1);
                            }

                            MatchInfo matchInfo;

                            if (bestList.Length < 1)
                            {
                                SendMessage(new CommonMessageResponse("目前没有最佳的匹配,继续尝试不佳的匹配吗?\r\n" +
                                                                      "【1】是 【2】否", _cm));
                                CommonMessage cmContinue = SessionCondition("1", "2");
                                if (cmContinue.Message == "1")
                                {
                                    MatchInfo[] notBestList = new MatchInfo[0];
                                    int         c           = count;
                                    while (notBestList.Length == 0 && c < 10000)
                                    {
                                        notBestList = canModList.Where(i =>
                                                                       Math.Abs(_myInfo.GetPreferanceTotalLength(i) -
                                                                                i.GetPreferanceTotalLength(_myInfo)) < c).ToArray();
                                        c += 50;
                                        Thread.Sleep(1);
                                    }

                                    matchInfo = notBestList[Rnd.Next(notBestList.Length)];
                                }
                                else
                                {
                                    return(new CommonMessageResponse("你已取消操作。请等待他人匹配或稍后重试。", _cm));
                                }
                            }
                            else
                            {
                                matchInfo = bestList[Rnd.Next(bestList.Length)];
                            }

                            var    data1 = CqApi.GetStrangerInfo(matchInfo.Qq).Data;
                            var    data2 = CqApi.GetStrangerInfo(_myInfo.Qq).Data;
                            string sub1 = "Ta", sub2 = "Ta";
                            string nick1 = "玩家", nick2 = "玩家";
                            if (data1 != null)
                            {
                                if (data1.Sex == "male")
                                {
                                    sub1 = "他";
                                }
                                else if (data1.Sex == "female")
                                {
                                    sub1 = "她";
                                }
                                nick1 = data1.Nickname;
                            }

                            if (data2 != null)
                            {
                                if (data2.Sex == "male")
                                {
                                    sub2 = "他";
                                }
                                else if (data2.Sex == "female")
                                {
                                    sub2 = "她";
                                }
                                nick2 = data2.Nickname;
                            }

                            _myInfo.Start(matchInfo.Qq);
                            matchInfo.Start(_myInfo.Qq);
                            SaveMatchList();     //apply

                            const string tip = "当你选择完成摸图时,对方会收到一条消息确认你的mod,反之亦然。" +
                                               "当双方互批完成时,M4M成功结束!\r\n" +
                                               "若有疑问,请与对方互相协商。详细情况请使用 \"/m4m\"。";

                            SendMessage(new CommonMessageResponse($"{nick2}({_myInfo.Qq}) 与你成功匹配\r\n" +
                                                                  $"{sub2}的地图:{_myInfo.SetUrl}\r\n" +
                                                                  $"{sub2}的备注:{_myInfo.Mark}\r\n" + tip,
                                                                  new Identity(matchInfo.Qq, MessageType.Private)));

                            return(new CommonMessageResponse($"你与{nick1}({matchInfo.Qq}) 成功匹配\r\n" +
                                                             $"{sub1}的地图:{matchInfo.SetUrl}\r\n" +
                                                             $"{sub1}的备注:{matchInfo.Mark}\r\n" + tip, _cm));

                        default:
                            return(new CommonMessageResponse("你开始了?走了.jpg", _cm));
                        }
                    }
                    catch (TimeoutException)
                    {
                        return(new CommonMessageResponse("由于长时间未操作,已经自动取消m4m状态。", _cm));
                    }
                }
            }
            catch (NotSupportedException)
            {
                return(new CommonMessageResponse("你已在进行m4m状态中。", messageObj, true));
            }
            finally
            {
                if (_myInfo != null)
                {
                    _myInfo.IsOperating = false;
                    SaveMatchList(); //apply
                }
            }
        }
Example #14
0
        private static void HandleMessage(CommonMessage cm)
        {
            long groupId   = Convert.ToInt64(cm.GroupId);
            long userId    = Convert.ToInt64(cm.UserId);
            long discussId = Convert.ToInt64(cm.DiscussId);
            var  type      = cm.MessageType;

            string group, sender, message = cm.Message;

            switch (cm.MessageType)
            {
            case MessageType.Private:
                group  = "私聊";
                sender = SessionInfo[cm.Identity].Name;
                break;

            case MessageType.Discuss:
                group  = SessionInfo[cm.Identity].Name;
                sender = cm.UserId;
                break;

            default:
            case MessageType.Group:
                var userInfo = CqApi.GetGroupMemberInfo(cm.GroupId, cm.UserId);     // 有点费时间
                group  = SessionInfo[cm.Identity].Name;
                sender = string.IsNullOrEmpty(userInfo.Data.Card)
                        ? userInfo.Data.Nickname
                        : userInfo.Data.Card;
                break;
            }

            Message($"({group}) {sender}:\r\n  {CqCode.DecodeToString(message)}");

            if (cm.Message.Substring(0, 1) == CommandFlag)
            {
                if (cm.Message.IndexOf(CommandFlag + "root ", StringComparison.InvariantCulture) == 0)
                {
                    if (cm.UserId != "2241521134")
                    {
                        SendMessage(new CommonMessageResponse(LoliReply.FakeRoot, cm));
                    }
                    else
                    {
                        cm.FullCommand     = cm.Message.Substring(6, cm.Message.Length - 6);
                        cm.PermissionLevel = PermissionLevel.Root;
                        HandleMessageCmd(cm);
                    }
                }
                else if (message.IndexOf(CommandFlag + "sudo ", StringComparison.InvariantCulture) == 0 &&
                         type == MessageType.Group)
                {
                    if (SessionInfo[cm.Identity].GroupInfo.Admins.Count(q => q.UserId == userId) == 0)
                    {
                        SendMessage(new CommonMessageResponse(LoliReply.FakeAdmin, cm));
                    }
                    else
                    {
                        cm.FullCommand     = message.Substring(6, message.Length - 6);
                        cm.PermissionLevel = PermissionLevel.Admin;
                        HandleMessageCmd(cm);
                    }
                }
                else
                {
                    cm.FullCommand = message.Substring(1, message.Length - 1);
                    HandleMessageCmd(cm);
                }
            }

            HandleMesasgeApp(cm);
            Thread.Sleep(Rnd.Next(MinTime, MaxTime));
        }
Example #15
0
 /// <summary>
 /// 添加日志
 /// </summary>
 /// <param name="level">日志等级</param>
 /// <param name="msg">内容</param>
 /// <param name="module">模块</param>
 private static void Log(LogerLevel level, string msg, string module)
 {
     CqApi.AddLoger(Sdk.Cqp.Enum.LogerLevel.Info, $"{flag}{module}", msg);
 }
Example #16
0
 public void Init()
 {
     instance = new CqApi();
 }
Example #17
0
        public void Json_Received(object sender, JsonReceivedEventArgs args)
        {
            string json = args.JsonString;

            dynamic obj = JsonConvert.DeserializeObject(json);

            // 判断post类别
            try
            {
                if (obj.post_type == "message")
                {
                    // 私聊
                    if (obj.message_type == "private")
                    {
                        PrivateMsg parsedObj = JsonConvert.DeserializeObject <PrivateMsg>(json);
                        Core.ReceiveMessage(parsedObj);
                    }

                    // 群聊
                    else if (obj.message_type == "group")
                    {
                        GroupMsg parsedObj = JsonConvert.DeserializeObject <GroupMsg>(json);
                        Core.ReceiveMessage(parsedObj);
                    }

                    // 讨论组
                    else if (obj.message_type == "discuss")
                    {
                        DiscussMsg parsedObj = JsonConvert.DeserializeObject <DiscussMsg>(json);
                        Core.ReceiveMessage(parsedObj);
                    }
                }
                else if (obj.post_type == "notice")
                {
                    // 群文件上传
                    if (obj.notice_type == "group_upload")
                    {
                        GroupFileUpload parsedObj = JsonConvert.DeserializeObject <GroupFileUpload>(json);
                        // TODO
                    }
                    // 群管理员变动
                    else if (obj.notice_type == "group_admin")
                    {
                        GroupAdminChange parsedObj = JsonConvert.DeserializeObject <GroupAdminChange>(json);
                        // TODO
                    }
                    // 群成员增加/减少
                    else if (obj.notice_type == "group_decrease" || obj.notice_type == "group_increase")
                    {
                        GroupMemberChange parsedObj = JsonConvert.DeserializeObject <GroupMemberChange>(json);
                        // TODO
                    }
                    // 好友添加
                    else if (obj.notice_type == "friend_add")
                    {
                        FriendAdd parsedObj = JsonConvert.DeserializeObject <FriendAdd>(json);
                        // TODO
                    }
                }
                else if (obj.post_type == "request")
                {
                    // 加好友请求
                    if (obj.request_type == "friend")
                    {
                        FriendRequest parsedObj = JsonConvert.DeserializeObject <FriendRequest>(json);
                        // TODO,临时
                        CqApi.SendPrivateMessage("2241521134",
                                                 string.Format("{0} ({1})邀请加我为好友",
                                                               CqApi.GetStrangerInfo(parsedObj.UserId.ToString()).Data?.Nickname, parsedObj.UserId));
                    }
                    // 加群请求/邀请
                    else if (obj.request_type == "group")
                    {
                        GroupInvite parsedObj = JsonConvert.DeserializeObject <GroupInvite>(json);
                        // TODO,临时
                        if (parsedObj.SubType == "invite")
                        {
                            CqApi.SendPrivateMessage("2241521134",
                                                     string.Format("{0} ({1})邀请我加入群{2}",
                                                                   CqApi.GetStrangerInfo(parsedObj.UserId.ToString()).Data?.Nickname, parsedObj.UserId,
                                                                   parsedObj.GroupId));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Exception(ex);
            }
        }