protected override void Invoking(MessageReceivedEventArgs e, ComplexMessage elements)
        {
            var version = VersionUtilities.GetTagVersion();

            e.Reply(Resources.Processing);

            if (VersionUtilities.GetLatestVersion(out Version latestVersion, out _))
            {
                if (version < latestVersion)
                {
                    e.Source.Send($"有新版本更新哦!(ૢ˃ꌂ˂⁎)\n当前版本:{version}\n最新 Release 版本:{latestVersion}\n\n如果需要更新,请发送 {Configuration.Prefix}update run");
                }
                else if (version == latestVersion)
                {
                    e.Source.Send($"当前版本已是最新版本!(ૢ˃ꌂ˂⁎)\n当前版本:{version}");
                }
                else
                {
                    e.Source.Send($"当前版本较最新 Release 版本新,可能你正在使用内测版本 (ノ´▽`)ノ♪\n当前版本:{version}\n最新 Release 版本:{latestVersion}");
                }
            }
            else
            {
                e.Reply("获取最新版本信息失败了 (;´д`)ゞ");
            }
        }
示例#2
0
        protected override void Invoking(MessageReceivedEventArgs e, ComplexMessage elements)
        {
            ((JObject)SlappingConfig.Config).Remove(e.Subject.Number.ToString());
            SlappingConfig.Save();

            e.Reply("你的拍一拍自定义语句重置好了 |ू・ω・` )");
        }
        protected override void Invoking(MessageReceivedEventArgs e, ComplexMessage elements)
        {
            var    version    = VersionUtilities.GetVersion();
            string sdkVersion = SdkInfo.Version;

#if DEBUG
            string versionStr = version + " (Debug)";
#else
            string versionStr = VersionUtilities.GetTagVersion() + " (Release)";
#endif
            string ricky = "Ricky8955555";
            string syc   = "SYC";

            if (e.Source is IGroup group)
            {
                var rickyMember = Member(RickyNumber, group);
                var sycMember   = Member(SYCNumber, group);

                try
                {
                    rickyMember.Request();
                    ricky = rickyMember.Mention().ToSendableString();
                }
                catch { }

                try
                {
                    sycMember.Request();
                    syc = sycMember.Mention().ToSendableString();
                }
                catch { }
            }

            e.Source.Send(string.Format(Resources.About, ricky, syc, Resources.ProjectURL, Resources.CommunityURL, Resources.SDKProjectURL, Resources.CoolQURL, Resources.HomepageURL) + $"\n\n插件版本:{versionStr}\nSDK版本:{sdkVersion}\n编译时间:{VersionUtilities.ToDateTime(version)}");
        }
        protected override void Invoking(MessageReceivedEventArgs e, ComplexMessage elements)
        {
            e.Reply(Resources.Processing);

            if (HttpUtilities.HttpGet(Resources.CovidStatusApiURL, out string content))
            {
                try
                {
                    var json       = JObject.Parse(content);
                    var dJson      = JObject.Parse(json["data"].ToString());
                    var chinaTotal = dJson["chinaTotal"];
                    var chinaAdd   = dJson["chinaAdd"];

                    e.Source.Send($"数据截至:{dJson["lastUpdateTime"]}\n" +
                                  $"累计确诊:{chinaTotal["confirm"]}(较昨日:{chinaAdd["confirm"].ToObject<int>():+#;-#;0})\n" +
                                  $"累计治愈:{chinaTotal["heal"]}(较昨日:{chinaAdd["heal"].ToObject<int>():+#;-#;0})\n" +
                                  $"累计死亡:{chinaTotal["dead"]}(较昨日:{chinaAdd["dead"].ToObject<int>():+#;-#;0})\n" +
                                  $"现有确诊:{chinaTotal["nowConfirm"]}(较昨日:{chinaAdd["nowConfirm"].ToObject<int>():+#;-#;0})\n" +
                                  $"现有疑似:{chinaTotal["suspect"]}(较昨日:{chinaAdd["suspect"].ToObject<int>():+#;-#;0})\n" +
                                  $"现有重症:{chinaTotal["nowSevere"]}(较昨日:{chinaAdd["nowSevere"].ToObject<int>():+#;-#;0})\n" +
                                  "(数据来源:腾讯新闻)");
                }
                catch
                {
                    e.Reply($"信息处理失败了 (;´д`)ゞ");
                }
            }
            else
            {
                e.Reply($"请求失败了 (;´д`)ゞ");
            }
        }
示例#5
0
        public static void ComplexMessage_OperationFormatUseLiteral()
        {
            System.ServiceModel.ChannelFactory <IEchoSoapService> factory = DispatcherHelper
                                                                            .CreateChannelFactory <EchoSoapService, IEchoSoapService>();
            factory.Open();
            IEchoSoapService channel = factory.CreateChannel();

            ((System.ServiceModel.Channels.IChannel)channel).Open();
            var expected = new ComplexMessage
            {
                Date          = System.DateTime.Now,
                InnerMessages = new InnerComplexMessage[]
                {
                    new InnerComplexMessage
                    {
                        Guid = System.Guid.NewGuid(),
                    },
                },
            };
            ComplexMessage actual = channel.GetComplexMessageLiteral(expected);

            Assert.Equal(expected, actual);
            ((System.ServiceModel.Channels.IChannel)channel).Close();
            factory.Close();
            TestHelper.CloseServiceModelObjects((System.ServiceModel.Channels.IChannel)channel, factory);
        }
示例#6
0
        public void SendComplexMessage(string message)
        {
            try
            {
                // Create the message to send
                ComplexMessage msg = new ComplexMessage
                {
                    UniqueID = Guid.NewGuid(),
                    Time = DateTimeOffset.Now,
                    Message = message
                };

                // Serialize the message to a binary array
                byte[] binaryMessage = SerializationHelper.Serialize(msg);

                // Send the message; the state is used by ClientSocket_WriteCompleted to display an output to the log
                string description = "<complex message: " + msg.UniqueID + ">";
                ClientSocket.WriteAsync(binaryMessage, description);

                Console.WriteLine("Sending message " + description);
            }
            catch (Exception ex)
            {
                ResetSocket();
                Console.WriteLine("Error sending message to socket: [" + ex.GetType().Name + "] " + ex.Message);
            }
            finally
            {
                RefreshDisplay();
            }
        }
示例#7
0
        protected bool GetParameter(string message, out ComplexMessage parameters)
        {
            string[] strs = message.Split(new string[] { " ", Constants.CQNewLine }, 2, StringSplitOptions.RemoveEmptyEntries);

            if (strs.Length > 0 && strs[0].ToLower() == ResponseCommand)
            {
                if (strs.Length == 1)
                {
                    parameters = null;
                }
                else
                {
                    var splitter = new CommandSplitter();
                    var command  = splitter.Split(strs[1]);
                    parameters = command?.Select(x => ComplexMessage.Parse(x).ToMessageElement()).ToComplexMessage();
                }

                return(true);
            }
            else
            {
                parameters = null;
                return(false);
            }
        }
示例#8
0
        protected override void Invoking(MessageReceivedEventArgs e, ComplexMessage elements = null)
        {
            string prefix    = PluginConfig.Config["Prefix"].ToString();
            var    appInfos  = GetApps(e.Source, e.Sender).Select(x => $"{(x.IsEnabled(e.Source) ? string.Empty : "【已停用】")}{x.DisplayName} ({x.Name}):\n" + string.Join("\n", x.Features.Where(f => f.Usage != null).Select(f => f.Usage).OrderBy(f => f))).OrderBy(x => x);
            int    pageCount = (int)Math.Ceiling((float)appInfos.Count() / MaxCount);
            int    pageIndex = 1;

            if (elements == null ||
                (elements != null && elements.Count == 1 && elements[0] is PlainText plainText && int.TryParse(plainText.Content, out pageIndex)))
            {
                if (pageIndex <= pageCount)
                {
                    int start         = (pageIndex - 1) * MaxCount;
                    int count         = pageIndex < pageCount ? MaxCount : appInfos.Count() - start;
                    var appInfosSplit = appInfos.Skip(start).Take(count);
                    e.Source.Send($"帮助菜单 (第 {pageIndex} 页 / 共 {pageCount} 页):\n" + string.Join("\n\n", appInfosSplit));
                }
                else if (pageIndex < 1)
                {
                    e.Source.Send($"页数不能小于等于 0 (T▽T)");
                }
                else if (pageIndex > pageCount)
                {
                    e.Source.Send($"对于你而言,该帮助菜单仅有 {pageCount} 页 |ω・`)");
                }
            }
示例#9
0
        protected override void Invoking(MessageReceivedEventArgs e, ComplexMessage elements = null)
        {
            var client = new HttpClient();
            var res    = client.GetAsync(Resources.CovidStatusApiURL).Result;

            if (res.IsSuccessStatusCode)
            {
                try
                {
                    var json       = JObject.Parse(res.Content.ReadAsStringAsync().Result);
                    var dJson      = JObject.Parse(json["data"].ToString());
                    var chinaTotal = dJson["chinaTotal"];
                    var chinaAdd   = dJson["chinaAdd"];

                    e.Source.Send($"数据截至:{dJson["lastUpdateTime"]}\n" +
                                  $"累计确诊:{chinaTotal["confirm"]}(较昨日:{chinaAdd["confirm"].ToObject<int>():+#;-#;0})\n" +
                                  $"累计治愈:{chinaTotal["heal"]}(较昨日:{chinaAdd["heal"].ToObject<int>():+#;-#;0})\n" +
                                  $"累计死亡:{chinaTotal["dead"]}(较昨日:{chinaAdd["dead"].ToObject<int>():+#;-#;0})\n" +
                                  $"现有确诊:{chinaTotal["nowConfirm"]}(较昨日:{chinaAdd["nowConfirm"].ToObject<int>():+#;-#;0})\n" +
                                  $"现有疑似:{chinaTotal["suspect"]}(较昨日:{chinaAdd["suspect"].ToObject<int>():+#;-#;0})\n" +
                                  $"现有重症:{chinaTotal["nowSevere"]}(较昨日:{chinaAdd["nowSevere"].ToObject<int>():+#;-#;0})\n" +
                                  "(数据来源:腾讯新闻)");
                }
                catch
                {
                    e.Reply($"信息处理失败了 (;´д`)ゞ");
                }
            }
            else
            {
                e.Reply($"请求失败了 (;´д`)ゞ");
            }
        }
示例#10
0
        public void ComplexMessageShouldCreate()
        {
            var newRoomId    = Guid.NewGuid();
            var roomNumber   = "2428B";
            var complexId    = Guid.NewGuid();
            var numberOfBeds = 4;
            var roomType     = "Apartment";
            var leaseStart   = DateTime.Now;
            var leaseEnd     = DateTime.Now.AddDays(3);
            var queOperator  = 0;

            var complexMessage = new ComplexMessage()
            {
                RoomId       = newRoomId,
                ComplexId    = complexId,
                LeaseStart   = leaseStart,
                LeaseEnd     = leaseEnd,
                NumberOfBeds = numberOfBeds,
                RoomNumber   = roomNumber,
                RoomType     = roomType,
                QueOperator  = queOperator
            };

            Assert.NotNull(complexMessage);
            Assert.True(complexMessage.RoomId == newRoomId);
            Assert.True(complexMessage.ComplexId == complexId);
            Assert.True(complexMessage.LeaseStart == leaseStart);
            Assert.True(complexMessage.LeaseEnd == leaseEnd);
            Assert.True(complexMessage.NumberOfBeds == numberOfBeds);
            Assert.True(complexMessage.RoomNumber == roomNumber);
            Assert.True(complexMessage.RoomType == roomType);
            Assert.True(complexMessage.QueOperator == queOperator);
            Assert.True(complexMessage.RoomType == roomType);
        }
示例#11
0
        protected override void Invoking(MessageReceivedEventArgs e, ComplexMessage elements)
        {
            var  config    = (JArray)BlacklistConfig.Config;
            long number    = long.MinValue;
            bool?operation = false;

            if (elements.Count == 1 && elements.TryDeconstruct(out PlainText plainText))
            {
                string[] splitText = plainText.Content.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                if (splitText.Length == 2 && long.TryParse(splitText[1], out number))
                {
                    operation = splitText[0].ToLower().ToBool("add", "remove");
                }
            }
            else if (elements.Count == 2 && elements.TryDeconstruct(out plainText, out Mention mention))
            {
                operation = plainText.Content.Trim().ToLower().ToBool("add", "remove");
                number    = mention.TargetNumber;
            }

            if (number == Owner || number == Bot.CurrentUser.Number)
            {
                e.Reply("无法将主人或机器人加入到黑名单 ─=≡Σ(((つ•̀ω•́)つ");
            }
            else
            {
                if ((!operation.HasValue) || number == long.MinValue)
                {
                    NotifyIncorrectUsage(e);
                }
                else if (operation.Value)
                {
                    if (config.Contains(number, true))
                    {
                        e.Reply($"{number} 已存在黑名单内 (ц`ω´ц*)");
                    }
                    else
                    {
                        config.Add(number);
                        BlacklistConfig.Save();
                        e.Reply($"已将 {number} 加入黑名单 ❥(ゝω・✿ฺ)");
                    }
                }
                else
                {
                    if (config.Contains(number, true))
                    {
                        BlacklistConfig.SetValueAndSave(config.Remove(number, true));
                        e.Reply($"已将 {number} 移出黑名单 ❥(ゝω・✿ฺ)");
                    }
                    else
                    {
                        e.Reply($"{number} 不存在黑名单内 (ц`ω´ц*)");
                    }
                }
            }
        }
示例#12
0
        private void EnterButtton_Click(object sender, EventArgs e)
        {
            this.m1              = SerializeAndDeserialize.Serialize(textBox1.Text);
            this.m2              = SerializeAndDeserialize.Serialize(textBox2.Text);
            this.cm.First        = this.m1;
            this.cm.Second       = this.m2;
            this.cm.NumberStatus = 1;
            this.m = SerializeAndDeserialize.Serialize(this.cm);
            data   = this.m.Data;
            stream.Write(data, 0, data.Length);
            if (stream.CanRead)
            {
                int    numberOfBytesRead = 0;
                byte[] readingData       = new byte[6297630];
                do
                {
                    numberOfBytesRead = stream.Read(readingData, 0, readingData.Length);
                } while (stream.DataAvailable);
                this.m.Data = readingData;
                this.cm     = (ComplexMessage)SerializeAndDeserialize.Deserialize(m);

                // Успешная авторизация
                if (cm.NumberStatus == 2)
                {
                    ComplexMessage complexMessage = (ComplexMessage)SerializeAndDeserialize.Deserialize(m);
                    User           user1          = (User)SerializeAndDeserialize.Deserialize(complexMessage.First);
                    Bonus          bonus          = (Bonus)SerializeAndDeserialize.Deserialize(complexMessage.Second);
                    if (user1.Role == "Admin")
                    {
                        AdminForm adminForm = new AdminForm();
                        adminForm.form1       = this;
                        adminForm.label1.Text = user1.Login;
                        adminForm.Show();
                    }
                    else
                    {
                        Form4 userForm = new Form4();
                        userForm.labelLogin.Text = user1.Login;
                        userForm.currentUser     = user1;
                        userForm.Show();
                        userForm.form1 = this;
                    }
                    // Здесь осуществляется вход в новую прогу (для 6 лабы)

                    this.Hide();
                }

                // Ошибка авторизации
                else if (cm.NumberStatus == 3)
                {
                    MessageBox.Show("Неверный логин или пароль");
                }
            }
        }
 protected override void Invoking(MessageReceivedEventArgs e, ComplexMessage elements)
 {
     if (Chattables.Switchs(e.Source))
     {
         e.Source.Send("已开启自动复读 ヾ(^Д^*)/");
     }
     else
     {
         e.Source.Send("已关闭自动复读 ヾ(^Д^*)/");
     }
 }
示例#14
0
 protected override void Invoking(MessageReceivedEventArgs e, ComplexMessage elements)
 {
     if (IsRunning)
     {
         e.Source.Send("配置正在运行中……");
         Handled = true;
     }
     else
     {
         IsRunning = true;
     }
 }
示例#15
0
        public void handleEvent(ComplexMessage <List <BookVM> > message)
        {
            if (message.Sender == this || message.Dest != this)
            {
                return;
            }

            if (message.MyEvent == ActionEvent.ReadyToDisplay)
            {
                Service.getBooks().InitWith(message.Message);
                message.Dest.move(new BookList());
            }
        }
示例#16
0
        public void SendComplexMessage(KeyValuePair<SimpleServerChildTcpSocket, ChildSocketState> childSocket, string message)
        {
            // This function sends a complex message to all connected clients
            ComplexMessage msg = new ComplexMessage();
            msg.UniqueID = Guid.NewGuid();
            msg.Time = DateTimeOffset.Now;
            msg.Message = message;

            string description = "<complex message: " + msg.UniqueID + ">";

            // Serialize it to a binary array
            byte[] binaryObject = SerializationHelper.Serialize(msg);

            SendSerializedMessage(childSocket, binaryObject, description);
        }
 protected override void Invoking(MessageReceivedEventArgs e, ComplexMessage elements)
 {
     try
     {
         var plainText = elements.OfType <PlainText>();
         if (plainText.Count() == elements.Count)
         {
             string str = string.Join(" ", plainText);
             e.Source.Send(string.Join(new string(' ', 3), str.ToCharArray()));
         }
     }
     catch (ApiException ex) when(ex.ErrorCode == -26)
     {
         e.Source.Send("发送出错了呀 (;´д`)ゞ");
     }
 }
示例#18
0
        protected virtual bool HandleMessage(object message, SimpleServerChildTcpSocket socket)
        {
            StringMessage stringMessage = message as StringMessage;
            if (stringMessage != null)
            {
                ConsoleService.Write("Socket read got a string message from " + socket.RemoteEndPoint + ": " + stringMessage.Message);
                return true;
            }

            ComplexMessage complexMessage = message as ComplexMessage;
            if (complexMessage != null)
            {
                ConsoleService.Write("Socket read got a complex message from " + socket.RemoteEndPoint + ": (UniqueID = " + complexMessage.UniqueID +
                    ", Time = " + complexMessage.Time + ", Message = " + complexMessage.Message + ")");
                return true;
            }

            return false;
        }
        protected override void Invoking(MessageReceivedEventArgs e, ComplexMessage elements)
        {
            var plainText = elements.OfType <PlainText>();

            if (plainText.Count() == elements.Count)
            {
                e.Reply(Resources.Processing);

                string str       = string.Join(" ", plainText);
                string musicName = str.Trim();

                if (HttpUtilities.HttpGet(string.Format(Resources.MusicApiURL, WebUtility.UrlEncode(musicName)), out string content))
                {
                    try
                    {
                        var json      = JObject.Parse(content);
                        var musicJson = json["result"]["songs"][0];
                        e.Reply($"这是您点的歌曲哦 φ(>ω<*) :{string.Join(" / ", musicJson["artists"].Select(x => x["name"]))} - {musicJson["name"]}");
                        e.Source.Send(new Music {
                            Id = musicJson["id"].ToObject <int>(), Platform = MusicPlatform.Netease
                        });
                    }
                    catch (ApiException ex) when(ex.ErrorCode == -11)
                    {
                        e.Reply("歌曲发送失败了 (;´д`)ゞ");
                    }
                    catch (ApiException)
                    {
                        throw;
                    }
                    catch
                    {
                        e.Reply($"没有叫 {musicName} 的歌曲哦 (๑>ڡ<)☆");
                    }
                }
                else
                {
                    e.Reply($"请求失败了 (;´д`)ゞ");
                }
            }
        }
示例#20
0
            static WcfTestClient()
            {
                _complexMessage = new ComplexMessage();

                var complexValues = new List<ComplexValue>();

                for (int i = 0; i < 200; i++)
                {
                    complexValues.Add(new ComplexValue
                    {
                        IntValue = i,
                        DoubleValue = i,
                        StringValue = i.ToString()
                    });
                }

                _complexMessage.Values = complexValues.ToArray();

                _smallStreamContent = Encoding.UTF8.GetBytes(new string('x', 0x1000));
                _largeStreamContent = Encoding.UTF8.GetBytes(new string('x', 0x100000));
            }
示例#21
0
        protected override void Invoking(MessageReceivedEventArgs e, ComplexMessage parameter = null)
        {
            var    assembly   = Assembly.GetExecutingAssembly();
            var    version    = assembly.GetName().Version;
            string sdkVersion = SdkInfo.Version;

#if DEBUG
            string versionStr = version + " (Debug)";
#else
            string versionStr = version + " (Release)";
#endif
            string ricky = "Ricky8955555";
            string syc   = "SYC";

            if (e.Source is IGroup group)
            {
                var rickyMember = Member(RickyNumber, group);
                var sycMember   = Member(SYCNumber, group);

                try
                {
                    ((IRequestable <IMember>)rickyMember).Request();
                    ricky = rickyMember.Mention().ToSendableString();
                }
                catch {}

                try
                {
                    ((IRequestable <IMember>)sycMember).Request();
                    syc = sycMember.Mention().ToSendableString();
                }
                catch {}
            }

            e.Source.Send(string.Format(Resources.About, ricky, syc, Resources.ProjectURL, Resources.SDKProjectURL, Resources.CoolQURL) + $"\n\n插件版本:{versionStr}\nSDK版本:{sdkVersion}\n编译时间:{ToDateTime(version)}");
        }
示例#22
0
        internal override void Invoke(MessageReceivedEventArgs e)
        {
            string message   = GetMessage(e.Message.ToString());
            string parameter = GetParameter(message);

            if (message?.Trim().ToLower() == ResponseCommand)
            {
                Invoking(e);
                Handled = true;
            }
            else if (parameter != null)
            {
                if (CanHaveParameter)
                {
                    Invoking(e, ComplexMessage.Parse(parameter));
                }
                else
                {
                    NotifyIncorrectUsage(e);
                }

                Handled = true;
            }
        }
示例#23
0
        private void changePasButton_Click(object sender, EventArgs e)
        {
            this.m1              = SerializeAndDeserialize.Serialize(newPasTextBox.Text);
            this.m2              = SerializeAndDeserialize.Serialize(textBoxEmail.Text);
            this.cm.First        = this.m1;
            this.cm.Second       = this.m2;
            this.cm.NumberStatus = 2;
            this.m = SerializeAndDeserialize.Serialize(this.cm);
            data   = this.m.Data;
            stream.Write(data, 0, data.Length);
            if (stream.CanRead)
            {
                int    numberOfBytesRead = 0;
                byte[] readingData       = new byte[6297630];
                do
                {
                    numberOfBytesRead = stream.Read(readingData, 0, readingData.Length);
                } while (stream.DataAvailable);
                this.m.Data = readingData;
                this.cm     = (ComplexMessage)SerializeAndDeserialize.Deserialize(m);

                // Успешная смена пароля
                if (cm.NumberStatus == 2)
                {
                    MessageBox.Show("Пароль успешно изменён");
                    form1.Show();
                    this.Hide();
                }

                // Ошибка смены пароля
                else if (cm.NumberStatus == 3)
                {
                    MessageBox.Show("Произошла ошибка при смене пароля");
                }
            }
        }
示例#24
0
        protected virtual bool HandleMessages(object message)
        {
            // Handle the message
            StringMessage stringMessage = message as StringMessage;
            if (stringMessage != null)
            {
                Console.WriteLine("Socket read got a string message: " + stringMessage.Message);
                if(stringMessage.Message.Equals("foo"))
                {
                    SendMessage("bar");
                }
                return true;
            }

            ComplexMessage complexMessage = message as ComplexMessage;
            if (complexMessage != null)
            {
                Console.WriteLine("Socket read got a complex message: (UniqueID = " + complexMessage.UniqueID +
                    ", Time = " + complexMessage.Time + ", Message = " + complexMessage.Message + ")");
                return true;
            }

            return false;
        }
示例#25
0
 protected abstract void Invoking(MessageReceivedEventArgs e, ComplexMessage elements);
示例#26
0
        public void Process()
        {
            while (true)
            {
                if (Stream.CanRead)
                {
                    byte[] myReadBuffer = new byte[6297630];
                    do
                    {
                        Stream.Read(myReadBuffer, 0, myReadBuffer.Length);
                    }while (Stream.DataAvailable);
                    Bonus bonus;
                    User  user;
                    MyLib.ComplexMessage complexMessage = new ComplexMessage();
                    MyLib.Message        message        = new MyLib.Message();
                    message.Data   = myReadBuffer;
                    complexMessage = (ComplexMessage)SerializeAndDeserialize.Deserialize(message);
                    // Регистрация
                    if (complexMessage.NumberStatus == 0)
                    {
                        try
                        {
                            bonus = (Bonus)SerializeAndDeserialize.Deserialize(complexMessage.First);
                        }
                        catch
                        {
                            bonus = null;
                        }

                        using (UserContainer db = new UserContainer())
                        {
                            user = (User)SerializeAndDeserialize.Deserialize(complexMessage.Second);
                            Bonus newBonus = new Bonus()
                            {
                                AmountBonus = bonus.AmountBonus
                            };
                            User newUser = new User()
                            {
                                Login = user.Login, Email = user.Email, Balance = user.Balance, Password = user.Password, Role = user.Role, Bonus = newBonus
                            };
                            db.UserSet.Add(newUser);
                            db.SaveChanges();
                        }
                    }
                    // Авторизация
                    else if (complexMessage.NumberStatus == 1)
                    {
                        using (UserContainer db = new UserContainer())
                        {
                            byte[] responseData;
                            for (int i = 0; i < db.UserSet.ToList().Count; i++)
                            {
                                if (db.UserSet.ToList()[i].Login == Convert.ToString(SerializeAndDeserialize.Deserialize(complexMessage.First)) && db.UserSet.ToList()[i].Password == CryptoService.GetHashString(Convert.ToString(SerializeAndDeserialize.Deserialize(complexMessage.Second))))
                                {
                                    Bonus bonus1 = db.UserSet.ToList()[i].Bonus;
                                    Bonus bonus2 = new Bonus()
                                    {
                                        Id          = bonus1.Id,
                                        AmountBonus = bonus1.AmountBonus
                                    };
                                    User user1 = db.UserSet.ToList()[i];
                                    User user2 = new User()
                                    {
                                        Id = user1.Id, Login = user1.Login, Password = user1.Password, Role = user1.Role, Balance = user1.Balance, basket = user1.basket, Email = user1.Email, Bonus = bonus2
                                    };
                                    m1 = SerializeAndDeserialize.Serialize(user2);

                                    m2 = SerializeAndDeserialize.Serialize(bonus2);

                                    cm.First        = m1;
                                    cm.Second       = m2;
                                    cm.NumberStatus = 2;
                                    m            = SerializeAndDeserialize.Serialize(cm);
                                    responseData = m.Data;
                                    Stream.Write(responseData, 0, responseData.Length);
                                    goto label;
                                }
                            }
                            cm.NumberStatus = 3;
                            m = SerializeAndDeserialize.Serialize(cm);

                            responseData = m.Data;
                            Stream.Write(responseData, 0, responseData.Length);
label:
                            responseData = null;
                        }
                    }
                    // Восстановление пароля
                    else if (complexMessage.NumberStatus == 2)
                    {
                        // First - новый пароль, Second - почта
                        string newPassword = Convert.ToString(SerializeAndDeserialize.Deserialize(complexMessage.First));
                        using (UserContainer db = new UserContainer())
                        {
                            byte[] responseData;
                            foreach (User usr in db.UserSet)
                            {
                                if (usr.Email == Convert.ToString(SerializeAndDeserialize.Deserialize(complexMessage.Second)))
                                {
                                    usr.Password    = CryptoService.GetHashString(newPassword);
                                    cm.First        = m1;
                                    cm.Second       = m2;
                                    cm.NumberStatus = 2;
                                    m            = SerializeAndDeserialize.Serialize(cm);
                                    responseData = m.Data;
                                    Stream.Write(responseData, 0, responseData.Length);
                                    goto labelSucess;
                                }
                            }
                            cm.NumberStatus = 3;
                            m = SerializeAndDeserialize.Serialize(cm);

                            responseData = m.Data;
                            Stream.Write(responseData, 0, responseData.Length);
labelSucess:
                            responseData = null;
                            db.SaveChanges();
                        }
                    }
                }
            }
        }
        protected override void Invoking(MessageReceivedEventArgs e, MultipartElement element, ComplexMessage elements)
        {
            ((JObject)SlappingConfig.Config).Add(new JProperty(e.Subject.Number.ToString(), element.ToSendableString()), true);
            SlappingConfig.Save();

            e.Reply("你的拍一拍自定义语句设置好了 |ू・ω・` )");
        }
示例#28
0
        protected override void Invoking(MessageReceivedEventArgs e, PlainText plainText, ComplexMessage elements)
        {
            e.Reply(Resources.Processing);

            if (HttpUtilities.HttpGet(string.Format(Resources.IPInfoApiURL, plainText), out string content))
            {
                try
                {
                    var json = JObject.Parse(content);
                    if (json["status"].ToString() == "success")
                    {
                        e.Reply($"状态:获取成功\n" +
                                $"IP {json["query"]} 信息:\n" +
                                $"洲:{json["continent"]}({json["continentCode"]})\n" +
                                $"国家:{json["country"]}({json["countryCode"]})\n" +
                                $"地区:{json["regionName"]}({json["region"]})\n" +
                                $"城市:{json["city"]}\n" +
                                $"邮政编码:{json["zip"]}\n" +
                                $"经纬度:{json["lat"]}, {json["lon"]}\n" +
                                $"时区:{json["timezone"]}\n" +
                                $"货币单位:{json["currency"]}\n" +
                                $"ISP:{json["isp"]}\n" +
                                $"所属组织:{json["org"]}\n" +
                                $"AS:{json["asname"]}({json["as"]})\n" +
                                $"反向DNS:{json["reverse"]}\n" +
                                $"移动数据接入:{(json["mobile"].ToObject<bool>() ? "是" : "否")}\n" +
                                $"代理:{(json["proxy"].ToObject<bool>() ? "是" : "否")}\n" +
                                $"托管/数据中心:{(json["hosting"].ToObject<bool>() ? "是" : "否")}");
                    }
                    else
                    {
                        e.Reply("获取 IP 信息失败" + (json.ContainsKey("message") ? ",错误原因:" + json["message"] : string.Empty));
                    }
                }
                catch
                {
                    e.Reply("信息处理失败了 (;´д`)ゞ");
                }
            }
            else
            {
                e.Reply("请求失败了 (;´д`)ゞ");
            }
        }
        protected override void Invoking(MessageReceivedEventArgs e, PlainText optionText, ComplexMessage elements)
        {
            var options = elements.OfType <PlainText>();

            if (optionText.Content.ToLower() == "options" && options.Count() == elements.Count)
            {
                e.Reply((ISendable)RandomUtilities.RandomOption(options));
            }
        }
 void IMessageVisitor.VisitComplex(ComplexMessage msg)
 {
     process complex message
 }
示例#31
0
        protected override void Invoking(MessageReceivedEventArgs e, PlainText plainText, PlainText countText, ComplexMessage elements)
        {
            if (int.TryParse(countText, out int count) && count < 100)
            {
                e.Reply(Resources.Processing);

                try
                {
                    var results        = PingUtilities.SendMoreAndGetRoundtripTime(plainText, count);
                    var successResults = results.Where(x => x > -1);
                    int timedoutCount  = results.Count() - successResults.Count();

                    if (timedoutCount == count)
                    {
                        e.Reply($"Ping {plainText} 超时");
                    }
                    else
                    {
                        e.Reply($"Ping {plainText} 结果:\n延迟:{Math.Round(successResults.Average())} ms\n丢包率:{timedoutCount / count * 100} %");
                    }
                }
                catch (PingException ex)
                {
                    e.Reply($"Ping {plainText} 出错,错误原因:{ex.Message}");
                }
            }
        }