public void Handle(CommandContext context, GomokuPlayerJoinGameCommand command, params object[] handleObjects)
        {
            var game     = (PlayGround)handleObjects[0];
            var mahuaApi = CommandFactory.GetMahuaApi();

            var result = game.PlayerJoinGame(context.From);

            switch (result)
            {
            case PlayerJoinStat.GameFull:
                mahuaApi.SendGroupMessage(context.FromGroup, "游戏已满,请等待游戏结束");
                return;

            case PlayerJoinStat.HaveJoined:
                mahuaApi.SendGroupMessage(context.FromGroup, "你已经加入过了");
                return;

            case PlayerJoinStat.Success:
                if (game.GameFull)
                {
                    mahuaApi.SendGroupMessage(context.FromGroup, $"白方:{CqCode.At(context.From)}成功加入!");
                    game.StartGame();
                    PrintStartMessage(context.FromGroup, game, mahuaApi);
                }
                else
                {
                    mahuaApi.SendGroupMessage(context.FromGroup, $"黑方:{CqCode.At(context.From)}成功加入!");
                }
                return;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
示例#2
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)));
        }
示例#3
0
        private CqMsg(string message)
        {
            OriginalString = message;
            Contents       = new List <CqCode> ();

            // 搜索消息中的 CQ码
            MatchCollection matches = _regex[0].Matches(message);

            if (matches.Count > 0)
            {
                foreach (Match match in matches)
                {
                    CqCode tempCode = new CqCode();

                    #region --解析 CQ码 类型--
                    CqCodeType type = CqCodeType.Unknown;
                    if (System.Enum.TryParse <CqCodeType> (match.Groups[1].Value, true, out type))
                    {
                        tempCode.Type = type;
                    }
                    #endregion

                    #region --键值对解析--
                    tempCode.Dictionary = new Dictionary <string, string> ();
                    MatchCollection kvResult = _regex[1].Matches(match.Groups[2].Value);
                    foreach (Match kvMatch in kvResult)
                    {
                        tempCode.Dictionary.Add(kvMatch.Groups[1].Value, kvMatch.Groups[2].Value);
                    }
                    #endregion

                    Contents.Add(tempCode);
                }
            }
        }
示例#4
0
        private void PrintStartMessage(string group, PlayGround game)
        {
            var message = new StringBuilder("开始游戏!\n");

            message.AppendLine("---------------------------------");
            message.AppendLine("命令列表: (您随时都可以使用/help查看命令)");
            message.AppendLine("   落子: x坐标y坐标");
            message.AppendLine("   退出: /ge");
            message.AppendLine("   投降: /gf");
            message.AppendLine("   投票结束: /ve");
            message.AppendLine("   查看Gomoku Credit: /gc");
            message.AppendLine("   查看Gomoku Credit排行榜: /gt");
            message.AppendLine("---------------------------------");

            switch (game.Role)
            {
            case Role.Black:
                message.Append($"黑方:{CqCode.At(game.BlackPlayer)}先手!请{CqCode.At(game.BlackPlayer)}走子!");
                break;

            case Role.White:
                message.Append($"白方:{CqCode.At(game.WhitePlayer)}先手!请{CqCode.At(game.WhitePlayer)}走子!");
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            _mahuaApi.SendGroupMessage(group)
            .Text(message.ToString())
            .Newline()
            .Text(CqCode.Image($"{game.GameId}\\ChessBoard_{game.Steps}.jpg"))
            .Done();
        }
示例#5
0
        private void PlayerJoinGame(PlayGround game, GroupMessageReceivedContext context)
        {
            var result = game.PlayerJoinGame(context.FromQq);

            switch (result)
            {
            case PlayerJoinStat.GameFull:
                _mahuaApi.SendGroupMessage(context.FromGroup, "游戏已满,请等待游戏结束");
                return;

            case PlayerJoinStat.HaveJoined:
                _mahuaApi.SendGroupMessage(context.FromGroup, "你已经加入过了");
                return;

            case PlayerJoinStat.Success:
                if (game.GameFull)
                {
                    _mahuaApi.SendGroupMessage(context.FromGroup, $"白方:{CqCode.At(context.FromQq)}成功加入!");
                    game.StartGame();
                    PrintStartMessage(context.FromGroup, game);
                }
                else
                {
                    _mahuaApi.SendGroupMessage(context.FromGroup, $"黑方:{CqCode.At(context.FromQq)}成功加入!");
                }
                return;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
示例#6
0
        public override CommonMessageResponse Message_Received(CommonMessage messageObj)
        {
            if (!messageObj.Message.Equals("/转"))
            {
                return(null);
            }
            using (Session session = new Session(1000 * 60, messageObj.Identity, messageObj.UserId))
            {
                SendMessage(new CommonMessageResponse("请发送图片,5张以内,1分钟内有效。", messageObj, true));
                try
                {
                    CommonMessage cm       = session.GetMessage();
                    var           infoList = CqCode.GetImageInfo(cm.Message);
                    if (infoList == null)
                    {
                        return(new CommonMessageResponse("你发送的消息没有包含图片。", cm));
                    }
                    if (infoList.Length > 5)
                    {
                        return(new CommonMessageResponse("你发送的图片过多。", cm));
                    }

                    List <Image> imgList = infoList.Select(imgInfo => HttpClientUtil.GetImageFromUrl(imgInfo.Url))
                                           .ToList();

                    var sendList = HandleImage(imgList);

                    return(new CommonMessageResponse(string.Join("\r\n", sendList), messageObj));
                }
                catch (TimeoutException)
                {
                    return(null);
                }
            }
        }
 public void ProcessGroupMessage(GroupMessageReceivedContext context)
 {
     if (context.Message.StartsWith("/image") && context.FromQq == Configuration.Me)
     {
         var image = context.Message.Substring(7);
         _mahuaApi.SendGroupMessage(context.FromGroup, CqCode.Image(image));
     }
 }
示例#8
0
        public override CommonMessageResponse Message_Received(CommonMessage messageObj)
        {
            if (messageObj.MessageType == MessageType.Private)
            {
                return(null);
            }
            var imgList = CqCode.GetImageInfo(messageObj.Message);

            if (imgList == null)
            {
                return(null);
            }

            string groupId = messageObj.GroupId ?? messageObj.DiscussId;

            if (!GroupDic.ContainsKey(groupId))
            {
                GroupDic.GetOrAdd(groupId, new GroupSettings
                {
                    GroupId    = groupId,
                    MessageObj = messageObj
                });
            }

            foreach (var item in imgList)
            {
                if (item.Extension.ToLower() == ".gif")
                {
                    continue;
                }
                if (item.FileInfo.Exists)
                {
                    GroupDic[groupId].PathQueue.Enqueue(item.FileInfo.FullName);
                }
                else
                {
                    string path = HttpClientUtil.SaveImageFromUrl(item.Url, System.Drawing.Imaging.ImageFormat.Jpeg);
                    GroupDic[groupId].PathQueue.Enqueue(path);
                }
#if DEBUG
                _totalCount++;
#endif
            }

            if (GroupDic[groupId].Task == null || GroupDic[groupId].Task.IsCompleted ||
                GroupDic[groupId].Task.IsCanceled)
            {
                GroupDic[groupId].Task = Task.Run(() => RunDetector(GroupDic[groupId]));
#if DEBUG
                Logger.Info("[" + groupId + "] (熊猫) 共 " + _totalCount);
#endif
            }

            return(null);
        }
示例#9
0
        private static bool TryParse(PropertyInfo prop, string argStr, out dynamic parsed)
        {
            try
            {
                if (prop.PropertyType == typeof(int))
                {
                    parsed = Convert.ToInt32(argStr);
                }
                else if (prop.PropertyType == typeof(long))
                {
                    parsed = Convert.ToInt64(argStr);
                }
                else if (prop.PropertyType == typeof(short))
                {
                    parsed = Convert.ToInt16(argStr);
                }
                else if (prop.PropertyType == typeof(float))
                {
                    parsed = Convert.ToSingle(argStr);
                }
                else if (prop.PropertyType == typeof(double))
                {
                    parsed = Convert.ToDouble(argStr);
                }
                else if (prop.PropertyType == typeof(string))
                {
                    parsed = CqCode.Decode(argStr); // Convert.ToString(cmd);
                }
                else if (prop.PropertyType == typeof(bool))
                {
                    string tmpCmd = argStr == "" ? "true" : argStr;
                    if (tmpCmd == "0")
                    {
                        tmpCmd = "false";
                    }
                    else if (tmpCmd == "1")
                    {
                        tmpCmd = "true";
                    }
                    parsed = Convert.ToBoolean(tmpCmd);
                }
                else
                {
                    throw new NotSupportedException("sb");
                }

                return(true);
            }
            catch (Exception ex)
            {
                Exception(ex);
                parsed = null;
                return(false);
            }
        }
示例#10
0
        public override CommonMessageResponse Message_Received(CommonMessage messageObj)
        {
            if (messageObj.MessageType == MessageType.Private)
            {
                return(null);
            }
            string groupId = messageObj.GroupId ?? messageObj.DiscussId;

            if (!GroupDic.ContainsKey(groupId))
            {
                GroupDic.GetOrAdd(groupId, new GroupSettings
                {
                    GroupId    = groupId,
                    MessageObj = messageObj
                });
            }
            //GroupDic[groupId].GroupType = messageObj.GroupId == null ? MessageType.Discuss : MessageType.Group;

            var imgList = CqCode.GetImageInfo(messageObj.Message);

            if (imgList == null)
            {
                return(null);
            }

            foreach (var item in imgList)
            {
                if (item.Extension.ToLower() == ".gif")
                {
                    continue;
                }
                if (item.FileInfo.Exists)
                {
                    GroupDic[groupId].PathQueue.Enqueue(item.FileInfo.FullName);
                }
                else
                {
                    WebRequestUtil.GetImageFromUrl(item.Url, item.Md5, item.Extension);
                    GroupDic[groupId].PathQueue.Enqueue(Path.Combine(Domain.CurrentDirectory, "images",
                                                                     item.Md5 + item.Extension));
                }

                _totalCount++;
            }

            if (GroupDic[groupId].Task == null || GroupDic[groupId].Task.IsCompleted ||
                GroupDic[groupId].Task.IsCanceled)
            {
                GroupDic[groupId].Task = Task.Run(() => RunDetector(GroupDic[groupId]));
                Logger.Info("[" + groupId + "] (熊猫) 共 " + _totalCount);
            }

            return(null);
        }
示例#11
0
        public void Handle(CommandContext context, GomokuPlayerGoCommand command, params object[] handleObjects)
        {
            var game = (PlayGround)handleObjects[0];

            var mahuaApi = CommandFactory.GetMahuaApi();

            if (game.IsActivatedAndValid(context.From) && game.IsBlackOrWhiteTurn(context.From))
            {
                var dropResult = game.ProcessGoCommand(context.Message);
                switch (dropResult.GameState)
                {
                case GameState.Success:
                    mahuaApi.SendGroupMessage(context.FromGroup)
                    .Text($"{(game.Role == Role.White ? "黑方成功落子" : "白方成功落子")}: [{dropResult.DropPoint.X},{Axis.NumberToYAxis(dropResult.DropPoint.Y)}]")
                    .Newline()
                    .Text(CqCode.Image($"{game.GameId}\\ChessBoard_{game.Steps}.jpg"))
                    .Done();
                    break;

                case GameState.IllegalDropLocation:
                    mahuaApi.SendGroupMessage(context.FromGroup, "诶呀,您落子的位置好像不太合理,再重新试试吧?");
                    return;

                case GameState.AbortCuzChessBoardFull:
                    mahuaApi.SendGroupMessage(context.FromGroup)
                    .Text("棋盘上已经没有地方了,和棋!")
                    .Newline()
                    .Text("游戏结束!")
                    .Done();
                    game.Dispose();
                    return;

                case GameState.IrrelevantMessage:
                    return;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                var winResult = game.IsWin(dropResult.DropPoint.X, dropResult.DropPoint.Y);
                if (winResult != Chessman.Empty)
                {
                    var isBlackWin = winResult == Chessman.Black;
                    mahuaApi.SendGroupMessage(context.FromGroup, game.GetWinMessage(isBlackWin));
                }
                else
                {
                    mahuaApi.SendGroupMessage(context.FromGroup, $"请{(game.Role == Role.White ? $"白方{CqCode.At(game.WhitePlayer)}走子!" : $"黑方{CqCode.At(game.BlackPlayer)}走子!")}");
                }
            }
        }
        public void Handle(CommandContext context, GomokuPlayerSurrenderCommand command, params object[] handleObjects)
        {
            var game     = (PlayGround)handleObjects[0];
            var mahuaApi = CommandFactory.GetMahuaApi();

            if (game.IsActivatedAndValid(context.From))
            {
                var isBlackWin = game.BlackPlayer != context.From;
                mahuaApi.SendGroupMessage(context.FromGroup)
                .Text($"{CqCode.At(context.From)}选择了投降!")
                .Newline()
                .Text(game.GetWinMessage(isBlackWin))
                .Done();
            }
        }
示例#13
0
        private static dynamic ParseStr(PropertyInfo prop, string argStr)
        {
            dynamic obj;

            if (prop.PropertyType == typeof(int))
            {
                obj = Convert.ToInt32(argStr);
            }
            else if (prop.PropertyType == typeof(long))
            {
                obj = Convert.ToInt64(argStr);
            }
            else if (prop.PropertyType == typeof(short))
            {
                obj = Convert.ToInt16(argStr);
            }
            else if (prop.PropertyType == typeof(float))
            {
                obj = Convert.ToSingle(argStr);
            }
            else if (prop.PropertyType == typeof(double))
            {
                obj = Convert.ToDouble(argStr);
            }
            else if (prop.PropertyType == typeof(string))
            {
                obj = CqCode.Decode(argStr); // Convert.ToString(cmd);
            }
            else if (prop.PropertyType == typeof(bool))
            {
                string tmpCmd = argStr == "" ? "true" : argStr;
                if (tmpCmd == "0")
                {
                    tmpCmd = "false";
                }
                else if (tmpCmd == "1")
                {
                    tmpCmd = "true";
                }
                obj = Convert.ToBoolean(tmpCmd);
            }
            else
            {
                throw new NotSupportedException("sb");
            }

            return(obj);
        }
示例#14
0
        /// <summary>
        /// 确定字体是否为空或有效。若为空或无效,则用默认语句替代。
        /// </summary>
        /// <returns></returns>
        private string GetRealWord(FontFamily font, string pandaPath)
        {
            string word = PandaWord;

            if (word == null || word.Replace("\n", "").Replace("\r", "").Trim() == "")
            {
                word = _blankReply[Rnd.Next(0, _blankReply.Length)];
                return(word);
            }

            word = CqCode.DecodeToString(PandaWord.Replace("!", "!").Replace("?", "?"));
            if (!IsLengthValid(word, pandaPath, font))
            {
                word = _invalidReply[Rnd.Next(0, _invalidReply.Length)];
            }
            return(word);
        }
示例#15
0
        public override CommonMessageResponse Message_Received(CommonMessage messageObj)
        {
            if (messageObj.Group == null)
            {
                return(null);
            }

            //if (user != "2241521134") return null;
            _user      = messageObj.UserId;
            _group     = messageObj.GroupId;
            _messageId = messageObj.MessageId;

            var imgList = CqCode.GetImageInfo(messageObj.Message);

            if (imgList == null)
            {
                return(null);
            }

            foreach (var item in imgList)
            {
                if (item.Extension.ToLower() == ".gif")
                {
                    continue;
                }
                if (item.FileInfo.Exists)
                {
                    _pathList.Add(item.FileInfo.FullName);
                }
                else
                {
                    WebRequestUtil.GetImageFromUrl(item.Url, item.Md5, item.Extension);
                    _pathList.Add(Path.Combine(Domain.CurrentDirectory, "images", item.Md5 + item.Extension));
                }

                _totalCount++;
            }

            _thread = new Thread(RunDetector);
            _thread.Start(_pathList);
            Logger.Warn("已经发送了请求,目前队列中共" + _totalCount);
            return(null);
        }
        public void Handle(CommandContext context, GomokuPlayerVoteEndCommand command, params object[] handleObjects)
        {
            var game     = (PlayGround)handleObjects[0];
            var mahuaApi = CommandFactory.GetMahuaApi();

            if (game.IsActivatedAndValid(context.From))
            {
                if (game.VoteForEnd.isVoting && game.IsMessageFromPlayer(context.From) && context.From != game.VoteForEnd.qq)
                {
                    mahuaApi.SendGroupMessage(context.FromGroup, $"投票通过,结束ID为{game.GameId}的游戏");
                    game.Dispose();
                }
                else if (!game.VoteForEnd.isVoting && game.IsMessageFromPlayer(context.From))
                {
                    mahuaApi.SendGroupMessage(context.FromGroup, $"{CqCode.At(context.From)}发起结束游戏投票!同意请输入/ve");
                    game.VoteForEnd = (context.From, true);
                }
            }
        }
        public void Handle(CommandContext context, GomokuPlayerExitCommand command, params object[] handleObjects)
        {
            var game = (PlayGround)handleObjects[0];

            if (game != null && game.IsMessageFromPlayer(context.From))
            {
                var sb = new StringBuilder();
                sb.Append($"{CqCode.At(context.From)}离开游戏,游戏结束!");

                if (game.GameStarted)
                {
                    sb.Append($"\n根据退赛惩罚机制,{CqCode.At(context.From)}将会被扣除20000点Gomoku Credit");
                    GomokuCredit.SetOrIncreaseCredit(context.From, -30000);
                }
                CommandFactory.GetMahuaApi().SendGroupMessage(context.FromGroup, sb.ToString());

                game.Dispose();
            }
        }
示例#18
0
        private void Parse()
        {
            MatchCollection matches = _regex[0].Matches(this.OriginalString);

            if (matches.Count > 0)
            {
                foreach (Match match in matches)
                {
                    CqCode tempCode = new CqCode();

                    #region --初始化CqCode--
                    tempCode.OriginalString = match.Groups[0].Value;
                    tempCode.Index          = match.Index;
                    #endregion

                    #region --解析CQ码类型--
                    CqCodeType type = CqCodeType.Unknown;
                    if (System.Enum.TryParse <CqCodeType> (match.Groups[1].Value, true, out type))
                    {
                        tempCode.Type = type;
                    }
                    #endregion

                    #region --键值对解析--
                    if (tempCode.Dictionary == null)
                    {
                        tempCode.Dictionary = new Dictionary <string, string> ();
                    }
                    MatchCollection kvResult = _regex[1].Matches(match.Groups[2].Value);
                    foreach (Match kvMatch in kvResult)
                    {
                        tempCode.Dictionary.Add(kvMatch.Groups[1].Value, kvMatch.Groups[2].Value);
                    }
                    #endregion

                    Contents.Add(tempCode);
                }
            }
        }
示例#19
0
        public override CommonMessageResponse Message_Received(CommonMessage messageObj)
        {
            if (messageObj.MessageType == MessageType.Private)
            {
                return(null);
            }

            string[] ids = CqCode.GetAt(messageObj.Message);
            if (ids == null || !ids.Contains("2181697779") && !ids.Contains("3421735167"))
            {
                return(null);
            }
            Thread.Sleep(Rnd.Next(200, 300));
            if (Rnd.NextDouble() < 0.9)
            {
                return(new CommonMessageResponse("", messageObj, true));
            }
            else
            {
                var cqImg = new FileImage(Path.Combine(PandaDir, "at.jpg"));
                return(new CommonMessageResponse(cqImg.ToString(), messageObj));
            }
        }
示例#20
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;
        }
示例#21
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));
        }
示例#22
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));
        }
示例#23
0
        public static void Query()
        {
            while (MessageQueue.Count != 0)
            {
                if (!MessageQueue.TryDequeue(out var messageObj))
                {
                    continue;
                }
                var cmd = messageObj.Command;

                const long cabbageId = 1020640876;
                string     uname;
                if (cmd == "statme" || cmd == "bpme" || cmd == "mybp" || cmd == "costme" || cmd == "mycost")
                {
                    BllUserRole        bllUserRole = new BllUserRole();
                    List <TblUserRole> userInfo    = bllUserRole.GetUserRoleByQq(long.Parse(messageObj.UserId));
                    if (userInfo.Count == 0)
                    {
                        CoolQDispatcher.SendMessage(new CommonMessageResponse(LoliReply.IdNotBound, messageObj, true));
                    }

                    uname = userInfo[0].CurrentUname;
                }
                else
                {
                    uname = messageObj.ArgString;
                }

                using (Session session = new Session(25000, new Identity(cabbageId, MessageType.Private), cabbageId))
                {
                    CoolQDispatcher.SendMessage(
                        new CommonMessageResponse($"!{cmd.Replace("my", "").Replace("me", "")} {uname}",
                                                  new Identity(cabbageId, MessageType.Private)));
                    try
                    {
                        CommonMessage result = session.GetMessage();
                        session.Timeout = 600;
                        CommonMessage result2 = null;
                        try
                        {
                            result2 = session.GetMessage();
                        }
                        catch
                        {
                            // ignored
                        }

                        ImageInfo[] imgList =
                            CqCode.GetImageInfo(result.Message) ?? CqCode.GetImageInfo(result2?.Message);

                        if (imgList == null)
                        {
                            CoolQDispatcher.SendMessage(new CommonMessageResponse(result.Message, messageObj));
                            if (result2 != null)
                            {
                                CoolQDispatcher.SendMessage(new CommonMessageResponse(result2.Message, messageObj));
                            }
                            continue;
                        }
                        //throw new IndexOutOfRangeException("查询失败:" + result.Message);
                        var message = CqCode.DecodeToString(result.Message);
                        foreach (var item in imgList)
                        {
                            var          str = new FileImage(new Uri(item.Url));
                            StringFinder sf  = new StringFinder(message);
                            sf.FindNext("[图片]");
                            string str1 = sf.Cut();
                            if (sf.FindNext("[图片]", false) > message.Length - 1)
                            {
                                message = str1 + str;
                                continue;
                            }

                            sf.FindToLast();
                            string str2 = sf.Cut();
                            message = str1 + str + str2;
                        }

                        CoolQDispatcher.SendMessage(
                            new CommonMessageResponse(message + "\r\n(查询由白菜支持)", messageObj));
                    }
                    catch (IndexOutOfRangeException e)
                    {
                        string msg = e.Message;
                        CoolQDispatcher.SendMessage(new CommonMessageResponse(msg, messageObj, true));
                    }
                    catch (TimeoutException)
                    {
                        string msg = "查询失败,白菜没有搭理人家..";
                        CoolQDispatcher.SendMessage(new CommonMessageResponse(msg, messageObj, true));
                    }
                    catch (Exception ex)
                    {
                        string msg = "查询失败,未知错误。";
                        Logger.Exception(ex);
                        CoolQDispatcher.SendMessage(new CommonMessageResponse(msg, messageObj, true));
                    } // catch
                }     // using
            }         // while
        }             //void