public async override Task ExecuteAsync(BotActivity bot, SendMessageArgs args)
        {
            args.Answer = Arguments[0];
            await WriteInStorage(bot.MasterId, args.AuthorId, Arguments[1].ToString(), args.Message);

            await bot.SendTextMessageAsync(args);
        }
Example #2
0
        /// <summary>
        /// Включение/выключение бота (только телеграм)
        /// </summary>
        /// <param name="request"></param>
        /// <param name="masterId"></param>
        /// <returns></returns>
        public async Task TurnBotAsync(TurnRequest request, int masterId)
        {
            Bot dataBot = await context.Bots.FirstOrDefaultAsync(b => b.Id == request.BotId);

            BotActivity bot = BotStorage.ActivityBots.FirstOrDefault(b => b.Id == request.BotId);

            if (dataBot != null && dataBot.MasterId == masterId)
            {
                if (!request.TurnOn)
                {
                    if (bot != null)
                    {
                        BotStorage.ActivityBots.Remove(bot);
                        dataBot.IsActive = false;
                    }
                }
                else
                {
                    if (bot == null)
                    {
                        // бот автоматом добавляется в конструкторе
                        dataBot.IsActive = true;
                        BotActivity botActive = await TakeAsBotActivity(dataBot);

                        botActive.Sessions = await context.Sessions.Where(s => s.BotId == botActive.Id).ToListAsync();

                        await botActive.UploadFunctionalAsync();
                    }
                }
                await context.SaveChangesAsync();
            }
        }
Example #3
0
 /// <summary>
 /// Выполнение метода с заданными аргументами
 /// </summary>
 /// <param name="methodArgs"></param>
 public async virtual Task ExecuteAsync(BotActivity bot, SendMessageArgs args)
 {
     //Type typeOfFS = typeof(FunctionsStorage);
     //var method = typeOfFS.GetMethod(MethodName);
     //if (method != null)
     //    method.Invoke(null, methodArgs);
 }
Example #4
0
        //public static void AddTelegramBot(TelegramBot bot)
        //{
        //    if (TelegramBots.FirstOrDefault(b => b.Name == bot.Name) == null)
        //        TelegramBots.Add(bot);
        //}

        public static void AddActivityBot(BotActivity bot)
        {
            if (ActivityBots.FirstOrDefault(b => b.Name == bot.Name) == null)
            {
                ActivityBots.Add(bot);
            }
        }
Example #5
0
 public async override Task ExecuteAsync(BotActivity bot, SendMessageArgs args)
 {
     args.Answer = "типа данные";
     await bot.SendTextMessageAsync(new SendMessageArgs()
     {
         Answer = await GetDataFromStorage(bot.MasterId, Arguments[0].ToString()), ChatId = args.ChatId
     });
 }
Example #6
0
 public async virtual void Execute(Message message, BotActivity bot, BotSession session)
 {
     if (!String.IsNullOrWhiteSpace(Response.Answer))
     {
         await bot.SendTextMessageAsync(new SendMessageArgs()
         {
             ChatId = message.Chat.Id, Answer = Response.Answer
         });
     }
 }
Example #7
0
        public async Task RemoveBot(int botId, Models.User user)
        {
            Bot bot = await context.Bots.FirstOrDefaultAsync(b => b.Id == botId);

            if (bot != null && bot.MasterId == user.Id)
            {
                BotActivity ba = BotStorage.ActivityBots.FirstOrDefault(b => b.Id == botId);
                if (ba != null)
                {
                    BotStorage.ActivityBots.Remove(ba);
                }
                context.Bots.Remove(bot);
                user.BotCount = user.BotCount > 0?(--user.BotCount):0;
                await context.SaveChangesAsync();
            }
        }
Example #8
0
        public async Task <JsonResult> SaveFunctional([FromBody] Functional functional)
        {
            Bot bot = await botServ.GetBotsByIdAsync(functional.BotId);

            if (bot != null && bot.MasterId == (await accServ.GetCurrentUserAsync(User.Identity.Name)).Id)
            {
                // Если бот неактивен, просто сохраняем функционал
                // иначе - сохраняем функционал и подгружаем его
                BotActivity botActive = BotStorage.ActivityBots.FirstOrDefault(b => b.Id == functional.BotId);
                if (botActive != null)
                {
                    await botActive.SaveAndUploadFunctionalAsync(functional);
                }
                else
                {
                    await bot.SaveFunctionalAsync(functional);
                }
                return(Json(true));
            }
            return(Json(false));
        }
Example #9
0
 public static Activity ToActivity(this BotActivity botActivity)
 {
     return(new Activity
     {
         Type = botActivity.Type,
         Id = botActivity.Id,
         Timestamp = botActivity.Timestamp.HasValue ? botActivity.Timestamp.Value : (DateTime?)null,
         ServiceUrl = botActivity.ServiceUrl,
         ChannelId = botActivity.ChannelId,
         ChannelData = botActivity.ChannelData.ToObject(),
         From = botActivity.From.ToChannelAccount(),
         Conversation = botActivity.Conversation.ToConversationAccount(),
         Entities = botActivity.Entities.ToEntityList(),
         Recipient = botActivity.Recipient.ToChannelAccount(),
         TextFormat = botActivity.TextFormat,
         TopicName = botActivity.TopicName,
         Locale = botActivity.Locale,
         Text = botActivity.Text,
         Summary = botActivity.Summary,
         ReplyToId = botActivity.ReplyToId,
         Attachments = botActivity.Attachments.ToAttachmentsList(),
         Value = botActivity.Value
     });
 }
Example #10
0
        /// <summary>
        /// Выполнение функции
        /// </summary>
        /// <param name="update"></param>
        /// <param name="botName"></param>
        /// <returns></returns>
        public async Task ExecuteFunctionAsync(Update update, string botName)
        {
            bool        executed = false;
            BotActivity bot      = BotStorage.ActivityBots.FirstOrDefault(b => b.Name == botName);

            if (bot != null)
            {
                BotSession session = await GetSessionByUserIdAsync(update.Message.From.Id);

                // если сессии с этим клиентом нет, создаем новую
                if (session == null)
                {
                    session = new BotSession()
                    {
                        BotId                  = bot.Id,
                        LastActivity           = DateTime.Now,
                        NextFunctionId         = 0,
                        UserId                 = update.Message.From.Id,
                        CurrentCommandFunction = null
                    };
                    context.Sessions.Add(session);
                }

                // функционал бота
                Functional functional = await bot.GetFunctionalAsync();

                // указатель на следующую функцию
                int functionId = session.NextFunctionId;

                // текущая командная функция
                string curBotComFunct = session.CurrentCommandFunction;

                string message = update.Message.Text.ToLower();

                if (message == "cmds")
                {
                    string commands = "";
                    foreach (var func in bot.Functions)
                    {
                        commands += func.Command + " " + func.InputFunctions.Count();
                    }
                    await bot.SendTextMessageAsync(new SendMessageArgs()
                    {
                        ChatId = update.Message.Chat.Id, Answer = "Доступные команды: " + commands + " "
                    });

                    executed = true;
                }
                if (curBotComFunct == null)
                {
                    // выполнение по команде

                    foreach (CommandFunction func in bot.Functions)
                    {
                        string funcCommand = func.Command;
                        if (message.Contains(funcCommand.ToLower()))
                        {
                            func.Execute(update.Message, bot, session);
                            executed = true;
                            // после выполенени командной функции, проверяем следующую на авто
                            var inputFunctions = bot.GetInputFunctions(functional, funcCommand);
                            if (inputFunctions != null)
                            {
                                int inputFunctionsCount = inputFunctions.Count();
                                if (inputFunctionsCount > 0)
                                {
                                    // если функции есть, устанавливам имя на текущую и смотрим, авто ли следующая
                                    session.CurrentCommandFunction = funcCommand;
                                    session.NextFunctionId         = 0;
                                    InputFunction nextFunction = bot.GetInputFunction(functional, funcCommand, session.NextFunctionId);
                                    // пока идут авто функции, выполняем их
                                    while (nextFunction != null && nextFunction.IsAuto)
                                    {
                                        var funct = nextFunction.GetAsFunction();
                                        await funct.ExecuteAsync(bot, new SendMessageArgs()
                                        {
                                            ChatId = update.Message.Chat.Id, Answer = "Hello!", Message = message
                                        });

                                        session.NextFunctionId = IncId(session.NextFunctionId, inputFunctionsCount);
                                        await context.SaveChangesAsync();

                                        // если при выполнении авто функций мы выполнили все функции, выходим из командной функции
                                        if (session.NextFunctionId == 0)
                                        {
                                            session.CurrentCommandFunction = null;
                                            break;
                                        }
                                        nextFunction = bot.GetInputFunction(functional, curBotComFunct, session.NextFunctionId);
                                    }
                                    // если первая функция не авто, то остается имя текущей командной функции и ссылка на первую функцию
                                }
                            }
                            break;
                        }
                    }
                }
                else
                {
                    // количество фукнций в цепочке
                    var cmndf = (await bot.GetFunctionalAsync()).CommandFunctions.FirstOrDefault(f => f.Command == curBotComFunct);
                    if (cmndf != null)
                    {
                        var fus = cmndf.InputFunctions;
                        if (fus != null)
                        {
                            int inputFunctionsCount = fus.Count();
                            if (functionId < inputFunctionsCount)
                            {
                                var function = bot.Functions.FirstOrDefault(f => f.Command == curBotComFunct).InputFunctions[functionId];
                                //InputFunction function = bot.GetInputFunction(functional, curBotComFunct, functionId);
                                if (function != null)
                                {
                                    await function.ExecuteAsync(bot, new SendMessageArgs()
                                    {
                                        ChatId = update.Message.Chat.Id, AuthorId = update.Message.From.Id, Message = message
                                    });

                                    executed = true;
                                    // установление ссылки на след функцию
                                    session.NextFunctionId = IncId(functionId, inputFunctionsCount);
                                    if (session.NextFunctionId == 0)
                                    {
                                        session.CurrentCommandFunction = null;
                                    }
                                    else
                                    {
                                        //// если следующая функция авто, вызываем сразу
                                        InputFunction nextFunction = bot.GetInputFunction(functional, curBotComFunct, session.NextFunctionId);
                                        while (nextFunction != null && nextFunction.IsAuto)
                                        {
                                            var funct = nextFunction.GetAsFunction();
                                            await funct.ExecuteAsync(bot, new SendMessageArgs()
                                            {
                                                ChatId = update.Message.Chat.Id, Answer = "Hello!", Message = message
                                            });

                                            session.NextFunctionId = IncId(session.NextFunctionId, inputFunctionsCount);
                                            // если при выполнении авто функций мы выполнили все функции, выходим из командной функции
                                            if (session.NextFunctionId == 0)
                                            {
                                                session.CurrentCommandFunction = null;
                                                break;
                                            }
                                            nextFunction = bot.GetInputFunction(functional, curBotComFunct, session.NextFunctionId);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                await context.SaveChangesAsync();

                if (!executed)
                {
                    string answer = "Упс, эту команду я не понимаю :)";
                    if (message.Contains("/start"))
                    {
                        answer = "Здравствуйте! Рад встрече :)";
                    }
                    else
                    {
                        await bot.SendTextMessageAsync(new SendMessageArgs()
                        {
                            ChatId = update.Message.Chat.Id, Answer = answer
                        });
                    }
                }
            }
        }