예제 #1
0
        protected override MessagesSendParams _handle(VkNet.Model.Message command)
        {
            var(func, _) = command.ParseFunc();

            string message;

            switch (func.ToLowerInvariant())
            {
            case "ping":
                message = Ping();
                break;

            case "pong":
                message = "ping";
                break;

            case "pang":
                message = "HHЫЬЫТолыо!!тЛылЬЬ;27~~&@!";
                break;

            default:
                throw new KeyNotFoundException();
            }


            var param = new MessagesSendParams
            {
                Message = message,
                PeerId  = command.GetPeerId()
            };

            return(param);
        }
예제 #2
0
        private bool UseCommand(User user, string message, BaseChat chat, Message messageData)
        {
            var starts = CommandStarts.Select(s => Regex.Escape(s)).ToList();

            foreach (var start in starts.ToArray())
            {
                starts.Add($@"\[(public|club){VkApi.GroupId}\|[\S\s]{{1,}}](,|) {start}");
            }

            string regStart = @"\A(" + string.Join('|', starts) + @")";

            message = Regex.Match(message, regStart + @"[\S\s]{1,}", RegexOptions.IgnoreCase).Value;

            if (!string.IsNullOrEmpty(message))
            {
                try
                {
                    message = Regex.Replace(message.Replace("ё", "е"), regStart, "", RegexOptions.IgnoreCase);

                    VkApi.Core.PluginManager.HandleCommand(user, chat, message, messageData);
                    return(true);
                }
                catch (Exception e)
                {
                    chat.SendMessageAsync("Команда задана неверно!");
                    VkApi.Core.Log.Error(e.ToString());
                }
            }
            return(false);
        }
예제 #3
0
        public Updates CallbackMessageHandler(Updates updates, VkCoreApiBase vkApi)
        {
            var msg = Message.FromJson(new VkResponse(updates.Object));

            vkApi.Core.Log.Debug($"message from Group:{updates.GroupId} and Chat:{msg.ChatId} by {msg.FromId} Action:{msg.Action?.Type?.ToString() ?? "text"}  \"{msg.Text}\"");
            return(updates);
        }
예제 #4
0
 public CommandContext(BotCore core, User sender, BaseChat chat, Message messageData, MethodInfo command)
 {
     Core        = core;
     Sender      = sender;
     Chat        = chat;
     MessageData = messageData;
     Command     = command;
 }
예제 #5
0
 protected override MessagesSendParams _handle(VkNet.Model.Message command)
 {
     return(new MessagesSendParams
     {
         Message = Coins[Random.Next() % 2],
         PeerId = command.GetPeerId()
     });
 }
예제 #6
0
 public void Run(IVkApi api, Message message)
 {
     api.Messages.Delete(new[] { (ulong)message.Id.Value }, deleteForAll: true);
     api.Messages.Send(new MessagesSendParams()
     {
         PeerId   = api.UserId,
         RandomId = Environment.TickCount,
         Message  = "я тут!"
     });
 }
예제 #7
0
        public object HandleCommand(User user, BaseChat chat, string cmdline, Message messageData)
        {
            var    split       = Regex.Split(cmdline, "(?<=^[^\"]*(?:\"[^\"]*\"[^\"]*)*) (?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
            string commandName = split[0].ToLower();

            string[] arguments = split.Skip(1).ToArray();

            Command command = null;

            command = GetCommand(commandName, chat.VkApi.GroupId);

            bool showErrorLine = Core.Configuration.GetValue("Config:Plugins:Commands:ShowErrorLine", true);

            if (command == null)
            {
                //Log.Warn($"Found no command {commandName}");
                if (showErrorLine)
                {
                    chat.SendMessageAsync($"[❗] Неизвестная команда \"/{commandName}\"! Полный список команд /help");
                }
                return(null);
            }

            var overloads = PermittedOverloads(command.Overloads.Values.OrderByDescending(o => o.Method.GetParameters().Length), user, chat as Chat);

            foreach (var overload in overloads)
            {
                try
                {
                    MethodInfo method = overload.Method;

                    if (!IsAvailable(method, chat.VkApi.GroupId) || !CorrectlyUsage(method, chat))
                    {
                        continue;
                    }

                    if (ExecuteCommand(method, user, chat, arguments, messageData, out object retVal))
                    {
                        return(retVal);
                    }
                }
                catch (Exception e)
                {
                    Core.Log.Error(chat, e.ToString());
                    continue;
                }
                Core.Log.Debug("No result from execution");
            }
            if (showErrorLine)
            {
                chat.SendMessageAsync("[❗] Неверный синтаксис команды! /help чтобы посмотреть полный список команд");
            }

            return(null);
        }
예제 #8
0
        protected override MessagesSendParams _handle(VkNet.Model.Message command)
        {
            var chatid  = command.ChatId ?? throw new AccessViolationException("Available only in chats");
            var adminid = _api.Messages.GetChat(chatid).AdminId ??
                          throw new AccessViolationException("Only chat admin can use these method");


            var(_, args) = command.ParseFunc();

            if (args.Length == 0 || args[0] == "load")
            {
                return(new MessagesSendParams
                {
                    PeerId = command.GetPeerId(),
                    Message = LoadQueue(chatid)
                });
            }

            if (args[0] == "add")
            {
                if (command.FromId != adminid && !_bot.Admins.Contains(command.FromId ?? 0))
                {
                    throw new AccessViolationException("Only chat admin can use these method");
                }

                return(new MessagesSendParams
                {
                    PeerId = command.GetPeerId(),
                    Message = AddQueue(chatid, string.Join(' ', args.Skip(1)), adminid)
                });
            }

            string message;

            switch (args[0])
            {
            case "join":
                message = JoinQueue(chatid, command.FromId ?? 0, "last");
                break;

            case "leave":
                message = LeaveQueue(chatid, command.FromId ?? 0, "last");
                break;

            default:
                message = "Error!";
                break;
            }

            return(new MessagesSendParams
            {
                PeerId = command.GetPeerId(),
                Message = message
            });
        }
예제 #9
0
        /// <summary>
        /// Logs the message before hadling it
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        /// <exception cref="KeyNotFoundException"></exception>
        public MessagesSendParams Handle(VkNet.Model.Message command)
        {
            Log.Information($"[ {GetType().Name} ]: called '{command.Text}' by https://vk.com/id{command.FromId}");

            if (State == ProviderState.Unloaded)
            {
                throw new KeyNotFoundException($"{GetType().Name} is not loaded");
            }

            return(_handle(command));
        }
예제 #10
0
        public static Message Map(VkNet.Model.Message vkMes, int metaContactId)
        {
            Mapper.Initialize(cfg => cfg.CreateMap <VkNet.Model.Message, Message>()
                              .ForMember("Text", x => x.MapFrom(c => c.Body))
                              .ForMember("DateTime", x => x.MapFrom(c => c.Date))
                              .ForMember("ContactIdentifier", x => x.MapFrom(c => c.UserId)));
            var message = Mapper.Map <VkNet.Model.Message, Message>(vkMes);

            message.Type          = "Vk";
            message.MetaContactId = metaContactId;
            return(message);
        }
예제 #11
0
        protected override MessagesSendParams _handle(VkNet.Model.Message command)
        {
            if (command.FromId.HasValue && !_bot.Admins.Contains(command.FromId.Value))
            {
                throw new AccessViolationException("Permission denied!");
            }

            var(func, args) = command.ParseFunc();

            string message;

            switch (func.ToLowerInvariant())
            {
            case "sleep":
                Sleep();
                message = "zZzzzzZzzz";
                break;

            case "wakeup":
                WakeUp();
                message = "Ready!";
                break;

            case "stop":
                Stop();
                message = "Bye";
                break;

            case "load":
                message = LoadModule(args);
                break;

            case "unload":
                message = UnloadModule(args);
                break;

            default:
                message = "Not implemented yet";
                break;
            }

            var param = new MessagesSendParams
            {
                Message = message,
                PeerId  = command.GetPeerId()
            };

            return(param);
        }
예제 #12
0
        private async Task <UpdateContext?> CreateUpdateContext(Update update)
        {
            switch (update.Type)
            {
            case "message_new":
                var originalMessage = VkMessage.FromJson(new VkResponse(update.Object));
                var message         = VkConverter.ToInMessage(originalMessage);
                var chat            = await _messenger.GetChat(originalMessage.PeerId !.Value).ConfigureAwait(false);

                var sender = await _messenger.GetUser(originalMessage.FromId !.Value).ConfigureAwait(false);

                return(new UpdateContext(_messenger, chat, sender, message));

            default:
                return(null);
            }
        }
예제 #13
0
        protected override MessagesSendParams _handle(VkNet.Model.Message command)
        {
            var(_, args) = command.ParseFunc();

            var(message, attachement) = GetVid(args[0]);

            var param = new MessagesSendParams
            {
                Message     = message,
                Attachments = new List <MediaAttachment> {
                    attachement
                },
                PeerId = command.GetPeerId()
            };

            return(param);
        }
예제 #14
0
        protected override MessagesSendParams _handle(VkNet.Model.Message command)
        {
            var(_, args) = command.ParseFunc();

            string message;

            if (args.Length != 2)
            {
                throw new ArgumentException("Wrong number of arguments provided");
            }

            switch (args[0])
            {
            case "now":
                message = Now(args[1]);
                break;

            case "today":
                message = Today(args[1]);
                break;

            case "tomorrow":
                message = Tomorrow(args[1]);
                break;

            case "week":
                message = Week(args[1]);
                break;

            default:
                throw new ArgumentException("Second argument is incorrect");
            }

            var param = new MessagesSendParams
            {
                Message = message,
                PeerId  = command.GetPeerId()
            };

            return(param);
        }
예제 #15
0
 private bool ClickButton(User user, string message, BaseChat chat, Message messageData)
 {
     if (!string.IsNullOrEmpty(messageData.Payload))
     {
         try
         {
             var payload = KeyboardButtonPayload.Deserialize(messageData.Payload);
             if (payload != null && payload.IsValid())
             {
                 if (payload.GroupId == VkApi.GroupId || payload.GroupId == 0)
                 {
                     OnButtonClick(chat, user, message, payload, messageData);
                 }
                 return(true);
             }
         }
         catch (Exception e)
         {
             VkApi.Core.Log.Error(e.ToString());
         }
     }
     return(false);
 }
예제 #16
0
        protected override MessagesSendParams _handle(VkNet.Model.Message command)
        {
            var(_, args) = command.ParseFunc();

            if (!args.Any() || args[0].ToLowerInvariant() == "all")
            {
                var s = new StringBuilder();

                foreach (var provider in _bot.Providers.Values)
                {
                    if (provider.State == ProviderState.Unloaded)
                    {
                        continue;
                    }
                    s.Append(provider.GetAllHelp());
                    s.AppendLine();
                }

                return(new MessagesSendParams
                {
                    Message = s.ToString(),
                    PeerId = command.GetPeerId()
                });
            }

            if (!_bot.Functions.ContainsKey(args[0]))
            {
                throw new KeyNotFoundException("No such module.");
            }

            return(new MessagesSendParams
            {
                Message = _bot.Functions[args[0]].Functions[args[0]],
                PeerId = command.GetPeerId()
            });
        }
예제 #17
0
 public GetMessageEventArgs(BaseChat chat, IUser sender, string message, Message messageData) : base(chat, sender, message, messageData)
 {
 }
예제 #18
0
        public virtual void OnMessage(IUser sender, string message, BaseChat chat, Message messageData)
        {
            //защита от дублированных или задержанных сообщений
            {
                long msgId = messageData.ConversationMessageId.Value;
                if (!_lastMessages.ContainsKey(chat))
                {
                    _lastMessages.Add(chat, new Queue <long>());
                }
                else
                {
                    if (_lastMessages[chat].Contains(msgId))
                    {
                        return;
                    }
                    _lastMessages[chat].Enqueue(msgId);
                    if (_lastMessages[chat].Count > 10)
                    {
                        _lastMessages[chat].Dequeue();
                    }
                }
            }
            //защита от дублированных или задержанных сообщений


            //actions
            if (messageData.Action != null && chat is Chat _chat)
            {
                if (messageData.Action.Type == MessageAction.ChatKickUser)
                {
                    //if (messageData.Action.MemberId == -VkApi.GroupId) //нет события при кике бота.
                    //	_chat.OnKick(sender);
                    //else
                    _chat.OnKickUser(VkApi.GetUser(messageData.Action.MemberId.Value), sender);
                    return;
                }
                else if (messageData.Action.Type == MessageAction.ChatInviteUser)
                {
                    if (messageData.Action.MemberId == -VkApi.GroupId)
                    {
                        _chat.Join(sender);
                    }
                    else
                    {
                        _chat.OnAddUser(VkApi.GetUser(messageData.Action.MemberId.Value), sender, false);
                    }
                    return;
                }
                else if (messageData.Action.Type == MessageAction.ChatInviteUserByLink)
                {
                    _chat.OnAddUser(sender, null, true);
                    return;
                }
            }

            if (sender is User user)
            {
                if (ClickButton(user, message, chat, messageData))
                {
                    return;
                }

                if (UseCommand(user, message, chat, messageData))
                {
                    return;
                }
            }

            if (!OnGetMessage(new GetMessageEventArgs(chat, sender, message, messageData)))
            {
                return;
            }

            chat.OnMessasge(sender, message, messageData);
        }
예제 #19
0
 public virtual void OnButtonClick(BaseChat chat, User user, string message, KeyboardButtonPayload payload, Message messageData)
 {
     if (!OnButtonClick(new ButtonClickEventArgs(chat, user, message, payload, messageData)))
     {
         return;
     }
     chat.InvokeButton(user, payload);
 }
예제 #20
0
 public CommandEventArgs(BaseChat chat, User sender, string message, MethodInfo command, string[] args, Message messageData) : base(chat, sender, message, messageData)
 {
     Command = command;
     Args    = args;
 }
예제 #21
0
 /// <summary>
 /// This function handles execution of a command
 /// </summary>
 /// <param name="command">Message to be handled</param>
 /// <returns>Response message</returns>
 protected abstract MessagesSendParams _handle(VkNet.Model.Message command);
예제 #22
0
        public static async Task <Tuple <Guid?, bool> > ReplyToMessage(DatabaseContext dbContext, long idGroup, Guid idSubscriber, VkNet.Model.Message message)
        {
            if (string.IsNullOrWhiteSpace(message.Body))
            {
                return(null);
            }

            var isChatAnswer = await dbContext.SubscribersInChatProgress
                               .AnyAsync(x => x.IdSubscriber == idSubscriber);

            if (isChatAnswer)
            {
                return(new Tuple <Guid?, bool>(await ChatScenarioContentReply(dbContext, idGroup, idSubscriber, message), true));
            }

            var scenario = await dbContext.Scenarios
                           .Where(x => x.IsEnabled)
                           .Where(x => x.IdGroup == idGroup)
                           .Where(x => x.Group.GroupAdmins.Any())
                           .FirstOrDefaultAsync(x => (x.IsStrictMatch && x.InputMessage.ToLower() == message.Body.ToLower()) || (!x.IsStrictMatch && message.Body.ToLower().Contains(x.InputMessage.ToLower())));

            if (scenario != null)
            {
                return(new Tuple <Guid?, bool>(await ScenarioReply(dbContext, idGroup, idSubscriber, scenario), true));
            }

            var chatScenario = await dbContext.ChatScenarios
                               .Where(x => x.IsEnabled)
                               .Where(x => x.IdGroup == idGroup)
                               .Where(x => x.Group.GroupAdmins.Any())
                               .FirstOrDefaultAsync(x => x.InputMessage.ToLower() == message.Body.ToLower());

            if (chatScenario != null)
            {
                return(new Tuple <Guid?, bool>(await ChatScenarioReply(dbContext, idGroup, idSubscriber, chatScenario), true));
            }
            //Тут бот или картинки

            return(new Tuple <Guid?, bool>(null, false));
        }
예제 #23
0
        private static async Task <Guid?> ChatScenarioContentReply(DatabaseContext dbContext, long idGroup, Guid idSubscriber, VkNet.Model.Message message)
        {
            Guid?result = null;

            var subscribersInChatProgress = await dbContext.SubscribersInChatProgress
                                            .Where(x => x.IdSubscriber == idSubscriber)
                                            .Include(x => x.ChatScenarioContent)
                                            .OrderBy(x => x.DtAdd)
                                            .LastOrDefaultAsync();

            await dbContext.History_SubscribersInChatScenariosContents.AddAsync(new History_SubscribersInChatScenariosContents()
            {
                IdChatScenarioContent = subscribersInChatProgress.IdChatScenarioContent,
                IdSubscriber          = idSubscriber,
                Dt = DateTime.UtcNow
            });

            var idChatScenario = subscribersInChatProgress.ChatScenarioContent.IdChatScenario;

            var chatScenarioContents = await dbContext.ChatScenarioContents
                                       .Where(x => x.IdChatScenario == idChatScenario)
                                       .OrderBy(x => x.Step)
                                       .ToArrayAsync();

            await dbContext.SubscriberChatReplies.AddAsync(new SubscriberChatReplies()
            {
                IdChatScenarioContent = subscribersInChatProgress.IdChatScenarioContent,
                IdSubscriber          = idSubscriber,
                Text     = message.Body,
                Dt       = DateTime.UtcNow,
                UniqueId = subscribersInChatProgress.UniqueId
            });

            await dbContext.SaveChangesAsync();

            var nextChatScenarioContent = chatScenarioContents.SkipWhile(x => x.Id != subscribersInChatProgress.IdChatScenarioContent).Skip(1).FirstOrDefault();

            if (nextChatScenarioContent != null)
            {
                subscribersInChatProgress.IdChatScenarioContent = nextChatScenarioContent.Id;
                result = nextChatScenarioContent.IdMessage;
            }
            else
            {
                dbContext.SubscribersInChatProgress.Remove(subscribersInChatProgress);
                await dbContext.SaveChangesAsync();

                var chatScenario = await dbContext.ChatScenarios.Where(x => x.Id == idChatScenario).FirstOrDefaultAsync();

                if (chatScenario.HasFormula)
                {
                    result = await EvaluateChatScenarioFormulaResult(dbContext, idGroup, idSubscriber, subscribersInChatProgress.UniqueId, chatScenario);
                }
            }

            return(result);
        }
예제 #24
0
        protected override MessagesSendParams _handle(VkNet.Model.Message command)
        {
            command.MarkAsRead(_api);
            var(_, args) = command.ParseFunc();


            Subreddit sub;

            try
            {
                sub = _reddit.GetSubredditAsync(args[0]).Result;
            }
            catch (WebException)
            {
                return(new MessagesSendParams
                {
                    Message = $"No sush subreddit: {args[0]}.",
                    PeerId = command.GetPeerId()
                });
            }

            if (sub == null)
            {
                return(new MessagesSendParams
                {
                    Message = $"No sush subreddit: {args[0]}.",
                    PeerId = command.GetPeerId()
                });
            }

            Listing <Post> listing;

            switch (args.Last().ToLowerInvariant())
            {
            case "top":
                listing = sub.GetTop(FromTime.Day);
                break;

            default:     // "hot" also
                listing = sub.GetPosts(Subreddit.Sort.Hot);
                break;

            case "new":
                listing = sub.GetPosts(Subreddit.Sort.New);
                break;
            }

            var posts = listing.Take(50).Where(p => p.Url.ToString().EndsWith(".jpg")).ToList().Result;

            var rand = new Random();

            if (posts.Count == 0)
            {
                return(new MessagesSendParams
                {
                    Message = "Error getting image",
                    PeerId = command.GetPeerId()
                });
            }

            var post  = posts[rand.Next(0, posts.Count)];
            var image = post.Url.ToString();

            if (command.IsFromChat() && post.NSFW)
            {
                return(new MessagesSendParams
                {
                    Message = $"Link for 'friend': {image}",
                    PeerId = command.GetPeerId(),
                    DontParseLinks = true
                });
            }

            var server = _api.Photo.GetMessagesUploadServer(command.GetPeerId());

            using (var wc = new WebClient())
            {
                try
                {
                    var imageBytes = wc.DownloadData(image);

                    var responseFile = UploadImage(server.UploadUrl, imageBytes).Result;

                    var photos = _api.Photo.SaveMessagesPhoto(responseFile);

                    return(new MessagesSendParams
                    {
                        Message = $"Reddit [/r/{sub.Name}] {post.Title}\nLink: {post.Shortlink}",
                        Attachments = photos,
                        PeerId = command.GetPeerId(),
                        DontParseLinks = true
                    });
                }
                catch (WebException)
                {
                    throw new WebException("Error getting image");
                }
            }
        }
예제 #25
0
        public IActionResult Callback([FromBody] Updates updates)
        {
            try
            {
                if (updates.SecretKey != _secretKey)
                {
                    return(BadRequest("Secret key is incorrect!"));
                }

                if (updates.Type == CallbackReceive.Confirmation)
                {
                    return(Ok(Core.Configuration.GetValue($"Config:Groups:{updates.GroupId}:Confirmation", Core.Configuration["Config:Confirmation"])));
                }

                new Thread(() =>
                {
                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Start();
                    try
                    {
                        VkCoreApiBase vkApi = Core.VkApi.Get(updates.GroupId);
                        Core.PluginManager.PluginCallbackHandler(ref updates, vkApi);
                        if (updates == null)
                        {
                            return;
                        }

                        var response = new VkResponse(updates.Object);

                        var update = GroupUpdate.FromJson(response);

                        switch (updates.Type)
                        {
                        case CallbackReceive.Message.New:
                            {
                                var msg = Message.FromJson(response);

                                if (msg.Date.HasValue && (DateTime.UtcNow - msg.Date.Value).TotalSeconds > _messageResendBlockTime)
                                {
                                    return;
                                }

                                IUser user    = vkApi.GetUser(msg.FromId.Value);
                                BaseChat chat = vkApi.GetChat(msg.PeerId.Value);

                                lock (chat)
                                {
                                    vkApi.MessageHandler.OnMessage(user, msg.Text, chat, msg);
                                }
                                break;
                            }

                        case CallbackReceive.Message.Event:
                            {
                                var msgEvent = MessageEvent.FromJson(response);

                                IUser user = vkApi.GetUser(msgEvent.UserId.Value);

                                if (user is User _user)
                                {
                                    BaseChat chat = vkApi.GetChat(msgEvent.PeerId.Value);

                                    lock (chat)
                                    {
                                        vkApi.MessageHandler.ClickButton(chat, _user, new UI.EventId(msgEvent.EventId), msgEvent.Payload);
                                    }
                                }
                                break;
                            }

                        case CallbackReceive.Group.OfficersEdit:
                            {
                                var msgEvent = GroupOfficersEdit.FromJson(response);

                                var userId = msgEvent.UserId.Value;

                                vkApi.Group.Managers.Remove(userId);

                                var level = (int)msgEvent.LevelNew.Value;

                                if (level > 0)
                                {
                                    var permissionLevel = (int)Math.Pow(10, level + 1);
                                    vkApi.Group.Managers.Add(userId, (UserPermission)level);
                                }
                                break;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Core.Log.Error(e.ToString());
                    }
                    Core.Log.Debug(stopwatch.ElapsedMilliseconds.ToString());
                    stopwatch.Stop();
                })
                {
                    IsBackground = true
                }.Start();
            }
예제 #26
0
        protected override MessagesSendParams _handle(VkNet.Model.Message command)
        {
            var(_, args) = command.ParseFunc();
            var expr = new Expression(string.Join(' ', args))
            {
                Parameters = _parameters
            };

            void Repeat(string name, FunctionArgs argz)
            {
                if (name.ToLowerInvariant() == "repeat")
                {
                    var ex = argz.Parameters[0];
                    ex.EvaluateFunction += Repeat;

                    var what  = ex.Evaluate().ToString();
                    var times = Math.Min((int)argz.Parameters[1].Evaluate(), 4096 / what.Length + 1);

                    var o = new StringBuilder(times * what.Length);
                    for (var i = 0; i < times; i++)
                    {
                        o.Append(what);
                    }

                    argz.Result = o.ToString();
                }
            }

            void Factorial(string name, FunctionArgs argz)
            {
                if (name.ToLowerInvariant() == "fact")
                {
                    var fact = (int)argz.Parameters[0].Evaluate();

                    if (fact < 0 || fact > 1491)
                    {
                        throw new ArgumentOutOfRangeException(nameof(fact), "Must be positive integer [0..1491].");
                    }

                    BigInteger result = 1;

                    for (var i = 2; i <= fact; i++)
                    {
                        result *= i;
                    }

                    argz.Result = result;
                }
            }

            expr.EvaluateFunction += Repeat;
            expr.EvaluateFunction += Factorial;

            var message = "Error! ";

            try
            {
                message = "Out[0] = " + expr.Evaluate();
            }
            catch (Exception e)
            {
                message += e.Message;
            }

            return(new MessagesSendParams
            {
                PeerId = command.GetPeerId(),
                Message = message
            });
        }
예제 #27
0
 public ButtonClickEventArgs(BaseChat chat, User sender, string message, KeyboardButtonPayload payload, Message messageData) : base(chat, sender, message, messageData)
 {
     Payload = payload;
 }
예제 #28
0
 public UniversalMessage(IService fromVkSrv, VkNet.Model.Message vkMessage, string authorName)
     : this(fromVkSrv, authorName, vkMessage.Body, vkMessage.Date.Value)
 {
 }
예제 #29
0
        private bool ExecuteCommand(MethodInfo method, User user, BaseChat chat, string[] args, Message messageData, out object result)
        {
            Core.Log.Info($"Execute command {method}");

            result = new object();
            CommandContext context = new CommandContext(Core, user, chat, messageData, method);

            var parameters = method.GetParameters();

            int addLenght = 0;

            if (parameters.Length > 0 && typeof(CommandContext).IsAssignableFrom(parameters[0].ParameterType))
            {
                addLenght = 1;
            }

            object[] objectArgs = new object[parameters.Length];

            try
            {
                int i = 0;
                for (int k = 0; k < parameters.Length; k++)
                {
                    var parameter = parameters[k];
                    if (k == 0 && addLenght == 1)
                    {
                        if (typeof(CommandContext).IsAssignableFrom(parameter.ParameterType))
                        {
                            objectArgs[k] = context;
                            continue;
                        }
                        Core.Log.Warn(chat, $"Command method {method.Name} missing Player as first argument.");
                        return(false);
                    }

                    bool isStringParam = IsParams(parameter) && parameter.ParameterType == typeof(string[]);

                    if ((parameter.IsOptional || isStringParam) && args.Length <= i)
                    {
                        if (isStringParam)
                        {
                            objectArgs[k] = new string[0];
                        }
                        else
                        {
                            objectArgs[k] = parameter.DefaultValue;
                        }
                        continue;
                    }

                    if (args.Length < k && !isStringParam)
                    {
                        Core.Log.Debug(chat, $"No math {k} arguments");
                        return(false);
                    }

                    if (typeof(IParameterSerializer).IsAssignableFrom(parameter.ParameterType))
                    {
                        var ctor = parameter.ParameterType.GetConstructor(Type.EmptyTypes);
                        IParameterSerializer defaultValue = ctor.Invoke(null) as IParameterSerializer;
                        defaultValue?.Deserialize(user, args[i++]);

                        objectArgs[k] = defaultValue;

                        continue;
                    }

                    if (typeof(IUser).IsAssignableFrom(parameter.ParameterType))
                    {
                        long   id;
                        string _id = Regex.Match(args[i++].Split(' ', '|').First(), @"(club|public|id)[0-9]*").Value;
                        _id = Regex.Replace(_id.Replace("id", ""), @"(club|public)", "-");
                        if (!long.TryParse(_id, out id))
                        {
                            return(false);
                        }
                        var _user = user.VkApi.GetUser(id);
                        if (!parameter.ParameterType.IsAssignableFrom(_user.GetType()) && !_user.GetType().IsAssignableFrom(parameter.ParameterType))
                        {
                            return(false);
                        }
                        objectArgs[k] = _user;
                        continue;
                    }

                    if (parameter.ParameterType == typeof(string))
                    {
                        objectArgs[k] = args[i++];
                        continue;
                    }
                    if (parameter.ParameterType == typeof(byte))
                    {
                        byte value;
                        if (!byte.TryParse(args[i++], out value))
                        {
                            return(false);
                        }
                        objectArgs[k] = value;
                        continue;
                    }
                    if (parameter.ParameterType == typeof(short))
                    {
                        short value;
                        if (!short.TryParse(args[i++], out value))
                        {
                            return(false);
                        }
                        objectArgs[k] = value;
                        continue;
                    }
                    if (parameter.ParameterType == typeof(int))
                    {
                        int value;
                        if (!int.TryParse(args[i++], out value))
                        {
                            return(false);
                        }
                        objectArgs[k] = value;
                        continue;
                    }
                    if (parameter.ParameterType == typeof(long))
                    {
                        long value;
                        if (!long.TryParse(args[i++], out value))
                        {
                            return(false);
                        }
                        objectArgs[k] = value;
                        continue;
                    }
                    if (parameter.ParameterType == typeof(bool))
                    {
                        bool value;
                        if (!bool.TryParse(args[i++], out value))
                        {
                            return(false);
                        }
                        objectArgs[k] = value;
                        continue;
                    }
                    if (parameter.ParameterType == typeof(float))
                    {
                        float value;
                        if (!float.TryParse(args[i++], out value))
                        {
                            return(false);
                        }
                        objectArgs[k] = value;
                        continue;
                    }
                    if (parameter.ParameterType == typeof(double))
                    {
                        double value;
                        if (!double.TryParse(args[i++], out value))
                        {
                            return(false);
                        }
                        objectArgs[k] = value;
                        continue;
                    }
                    if (parameter.ParameterType.IsEnum)
                    {
                        string val = args[i++];

                        if (long.TryParse(val, out _) || !Enum.TryParse(parameter.ParameterType, val, true, out object value) || value as Enum == null)
                        {
                            Core.Log.Warn($"Could not convert to valid enum value: {val}");
                            return(false);
                        }

                        objectArgs[k] = value;
                        continue;
                    }

                    if (isStringParam)
                    {
                        List <string> strings = new List <string>();
                        for (; i < args.Length; i++)
                        {
                            strings.Add(args[i]);
                        }
                        objectArgs[k] = strings.ToArray();
                        continue;
                    }

                    return(false);
                }

                if (i < args.Length)
                {
                    return(false);
                }
            }
            catch (Exception e)
            {
                //if (Log.IsDebugEnabled)
                //{
                //	Log.Error("Trying to execute command overload", e);
                //}
                //chat.SendMessage(e);
                Core.Log.Error(chat, e.ToString());

                return(false);
            }

            try
            {
                object pluginInstance = _plugins.FirstOrDefault(plugin => method.DeclaringType.IsInstanceOfType(plugin)) ?? method.DeclaringType;
                if (pluginInstance == null)
                {
                    return(false);
                }

                if (!OnCommandExecute(new CommandEventArgs(chat, user, messageData.Text, method, args, messageData)))
                {
                    return(true);
                }

                ICommandFilter filter = pluginInstance as ICommandFilter;
                if (filter != null)
                {
                    filter.OnCommandExecuting(user);
                }

                if (method.IsStatic)
                {
                    result = method.Invoke(null, objectArgs);
                }
                else
                {
                    if (method.DeclaringType == null)
                    {
                        return(false);
                    }

                    Plugin.CurrentContext = context;                  // Setting thread local for call
                    result = method.Invoke(pluginInstance, objectArgs);
                    Plugin.CurrentContext = null;                     // Done with thread local, we using pool to make sure it's reset.
                }

                if (filter != null)
                {
                    filter.OnCommandExecuted();
                }

                return(true);
            }
            catch (Exception e)
            {
                Core.Log.Error(chat, e.ToString());
                //Log.Error($"Error while executing command {method}", e);
                //chat.SendMessage(e);
            }

            return(false);
        }
예제 #30
0
 public Command(VkNet.Model.Message message, Func <VkNet.Model.Message, MessagesSendParams> f)
 {
     Function = f;
     Message  = message;
 }