コード例 #1
0
ファイル: BotController.cs プロジェクト: zysr/ArchiSteamFarm
		public async Task<ActionResult<GenericResponse>> BotPost(string botNames, [FromBody] BotRequest request) {
			if (string.IsNullOrEmpty(botNames) || (request == null)) {
				ASF.ArchiLogger.LogNullError(nameof(botNames) + " || " + nameof(request));

				return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(botNames) + " || " + nameof(request))));
			}

			(bool valid, string errorMessage) = request.BotConfig.CheckValidation();

			if (!valid) {
				return BadRequest(new GenericResponse(false, errorMessage));
			}

			request.BotConfig.ShouldSerializeEverything = false;
			request.BotConfig.ShouldSerializeHelperProperties = false;

			HashSet<string> bots = botNames.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Where(botName => botName != SharedInfo.ASF).ToHashSet(Bot.BotsComparer);

			Dictionary<string, bool> result = new Dictionary<string, bool>(bots.Count, Bot.BotsComparer);

			foreach (string botName in bots) {
				if (Bot.Bots.TryGetValue(botName, out Bot bot)) {
					if (!request.BotConfig.IsSteamLoginSet && bot.BotConfig.IsSteamLoginSet) {
						request.BotConfig.SteamLogin = bot.BotConfig.SteamLogin;
					}

					if (!request.BotConfig.IsSteamPasswordSet && bot.BotConfig.IsSteamPasswordSet) {
						request.BotConfig.DecryptedSteamPassword = bot.BotConfig.DecryptedSteamPassword;
					}

					if (!request.BotConfig.IsSteamParentalCodeSet && bot.BotConfig.IsSteamParentalCodeSet) {
						request.BotConfig.SteamParentalCode = bot.BotConfig.SteamParentalCode;
					}

					if ((bot.BotConfig.AdditionalProperties != null) && (bot.BotConfig.AdditionalProperties.Count > 0)) {
						if (request.BotConfig.AdditionalProperties == null) {
							request.BotConfig.AdditionalProperties = new Dictionary<string, JToken>(bot.BotConfig.AdditionalProperties.Count, bot.BotConfig.AdditionalProperties.Comparer);
						}

						foreach ((string key, JToken value) in bot.BotConfig.AdditionalProperties.Where(property => !request.BotConfig.AdditionalProperties.ContainsKey(property.Key))) {
							request.BotConfig.AdditionalProperties.Add(key, value);
						}

						request.BotConfig.AdditionalProperties.TrimExcess();
					}
				}

				string filePath = Bot.GetFilePath(botName, Bot.EFileType.Config);

				if (string.IsNullOrEmpty(filePath)) {
					ASF.ArchiLogger.LogNullError(filePath);

					return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsInvalid, nameof(filePath))));
				}

				result[botName] = await BotConfig.Write(filePath, request.BotConfig).ConfigureAwait(false);
			}

			return Ok(new GenericResponse<IReadOnlyDictionary<string, bool>>(result.Values.All(value => value), result));
		}
コード例 #2
0
ファイル: BotAPI.cs プロジェクト: StonedWizzard/TBotCore
        /// <summary>
        /// transforms user input to request
        /// </summary>
        public virtual BotRequest HandleUserInputMessage(Message msg, IUser user)
        {
            bool       isEmpty = String.IsNullOrEmpty(msg.Text) && String.IsNullOrEmpty(msg.Caption);
            BotRequest request = new BotRequest();

            // no text to handle - no money, no honey...
            if (isEmpty)
            {
                return(request);
            }

            string txt = !String.IsNullOrEmpty(msg.Text) ? msg.Text : msg.Caption;

            // parse message if it command, because them has hiegher priority
            // and able even interrupt serial dialogs!
            var command = Commands.GetCommand(txt, user);

            if (command != null)
            {
                // it's realy command, create request
                string commData = txt;  // ToDo - may be parse it in some way?
                request = new BotRequest(commData, BotRequest.RequestType.Command, user, msg);
            }
            else
            {
                // ...just text
                request = new BotRequest(txt, BotRequest.RequestType.TextMessage, user, msg);
            }

            return(request);
        }
コード例 #3
0
        public ActionResult ReceivePost(BotRequest data)
        {
            Task.Factory.StartNew(() =>
            {
                foreach (var entry in data.Entry)
                {
                    foreach (var message in entry.Messaging)
                    {
                        if (string.IsNullOrWhiteSpace(message?.Message?.Text))
                        {
                            continue;
                        }

                        string _typeText = message.Message.Text;

                        switch (_typeText)
                        {
                        case "1":
                            FirstMessage(message);
                            break;

                        case "2":
                            SendURL(message);
                            break;

                        case "3":
                            SendButtonURL(message);
                            break;
                        }
                    }
                }
            });

            return(new HttpStatusCodeResult(HttpStatusCode.OK));
        }
コード例 #4
0
		public async Task<ActionResult<GenericResponse>> BotPost(string botName, [FromBody] BotRequest request) {
			if (string.IsNullOrEmpty(botName) || (request == null)) {
				ASF.ArchiLogger.LogNullError(nameof(botName) + " || " + nameof(request));
				return BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(botName) + " || " + nameof(request))));
			}

			(bool valid, string errorMessage) = request.BotConfig.CheckValidation();
			if (!valid) {
				return BadRequest(new GenericResponse(false, errorMessage));
			}

			if (Bot.Bots.TryGetValue(botName, out Bot bot)) {
				if (!request.BotConfig.IsSteamLoginSet && bot.BotConfig.IsSteamLoginSet) {
					request.BotConfig.SteamLogin = bot.BotConfig.SteamLogin;
				}

				if (!request.BotConfig.IsSteamPasswordSet && bot.BotConfig.IsSteamPasswordSet) {
					request.BotConfig.DecryptedSteamPassword = bot.BotConfig.DecryptedSteamPassword;
				}

				if (!request.BotConfig.IsSteamParentalCodeSet && bot.BotConfig.IsSteamParentalCodeSet) {
					request.BotConfig.SteamParentalCode = bot.BotConfig.SteamParentalCode;
				}
			}

			request.BotConfig.ShouldSerializeEverything = false;

			string filePath = Path.Combine(SharedInfo.ConfigDirectory, botName + SharedInfo.ConfigExtension);

			bool result = await BotConfig.Write(filePath, request.BotConfig).ConfigureAwait(false);
			return Ok(new GenericResponse(result));
		}
コード例 #5
0
        private void Refresh(object sender, RoutedEventArgs e)
        {
            BotRequest req = new BotRequest();

            req.Type = BotRequestType.ANNOUNCE_ALL;
            req.args.Add("Hello!!!!");
            _bot.SendRequest(req);
        }
コード例 #6
0
 private async Task <bool> TryRunRepostCommand(BotRequest botRequest)
 {
     if (MessageRepostRequest.IsRepostRequest(botRequest))
     {
         var command = new RepostCommand(botRequest.Messenger, botRequest.ChannelId, botRequest.UserId, botRequest.Text);
         return(await _mediator.Send(command));
     }
     return(false);
 }
コード例 #7
0
        private async Task <bool> TryRunSetVacationCommand(BotRequest botRequest)
        {
            var request = SetVacationRequest.TryParse(botRequest);

            if (request != null)
            {
                return(await _mediator.Send(new SetVacationCommand(botRequest.Messenger, botRequest.ChannelId, botRequest.UserId, request.From, request.To)));
            }
            return(false);
        }
コード例 #8
0
        private void BaseWindow_Closing(object sender, CancelEventArgs e)
        {
            if (_bot.getStatus)
            {
                BotRequest req = new BotRequest();
                req.Type = BotRequestType.DISCONNECT;
                _bot.SendRequest(req);
            }

            UI_updateTimer.Stop();
        }
コード例 #9
0
        public async Task <IActionResult> Webhook([FromBody] BotRequest model)
        {
            if (model != null && ModelState.IsValid)
            {
                foreach (var entry in model.entry)
                {
                    var webhookEvent = entry.messaging.FirstOrDefault();
                    var id           = webhookEvent.sender.id;

                    var result = new Result();
                    if (webhookEvent.message != null)
                    {
                        result = await _fbSender.HandleMessage(webhookEvent.sender.id, webhookEvent.message);
                    }
                    else if (webhookEvent.postback != null)
                    {
                        result = await _fbSender.HandlePostback(webhookEvent.sender.id, webhookEvent.postback);
                    }

                    if (!result.Success)
                    {
                        _logger.LogError(Messages.MessageNotSend, model);
                        ModelState.AddModelError("", Messages.MessageNotSend);
                    }

                    var username = await _fbSender.GetUsername(id);

                    if (webhookEvent.postback == null && !string.IsNullOrWhiteSpace(id) && !string.IsNullOrWhiteSpace(username))
                    {
                        var user = new FacebookUser
                        {
                            Username    = username,
                            PSID        = id,
                            CreatedDate = DateTime.Now
                        };

                        var success = await _repository.AddFacebookUser(user);

                        if (!success)
                        {
                            _logger.LogError(Messages.UserExists, user);
                        }
                    }
                }

                if (ModelState.ErrorCount == 0)
                {
                    return(Ok());
                }
            }

            return(BadRequest(ModelState));
        }
コード例 #10
0
ファイル: RequestHandler.cs プロジェクト: caspien6/chatbot
 public async Task HandleRequest(BotRequest data)
 {
     await Task.Factory.StartNew(() =>
     {
         using (var scope = _scopeFactory.CreateScope())
         {
             _repository   = scope.ServiceProvider.GetService <IUserRepository>();
             _stateMachine = scope.ServiceProvider.GetService <MainMenuStateMachine>();
             _logger       = scope.ServiceProvider.GetService <ILogger <RequestHandler> >();
             RequestData(data);
         }
     });
 }
コード例 #11
0
        private async Task <bool> TryRunCheckVacationCommand(BotRequest botRequest)
        {
            var vacationInfoRequest = VacationInfoRequest.TryParse(botRequest);

            if (vacationInfoRequest != null)
            {
                return(await _mediator.Send(new CheckVacationCommand(botRequest.Messenger, botRequest.ChannelId, botRequest.UserId,
                                                                     new UserInfo {
                    SlackId = vacationInfoRequest.SlackId, FullName = vacationInfoRequest.FullName
                })));
            }
            return(false);
        }
コード例 #12
0
        public void TestIfSameReturnEqual()
        {
            Team       team       = Team.Blue;
            AiHero     hero       = AiHero.Ana;
            IBotRule   rule       = new BotRuleEqualTeams();
            Difficulty difficulty = Difficulty.Medium;
            int        min        = 2;
            int        max        = 4;

            BotRequest sut1 = new BotRequest(team, hero, difficulty, rule, min, max);
            BotRequest sut2 = new BotRequest(team, hero, difficulty, rule, min, max);

            Assert.IsTrue(sut1.Equals(sut2));
        }
コード例 #13
0
        public void TestIfDifferentDifficultyNotReturnEqual()
        {
            Team       team        = Team.Blue;
            AiHero     hero        = AiHero.Ana;
            IBotRule   rule        = new BotRuleEqualTeams();
            Difficulty difficulty1 = Difficulty.Medium;
            Difficulty difficulty2 = Difficulty.Hard;
            int        min         = 3;
            int        max         = 3;

            BotRequest sut1 = new BotRequest(team, hero, difficulty1, rule, min, max);
            BotRequest sut2 = new BotRequest(team, hero, difficulty2, rule, min, max);

            Assert.AreNotEqual(sut1, sut2);
        }
コード例 #14
0
        public void TestIfDifferentHeroNotReturnEqual()
        {
            Team       team       = Team.Blue;
            AiHero     hero1      = AiHero.Ana;
            AiHero     hero2      = AiHero.Bastion;
            IBotRule   rule       = new BotRuleEqualTeams();
            Difficulty difficulty = Difficulty.Medium;
            int        min        = 0;
            int        max        = 3;

            BotRequest sut1 = new BotRequest(team, hero1, difficulty, rule, min, max);
            BotRequest sut2 = new BotRequest(team, hero2, difficulty, rule, min, max);

            Assert.AreNotEqual(sut1, sut2);
        }
コード例 #15
0
        public async Task HandleRequestAsync(BotRequest botRequest)
        {
            // default destination (sender)

            if (botRequest.IsDirectMessage)
            {
                try
                {
                    bool isRegistered = await _botRepository.IsLinkRegistered(botRequest.Messenger, botRequest.UserId);

                    if (!isRegistered)
                    {
                        var bindAccountCommand = new BindAccountCommand(botRequest.Messenger, botRequest.ChannelId, botRequest.UserId);
                        await _mediator.Send(bindAccountCommand);

                        return;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }

            var isSuccess = await TryRunCheckVacationCommand(botRequest);

            if (isSuccess)
            {
                return;
            }

            isSuccess = await TryRunSetVacationCommand(botRequest);

            if (isSuccess)
            {
                return;
            }

            isSuccess = await TryRunRepostCommand(botRequest);

            if (isSuccess)
            {
                return;
            }

            var command = new UnknownCommand(botRequest.Messenger, botRequest.ChannelId, botRequest.UserId, botRequest.Text);
            await _mediator.Send(command);
        }
コード例 #16
0
        public async Task <ActionResult> ReceivePost(BotRequest data)
        {
            try
            {
                await _handler.HandleRequest(data);
            }
            catch (Exception e)
            {
                logger.LogError(e.Message);
                logger.LogError(e.StackTrace);
                return(NotFound(e.Message));
            }


            return(Ok());
        }
コード例 #17
0
 private async void OnMessageReceived(object sender, MessageEventArgs messageEventArgs)
 {
     using (var scope = _serviceProvider.CreateScope())
     {
         MessageHandler messageHandler = scope.ServiceProvider.GetService <MessageHandler>();
         var            botRequest     = new BotRequest()
         {
             Messenger       = Messenger.Telegram,
             ChannelId       = messageEventArgs.Message.Chat.Id.ToString(),
             UserId          = messageEventArgs.Message.From.Id.ToString(),
             IsDirectMessage = messageEventArgs.Message.Chat.Type == ChatType.Private,
             Text            = messageEventArgs.Message.Text,
         };
         await messageHandler.HandleRequestAsync(botRequest);
     }
 }
コード例 #18
0
ファイル: WechatBot.cs プロジェクト: loudy2000/WechatBot-3
        string tulingBot(string info, string userid)
        {
            BotRequest req = new BotRequest();

            req.key    = "cb85047a815e418eb334263af2f9830a";
            req.userid = userid;
            req.info   = info;
            string json = JsonConvert.SerializeObject(req);

            string              url        = "http://www.tuling123.com/openapi/api";
            HttpClient          httpClient = new HttpClient();
            HttpResponseMessage response   = httpClient.PostAsync(new Uri(url), new StringContent(json)).Result;
            string              ret        = response.Content.ReadAsStringAsync().Result;
            var rep = JsonConvert.DeserializeObject <BotResponse>(ret);

            return(rep.text);
        }
コード例 #19
0
ファイル: OopEzzController.cs プロジェクト: CyTruong/OOpEzz
        public ActionResult ReceivePost(BotRequest data)
        {
            Task task = Task.Run(() =>
            {
                foreach (var entry in data.entry)
                {
                    foreach (var message in entry.messaging)
                    {
                        if (message.recipient.id.Equals(AppInstance.getInstance().getFbPageId()))
                        {
                            ProgressRequest(message);
                        }
                    }
                }
            });

            return(new HttpStatusCodeResult(HttpStatusCode.OK));
        }
コード例 #20
0
        public void Webhook()
        {
            var json = (dynamic)null;

            try
            {
                using (StreamReader sr = new StreamReader(this.Request.Body))
                {
                    json = sr.ReadToEnd();
                }

                Task.Run(async() =>
                {
                    dynamic data   = JsonConvert.DeserializeObject(json);
                    BotRequest req = JsonConvert.DeserializeObject <BotRequest>(json);


                    if (req?.entry?[0].messaging != null)
                    {
                        PostToFb((string)data.entry[0].messaging[0].sender.id, (string)data.entry[0].messaging[0].message.text);
                    }
                    else
                    {
                        var convId = (string)data.entry[0].changes[0].value.thread_id;
                        //read conversation
                        var messagesJson = await Get(string.Format(ConversationMessages, convId));
                        dynamic result   = JsonConvert.DeserializeObject(messagesJson);

                        if ((string)(result.messages.data[0].from.id) == PageId)
                        {
                            return;
                        }

                        var lastMsg = (string)(result.messages.data[0].message);

                        await PostToFb(convId, lastMsg);
                    }
                });
            }
            catch (Exception ex)
            {
                return;
            }
        }
コード例 #21
0
        public async Task <ActionResult> ReceivePost(BotRequest data)
        {
            foreach (var entry in data.entry)
            {
                foreach (var message in entry.messaging)
                {
                    if (string.IsNullOrWhiteSpace(message?.message?.text))
                    {
                        continue;
                    }

                    var fbmsg = message.message.text;
                    try
                    {
                        Chat._fbUserId = message.sender.id;
                        var chatMessage = chatService.AddFBMessage(message.sender.id, fbmsg);

                        await Hubs.ChatMessage.SendMessage(chatMessage.Text);

                        if (chatMessage.ChatRoom.AgentId != null)
                        {
                            //var chatUser = chatService.GetChatUserByAgentId(chatMessage.ChatRoom.AgentId);
                            //if (chatUser != null)
                            //{
                            var notificationHub = GlobalHost.ConnectionManager.GetHubContext <Hubs.Chat>();
                            //foreach (var connectedClient in chatUser.ConnectedClients)
                            //{
                            //    await (Task)notificationHub.Clients.Client(connectedClient.ConnectionId).addNewMessageToPage("Facebook User", chatMessage.Text);
                            //}
                            await(Task) notificationHub.Clients.Client(chatMessage.ChatRoom.ConnectionId).addNewMessageToPage("Facebook User", chatMessage.Text);

                            //}
                        }
                    }
                    catch (Exception ex)
                    {
                        fBService.Send(message.sender.id, $"Error: {ex.Message}. Please wait few minutes!");
                    }
                }
            }

            return(new HttpStatusCodeResult(HttpStatusCode.OK));
        }
コード例 #22
0
ファイル: BotService.cs プロジェクト: GYuki/BotGenerator
        public override async Task <BotResponse> GetBotById(BotRequest request, ServerCallContext context)
        {
            _logger.LogInformation("Begin grpc call from method {Method} for bot id {Id}", context.Method, request.Id);

            var data = await _repository.GetBotAsync(request.Id);

            if (data != null)
            {
                context.Status = new Status(StatusCode.OK, $"Bot with ID {request.Id} do exist");

                return(MapToBotResponse(data));
            }
            else
            {
                context.Status = new Status(StatusCode.NotFound, $"Bot with id {request.Id} do not exist");
            }

            return(new BotResponse());
        }
コード例 #23
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            var connector         = new SlackConnector.SlackConnector();
            ISlackConnection conn = await connector.Connect(_config.SlackToken);

            conn.OnMessageReceived += message => Task.Run(async() => {
                using (var scope = _serviceProvider.CreateScope()) {
                    var botRequest = new BotRequest {
                        Messenger       = Messenger.Slack,
                        ChannelId       = message.ChatHub.Id,
                        UserId          = message.User.Id,
                        IsDirectMessage = message.ChatHub.Type == SlackConnector.Models.SlackChatHubType.DM,
                        Text            = message.Text,
                    };

                    MessageHandler messageHandler = scope.ServiceProvider.GetService <MessageHandler>();
                    await messageHandler.HandleRequestAsync(botRequest);
                }
            }, cancellationToken);
        }
コード例 #24
0
ファイル: RequestHandler.cs プロジェクト: caspien6/chatbot
        private void RequestData(BotRequest data)
        {
            _logger.LogInformation("Begin data processing");
            foreach (var entry in data.entry)
            {
                _logger.LogInformation("Entry");
                foreach (var message in entry.messaging)
                {
                    _logger.LogInformation("Message");
                    if (string.IsNullOrWhiteSpace(message?.message?.text))
                    {
                        continue;
                    }


                    User u = null;

                    u = _repository.FindUser(UInt64.Parse(message.sender.id));
                    if (u == null)
                    {
                        u = _repository.CreateUser(UInt64.Parse(message.sender.id), message.sender.id);
                    }
                    _stateMachine._state = u.SavedState;

                    GetResponseMessage(message, u);
                    u.SavedState = _stateMachine._state;
                    _repository.UpdateUser(u);
                    //Todo mindegyiknél prepare message et kikötni!

                    /*if (u != null)
                     * {
                     *  PrepareMessage(msg, u.Facebook_id.ToString());
                     * }
                     * else
                     * {
                     *  PrepareMessage(msg, message.sender.id);
                     * }*/
                }
            }
        }
コード例 #25
0
        public ActionResult ReceivePost(BotRequest data)
        {
            Task.Factory.StartNew(() =>
            {
                foreach (var entry in data.entry)
                {
                    foreach (var message in entry.messaging)
                    {
                        if (string.IsNullOrWhiteSpace(message?.message?.text))
                        {
                            continue;
                        }

                        var msg  = "You said: " + message.message.text;
                        var json = $@" {{recipient: {{  id: {message.sender.id}}},message: {{text: ""{msg}"" }}}}";
                        PostRaw("https://graph.facebook.com/v2.6/me/messages?access_token=" + VERIFY_TOKEN, json);
                    }
                }
            });

            return(new HttpStatusCodeResult(HttpStatusCode.OK));
        }
コード例 #26
0
        public async Task <ActionResult <GenericResponse> > Post(string botName, [FromBody] BotRequest request)
        {
            if (string.IsNullOrEmpty(botName) || (request == null))
            {
                ASF.ArchiLogger.LogNullError(nameof(botName) + " || " + nameof(request));
                return(BadRequest(new GenericResponse(false, string.Format(Strings.ErrorIsEmpty, nameof(botName) + " || " + nameof(request)))));
            }

            if (request.KeepSensitiveDetails && Bot.Bots.TryGetValue(botName, out Bot bot))
            {
                if (string.IsNullOrEmpty(request.BotConfig.SteamLogin) && !string.IsNullOrEmpty(bot.BotConfig.SteamLogin))
                {
                    request.BotConfig.SteamLogin = bot.BotConfig.SteamLogin;
                }

                if (string.IsNullOrEmpty(request.BotConfig.SteamParentalPIN) && !string.IsNullOrEmpty(bot.BotConfig.SteamParentalPIN))
                {
                    request.BotConfig.SteamParentalPIN = bot.BotConfig.SteamParentalPIN;
                }

                if (string.IsNullOrEmpty(request.BotConfig.SteamPassword) && !string.IsNullOrEmpty(bot.BotConfig.SteamPassword))
                {
                    request.BotConfig.SteamPassword = bot.BotConfig.SteamPassword;
                }
            }

            request.BotConfig.ShouldSerializeEverything = false;

            string filePath = Path.Combine(SharedInfo.ConfigDirectory, botName + SharedInfo.ConfigExtension);

            if (!await BotConfig.Write(filePath, request.BotConfig).ConfigureAwait(false))
            {
                return(BadRequest(new GenericResponse(false, Strings.WarningFailed)));
            }

            return(Ok(new GenericResponse(true)));
        }
コード例 #27
0
        public async Task <ActionResult> Receive(BotRequest data)
        {
            foreach (var entry in data.entry)
            {
                foreach (var message in entry.messaging)
                {
                    if (string.IsNullOrWhiteSpace(message?.message?.text))
                    {
                        continue;
                    }

                    var fbmsg = message.message.text;
                    try
                    {
                        await _chatService.MessageFromFB(message.sender.id, fbmsg);
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }

            return(Ok());
        }
コード例 #28
0
 public ActionResult ReceivePost(BotRequest data)
 {
     return(null);
 }
コード例 #29
0
        public ActionResult ReceivePost(BotRequest data)
        {
            try
            {
                string strResult = data.entry.FirstOrDefault().messaging.FirstOrDefault().message.quick_reply.payload;
                string idMess    = data.entry.FirstOrDefault().messaging.FirstOrDefault().sender.id;
                if (strResult == "True")
                {
                    try
                    {
                        JsonMessengerText jsonTextMessenger = new JsonMessengerText();
                        jsonTextMessenger.recipient.id = idMess;
                        MessJson messExplaintion = new MessJson();
                        messExplaintion.text      = "Chính xác";
                        jsonTextMessenger.message = messExplaintion;
                        PostRaw("", JsonConvert.SerializeObject(jsonTextMessenger));
                        //isContinue = 2;
                        //Update status
                        UpdateLiteDb(jsonTextMessenger.recipient.id, 2);
                    }
                    catch
                    {
                    }
                }
                else if (strResult == "False")
                {
                    try
                    {
                        JsonMessengerText jsonTextMessenger = new JsonMessengerText();
                        jsonTextMessenger.recipient.id = idMess;
                        MessJson messExplaintion = new MessJson();
                        messExplaintion.text      = "Sai rồi, bạn vui lòng làm lại nha!";
                        jsonTextMessenger.message = messExplaintion;
                        PostRaw("", JsonConvert.SerializeObject(jsonTextMessenger));
                        // isContinue = 1;
                        UpdateLiteDb(jsonTextMessenger.recipient.id, 1);
                    }
                    catch
                    {
                    }
                }
            }
            catch
            {
                //try
                //{
                //    if (data.entry.FirstOrDefault().messaging.FirstOrDefault().message == null)
                //    {
                //        JsonMessengerText jsonTextMessenger = new JsonMessengerText();
                //        jsonTextMessenger.recipient.id = data.entry.FirstOrDefault().messaging.FirstOrDefault().sender.id;
                //        MessJson messExplaintion = new MessJson();
                //        messExplaintion.text = "Có lỗi xay ra, mong bạn thông cảm !";
                //        jsonTextMessenger.message = messExplaintion;
                //        PostRaw("", JsonConvert.SerializeObject(jsonTextMessenger));
                //        isContinue = 1;
                //    }
                //}
                //catch
                //{

                //}
            }
            return(new HttpStatusCodeResult(HttpStatusCode.OK));
        }
コード例 #30
0
        public async Task <ActionResult <GenericResponse <IReadOnlyDictionary <string, bool> > > > BotPost(string botNames, [FromBody] BotRequest request)
        {
            if (string.IsNullOrEmpty(botNames) || (request == null))
            {
                ASF.ArchiLogger.LogNullError(nameof(botNames) + " || " + nameof(request));

                return(BadRequest(new GenericResponse <IReadOnlyDictionary <string, bool> >(false, string.Format(Strings.ErrorIsEmpty, nameof(botNames) + " || " + nameof(request)))));
            }

            (bool valid, string errorMessage) = request.BotConfig.CheckValidation();

            if (!valid)
            {
                return(BadRequest(new GenericResponse <IReadOnlyDictionary <string, bool> >(false, errorMessage)));
            }

            request.BotConfig.ShouldSerializeEverything       = false;
            request.BotConfig.ShouldSerializeHelperProperties = false;

            string originalSteamLogin             = request.BotConfig.SteamLogin;
            string originalDecryptedSteamPassword = request.BotConfig.DecryptedSteamPassword;
            string originalSteamParentalCode      = request.BotConfig.SteamParentalCode;

            HashSet <string> bots = botNames.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Where(botName => botName != SharedInfo.ASF).ToHashSet();

            Dictionary <string, bool> result = new Dictionary <string, bool>(bots.Count);

            foreach (string botName in bots)
            {
                bool botExists = Bot.Bots.TryGetValue(botName, out Bot bot);

                if (botExists)
                {
                    if (!request.BotConfig.IsSteamLoginSet && bot.BotConfig.IsSteamLoginSet)
                    {
                        request.BotConfig.SteamLogin = bot.BotConfig.SteamLogin;
                    }

                    if (!request.BotConfig.IsSteamPasswordSet && bot.BotConfig.IsSteamPasswordSet)
                    {
                        request.BotConfig.DecryptedSteamPassword = bot.BotConfig.DecryptedSteamPassword;
                    }

                    if (!request.BotConfig.IsSteamParentalCodeSet && bot.BotConfig.IsSteamParentalCodeSet)
                    {
                        request.BotConfig.SteamParentalCode = bot.BotConfig.SteamParentalCode;
                    }
                }

                string filePath = Path.Combine(SharedInfo.ConfigDirectory, botName + SharedInfo.ConfigExtension);
                result[botName] = await BotConfig.Write(filePath, request.BotConfig).ConfigureAwait(false);

                if (botExists)
                {
                    request.BotConfig.SteamLogin             = originalSteamLogin;
                    request.BotConfig.DecryptedSteamPassword = originalDecryptedSteamPassword;
                    request.BotConfig.SteamParentalCode      = originalSteamParentalCode;
                }
            }

            return(Ok(new GenericResponse <IReadOnlyDictionary <string, bool> >(result.Values.All(value => value), result)));
        }