Example #1
0
        public void UpdateManagerStatus(int StoreManagerID, string Status)
        {
            StoreManagerService.UpdateManagerStatus(StoreManagerID, Status);
            var GroupList = LineBindingService.GetGroupList(StoreManagerID);

            foreach (var item in GroupList)
            {
                BotService.LeaveGroup(item.LineGroupID);
            }
            LineBindingService.UpdateManagerAllGroupStatus(StoreManagerID, Status);
        }
Example #2
0
        public static async Task StartBot()
        {
            BotService service = new BotService();

            bool success = await service.Initialize();

            if (success)
            {
                await Task.Delay(-1);
            }
        }
Example #3
0
        protected async Task StartBot()
        {
            Logger.LogInformation("Starting the bot");
            await BotService.StartBot();

            await BotService.ChangeBotState(BotState.Started);

            Logger.LogInformation("Started the bot");

            StateHasChanged();
        }
Example #4
0
        public BotServiceTest()
        {
            _fakedBotRepoService     = A.Fake<IBotRepoService>();
            _fakedItemRepoService    = A.Fake<IItemRepoService>();
            _fakedRepoServiceFactory = A.Fake<IRepoServiceFactory>();

            A.CallTo(() => _fakedRepoServiceFactory.ItemRepoService).Returns(_fakedItemRepoService);
            A.CallTo(() => _fakedRepoServiceFactory.BotRepoService).Returns(_fakedBotRepoService);

            _botService = new BotService(_fakedRepoServiceFactory);
        }
Example #5
0
        public async Task TestInitRunAndShutDownBotService()
        {
            var botService = new BotService(ConfigureServices());
            await botService.InitAsync().ConfigureAwait(false);

            await botService.RunAsync().ConfigureAwait(false);

            botService.IsRunning.Should().BeTrue();
            await botService.ShutdownAsync().ConfigureAwait(false);

            botService.IsRunning.Should().BeFalse();
        }
Example #6
0
        public AWBot(BotService services, ConversationState conversationState, UserState userState)
        {
            _services = services ?? throw new System.ArgumentNullException(nameof(services));

            if (!_services.LuisServices.ContainsKey(LuisKey))
            {
                throw new System.ArgumentException($"Invalid configuration....");
            }

            _conversationState = conversationState;
            _userState         = userState;
        }
Example #7
0
 /// <summary>
 /// Constructor of SettingsHandler
 /// </summary>
 /// <param name="logger"></param>
 /// <param name="chatService"></param>
 /// <param name="settingsService"></param>
 public SettingsHandler(
     ILogger <SettingsHandler> logger,
     BotService botService,
     ChatService chatService,
     SettingsService settingsService
     )
 {
     _logger          = logger;
     _botService      = botService;
     _chatService     = chatService;
     _settingsService = settingsService;
 }
Example #8
0
        public async Task GetByIdTest()
        {
            var botRepository = _repository.Setup(x => x.GetBotById(new Guid("83eb6280-61db-43c3-9851-911d154a3817"), CancellationToken.None)).ReturnsAsync(_bot);

            Assert.NotNull(botRepository);

            var service = new BotService(_repository.Object);

            var bot = await service.GetBotById(new Guid("83eb6280-61db-43c3-9851-911d154a3817"), CancellationToken.None);

            Assert.Equal("Mary", bot.name);
        }
Example #9
0
        public ActionResult PushMessageToLineGroup(int GroupOrderID)
        {
            string lineGroupId = string.Empty;
            string msg         = BotService.SetMsgFormat(GroupOrderID, ref lineGroupId);

            BotService.BotPushMsg(lineGroupId, msg);
            GroupOrderService groupOrderService = new GroupOrderService();

            groupOrderService.UpdateBtnGroupClickDateTime(GroupOrderID, DateTime.UtcNow.AddHours(8));

            return(Json("OK"));
        }
Example #10
0
        public ActionResult SettingCampaign(CampaignViewModel cvm, string LineGroupID)
        {
            int id = LineBindingService.GetIdByGroupId(LineGroupID);

            cvm.GroupID  = id;
            cvm.PostTime = DateTime.UtcNow.AddHours(8);
            CampaignService campaignService = new CampaignService();

            campaignService.InsertCampaign(cvm);
            BotService.BotPushMsg(LineGroupID, cvm.Detail);
            return(RedirectToAction("FanPageName", "Setting"));
        }
Example #11
0
 public QuickReplyController(ApplicationSettings appSettings, ICaseMgmtService caseMgmtService,
                             TicketSysUserMgmtService jiraUserMgmtService,
                             IFbApiClientService fbApiClientService, CompanyService companyService, BotService botService, OneTimeNotificationService oneTimeNotifService)
 {
     _appSettings         = appSettings;
     _caseMgmtService     = caseMgmtService;
     _jiraUserMgmtService = jiraUserMgmtService;
     _fbApiClientService  = fbApiClientService;
     _companyService      = companyService;
     _botService          = botService;
     _oneTimeNotifService = oneTimeNotifService;
 }
Example #12
0
        public MainPage()
        {
            InitializeComponent();

            this.botService = new BotService();
            this.botService.AttachOnReceiveMessage(this.OnBotMessageReceived);
            this.botAuthor = new Author {
                Name = "botty"
            };

            ((INotifyCollectionChanged)this.chat.Items).CollectionChanged += ChatItems_CollectionChanged;
        }
Example #13
0
        private static void ConfigureServices()
        {
            var context = new DictionaryContext();

            context.Database.Migrate();

            IUnitOfWork unitOfWork = new UnitOfWork(context);

            _dictionaryService = new DictionaryService(unitOfWork);
            _bot     = BotService.GetBot();
            _manager = new CommandManager(_bot, _dictionaryService);
        }
        public CreateAccountViewModel(PageNavigator pageNavigator, SafeCommandFactory commandFactory,
                                      Func <DateTimeOffset> timeStamp, ILoggerService loggerService, IPropertiesRepository propertiesRepository,
                                      BotService botService, AccountService accountService, GuidService guidService,
                                      BlockChainConfiguration config, StateSynchronizer stateSynchronizer)
            : base(pageNavigator, commandFactory, timeStamp, loggerService, propertiesRepository, botService)
        {
            this.accountService = accountService;
            this.guidService    = guidService;
            this.config         = config;

            RemoteState = CommandFactory.Create(async() => { await stateSynchronizer.SetStartState(Identifier); });
        }
Example #15
0
        public ChoicePartnerNicknameViewModel(PageNavigator pageNavigator, SafeCommandFactory commandFactory,
                                              Func <DateTimeOffset> timeStamp, ILoggerService loggerService, IPropertiesRepository propertiesRepository,
                                              BotService botService, IUserDataRepository userDataRepository) : base(pageNavigator, commandFactory,
                                                                                                                    timeStamp, loggerService, propertiesRepository,
                                                                                                                    botService)
        {
            this.userDataRepository = userDataRepository;

            GoToCreateDocument = commandFactory.Create(async() =>
                                                       await PageNavigator.PushPageAsync <CreateDocumentPage>(Identifier, DialogContext,
                                                                                                              NavigationType.PageToPage));
        }
Example #16
0
 public FeatureService(
     ILogger <FeatureService> logger,
     IOptionsSnapshot <FeatureConfig> featureConfig,
     BotService botService,
     RateLimitingInMemory rateLimitingInMemory
     )
 {
     _logger               = logger;
     _botService           = botService;
     _rateLimitingInMemory = rateLimitingInMemory;
     _featureConfig        = featureConfig.Value;
 }
Example #17
0
        public async Task TestStartupProgressMessageAndShutDown()
        {
            CommandHandler.Clear();
            CommandHandler.Register(new CommandDefinition(typeof(PingCommand), new List <string>()
            {
                "ping"
            }));
            Assert.True(CommandHandler.Count == 1);
            ConfigureServicesForTests();
            BotService botService = new BotService(msgHandlerMock.Object);
            await botService.InitAsync().ConfigureAwait(false);

            await botService.RunAsync().ConfigureAwait(false);

            Assert.True(botService.IsRunning);
            msgHandlerMock.Verify(m => m.InitAsync(), Times.Once);
            msgHandlerMock.Verify(m => m.RunAsync(), Times.Once);
            bool            isPublic        = false;
            CommandResponse commandResponse = new CommandResponse(CommandStatus.Error, "");

            Mock <IMessageChannel> msgChannelMock = new Mock <IMessageChannel>(MockBehavior.Strict);

            msgChannelMock.SetupGet(m => m.IsPrivate).Returns(true);

            msgChannelMock.Setup(m => m.WriteToAsync(It.IsAny <bool>(), It.IsAny <CommandResponse>()))
            .Callback <bool, CommandResponse>((b, cr) =>
            {
                isPublic        = b;
                commandResponse = cr;
            })
            .Returns(Task.CompletedTask);

            Message message = new Message(0, "ping", msgChannelMock.Object);
            MessageReceivedEventArgs eventArgs = new MessageReceivedEventArgs(message);

            msgHandlerMock.Raise(m => m.MessageReceived += null, this, eventArgs);

            message   = new Message(0, "test", msgChannelMock.Object);
            eventArgs = new MessageReceivedEventArgs(message);
            msgHandlerMock.Raise(m => m.MessageReceived += null, this, eventArgs);

            await Task.Delay(1000).ConfigureAwait(false);

            Assert.True(isPublic);
            Assert.Equal(CommandStatus.Success, commandResponse.Status);
            Assert.Equal("Pong !", commandResponse.Content);

            await botService.ShutdownAsync().ConfigureAwait(false);

            Assert.False(botService.IsRunning);
            msgHandlerMock.Verify(m => m.ShutdownAsync(), Times.Once);
        }
        public IHttpActionResult GetPath()
        {
            BotService service = new BotService();
            var        str     = "天秤座運勢";
            var        msg     = "";

            if (str.Contains("座"))
            {
                msg = service.GetHoroscope(str.Substring(str.IndexOf("座") - 2, str.IndexOf("座")));
            }

            return(Ok(msg));
        }
Example #19
0
        public async Task TestInitRunAndShutDownBotService()
        {
            var msgHandler = msgHandlerMock.Object;
            var botService = new BotService(msgHandler);
            await botService.InitAsync().ConfigureAwait(false);

            await botService.RunAsync().ConfigureAwait(false);

            Assert.True(botService.IsRunning);
            await botService.ShutdownAsync().ConfigureAwait(false);

            Assert.False(botService.IsRunning);
        }
Example #20
0
        public BaseTelegramViewModel(PageNavigator pageNavigator, SafeCommandFactory commandFactory,
                                     Func <DateTimeOffset> timeStamp, ILoggerService loggerService,
                                     IPropertiesRepository propertiesRepository,
                                     BotService botService)
            : base(pageNavigator, commandFactory, timeStamp, loggerService, propertiesRepository)
        {
            BotService = botService;

            SendMessage        = CommandFactory.Create <string>(SendMessageAsync);
            SendInlineKeyboard = CommandFactory.Create <InlineMenu>(SendInlineKeyboardAsync);
            SendReplyKeyboard  = CommandFactory.Create <ReplyMenu>(SendKeyboardAsync);
            GoBack             = CommandFactory.Create(GoBackAsync);
        }
Example #21
0
    void Start()
    {
        int unUsed;

        Microphone.GetDeviceCaps(deviceName, out unUsed, out samplingRate);
        StartCoroutine(FetchToken(true));
        startTime   = Time.time;
        botService  = new BotService();
        audioSource = gameObject.GetComponent <AudioSource>();
#if WINDOWS_UWP
        botService.StartConversation();
#endif
    }
Example #22
0
 /// <summary>
 /// Constructor of StartHandler
 /// </summary>
 /// <param name="logger"></param>
 /// <param name="envConfig"></param>
 /// <param name="chatService"></param>
 /// <param name="settingsService"></param>
 public StartHandler(
     ILogger <StartHandler> logger,
     IOptionsSnapshot <EnginesConfig> envConfig,
     BotService botService,
     ChatService chatService,
     SettingsService settingsService
     )
 {
     _logger          = logger;
     _botService      = botService;
     _chatService     = chatService;
     _settingsService = settingsService;
     _enginesConfig   = envConfig.Value;
 }
Example #23
0
 public ChatProcessor(IHubContext <ChatHub> chatHubContext, AuthorService authorService,
                      BotService botService, IntegrationManager integrationManager, ChatRulesService chatRulesService,
                      ChatMessageService chatMessageService, ILogger <ChatMessageService> logger, MessageTemplateService messageTemplateService, EmoticonService emoticonService)
 {
     this.chatHubContext         = chatHubContext;
     this.authorService          = authorService;
     this.botService             = botService;
     this.integrationManager     = integrationManager;
     this.chatRulesService       = chatRulesService;
     this.chatMessageService     = chatMessageService;
     this.logger                 = logger;
     this.messageTemplateService = messageTemplateService;
     this.emoticonService        = emoticonService;
 }
        public static async Task <object> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("PolicyEnquiry was triggered!");

            // Initialize the azure bot
            using (BotService.Initialize())
            {
                ConfigureStateStore();

                // Deserialize the incoming activity
                var activity = JsonConvert.DeserializeObject <Activity>(await req.Content.ReadAsStringAsync());

                // authenticate incoming request and add activity.ServiceUrl to MicrosoftAppCredentials.TrustedHostNames
                // if request is authenticated
                if (!await BotService.Authenticator.TryAuthenticateAsync(req, new[] { activity }, CancellationToken.None))
                {
                    return(BotAuthenticator.GenerateUnauthorizedResponse(req));
                }

                if (activity != null)
                {
                    // one of these will have an interface and process it
                    switch (activity.GetActivityType())
                    {
                    case ActivityTypes.Message:
                        await Conversation.SendAsync(activity, () => new RootDialog());

                        break;

                    case ActivityTypes.ConversationUpdate:
                        var client = new ConnectorClient(new Uri(activity.ServiceUrl));
                        IConversationUpdateActivity update = activity;

                        if (update.MembersAdded.Any())
                        {
                            var reply = activity.CreateReply();
                            reply.Text = "Hey! I am Polen. I can answer quick questions for your policy.";
                            await client.Conversations.ReplyToActivityAsync(reply);
                        }
                        break;

                    default:
                        log.Error($"Unknown activity type ignored: {activity.GetActivityType()}");
                        break;
                    }
                }

                return(req.CreateResponse(HttpStatusCode.Accepted));
            }
        }
Example #25
0
        public async Task BotService_AGivenCommand_EnqueueMessage()
        {
            var stock            = @"Symbol,Date,Time,Open,High,Low,Close,Volume
AAPL.US,2019-04-26,22:00:20,204.9,205,202.12,204.3,18649102";
            var fakeStockService = new FakeStockService(stock);
            var messageQueue     = new InMemoryQueue <Message>();
            var botService       = new BotService(fakeStockService, messageQueue);

            await botService.QueryAndSend(stockCode : "aapl.us");

            var lastMessage = await messageQueue.DequeueAsync();

            Assert.IsNotNull(lastMessage);
        }
Example #26
0
        public static async Task <object> Run([HttpTrigger(WebHookType = "genericJson")] HttpRequestMessage req, TraceWriter log)
        {
            // Initialize the azure bot
            using (BotService.Initialize())
            {
                log.Info($"Webhook was triggered! - messages");

                string jsonContent = await req.Content.ReadAsStringAsync();

                var activity = JsonConvert.DeserializeObject <Activity>(jsonContent);

                if (activity != null)
                {
                    // one of these will have an interface and process it
                    switch (activity.GetActivityType())
                    {
                    case ActivityTypes.Message:
                        //here is where we will navigate to root dialogue
                        await Conversation.SendAsync(activity, () => new RootDialog());

                        //var client = new ConnectorClient(new Uri(activity.ServiceUrl));
                        //var triggerReply = activity.CreateReply();

                        //triggerReply.Text = $"Hey you said '{activity.Text}'.";
                        //await client.Conversations.ReplyToActivityAsync(triggerReply);

                        break;

                    case ActivityTypes.ConversationUpdate:

                        if (activity.MembersAdded.Any(o => o.Id == activity.Recipient.Id))
                        {
                            var reply = activity.CreateReply("Welcome to our Bot!");
                            reply.AddHeroCard("Where do you want to go?", MenuHelpers.getMenuOptions("Home"));

                            ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

                            await connector.Conversations.ReplyToActivityAsync(reply);
                        }

                        break;

                    default:
                        log.Error($"Unknown activity type ignored: {activity.GetActivityType()}");
                        break;
                    }
                }
                return(req.CreateResponse(HttpStatusCode.Accepted));
            }
        }
Example #27
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result)
        {
            var activity = await result as Activity;

            if (activity?.Text != null)
            {
                var service = new BotService();

                var replyToConversation = service.Run(activity);
                await context.PostAsync(replyToConversation.Result.Text);
            }

            context.Wait(MessageReceivedAsync);
        }
Example #28
0
        public static async Task <object> BotMessageHandler([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "bot/messages", WebHookType = "genericJson")] HttpRequestMessage req, TraceWriter log)
        {
            // Initialize the azure bot
            using (BotService.Initialize())
            {
                // Deserialize the incoming activity
                string jsonContent = await req.Content.ReadAsStringAsync();

                var activity = JsonConvert.DeserializeObject <Activity> (jsonContent);

                // authenticate incoming request and add activity.ServiceUrl to MicrosoftAppCredentials.TrustedHostNames
                // if request is authenticated
                if (!await BotService.Authenticator.TryAuthenticateAsync(req, new[] { activity }, CancellationToken.None))
                {
                    return(BotAuthenticator.GenerateUnauthorizedResponse(req));
                }

                if (activity != null)
                {
                    if (activity.GetActivityType() == ActivityTypes.Message)
                    {
                        var typing = activity.CreateReply();

                        typing.Type = ActivityTypes.Typing;

                        await activity.ClientForReply().Conversations.ReplyToActivityAsync(typing);

                        if (SimpleQnAMakerDialog.IsQuestion(activity.Text))
                        {
                            await Conversation.SendAsync(activity, () => new SimpleQnAMakerDialog());
                        }
                        else
                        {
                            await Conversation.SendAsync(activity, () => new FaqDialog());
                        }
                    }
                    else
                    {
                        var reply = HandleSystemMessage(activity, log);

                        if (reply != null)
                        {
                            await activity.ClientForReply().Conversations.ReplyToActivityAsync(reply);
                        }
                    }
                }

                return(req.CreateResponse(HttpStatusCode.Accepted));
            }
        }
Example #29
0
        public async Task Process(long chatId, string word, string commandName = null)
        {
            try
            {
                ICommand         command  = GetCommand(commandName);
                ICommandResponse response = await command.ExecuteAsync(chatId, word);

                await response.SendAsync(_bot, chatId);
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                await BotService.Send(_bot, chatId, Resources.ExceptionMessage);
            }
        }
Example #30
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result)
        {
            var activity = await result as Activity;

            TMDbClient client = new TMDbClient("b7290a98a01bc42d6c1ec6a8cb92a0c0");

            if (activity?.Text != null)
            {
                var service           = new BotService();
                var replyConversation = service.Run(activity);
                await context.PostAsync(replyConversation.Result.Text);
            }

            context.Wait(MessageReceivedAsync);
        }