Exemplo n.º 1
0
        /// <summary>
        /// 将消息中的东西替换为CQ码
        /// </summary>
        /// <param name="message">原始消息</param>
        /// <returns></returns>
        public static string Start(ReceiveMessage message)
        {
            string result = string.Empty;
            string msg    = message.CurrentPacket.Data.Content;

            switch (message.CurrentPacket.Data.MsgType)
            {
            case "AtMsg":
            {
                TextMessage textMessage = JsonConvert.DeserializeObject <TextMessage>(msg);
                result = textMessage.Content;
                GroupMemberList ls = JsonConvert.DeserializeObject <GroupMemberList>(WebAPI.GetGroupMemberList(message.CurrentPacket.Data.FromGroupId));
                foreach (var item in textMessage.UserID)
                {
                    GroupMemberList.Memberlist mem = ls.MemberList.Where(x => x.MemberUin == item).First();
                    foreach (var pro in mem.GetType().GetProperties())
                    {
                        if (string.IsNullOrEmpty(pro.GetValue(mem).ToString()))
                        {
                            pro.SetValue(mem, null);
                        }
                    }
                    string originStr = "@" + (mem.AutoRemark ?? mem.GroupCard ?? mem.NickName);
                    result = result.Replace(originStr, CQApi.CQCode_At(item).ToSendString());
                }
                break;
            }

            case "TextMsg":
                result = msg;
                break;

            case "PicMsg":
            {
                PicMessage picMessage = JsonConvert.DeserializeObject <PicMessage>(message.CurrentPacket.Data.Content);
                if (!Directory.Exists("data\\image"))
                {
                    Directory.CreateDirectory("data\\image");
                }
                result = picMessage.Content;
                foreach (var item in picMessage.GroupPic)
                {
                    string md5  = GenerateMD5(item.FileMd5).ToUpper();
                    string path = $"data\\image\\{md5}.cqimg";
                    if (!File.Exists(path))
                    {
                        IniConfig ini = new IniConfig(path);
                        ini.Object.Add(new ISection("image"));
                        ini.Object["image"]["md5"]  = item.FileMd5;
                        ini.Object["image"]["size"] = item.FileSize;
                        ini.Object["image"]["url"]  = item.Url;
                        ini.Save();
                    }
                    result += CQApi.CQCode_Image(md5);
                }
                break;
            }

            case "VoiceMsg":
            {
                if (!Directory.Exists("data\\record\\"))
                {
                    Directory.CreateDirectory("data\\record\\");
                }
                JObject json = JObject.Parse(msg);
                string  url  = json["Url"].ToString();
                string  MD5  = GenerateMD5(url);
                string  path = "data\\record\\" + MD5 + ".silk";
                if (!File.Exists(path))
                {
                    IniConfig ini = new IniConfig(path);
                    ini.Object.Add(new ISection("record"));
                    ini.Object["record"]["url"] = url;
                    ini.Save();
                }
                result = CQApi.CQCode_Record(MD5 + ".silk").ToString();
                break;
            }
            }
            result = Regex.Replace(result, "\\[表情(\\d*)\\]", "[CQ:face,id=$1]");
            foreach (var a in result)
            {
                if (a == '\ud83d' && result.IndexOf(a) != result.Length - 1)
                {
                    string str  = a.ToString() + result[result.IndexOf(a) + 1].ToString();
                    string text = "";
                    foreach (var item in Encoding.UTF32.GetBytes(str))
                    {
                        text += item.ToString("x");
                    }
                    result = result.Replace(str, CQApi.CQCode_Emoji(Convert.ToInt32(text, 16)).ToString());
                    break;
                }
            }
            return(result);
        }
Exemplo n.º 2
0
        /// <summary>
        /// 将消息中的东西替换为CQ码
        /// </summary>
        /// <param name="message">原始消息</param>
        /// <returns></returns>
        public static string Start(ReceiveMessage message)
        {
            string result = string.Empty;
            string msg    = message.CurrentPacket.Data.Content;

            switch (message.CurrentPacket.Data.MsgType)
            {
            case "TempSessionMsg":
                if (msg.Contains("图片"))
                {
                    var c = JsonConvert.DeserializeObject <PicMessage>(msg).FriendPic;
                    foreach (var item in c)
                    {
                        result += MakeCQImage(item);
                    }
                }
                else
                {
                    result = JObject.Parse(msg)["Content"].ToString();
                }

                break;

            case "AtMsg":
            {
                //at消息主要将消息中的at消息转变为CQ码
                //而@人名 中的人名格式可能会不同,不能直接用群名片替换,所以要从群成员列表寻找这个人
                //按备注->群名片->昵称的顺序,替换可能出现的名称
                TextMessage textMessage = JsonConvert.DeserializeObject <TextMessage>(msg);
                result = textMessage.Content;
                //从缓存寻找这个群
                GroupMemberList ls = MemberSave.Find(x => x.GroupUin == message.CurrentPacket.Data.FromGroupId);
                if (ls == null)         //未在缓存找到,将这个群加入缓存
                {
                    ls = JsonConvert.DeserializeObject <GroupMemberList>(
                        WebAPI.GetGroupMemberList(message.CurrentPacket.Data.FromGroupId));
                    MemberSave.Add(ls);
                }

                foreach (var item in textMessage.UserID)
                {
                    GroupMemberList.Memberlist mem = ls.MemberList.Where(x => x.MemberUin == item).First();
                    foreach (var pro in mem.GetType().GetProperties())
                    {
                        //将空文本变成null,方便后续??运算符
                        try
                        {
                            if (string.IsNullOrEmpty(pro.GetValue(mem).ToString()))
                            {
                                pro.SetValue(mem, null);
                            }
                        }
                        catch (NullReferenceException e)
                        {
                            pro.SetValue(mem, null);         //如果是null则会跳至catch块
                        }
                    }

                    string originStr = "@" + (mem.AutoRemark ?? mem.GroupCard ?? mem.NickName);
                    result = result.Replace(originStr, CQApi.CQCode_At(item).ToSendString());
                }

                break;
            }

            case "TextMsg":
                result = msg;
                break;

            case "PicMsg":
            {
                //图片消息是将图片消息的信息配置进image文件夹下的以MD5为名称的cqimg文件内
                PicMessage picMessage =
                    JsonConvert.DeserializeObject <PicMessage>(message.CurrentPacket.Data.Content);
                if (!Directory.Exists("data\\image"))
                {
                    Directory.CreateDirectory("data\\image");
                }
                result = picMessage.Content;
                if (picMessage.GroupPic != null)         //是群图片消息
                {
                    foreach (var item in picMessage.GroupPic)
                    {
                        result += MakeCQImage(item);
                    }
                }
                else         //是好友图片消息
                {
                    foreach (var item in picMessage.FriendPic)
                    {
                        result += MakeCQImage(item);
                    }
                }
                break;
            }

            case "VoiceMsg":
            {
                if (!Directory.Exists("data\\record\\"))
                {
                    Directory.CreateDirectory("data\\record\\");
                }
                JObject json = JObject.Parse(msg);
                string  url  = json["Url"].ToString();
                string  MD5  = GenerateMD5(url);
                string  path = "data\\record\\" + MD5 + ".silk";
                if (!File.Exists(path))
                {
                    IniConfig ini = new IniConfig(path);
                    ini.Object.Add(new ISection("record"));
                    ini.Object["record"]["url"] = url;
                    ini.Save();
                }

                result = CQApi.CQCode_Record(MD5 + ".silk").ToString();
                break;
            }

            case "RedBagMsg":
            {
                string title = JObject.Parse(msg)["Content"]?.ToString();
                result = $"[CQ:hb,title={title}]";
                break;
            }

            case "XmlMsg":
            {
                result = JObject.Parse(msg)["Content"].ToString();
                var xml   = new XmlDocument();
                int index = result.IndexOf("</msg>");
                result = result.Substring(0, index + "</msg>".Length);
                xml.LoadXml(result);
                var root = xml.FirstChild.NextSibling;
                foreach (XmlAttribute item in root.Attributes)
                {
                    if (item.Name == "actionData" && item.Value.Contains("group:"))
                    {
                        result = $"[CQ:contact,id={item.Value.Replace("group:", "")},type=group]";
                        break;
                    }
                    else if (item.Name == "actionData" && item.Value.Contains("AppCmd://OpenContactInfo/?uin"))
                    {
                        result = $"[CQ:contact,id={item.Value.Replace("AppCmd://OpenContactInfo/?uin=", "")},type=qq]";
                        break;
                    }
                    else if (item.Name == "url" && item.Value.Contains("y.music.163.com"))
                    {
                        int musicid = Convert.ToInt32(Regex.Replace(item.Value, "https:\\/\\/y.music.163.com\\/m/song\\/([0-9]*)\\/\\?userid=([0-9]*)", "$1"));
                        int userid  = Convert.ToInt32(Regex.Replace(item.Value, "https:\\/\\/y.music.163.com\\/m/song\\/([0-9]*)\\/\\?userid=([0-9]*)", "$2"));
                        result = $"[CQ:music,type=163,id={musicid},userid={userid}]";
                        break;
                    }
                }
                if (!result.StartsWith("[CQ:"))
                {
                    result = $"[CQ:rich,content={result.Replace("\n","").Replace("\r","")}]";
                }
                break;
            }

            case "JsonMsg":
            {
                result = JObject.Parse(msg)["Content"].ToString();
                result = result.Substring(result.IndexOf("{\"app\":\""));
                var json = JObject.Parse(result);
                if (json["meta"]["music"] != null)
                {
                    var musicroot = json["meta"]["music"];
                    int musicid   = Convert.ToInt32(Regex.Replace(musicroot["jumpUrl"].ToString(), "https:\\/\\/y.music.163.com\\/m/song\\/([0-9]*)\\/\\?userid=([0-9]*)", "$1"));
                    int userid    = Convert.ToInt32(Regex.Replace(musicroot["jumpUrl"].ToString(), "https:\\/\\/y.music.163.com\\/m/song\\/([0-9]*)\\/\\?userid=([0-9]*)", "$2"));
                    result = $"[CQ:music,type=163,id={musicid},userid={userid},title={musicroot["title"]},desc={musicroot["desc"]}]";
                }
                else
                {
                    result = $"[CQ:rich,title={json["prompt"]}]";
                }
                break;
            }
            }

            result = Regex.Replace(result, "\\[表情(\\d*)\\]", "[CQ:face,id=$1]"); //处理QQ表情信息
            //处理emoji消息
            foreach (var a in result)
            {
                //UTF-8下,大部分的emoji都是以\ud83d开头
                if (a == '\ud83d' && result.IndexOf(a) != result.Length - 1)
                {
                    //取这个emoji
                    string        str   = a.ToString() + result[result.IndexOf(a) + 1].ToString();
                    UTF32Encoding enc   = new UTF32Encoding(true, false);
                    byte[]        bytes = enc.GetBytes(str); //转换字节数组
                    //使用BitConvert将字节数组转换为16进制,之后转换为10进制即可
                    result = result.Replace(str,
                                            CQApi.CQCode_Emoji(Convert.ToInt32(BitConverter.ToString(bytes).Replace("-", ""), 16))
                                            .ToString());
                    break;
                }
            }

            return(result);
        }
Exemplo n.º 3
0
        public static void Poster()
        {
posthead:
            Random r = new Random(Guid.NewGuid().GetHashCode());

            try
            {
                if (Event_GroupMessage.ProtectCount >= 3)
                {
                    Log($"trapped in bug:{ReportBUGTime},{GetTickCount()}");
                    if (ReportBUGTime > 0)
                    {
                        if (GetTickCount() >= ReportBUGTime)
                        {
                            Log($"Unlimited network:{Event_GroupMessage.ProtectCount}/ ms", ConsoleColor.Red);
                            ReportBUGTime = 0;
                            string bugr = $"{DateTime.Now.ToString()}\n" +
                                          "机器人在处理消息时发现消息流量异常,可能机器人进程被长时间挂起。" +
                                          "为了避免机器人继续处理消息导致暴走,已经切断消息处理。" +
                                          "请持有32766级别以上权限的用户发送.bugclose解除切断。" +
                                          $"\n异常消息流量:{Event_GroupMessage.ProtectCount}条/毫秒\n\n若无人协助,则切断将在{Event_GroupMessage.ProtectCount * 10}秒后解除。";
                            new QQ(pCQ, 1361778219).SendPrivateMessage(bugr);
                            List <GroupInfo> gi = pCQ.GetGroupList();
                            foreach (GroupInfo gii in gi)
                            {
                                //gii.Group.SendGroupMessage(bugr);
                            }
                        }
                    }
                    Event_GroupMessage.ProtectCount--;
                    Thread.Sleep(10000);
                    goto posthead;
                }

                if (r.Next(0, 1000) == 88)
                {
                    if (DateTime.Now.Hour >= 7 && DateTime.Now.Hour < 24)
                    {
                        List <GroupInfo> lg = pCQ.GetGroupList();
                        Event_GroupMessage.Artifical(lg[r.Next(0, lg.Count)].Group);
                    }
                }

                //OSU
                if (LastOSUTime == DateTime.Now.Hour && DateTime.Now.Minute == 30)
                {
                    Storage ignore = new Storage("ignore");
                    if (ignore.getkey("577344771", "artist") == "√")
                    {
                        goto NoPOSU;
                    }
                    LastOSUTime = (DateTime.Now.Hour + 1) % 24;
                    Group droid = new Group(pCQ, 577344771);
                    List <GroupMemberInfo> gml = droid.GetGroupMemberList();
                    GroupMemberInfo        gmi = gml[r.Next(0, gml.Count)];
                    long   qq      = gmi.QQ.Id;
                    string targett = MessagePoster.ptList[r.Next(0, MessagePoster.ptList.Count)];
                    ScriptDrawer.Draw("C:\\DataArrange\\PTemple\\" + targett + ".txt",
                                      MessagePoster.workpath + "\\data\\image\\" + targett + ".png",
                                      "[qq]", qq.ToString(),
                                      "[nick]", gmi.Nick,
                                      "[card]", gmi.Card == "" ? gmi.Nick : gmi.Card,
                                      "[sex]", gmi.Sex.ToString(),
                                      "[age]", gmi.Age.ToString(),
                                      "[group]", "577344771"
                                      );
                    droid.SendGroupMessage("现在是 " + DateTime.Now.Hour +
                                           "时30分 不整,恭喜幸运小朋友:" + CQApi.CQCode_At(qq) + "\n"
                                           + CQApi.CQCode_Image(targett + ".png"));
                }
NoPOSU:

                //BlackDied
                if (DateTime.Now.Hour == 24 || DateTime.Now.Hour == 0)
                {
                    if (DateTime.Now.Month == 3 && DateTime.Now.Day == 27)
                    {
                        if (!HasSendDie)
                        {
                            List <GroupInfo> gi = pCQ.GetGroupList();
                            foreach (GroupInfo gii in gi)
                            {
                                gii.Group.SendGroupMessage("今天。是黑嘴去世" + (DateTime.Now.Year - 2015) + "周年的日子。在这里打扰了大家,非常抱歉。\n黑嘴,名字来源于本机作者的一只狗,这只狗在本机作者的精神支柱上有很大的作用【虽然这听起来很荒唐】,它也渐渐在本机主人的脑子里逐渐扭曲抽象成了一种精神依靠。\n祝你在天堂快乐,黑嘴。       -3.27\n不接受任何对此条消息的议论。");
                            }
                            HasSendDie = true;
                        }
                    }
                }

                //Moring Protection
                Storage sys = new Storage("system");
                if (DateTime.Now.Hour >= 3 && DateTime.Now.Hour <= 5)
                {
                    if (sys.getkey("root", "sleep") != "zzz")
                    {
                        sys.putkey("root", "sleep", "zzz");
                        QQ master = new QQ(pCQ, 1361778219);
                        master.SendPrivateMessage("主人晚安~");
                        Console.Clear();
                        Log("[SLEEP] zzzzzzz");
                        logid = Guid.NewGuid().ToString();
                        //Application.Restart();
                        //System.Diagnostics.Process.Start(workpath + "\\CQA.exe", "/account 3529296290");
                        //System.Environment.Exit(0);
                    }
                    Thread.Sleep(1000);
                    goto posthead;
                }
                if (sys.getkey("root", "sleep") == "zzz")
                {
                    Log("[WAKE UP] ouch");
                    QQ master = new QQ(pCQ, 1361778219);
                    master.SendPrivateMessage("主人早上好~");
                    sys.putkey("root", "sleep", "!!");
                }

                Group g;
                //Say
                try
                {
                    for (int i = 0; i < delays.Count; i++)
                    {
resay:
                        delaymsg dm = delays[i];
                        if (GetTickCount() >= dm.time)
                        {
                            if (dm.voice == true)
                            {
                                SpeechSynthesizer reader = new SpeechSynthesizer();
                                string            fname  = GetTickCount().ToString();
                                reader.SetOutputToWaveFile(
                                    workpath + "\\data\\record\\say_" + fname + ".wav",
                                    new SpeechAudioFormatInfo(32000, AudioBitsPerSample.Sixteen, AudioChannel.Mono)
                                    );
                                reader.Rate   = -2 + new Random(Guid.NewGuid().GetHashCode()).Next(0, 4);
                                reader.Volume = 100;
                                //reader.SelectVoice("Microsoft Lili");
                                PromptBuilder builder = new PromptBuilder();
                                builder.AppendText(dm.msg);
                                Log("Speak started at :" + GetTickCount());
                                reader.Speak(builder);
                                Log("Speak successfully :" + GetTickCount());
                                reader.Dispose();
                                if (dm.kind == 0)
                                {
                                    new Group(pCQ, dm.group).SendGroupMessage(CQApi.CQCode_Record("say_" + fname + ".wav"));
                                }
                                else
                                {
                                    new QQ(pCQ, dm.group).SendPrivateMessage(CQApi.CQCode_Record("say_" + fname + ".wav"));
                                }
                            }
                            else
                            {
                                Log("Send successfully.");
                                if (dm.kind == 0)
                                {
                                    new Group(pCQ, dm.group).SendGroupMessage(dm.msg);
                                }
                                else
                                {
                                    new QQ(pCQ, dm.group).SendPrivateMessage(dm.msg);
                                }
                            }
                            delays.Remove(dm); goto resay;
                        }
                    }
                }
                catch
                {
                }

                //Undertale
                if (UT.targetg != 0)
                {
                    if (GetTickCount() - UT.tick >= 20000)
                    {
                        g = new Native.Csharp.Sdk.Cqp.Model.Group(pCQ, UT.targetg);
                        if (UT.winstr == "")
                        {
                            g.SendGroupMessage("nobody passed round" + UT.round + ",answer:" + UT.role);
                        }
                        else
                        {
                            g.SendGroupMessage("answer:" + UT.role + "\n" + UT.winstr);
                        }

                        if (UT.round == 5)
                        {
                            string playstr = "";
                            for (int i = 0; i < UT.ps.Count; i++)
                            {
                                playstr = playstr + CQApi.CQCode_At(UT.ps[i].qq) + " " + (int)(UT.ps[i].score * 10) / 10 + " points\n";
                            }
                            UT.targetg = 0;
                            g.SendGroupMessage("game closed\n" + playstr);
                        }
                        else
                        {
                            UT.nextRound(); UT.tick = GetTickCount();
                            g.SendGroupMessage("round " + UT.round + "(result:20s later):" + UT.dialog);
                        }
                    }
                }

                //Hot Poster
                string fstr = ""; string estr = ""; string[] qtemp;
                HotMsg hhmsg = new HotMsg();
                for (int s = 0; s < Manager.mHot.data.Count; s++)
                {
                    hhmsg = (HotMsg)Manager.mHot.data[s];
                    if (DateTime.Now.Hour >= 22 && hhmsg.hasup == false && TenClockLock == false)
                    {
                        TenClockLock = true;
                        Log("Annouce:" + hhmsg.group, ConsoleColor.Green);
                        qtemp = hhmsg.banqq.Split(';');
                        for (int i = 0; i < qtemp.Length - 1; i++)
                        {
                            estr = estr + CQApi.CQCode_At(Convert.ToInt64(qtemp[i]));
                        }
                        qtemp = hhmsg.qq.Split(';');
                        for (int i = 0; i < qtemp.Length - 1; i++)
                        {
                            fstr = fstr + CQApi.CQCode_At(Convert.ToInt64(qtemp[i]));
                        }
                        hhmsg.hasup = true;
                        g           = new Native.Csharp.Sdk.Cqp.Model.Group(pCQ, Convert.ToInt64(hhmsg.group));
                        g.SendGroupMessage(hhmsg.msg);
                        Manager.mHot.data[s] = hhmsg;
                    }
                }
                //Homework network
                string f = "0";
                if (File.Exists("C:\\DataArrange\\homeworklock.bin"))
                {
                    f = File.ReadAllText("C:\\DataArrange\\homeworklock.bin", Encoding.UTF8);
                }
                if (Convert.ToInt64(f) == 1)
                {
                    Log("New homework recevied !", ConsoleColor.Green);
                    f = File.ReadAllText("C:\\DataArrange\\homework.bin", Encoding.UTF8);
                    g = new Native.Csharp.Sdk.Cqp.Model.Group(pCQ, 817755769);
                    g.SendGroupMessage("[今日作业推送消息]\n" + f + "\n————来自黑嘴稽气人的自动推送");
                    File.WriteAllText("C:\\DataArrange\\homeworklock.bin", "0");
                }
                f = "";
                if (File.Exists("C:\\DataArrange\\announcer.bin"))
                {
                    f = File.ReadAllText("C:\\DataArrange\\announcer.bin", Encoding.UTF8);
                }
                if (f != "")
                {
                    Log("Announce:" + f, ConsoleColor.Green);
                    string[] p = f.Split('\\'); long gr = 0;
                    if (p[0] == "class")
                    {
                        gr = 817755769;
                    }
                    if (p[0] == "inter")
                    {
                        gr = 554272507;
                    }
                    g = new Native.Csharp.Sdk.Cqp.Model.Group(pCQ, gr);
                    switch (p[1])
                    {
                    case ("hlesson"):
                        f = "今天上午的网课出炉啦~\n地址:{url}\n往期网课精彩回顾:https://space.bilibili.com/313086171/channel/detail?cid=103565 ".Replace("{url}", p[2]);
                        break;

                    case ("lesson"):
                        f = "今天全天的网课出炉啦~\n地址:{url}\n往期网课精彩回顾:https://space.bilibili.com/313086171/channel/detail?cid=103565 ".Replace("{url}", p[2]);
                        break;

                    case ("default"):
                        f = p[2];
                        break;

                    default:
                        Log("Unkown announce .", ConsoleColor.Red);
                        return;
                    }
                    g.SendGroupMessage("[通知]\n" + f + "\n————来自黑嘴稽气人的自动推送");
                    File.WriteAllText("C:\\DataArrange\\announcer.bin", "");
                }
            }
            catch (Exception err)
            {
                Log(err.StackTrace + "\n" + err.Message, ConsoleColor.Red);
            }
            Thread.Sleep(1000);
            goto posthead;
        }