Ejemplo n.º 1
0
        /// <summary>
        /// Рисует все пути на карте этажа
        /// </summary>
        /// <param name="dataOfBot"></param>
        /// <param name="FloorNumber"></param>
        /// <returns></returns>
        public BitmapSettings DrawAllWaysAndAllShops(CachedDataModel dataOfBot, int FloorNumber)
        {
            var bitmap = new BitmapSettings(new Bitmap(Image.FromFile(ConfigurationManager.AppSettings["ContentPath"] + $"Floors\\{dataOfBot.Floors.FirstOrDefault(x => x.Number == FloorNumber).FloorID}.{dataOfBot.Floors.FirstOrDefault(x => x.Number == FloorNumber).FileExtension}")));

            var mbMapHelper = new BotMapHelper();
            var graph       = mbMapHelper.GetOneLayer(dataOfBot, dataOfBot.Floors.FirstOrDefault(x => x.Number == FloorNumber));

            DrawAllShops(graph, dataOfBot);
            var layer = graph.Layers[0];

            using (var gr = Graphics.FromImage(bitmap.Bmp))
            {
                gr.SmoothingMode      = SmoothingMode.HighQuality;
                gr.CompositingQuality = CompositingQuality.HighQuality;
                gr.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                gr.PixelOffsetMode    = PixelOffsetMode.HighQuality;

                foreach (var item in layer.Segments)
                {
                    gr.DrawLine(bitmap.MyPen,
                                (float)(item.Vertex0.Point.X) / ZoomOfPicture + bitmap.I,
                                (float)(item.Vertex0.Point.Y) / ZoomOfPicture + bitmap.J,
                                (float)(item.Vertex1.Point.X) / ZoomOfPicture + bitmap.I,
                                (float)(item.Vertex1.Point.Y) / ZoomOfPicture + bitmap.J);
                }
            }
            DrawLandMarksExtra(dataOfBot, FloorNumber);

            var tmp = $"Этаж {FloorNumber.ToString()}   {dataOfBot.Customers[0].Name} {dataOfBot.Customers[0].LocaleCity}";

            DrawText(tmp, BotTextHelper.LengthOfString(tmp, bitmap), 5F, 23, Color.DarkSlateGray, true);

            return(bitmap);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Анализирует полезные данные для генерации талона. Генерирует талон - строку, которая будет отправлена пользователю
        /// </summary>
        /// <param name="cacheHelper"></param>
        /// <param name="talon"></param>
        /// <param name="message"></param>
        /// <param name="serviceName"></param>
        /// <param name="office"></param>
        /// <returns></returns>
        public static string AnaliseTalon(EnquequeResponse talon, string message, string serviceName = null, DBHelpers.Models.MFCModels.Office office = null)
        {
            if (office != null)
            {
                message = message.Replace("%office%", office.DisplayName);
            }

            message = message.Replace("%number%", BotTextHelper.GetVKSmileNumber(talon.ID));
            if (serviceName != null)
            {
                message = message.Replace("%servicename%", serviceName);
            }
            //Дата в талоне
            if (talon.TimeOfReceipt == null || talon.TimeOfReceipt.Year == 0001)
            {
                message = message.Replace("%time%", DateTime.Now.ToString("HH:mm  dd.MM.yyyy"));
            }
            else
            {
                message = message.Replace("%time%", talon.TimeOfReceipt.ToString("HH:mm  dd.MM.yyyy"));
            }
            //перед вами в очереди
            message = message.Replace("%queuecount%", talon.QueueSize?.toWindows.ToString());
            //офис в котором юзер
            if (office != null)
            {
                message = message.Replace("%adress%", office.DisplayAddress);
            }
            return(message);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Маршрутизатор текстовых сообщений
        /// </summary>
        /// <param name="thisQuery"></param>
        /// <param name="type"></param>
        /// <param name="Bot"></param>
        /// <param name="botUser"></param>
        /// <param name="text"></param>
        /// <param name="Requests"></param>
        /// <returns></returns>
        public async Task <int> SendText(string text)
        {
            TelegramBotClient telegram = null;
            FacebookApiHelper facebook = null;
            int IsError = 0;

            if (type == SocialNetworkType.Telegram)
            {
                telegram = (TelegramBotClient)Bot;
            }
            if (type == SocialNetworkType.Facebook)
            {
                facebook = (FacebookApiHelper)Bot;
            }

            if (type == SocialNetworkType.VK)
            {
                //var cont = new SenderContext("Z_Messages");
                //cont.Message.Add(new BotMessage { BotUserVKID = botUser.BotUserVKID, Text = text, DateTime = DateTime.Now, IsSended = false });
                //cont.SaveChanges();
                Requests.Add(new VKApiRequestModel(ulong.Parse(botUser.BotUserVKID), text));
            }
            if (type == SocialNetworkType.Telegram)
            {
                text = BotTextHelper.SmileCodesReplace(text);
                await telegram.SendTextMessageAsync(botUser.BotUserTelegramID, text);
            }
            if (type == SocialNetworkType.Facebook)
            {
                IsError = await facebook.SendMessage(botUser.BotUserFacebookID, text);
            }

            return(IsError);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Генерит jsonчик и отправляет его фейсбуку
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private async Task <int> Send(SendMessageModel model)
        {
            string jsonContent = JsonConvert.SerializeObject(model,
                                                             Formatting.None,
                                                             new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            });

            jsonContent = BotTextHelper.SmileCodesReplace(jsonContent, SocialNetworkType.Facebook);

            HttpResponseMessage responce;
            StringContent       content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            string url = $"https://graph.facebook.com/v2.6/me/messages?access_token={_token}";

            using (var client = new HttpClient())
            {
                using (var r = await client.PostAsync(new Uri(url), content))
                {
                    responce = r;
                    string responceString = await r.Content.ReadAsStringAsync();

                    if (responceString.ToLower().Contains("error"))
                    {
                        Logging.Logger.Error($"Facebook Api Send: NOT OK!! {responceString}");
                        return(1);
                    }
                    else
                    {
                        return(0);
                    }
                }
            }
        }
Ejemplo n.º 5
0
        public MainAnswerHelper(BotUserRequest _thisRequest, object _Bot, SocialNetworkType _type, BotUser _botUser, List <MallBotContext> _dbContextes, List <VKApiRequestModel> _Requests = null)
        {
            botUser     = _botUser;
            dbContextes = _dbContextes;
            Requests    = _Requests;
            Bot         = _Bot;
            type        = _type;
            thisRequest = _thisRequest;

            #region Кэшируем
            string CachedItemKey = "MallBotData";
            var    datafromCache = cacher.Get(CachedItemKey);
            if (datafromCache == null)
            {
                datasOfBot = cacher.Update(CachedItemKey, dbContextes);
            }
            else
            {
                datasOfBot = (List <CachedDataModel>)datafromCache;
            }
            #endregion

            texter     = new BotTextHelper(botUser.Locale, type, datasOfBot[0].Texts);
            sender     = new ApiRouter(type, Bot, botUser, Requests);
            dataGetter = new GetDataHelper(datasOfBot);

            if (botUser.NowIs != MallBotWhatIsHappeningNow.SettingCustomer)
            {
                char usersdbID  = botUser.CustomerCompositeID[0];
                var  customerID = int.Parse(botUser.CustomerCompositeID.Remove(0, 1));
                currentCustomer = dataGetter.GetStructuredCustomers(true).FirstOrDefault(x => x.DBaseID == usersdbID).Customers.FirstOrDefault(x => x.CustomerID == customerID); //дает возможность работы в тц не из тестового режима
            }
        }
Ejemplo n.º 6
0
 void ProcessCommonResponse(string message, out BotResponse response)
 {
     response      = new BotResponse();
     response.From = message;
     response.Text = string.Format("{0}", BotTextHelper.GetCommonText(message));
     response.Rank = ResponseRank.Normal;
     object[] parameter = new object[] { response };
     response.RtfText = RtfDocumentHelper.GetRtfText(parameter);
 }
Ejemplo n.º 7
0
 void ProcessDefaultResponse(string messageText, out BotResponse response)
 {
     response      = new BotResponse();
     response.From = messageText;
     response.Text = string.Format("{0}", BotTextHelper.GetRandomText());
     response.Rank = ResponseRank.Low;
     object[] parameter = new object[] { response };
     response.RtfText = RtfDocumentHelper.GetRtfText(parameter);
 }
Ejemplo n.º 8
0
 public AnswerWithPhotoHelper(SocialNetworkType _type, FindedInformation _answer, ApiRouter _sender, BotUser _botUser, BotTextHelper _texter, CachedDataModel _dataOfBot)
 {
     answer    = _answer;
     sender    = _sender;
     botUser   = _botUser;
     texter    = _texter;
     type      = _type;
     dataOfBot = _dataOfBot;
 }
Ejemplo n.º 9
0
        private async Task <int> AnaliseSearchCustomerResult(List <FuzzySearchResult> result)
        {
            string message;

            switch (result.Count)
            {
            case 0:
                message = GetBeauteCustomersString();
                if (botUser.IsNewUser)
                {
                    message = texter.GetMessage("%start%") + "\\r\\n\\r\\n" + texter.GetMessage("%mallsearchstart%", "%malls%", message);
                    await sender.SendText(message);
                }
                else
                {
                    message = texter.GetMessage("%ctmrsearchfail%") + "\\r\\n\\r\\n" + texter.GetMessage("%mallsearchstart%", "%malls%", message);
                    await sender.SendText(message);
                }
                return(1);

            case 1:
                cacher.Remove($"SETCUSTOMER{botUser.BotUserID}");
                // изменям информацию по пользователю
                botUser.CustomerCompositeID = result[0].CustomersKey;
                botUser.NowIs        = MallBotWhatIsHappeningNow.SearchingOrganization;
                botUser.ModifiedDate = DateTime.Now;

                message = texter.GetMessage("%ctmrsearchoneres%", "%mall%", result[0].Name, result[0].LocaleCity) + "\\r\\n\\r\\n" + texter.GetMessage("%orgsearchstart%", "%mall%", result[0].Name + " " + result[0].LocaleCity);
                await sender.SendText(message);

                return(1);

            default:
                string p = "";
                for (int i = 0; i < result.Count; i++)
                {
                    if (botUser.Locale == "ru_RU" || result[i].LocaleCity.Length == 1)
                    {
                        p += $"{BotTextHelper.GetEmojiNumber(i + 1)} " + result[i].Name + "  " + result[i].LocaleCity[0] + "\\r\\n";
                    }
                    else
                    {
                        p += $"{BotTextHelper.GetEmojiNumber(i+1)} " + result[i].Name + "  " + result[i].LocaleCity[1] + "\\r\\n";
                    }
                }
                await sender.SendText(texter.GetMessage("%ctmrsearchmanyres%", "%malls%", p));

                string customersIDs = "";
                foreach (var item in result)
                {
                    customersIDs += item.CustomersKey + ";";
                }
                cacher.Set($"SETCUSTOMER{botUser.BotUserID}", customersIDs, 35);
                return(1);
            }
        }
Ejemplo n.º 10
0
        public MainAnswerHelper(DBHelpers.Models.MFCModels.BotUser _botUser, MFCBotContext _context, BotUserRequest _thisRequest, List <VKApiRequestModel> _requests)
        {
            context     = _context;
            botUser     = _botUser;
            thisRequest = _thisRequest;
            requests    = _requests;

            string key           = "MFCDATAOFBOT";
            var    datafromCache = cacheHelper.Get(key);

            if (datafromCache == null)
            {
                mfcDataOfBot = cacheHelper.Update(key, context);
            }
            else
            {
                mfcDataOfBot = (MFCBotModel)datafromCache;
            }

            if (botUser.NowIs != MFCBotWhatIsHappeningNow.SettingOffice)
            {
                var usersOffice = mfcDataOfBot.Offices.FirstOrDefault(x => x.AisMFCID == botUser.OfficeID);
                if (usersOffice.Name == "Ярмарка")
                {
                    usersOffice.OfficeID = 326;
                }
                //получаем все секции, которые относятся к выбранному филиалу
                mfcDataOfBot.Sections = mfcDataOfBot.AllSections.
                                        Where(x => mfcDataOfBot.SectionOffices.
                                              Where(z => z.OfficeID == usersOffice.OfficeID).
                                              Select(y => y.SectionID).Contains(x.SectionID)).DistinctBy(x => x.Name).ToList();
                //сохраняем из них только листья
                mfcDataOfBot.RetainLeafs();
            }

            sendHelper = new ApiRouter(SocialNetworkType.VK, null, botUser, requests);
            textHelper = new BotTextHelper(botUser.Locale, SocialNetworkType.VK, mfcDataOfBot.Texts);
        }
Ejemplo n.º 11
0
        public async Task <int> AnalyseBadRequest(BotUser botUser, SocialNetworkType type, object bot, List <BotText> botTexts, List <VKApiRequestModel> Requests = null)
        {
            var texter = new BotTextHelper(botUser.Locale, type, botTexts);
            var sender = new ApiRouter(type, bot, botUser, Requests);

            switch (botUser.NowIs)
            {
            case MallBotWhatIsHappeningNow.SettingCustomer:
                return(await sender.SendText(texter.GetMessage("%badrequest1%")));

            case MallBotWhatIsHappeningNow.SearchingOrganization:
                return(await sender.SendText(texter.GetMessage("%badrequest2%")));

            case MallBotWhatIsHappeningNow.SearchingWay:
                return(await sender.SendText(texter.GetMessage("%badrequest3%")));

            case MallBotWhatIsHappeningNow.GettingAllOrganizations:
                return(await sender.SendText(texter.GetMessage("%badrequest4%")));

            default:
                return(0);
            }
        }
Ejemplo n.º 12
0
        private string GetBeauteCustomersString()
        {
            var customers = dataGetter.GetStructuredCustomers(Convert.ToBoolean(botUser.IsTestMode));

            string message = "";
            int    number  = 1;

            foreach (var dbData in customers)
            {
                foreach (var customer in dbData.Customers)
                {
                    if (botUser.Locale == "ru_RU" || customer.LocaleCity.Length == 1)
                    {
                        message += $"{BotTextHelper.GetEmojiNumber(number)} " + customer.Name + "  " + customer.LocaleCity[0] + "\\r\\n";
                    }
                    else
                    {
                        message += $"{BotTextHelper.GetEmojiNumber(number)} " + customer.Name + "  " + customer.LocaleCity[1] + "\\r\\n";
                    }
                    number++;
                }
            }
            return(message);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Возвращает текст, соответствующий статусу талона с запрошенным номером
        /// </summary>
        /// <param name="botUser"></param>
        /// <param name="office"></param>
        /// <param name="TalonID"></param>
        /// <param name="service"></param>
        /// <param name="textHelper"></param>
        /// <returns></returns>
        public static string GetAnalysedAnswer(DBHelpers.Models.MFCModels.BotUser botUser, DBHelpers.Models.MFCModels.Office office, int TalonID, BotTextHelper textHelper, List <WindowsOffice> windows)
        {
            var talon = new EnquequeResponse();

            switch (CheckUsersTalonNumber(out talon, botUser.OfficeID, TalonID))
            {
            case GetTicketInformationErrors.UnknownError:
                return(textHelper.GetMessage("%ginfuncknow%",
                                             new string[] { "%officename%", "%adress%" },
                                             new string[] { office.DisplayName, office.DisplayAddress }));

            case GetTicketInformationErrors.NoExist:
                return(textHelper.GetMessage("%ginfnoexist%",
                                             new string[] { "%officename%", "%adress%" },
                                             new string[] { office.DisplayName, office.DisplayAddress }));

            case GetTicketInformationErrors.Ended:
                return(textHelper.GetMessage("%ginfended%",
                                             new string[] { "%officename%", "%adress%" },
                                             new string[] { office.DisplayName, office.DisplayAddress }));

            case GetTicketInformationErrors.Absence:
                return(textHelper.GetMessage("%ginfabsebce%",
                                             new string[] { "%officename%", "%adress%" },
                                             new string[] { office.DisplayName, office.DisplayAddress }));

            case GetTicketInformationErrors.Waiting:
                var s = AnaliseTalon(talon, textHelper.GetMessage("%getinfo%") + "\\r\\n\\r\\n" + textHelper.GetMessage("%queue%"), BotTextHelper.DecodeToUtf8(talon.services[0].name), office);
                //сохраняем информацию по талону => делаем его выбранным пользователем
                botUser.TalonID   = TalonID;
                botUser.ServiceID = talon.services[0].id;
                botUser.NowIs     = MFCBotWhatIsHappeningNow.QueueWaiting;
                s += "\\r\\n\\r\\n" + textHelper.GetMessage("%statustext%");
                Logging.Logger.Debug(s);
                return(s);

            case GetTicketInformationErrors.InProces:
                string usefulInf = BotTextHelper.DecodeToUtf8(talon.stateTicket.description);
                //получаем последнее число из строки
                string windowStringID = Regex.Match(usefulInf, @"\d+(?!\D*\d)").Value;
                int    windowID       = int.Parse(windowStringID);
                usefulInf = usefulInf.Replace(windowStringID, windows.FirstOrDefault(x => x.WindowID == windowID).Number.ToString());

                s  = $"\U00002705 {usefulInf}\\r\\n\\r\\n";
                s += AnaliseTalon(talon, textHelper.GetMessage("%getinfo%"), BotTextHelper.DecodeToUtf8(talon.services[0].name), office) + "\\r\\n\\r\\n";
                s += textHelper.GetMessage("%helptext%");
                //Обслуживается => забываем о пользователе. Сессия окончена
                botUser.OfficeID  = 0;
                botUser.TalonID   = 0;
                botUser.ServiceID = 0;
                botUser.NowIs     = MFCBotWhatIsHappeningNow.SettingOffice;
                Logging.Logger.Debug(s);
                return(s);

            default:
                //начальное сообщение
                return(textHelper.GetMessage("%gtinfstart%",
                                             new string[] { "%officename%", "%adress%", "%business%" },
                                             new string[] { office.DisplayName, office.DisplayAddress, MainAnswerHelper.GetBusynessOffice(office.OfficeID) }));
            }
        }
Ejemplo n.º 14
0
        public async Task <HttpResponseMessage> PostMessage(JObject jsonResponce)
        {
            DateTime TimeToStartAnswer = DateTime.Now;
            var      telegramResponce  = jsonResponce.ToObject <Update>();

            Logging.Logger.Debug($"PostMessage message={jsonResponce}");

            if (telegramResponce == null)
            {
                Logging.Logger.Error("Пустой запрос");
                return(new HttpResponseMessage(HttpStatusCode.OK));
            }


            if (telegramResponce.Type == UpdateType.MessageUpdate)
            {
                var _Bot = new Telegram.Bot.Api(_token);

                await _Bot.SendChatActionAsync(telegramResponce.Message.Chat.Id, ChatAction.Typing);

                if (telegramResponce.Message.Text == null)
                {
                    await _Bot.SendTextMessageAsync(telegramResponce.Message.Chat.Id, "Простите, но я не поняла вас \U0001F614");
                }
                else
                {
                    try
                    {
                        // кэшируем
                        #region
                        string trimmedLoweredQuery = telegramResponce.Message.Text.ToLower().Trim(QueryAnaliser.splitters);
                        var    thisQuery           = new BotUserQuery {
                            IsError = 0
                        };

                        var mbFunctional    = new MallBotFunctional();
                        var mbDBHelper      = new MallBotDBHelper();
                        var mbApiFunctional = new MallBotApiTelegramFunctional();

                        string       MainCachedItemKey   = "MainDataOfBot";
                        string       RadugaCachedItemKey = "RadugaDataOfBot";
                        MallBotModel MainDataOfBot       = null;
                        MallBotModel RadugaDataOfBot     = null;

                        var dbMainContext   = new MallBotContext(); dbMainContext.Configuration.ProxyCreationEnabled = false;
                        var dbRadugaContext = new MallBotContext(1); dbMainContext.Configuration.ProxyCreationEnabled = false;

                        object MaindataFromCache   = MemoryCache.Default.Get(MainCachedItemKey, null);
                        object RadugadataFromCache = MemoryCache.Default.Get(RadugaCachedItemKey, null);

                        if (trimmedLoweredQuery == "update")
                        {
                            if (MaindataFromCache != null)
                            {
                                MemoryCache.Default.Remove(MainCachedItemKey, null);
                            }
                            if (RadugadataFromCache != null)
                            {
                                MemoryCache.Default.Remove(RadugaCachedItemKey, null);
                            }

                            MaindataFromCache   = null;
                            RadugadataFromCache = null;
                        }

                        if (MaindataFromCache == null || RadugadataFromCache == null)
                        {
                            List <int?> ids = new List <int?> {
                                3, 5
                            };
                            MainDataOfBot = new MallBotModel(dbMainContext, ids);

                            ids = new List <int?> {
                                1
                            };
                            RadugaDataOfBot = new MallBotModel(dbRadugaContext, ids);

                            string[]        TimeOfExpiration = ConfigurationManager.AppSettings["TimeOfExpiration"].ToString().Split(':');
                            CacheItemPolicy cip = new CacheItemPolicy()
                            {
                                AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddHours(int.Parse(TimeOfExpiration[0])).AddMinutes(int.Parse(TimeOfExpiration[1])).AddSeconds(int.Parse(TimeOfExpiration[2])))
                            };
                            MemoryCache.Default.Set(new CacheItem(MainCachedItemKey, (object)MainDataOfBot), cip);
                            MemoryCache.Default.Set(new CacheItem(RadugaCachedItemKey, (object)RadugaDataOfBot), cip);
                        }
                        else
                        {
                            MainDataOfBot   = (MallBotModel)MaindataFromCache;
                            RadugaDataOfBot = (MallBotModel)RadugadataFromCache;
                        }
                        #endregion
                        var botUsers = dbMainContext.BotUser.ToList();
                        var botUser  = botUsers.FirstOrDefault(x => x.BotUserTelegramID == telegramResponce.Message.Chat.Id.ToString());
                        QueryAnaliserResult answer    = null;
                        MallBotModel        DataOfBot = null;
                        var customers = MainDataOfBot.Customers;
                        customers.AddRange(RadugaDataOfBot.Customers);

                        var IsTutorial = true;
                        if (
                            #region
                            botUser == null ||
                            trimmedLoweredQuery == "place" ||
                            trimmedLoweredQuery == "место" ||
                            trimmedLoweredQuery == "сменить тц" ||
                            trimmedLoweredQuery == "тц" ||
                            botUser.CustomerName == "newuser" ||
                            trimmedLoweredQuery == "help" && (botUser.CustomerName == "newuser" || botUser.CustomerName == "empty") ||
                            trimmedLoweredQuery == "помощь" && (botUser.CustomerName == "newuser" || botUser.CustomerName == "empty")
                            #endregion
                            )
                        {
                            if (trimmedLoweredQuery == "help" || trimmedLoweredQuery == "помощь")
                            {
                                var message = MainDataOfBot.Texts.FirstOrDefault(x => x.Locale == botUser.Locale && x.Key == "%priorityhelp%").Text;
                                message = message.Replace("%place%", "/place");
                                message = BotTextHelper.SmileCodesReplace(message);
                                await _Bot.SendTextMessageAsync(telegramResponce.Message.Chat.Id, message);
                            }
                            else
                            {
                                if (botUser == null)
                                {
                                    dbMainContext = mbDBHelper.AddBotUser(ulong.Parse(telegramResponce.Message.Chat.Id.ToString()), 2, null, telegramResponce.Message.From.FirstName, telegramResponce.Message.From.LastName, 0, null, "ru_RU", false, dbMainContext);
                                    botUser       = dbMainContext.BotUser.FirstOrDefault(x => x.BotUserTelegramID == telegramResponce.Message.Chat.Id.ToString());
                                }

                                botUser.CustomerName = "empty";
                                if (botUser.LevelTutorial != 4)
                                {
                                    botUser.LevelTutorial = 0;
                                }
                                botUser.ModifiedDate = DateTime.Now;
                                dbMainContext.SaveChanges();

                                var message = MainDataOfBot.Texts.FirstOrDefault(x => x.Locale == botUser.Locale && x.Key == "%mallselect%").Text;
                                message = message.Replace("%mall1%", "1. " + customers[0].Name + "  " + customers[0].City);
                                message = message.Replace("%mall2%", "2. " + customers[1].Name + "  " + customers[1].City);
                                message = message.Replace("%mall3%", "3. " + customers[2].Name + "  " + customers[2].City);
                                message = BotTextHelper.SmileCodesReplace(message);
                                await _Bot.SendTextMessageAsync(telegramResponce.Message.Chat.Id, message);
                            }
                        }
                        else
                        {
                            if (botUser.CustomerName == "empty")
                            {
                                var qa  = new QueryAnaliser();
                                var res = mbFunctional.SearchCustomer(qa.NormalizeQuery(telegramResponce.Message.Text), customers);

                                if (res.Count != 0)
                                {
                                    var findedCustomer = customers.FirstOrDefault(x => x.CustomerID == res[0].ID);

                                    var message = MainDataOfBot.Texts.FirstOrDefault(x => x.Locale == botUser.Locale && x.Key == "%mallselectsucces%").Text;
                                    message = message.Replace("%findedmall%", findedCustomer.Name + "  " + findedCustomer.City);
                                    message = message.Replace("%place%", "/place");
                                    message = BotTextHelper.SmileCodesReplace(message);
                                    await _Bot.SendTextMessageAsync(telegramResponce.Message.Chat.Id, message);

                                    botUser.CustomerName = res[0].Name;
                                    dbMainContext.SaveChanges();
                                    if (botUser.LevelTutorial != 4)
                                    {
                                        answer = await mbApiFunctional.doTutorial(botUser, telegramResponce.Message.Text, _Bot, telegramResponce.Message.Chat.Id, dbMainContext, MainDataOfBot);
                                    }
                                }
                                else
                                {
                                    var message = MainDataOfBot.Texts.FirstOrDefault(x => x.Locale == botUser.Locale && x.Key == "%mallselectfail%").Text;
                                    message = message.Replace("%notfindedmall%", telegramResponce.Message.Text);
                                    message = BotTextHelper.SmileCodesReplace(message);
                                    await _Bot.SendTextMessageAsync(telegramResponce.Message.Chat.Id, message);
                                }
                            }
                            else
                            {
                                if (botUser.CustomerName == RadugaDataOfBot.Customers[0].Name)
                                {
                                    DataOfBot       = RadugaDataOfBot;
                                    DataOfBot.Texts = MainDataOfBot.Texts;
                                }
                                else
                                {
                                    DataOfBot = mbDBHelper.SelectData(MainDataOfBot, botUser, customers);
                                }

                                // Блок для описания команд
                                if (trimmedLoweredQuery.Contains("testfunc")) // команды для разработчиков
                                {
                                    await mbApiFunctional.doDebelopersCommands(trimmedLoweredQuery, DataOfBot, _Bot, telegramResponce.Message.Chat.Id);
                                }
                                else // команды для пользователей
                                {
                                    var message = "";
                                    switch (trimmedLoweredQuery)
                                    {
                                    case "start":
                                        message = MainDataOfBot.Texts.FirstOrDefault(x => x.Locale == botUser.Locale && x.Key == "%start%").Text;
                                        message = message.Replace("%help%", "/help");
                                        message = BotTextHelper.SmileCodesReplace(message);
                                        await _Bot.SendTextMessageAsync(telegramResponce.Message.Chat.Id, message);

                                        break;

                                    case "update":
                                        message = MainDataOfBot.Texts.FirstOrDefault(x => x.Locale == botUser.Locale && x.Key == "%cacheupdate%").Text;
                                        message = BotTextHelper.SmileCodesReplace(message);
                                        await _Bot.SendTextMessageAsync(telegramResponce.Message.Chat.Id, message);

                                        break;

                                    case "clear":
                                        botUser.LevelTutorial = 0;
                                        botUser.CustomerName  = "newuser";
                                        botUser.ModifiedDate  = DateTime.Now;
                                        dbMainContext.SaveChanges();

                                        message = MainDataOfBot.Texts.FirstOrDefault(x => x.Locale == botUser.Locale && x.Key == "%clear%").Text;
                                        message = BotTextHelper.SmileCodesReplace(message);
                                        await _Bot.SendTextMessageAsync(telegramResponce.Message.Chat.Id, message);

                                        break;

                                    case "skip":
                                        botUser.LevelTutorial = 4;
                                        botUser.ModifiedDate  = DateTime.Now;
                                        dbMainContext.SaveChanges();

                                        message = MainDataOfBot.Texts.FirstOrDefault(x => x.Locale == botUser.Locale && x.Key == "%skip%").Text;
                                        message = BotTextHelper.SmileCodesReplace(message);
                                        await _Bot.SendTextMessageAsync(telegramResponce.Message.Chat.Id, message);

                                        break;

                                    case "привет":
                                    case "hello":
                                    case "здравствуйте":
                                    case "пряффки":
                                    case "hi":

                                        message = MainDataOfBot.Texts.FirstOrDefault(x => x.Locale == botUser.Locale && x.Key == "%hello%").Text;
                                        message = BotTextHelper.SmileCodesReplace(message);
                                        await _Bot.SendTextMessageAsync(telegramResponce.Message.Chat.Id, message);

                                        break;

                                    case "пока":
                                    case "до свидания":
                                    case "спасибо":
                                    case "покеда":
                                    case "досвидули":
                                    case "большоеспасибо":
                                    case "прощай":
                                        message = MainDataOfBot.Texts.FirstOrDefault(x => x.Locale == botUser.Locale && x.Key == "%thkx%").Text;
                                        message = BotTextHelper.SmileCodesReplace(message);
                                        await _Bot.SendTextMessageAsync(telegramResponce.Message.Chat.Id, message);

                                        break;

                                    case "помощь":
                                    case "help":
                                    case "как это работает":
                                    case "хелп":
                                        message = MainDataOfBot.Texts.FirstOrDefault(x => x.Locale == botUser.Locale && x.Key == "%help%").Text;
                                        message = message.Replace("%place%", "/place");
                                        message = message.Replace("%tutorial%", "/tutorial");
                                        message = message.Replace("%help%", "/help");
                                        message = BotTextHelper.SmileCodesReplace(message);
                                        await _Bot.SendTextMessageAsync(telegramResponce.Message.Chat.Id, message);

                                        break;

                                    case "что делать":
                                    case "tutorial":
                                    case "обучение":
                                    case "туториал":
                                        answer = await mbApiFunctional.doTutorial(botUser, telegramResponce.Message.Text, _Bot, telegramResponce.Message.Chat.Id, dbMainContext, DataOfBot, true);

                                        break;

                                    default:
                                        if (botUser.LevelTutorial != 4)
                                        {
                                            answer = await mbApiFunctional.doTutorial(botUser, telegramResponce.Message.Text, _Bot, telegramResponce.Message.Chat.Id, dbMainContext, DataOfBot);
                                        }
                                        else
                                        {
                                            var mbFunctionalAnalizer = new MallBotFunctionalAnalizeTelegramHelper();
                                            answer = await mbFunctionalAnalizer.AnaliseDoWorkResult(telegramResponce.Message.Text, telegramResponce.Message.Chat.Id, DataOfBot, _Bot, botUser);

                                            IsTutorial = false;
                                        }
                                        break;
                                    }
                                }
                            }
                        }

                        //пишем  в базу запрос
                        if (botUser != null)
                        {
                            if (DataOfBot == null)
                            {
                                mbDBHelper.AddBotQuery(botUser, ulong.Parse(telegramResponce.Message.Chat.Id.ToString()), 2, answer, telegramResponce.Message.Text, IsTutorial, TimeToStartAnswer, thisQuery);
                            }
                            else
                            {
                                mbDBHelper.AddBotQuery(botUser, ulong.Parse(telegramResponce.Message.Chat.Id.ToString()), 2, answer, telegramResponce.Message.Text, IsTutorial, TimeToStartAnswer, thisQuery);
                            }
                        }

                        return(new HttpResponseMessage(HttpStatusCode.OK)
                        {
                            Content = new StringContent("ok"),
                        });
                    }
                    catch (Exception exc)
                    {
                        Logging.Logger.Error(exc);
                        return(new HttpResponseMessage(HttpStatusCode.OK));
                    }
                }
            }

            return(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("ok"),
            });
        }
Ejemplo n.º 15
0
        public async Task <BotUserRequest> Main(object usefulData)
        {
            string query = "";

            if (botUser.InputDataType == InputDataType.Text)
            {
                //добавлена возможность задать вопрос пользователю. isQuestion - кэшированный флаг. Говорит о том, что текущее сообщение это вопрос от пользователя
                #region Question
                query = usefulData.ToString();
                var isQuestion = cacheHelper.Get($"QUESTION{botUser.BotUserVKID}"); //isQuestion - кэшированный флаг. Говорит о том, что текущее сообщение это вопрос от пользователя
                if (isQuestion != null && query != "назад" && query != "вопрос")
                {
                    cacheHelper.Remove($"QUESTION{botUser.BotUserVKID}");
                    // пересылаем оператору, ID которого указано в конфиг файле
                    thisRequest.IsSendingError = await VK.SendMessage(ulong.Parse(ConfigurationManager.AppSettings["OperatorVKID"]), $"Вопрос:\r\n{query}\U00002753\r\n\r\nКто задал -> https://vk.com/id{botUser.BotUserVKID} \U00002709");

                    if (thisRequest.IsSendingError == 0)
                    {// все ок
                        await sendHelper.SendText(textHelper.GetMessage("%questionsuccss%"));

                        return(thisRequest);
                    }
                    else
                    {// произошла ошибка при отправке сообщения оператору
                        await sendHelper.SendText(textHelper.GetMessage("%questionfail%"));

                        return(thisRequest);
                    }
                }
                #endregion
                if (await AnaliseCommands(query) == 1)
                {
                    return(thisRequest);
                }
            }

            var    office       = new DBHelpers.Models.MFCModels.Office();
            var    searchHelper = new SearchHelper(mfcDataOfBot);
            object alreadyFinded;
            switch (botUser.NowIs)
            {
            case MFCBotWhatIsHappeningNow.SettingOffice:
                #region SetOffice
                // включение/отключение расписаний филиалов
                if (ConfigurationManager.AppSettings["Schedules"] == "Enable")
                {
                    mfcDataOfBot.Offices = SetSchedules(mfcDataOfBot.Offices);
                }
                List <FuzzySearchResult> result = null;
                switch (botUser.InputDataType)
                {
                case InputDataType.Image:
                    //хз ваще
                    break;

                case InputDataType.GeoLocation:
                    result             = searchHelper.SearchOfficeByGeocode((DbGeography)usefulData);
                    thisRequest.Answer = GetAnswer(result);
                    break;

                case InputDataType.Text:
                    alreadyFinded = cacheHelper.Get($"SETOFFICES{botUser.BotUserVKID}");
                    if (alreadyFinded == null)
                    {
                        result             = searchHelper.SearchOfficeByName(query);
                        thisRequest.Answer = GetAnswer(result);
                    }
                    else
                    {
                        result             = searchHelper.SearchOfficeByName(query, (string)alreadyFinded);
                        thisRequest.Answer = GetAnswer(result);
                    }
                    break;
                }

                if (result.Count == 1 && ConfigurationManager.AppSettings["IsTestMode"] != "off")
                {
                    result = DoDummy();
                }

                thisRequest.Answer = GetAnswer(result);
                await AnaliseSearchOfficeResult(result);

                #endregion
                break;

            case MFCBotWhatIsHappeningNow.SettingOpportunity:     //новый флаг! нужен для идентификации выбора (проверить статус/записаться на услугу)
                #region SetOpp
                int numFromList;
                if (int.TryParse(query, out numFromList) && (numFromList == 1 || numFromList == 2))
                {
                    if (numFromList == 1)   // выбрана проверка статуса
                    {
                        botUser.NowIs = MFCBotWhatIsHappeningNow.GetingTicketInformation;
                        office        = mfcDataOfBot.Offices.FirstOrDefault(x => x.AisMFCID == botUser.OfficeID);
                        await sendHelper.SendText(textHelper.GetMessage("%gtinfstart%",
                                                                        new string[] { "%officename%", "%adress%", "%business%" },
                                                                        new string[] { office.DisplayName, office.DisplayAddress, GetBusynessOffice(office.AisMFCID) }));
                    }
                    if (numFromList == 2)    // выбрана запись на услугу
                    {
                        botUser.NowIs = MFCBotWhatIsHappeningNow.SettingService;
                        office        = mfcDataOfBot.Offices.FirstOrDefault(x => x.AisMFCID == botUser.OfficeID);
                        await SelectSendSetTenPopularServices(office.DisplayName, office.AisMFCID, office.DisplayAddress);
                    }
                }
                else
                {    // что-то другое
                    await sendHelper.SendText(textHelper.GetMessage("%slctopfail%"));
                }
                #endregion
                break;

            case MFCBotWhatIsHappeningNow.SettingService:
                #region SetService
                alreadyFinded = cacheHelper.Get($"SETSERVICE{botUser.BotUserVKID}");
                if (alreadyFinded == null)
                {
                    alreadyFinded = cacheHelper.Get($"SETSERVICES{botUser.BotUserVKID}");
                    if (alreadyFinded == null)
                    {
                        office = mfcDataOfBot.Offices.FirstOrDefault(x => x.AisMFCID == botUser.OfficeID);
                        await SelectSendSetTenPopularServices(office.DisplayName, office.AisMFCID, office.DisplayAddress);

                        return(thisRequest);
                    }
                    //если есть информация о множестве услуг, значит ведем поиск по ним
                    if (int.TryParse(query, out numFromList))
                    {
                        //теперь поиск ведется по секциям, а не сервисам
                        result             = searchHelper.SearchSectionByName(query, (string)alreadyFinded);
                        thisRequest.Answer = GetAnswer(result);
                        if (result.Count == 0)
                        {
                            await sendHelper.SendText(textHelper.GetMessage("%slctsrvicefail%"));

                            return(thisRequest);
                        }
                    }
                    else
                    {
                        if (alreadyFinded.ToString().Last() == '¡' || alreadyFinded.ToString().Last() == '!')    //в данном случае, это флаг, который говорит, что кэшированные данные относятся к списку 10-ти самых популярных услуг
                        {
                            //теперь поиск ведется по секциям, а не сервисам
                            result             = searchHelper.SearchSectionByName(query);
                            thisRequest.Answer = GetAnswer(result);
                        }
                        else
                        {
                            await sendHelper.SendText(textHelper.GetMessage("%slctsrvicesucs%"));

                            return(thisRequest);
                        }
                    }

                    await AnaliseSearchServiceResult(result);
                }
                else    // если есть информация об услуге, значит ждем подтвержденеия
                {
                    if (!string.IsNullOrWhiteSpace(query) && query == "да")
                    {
                        var service = mfcDataOfBot.Sections.FirstOrDefault(x => x.SectionID == (int)alreadyFinded);
                        office = mfcDataOfBot.Offices.FirstOrDefault(x => x.AisMFCID == botUser.OfficeID);
                        var message = textHelper.GetMessage("%talon%");
                        var talon   = mfcservice.Enqueue(service.SectionID, botUser.OfficeID);

                        if (talon == null || talon?.ID == 0)     //аис не выдал талон => не поставил пользователя в очередь
                        {
                            await sendHelper.SendText(textHelper.GetMessage("%talonerr%"));
                        }
                        else
                        {
                            message = Analiser.AnaliseTalon(talon, message, service.Name, office);

                            botUser.TalonID   = talon.ID;
                            botUser.ServiceID = service.SectionID;
                            botUser.NowIs     = MFCBotWhatIsHappeningNow.QueueWaiting;

                            await sendHelper.SendText(message);
                        }
                        cacheHelper.Clear(botUser.BotUserVKID);
                    }
                    else
                    {
                        office = mfcDataOfBot.Offices.FirstOrDefault(x => x.AisMFCID == botUser.OfficeID);
                        await SelectSendSetTenPopularServices(office.DisplayName, office.AisMFCID, office.DisplayAddress);
                    }
                    cacheHelper.Remove($"SETSERVICE{botUser.BotUserVKID}");
                }
                #endregion
                break;

            case MFCBotWhatIsHappeningNow.GetingTicketInformation:
                #region GetTicketInfo
                office = mfcDataOfBot.Offices.FirstOrDefault(x => x.AisMFCID == botUser.OfficeID);
                if (int.TryParse(query, out numFromList))
                {
                    //проверяем введенный номер
                    await sendHelper.SendText(Analiser.GetAnalysedAnswer(botUser, office, numFromList, textHelper, mfcDataOfBot.WindowsOffices));
                }
                else
                {
                    await sendHelper.SendText(textHelper.GetMessage("%gtinfstart%",      //начальное сообщение
                                                                    new string[] { "%officename%", "%adress%", "%business%" },
                                                                    new string[] { office.DisplayName, office.DisplayAddress, GetBusynessOffice(office.AisMFCID) }));
                }
                #endregion
                break;

            case MFCBotWhatIsHappeningNow.QueueWaiting:
                #region QueueWait
                //var rnd = new Random();
                //var joke = mfcDataOfBot.Jokes[rnd.Next(mfcDataOfBot.Jokes.Count)];
                //await sendHelper.BotSendText(joke.Text);
                //thisRequest.Answer = "joke";
                await sendHelper.SendText(textHelper.GetMessage("%waitinghelp%", "%number%", BotTextHelper.GetEmojiNumber((int)botUser.TalonID)));

                #endregion
                break;
            }
            return(thisRequest);
        }
Ejemplo n.º 16
0
        public async Task <int> AnaliseSearchOfficeResult(List <FuzzySearchResult> result)
        {
            string p = "";

            switch (result.Count)
            {
            case 0:
                if (botUser.IsNewUser)
                {
                    await sendHelper.SendText(textHelper.GetMessage("%setofficehelp%"));
                }
                else
                {
                    await sendHelper.SendText(textHelper.GetMessage("%srchofficefail%"));
                }
                return(1);

            case 1:
                cacheHelper.Remove($"SETOFFICES{botUser.BotUserVKID}");
                // изменям информацию по пользователю
                botUser.OfficeID = result[0].ID;
                var office = mfcDataOfBot.Offices.FirstOrDefault(x => x.AisMFCID == result[0].ID);

                if (office.IsOpen == true || result[0].Name == "Ярмарка")     // если офис открыт или он ярмарка
                {
                    //(если офис не центральный и не индустриальный или он ярмарка) и при этом запись в очередь работает
                    if ((result[0].ID != 21 && result[0].ID != 49 || result[0].Name == "Ярмарка") && context.AISMFCServiceStatus.FirstOrDefault(x => x.ServiceName == "enqueue").Status == "ok")
                    {    //то даем возможность записать
                        botUser.NowIs = MFCBotWhatIsHappeningNow.SettingOpportunity;
                        await sendHelper.SendText(textHelper.GetMessage("%slctopstart%",
                                                                        new string[] { "%officename%", "%adress%", "%business%" },
                                                                        new string[] { office.DisplayName, office.DisplayAddress, GetBusynessOffice(office.AisMFCID) }));
                    }
                    else
                    {    //иначе отправляем проверять статус
                        //если сервисы проверки статуса талона работают
                        if (context.AISMFCServiceStatus.FirstOrDefault(x => x.ServiceName == "getTicketInformation").Status == "ok" && context.AISMFCServiceStatus.FirstOrDefault(x => x.ServiceName == "getQueueInformation").Status == "ok")
                        {
                            botUser.NowIs = MFCBotWhatIsHappeningNow.GetingTicketInformation;
                            await sendHelper.SendText(textHelper.GetMessage("%gtinfstart%",
                                                                            new string[] { "%officename%", "%adress%", "%business%" },
                                                                            new string[] { office.DisplayName, office.DisplayAddress, GetBusynessOffice(office.AisMFCID) }));
                        }
                        else
                        {
                            botUser.NowIs = MFCBotWhatIsHappeningNow.SettingOffice;
                            await sendHelper.SendText(textHelper.GetMessage("%getQueueError%"));    //Произошла серьезная неполадка \U0001F631 \r\n\U00002705 Пожалуйста повторите запрос позже
                        }
                    }
                }
                else
                {    //если офис зарыт
                    await sendHelper.SendText(textHelper.GetMessage("%officeclosed%",
                                                                    new string[] { "%officename%", "%adress%" },
                                                                    new string[] { office.DisplayName, office.DisplayAddress }));
                }
                return(1);

            default:
                for (int i = 0; i < result.Count; i++)
                {
                    office = mfcDataOfBot.Offices.FirstOrDefault(x => x.AisMFCID == result[i].ID);
                    //офис закрыт или открыт
                    if (office.IsOpen == true)
                    {
                        p += BotTextHelper.GetVKSmileNumber(i + 1) + office.DisplayName + $" \U00002600 Открыт\\r\\n\U0001F449 {office.DisplayAddress}" + "\\r\\n" + GetBusynessOffice(office.AisMFCID) + "\\r\\n\\r\\n";
                    }
                    else
                    {
                        p += BotTextHelper.GetVKSmileNumber(i + 1) + office.DisplayName + $" \U0001F4A4 Закрыт\\r\\n\U0001F449 {office.DisplayAddress}" + "\\r\\n\\r\\n";
                    }
                }
                await sendHelper.SendText(textHelper.GetMessage("%srchofficemanyres%", "%offices%", p));

                string Offices = "";
                foreach (var item in result)
                {
                    Offices += item.ID + ";";
                }
                cacheHelper.Set($"SETOFFICES{botUser.BotUserVKID}", Offices, 35);
                return(1);
            }
        }
Ejemplo n.º 17
0
        public async Task <int> AnalyseSearchOrganizationForWayResult()
        {
            var cacher = new CacheHelper();

            switch (answer.Result.QueryResults.Count)
            {
            case 0:
                await sender.SendText(texter.GetMessage("%wayserchfail%", "%query%", answer.Result.QueryText));

                return(1);

            case 1:
                if (dataOfBot.Organizations.FirstOrDefault(x => x.OrganizationID == answer.Result.QueryResults[0].ID).OrganizationMapObject.Where(z => z.MapObject.Params == null).Count() > 1)
                {
                    await sender.SendText(texter.GetMessage("%getwayerror%"));

                    return(1);
                }

                object previousObjAnswer = cacher.Get($"FINDEDFIRSTORG{botUser.BotUserID}");
                if (previousObjAnswer == null)
                {
                    cacher.Clear(botUser.BotUserID);
                    botUser.NowIs = MallBotWhatIsHappeningNow.SearchingOrganization;
                    await sender.SendText(texter.GetMessage("%ready%", "%mall%", dataOfBot.Customers[0].Name, dataOfBot.Customers[0].LocaleCity) + "\\r\\n\\r\\n" + texter.GetMessage("%orgsrchstartback%"));

                    return(1);
                }

                var previousAnswer = (FindedInformation)previousObjAnswer;
                if (previousAnswer.Result.QueryResults[0].ID == answer.Result.QueryResults[0].ID)
                {
                    await sender.SendText(texter.GetMessage("%srchwaysameorgs%", "%org%", answer.Result.QueryResults[0].Name));

                    return(1);
                }

                var mapHelper = new BotMapHelper();
                var way       = mapHelper.GetClosestWay(answer.Result.QueryResults[0], previousAnswer.Result.QueryResults, dataOfBot);
                if (way.Way == null)
                {
                    cacher.Clear(botUser.BotUserID);
                    botUser.NowIs = MallBotWhatIsHappeningNow.SearchingOrganization;
                    await sender.SendText(texter.GetMessage("%getwayfail%") + "\\r\\n\\r\\n" + texter.GetMessage("%ready%", "%mall%", dataOfBot.Customers[0].Name, dataOfBot.Customers[0].LocaleCity)
                                          + "\\r\\n\\r\\n" + texter.GetMessage("%orgsrchstartback%"));

                    return(1);
                }
                await SendWayWithPhoto(way.From, way.To, way.Way);

                return(1);

            default:
                if (answer.Result.QueryResults.Count != answer.Result.QueryResults.DistinctBy(x => x.Name).Count())
                {
                    await sender.SendText(texter.GetMessage("%getwayerror%"));

                    return(1);
                }

                string p = "";
                for (int i = 0; i < answer.Result.QueryResults.Count; i++)
                {
                    p += $"{BotTextHelper.GetEmojiNumber(i + 1)} {answer.Result.QueryResults[i].Name} \\r\\n";
                }
                await sender.SendText(texter.GetMessage("%getwaymanyres%", "%shops%", p));

                string orgIDs = "";
                foreach (var item in answer.Result.QueryResults)
                {
                    orgIDs += item.ID + ";";
                }
                cacher.Set($"SEARCHWAY{botUser.BotUserID}", orgIDs, 35);
                return(1);
            }
        }
Ejemplo n.º 18
0
        public async Task <int> AnaliseSearchServiceResult(List <FuzzySearchResult> result)
        {
            string message = "";

            switch (result.Count)
            {
            case 0:
                await sendHelper.SendText(textHelper.GetMessage("%srchservicefail%"));

                return(1);

            case 1:
                cacheHelper.Remove($"SETSERVICES{botUser.BotUserVKID}");

                message = textHelper.GetMessage("%srchserviceoneres%", "%findedservicename%", result[0].Name);

                var res = mfcservice.GetQueue(result[0].ID, botUser.OfficeID);
                if (res == null)
                {
                    await sendHelper.SendText(textHelper.GetMessage("%getQueueError%"));
                }
                else
                {
                    cacheHelper.Set($"SETSERVICE{botUser.BotUserVKID}", result[0].ID, 35);

                    message = message.Replace("%queuecount%", res.Waiting.ToString());
                    message = message.Replace("%windowcount%", res.Working.ToString());
                    await sendHelper.SendText(message);
                }
                return(1);

            default:
                message = textHelper.GetMessage("%srchservicemanyres%");
                var partsOfmessage = message.Split(';');
                var p = partsOfmessage.First();

                for (int i = 0; i < result.Count; i++)
                {
                    p += BotTextHelper.GetVKSmileNumber(i + 1) + result[i].Name + "\\r\\n\\r\\n";

                    if (i >= 10 && i % 10 == 0 || i == result.Count - 1)
                    {
                        if (i != result.Count - 1)
                        {
                            await sendHelper.SendText(p);

                            p = "";
                        }
                        else
                        {
                            await sendHelper.SendText(p + partsOfmessage.Last());
                        }
                    }
                }

                if (requests.Count > 20)
                {
                    requests.Clear();
                    await sendHelper.SendText(textHelper.GetMessage("%toomuch%"));

                    return(1);
                }

                string Services = "";
                foreach (var item in result)
                {
                    Services += item.ID + ";";
                }
                cacheHelper.Set($"SETSERVICES{botUser.BotUserVKID}", Services, 35);
                return(1);
            }
        }
Ejemplo n.º 19
0
 public SpecialCommandsHelper(BotUser _botUser, BotTextHelper _textHelper)
 {
     botUser    = _botUser;
     textHelper = _textHelper;
 }
Ejemplo n.º 20
0
        /// <summary>
        /// Рисует путь way от orgFrom до orgTo
        /// </summary>
        /// <param name="orgFrom"></param>
        /// <param name="orgTo"></param>
        /// <param name="way"></param>
        /// <returns></returns>
        public FindedInformation DrawWay(MapObject orgFrom, MapObject orgTo, List <MapHelper.Vertex> way)
        {
            int  i        = 0;
            bool Continue = true;

            while (Continue)
            {
                var Floor  = dataOfBot.Floors.FirstOrDefault(x => x.Number == way[i].Layer.LayerID);
                var bitmap = new BitmapSettings(new Bitmap(Image.FromFile(ConfigurationManager.AppSettings["ContentPath"] + $"Floors\\{dataOfBot.Floors.FirstOrDefault(x => x.FloorID == Floor.FloorID).FloorID}.{dataOfBot.Floors.FirstOrDefault(x => x.FloorID == Floor.FloorID).FileExtension}")));
                var points = new List <Point>();

                bitmap.DrawSignPoint(dataOfBot, Floor.FloorID, dataOfBot.Customers[0].Name);
                if (i == 0)
                {
                    bitmap.DrawLocation(way[i].Point.X, way[i].Point.Y, "A");
                }

                bool flag = true;
                while (flag && i < way.Count)
                {
                    if (Floor.Number == way[i].Layer.LayerID)
                    {
                        points.Add(new Point((int)(way[i].Point.X / bitmap.ZoomOfPicture) + bitmap.I, (int)(way[i].Point.Y / bitmap.ZoomOfPicture + bitmap.J)));
                        i++;
                    }
                    else
                    {
                        flag = false;

                        if (points.Count > 1)
                        {
                            bitmap.DrawCurve(points);
                            bitmap.DrawLandMarksExtra(dataOfBot, Floor.FloorID);
                            bitmap.DrawLandMarksOrganizations(dataOfBot, Floor.FloorID);

                            var mapHelper = new BotMapHelper();

                            answer.TextDescription.AddRange(mapHelper.FindOrientirs(points, Floor.FloorID, dataOfBot, bitmap, orgFrom, orgTo));
                            var lstMapObj = answer.TextDescription.Where(x => x.FloorID == Floor.FloorID).ToList();
                            bitmap.DrawSpecialOrgs(lstMapObj, dataOfBot.GetOrganizations(lstMapObj));

                            var text = title.Replace("%floornumber%", Floor.Number.ToString());
                            bitmap.DrawText(text, BotTextHelper.LengthOfString(text, bitmap), 5F, 23, Color.DarkSlateGray, true);

                            answer.FloorsPictures.Add(bitmap);
                        }
                    }
                }
                if (i == way.Count)
                {
                    Continue = false;

                    if (points.Count > 1)
                    {
                        bitmap.DrawCurve(points);
                        bitmap.DrawLandMarksExtra(dataOfBot, Floor.FloorID);
                        bitmap.DrawLandMarksOrganizations(dataOfBot, Floor.FloorID);
                        bitmap.DrawLocation(way[i - 1].Point.X, way[i - 1].Point.Y, "B");

                        var mapHelper = new BotMapHelper();

                        answer.TextDescription.AddRange(mapHelper.FindOrientirs(points, Floor.FloorID, dataOfBot, bitmap, orgFrom, orgTo));
                        var lstMapObj = answer.TextDescription.Where(x => x.FloorID == Floor.FloorID).ToList();
                        bitmap.DrawSpecialOrgs(lstMapObj, dataOfBot.GetOrganizations(lstMapObj));

                        var text = title.Replace("%floornumber%", Floor.Number.ToString());
                        bitmap.DrawText(text, BotTextHelper.LengthOfString(text, bitmap), 5F, 23, Color.DarkSlateGray, true);

                        answer.FloorsPictures.Add(bitmap);
                    }
                }
            }
            return(answer);
        }
Ejemplo n.º 21
0
        public async Task <int> Wall_Post(string groupID, string message, byte[] image = null)
        {
            try
            {
                var handler = new HttpClientHandler();
                handler.CookieContainer = new CookieContainer();

                using (var client = new HttpClient(handler))
                {
                    message = BotTextHelper.SmileCodesReplace(message, SocialNetworkType.VK);
                    message = message.Replace("\\n", "\n");
                    message = HttpUtility.UrlEncode(message);
                    string responceString;

                    if (image != null)
                    {
                        var url = $"https://api.vk.com/method/photos.getWallUploadServer?access_token={_apptoken}&group_id={groupID}";
                        using (var responce = await client.GetAsync(url))
                        {
                            responceString = responce.Content.ReadAsStringAsync().Result;
                            if (responceString.Contains("error") || !responce.IsSuccessStatusCode)
                            {
                                Logging.Logger.Error($"VK Api Wall Post GetUrl: NOT OK {responceString}");
                                return(1);
                            }
                        }

                        JObject json           = JObject.Parse(responceString);
                        var     uploadImageUrl = json["response"]["upload_url"].ToString();

                        //Загружаем изображение
                        MultipartFormDataContent form = new MultipartFormDataContent();
                        form.Add(new ByteArrayContent(image), "photo", "photo.jpg");
                        using (var responce = await client.PostAsync(uploadImageUrl, form))
                        {
                            responceString = responce.Content.ReadAsStringAsync().Result;
                            if (responceString.Contains("error") || !responce.IsSuccessStatusCode)
                            {
                                Logging.Logger.Error($"VK Api Wall Post LoadPhotoToVkServ: NOT OK {responceString}");
                                return(1);
                            }
                        }
                        json = JObject.Parse(responceString);

                        var photo  = json["photo"];
                        var server = json["server"];
                        var hash   = json["hash"];

                        url = $"https://api.vk.com/method/photos.saveWallPhoto?access_token={_apptoken}&group_id={groupID}&server={server}&photo={photo}&hash={hash}";
                        using (var responce = await client.GetAsync(url))
                        {
                            responceString = responce.Content.ReadAsStringAsync().Result;

                            if (responceString.Contains("error") || !responce.IsSuccessStatusCode)
                            {
                                Logging.Logger.Error($"VK Api SavePhotoToVkServ: NOT OK {responceString}");
                                return(1);
                            }
                        }
                        json = JObject.Parse(responceString);
                        var attachment = json["response"][0]["id"].ToString();//photo{owner_id}_{pid}


                        url = $"https://api.vk.com/method/wall.post?owner_id=-{groupID}&message={message}&attachments={attachment}&access_token={_apptoken}";

                        using (var res = await client.GetAsync(url))
                        {
                            responceString = res.Content.ReadAsStringAsync().Result;

                            if (responceString.Contains("error") || !res.IsSuccessStatusCode)
                            {
                                Logging.Logger.Error($"Vk Api SendMessageWithPhoto: NOT OK {responceString}");
                                return(1);
                            }
                        }
                        return(0);
                    }
                    else
                    {
                        var url = $"https://api.vk.com/method/wall.post?owner_id=-{groupID}&message={message}&access_token={_apptoken}";
                        using (var res = await client.GetAsync(url))
                        {
                            responceString = res.Content.ReadAsStringAsync().Result;
                            if (responceString.Contains("error") || !res.IsSuccessStatusCode)
                            {
                                Logging.Logger.Error($"Vk Api SendMessageWithPhoto: NOT OK {responceString}");
                                return(1);
                            }
                        }
                        return(0);
                    }
                }
            }

            catch (Exception exc)
            {
                Logging.Logger.Error(exc);
                return(1);
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Не больше 25 сообщений за раз.
        /// </summary>
        /// <param name="Requests"></param>
        /// <returns></returns>
        public async Task <int> SendAllRequests(List <VKApiRequestModel> Requests)
        {
            var handler = new HttpClientHandler();

            handler.CookieContainer = new CookieContainer();
            var httpClient = new HttpClient(handler);

            string uploadImageUrl        = "";
            var    IsError               = 0;
            string url                   = "";
            HttpResponseMessage responce = null;
            var     responceString       = "";
            JObject json                 = null;

            if (Requests.Where(x => x.Type == RequestType.SendMessageWithPhoto).Count() > 0)
            {
                // получаем url для загрузки изображений на сервак
                url      = $"https://api.vk.com/method/photos.getMessagesUploadServer?access_token={_token}&v=5.57";
                responce = await httpClient.GetAsync(url);

                responceString = responce.Content.ReadAsStringAsync().Result;

                if (responceString.Contains("error"))
                {
                    IsError = 1;
                    Logging.Logger.Error($"VK Api Get Url: NOT OK {responceString}");
                }

                json           = JObject.Parse(responceString);
                uploadImageUrl = json["response"]["upload_url"].ToString();
            }
            string ids      = "";
            string messages = "";
            string types    = "";
            string photos   = "";
            string hashs    = "";
            string servers  = "";

            foreach (var item in Requests)
            {
                ids      += item.User_ID.ToString() + ", ";
                messages += "\"" + item.Message.Replace("\"", "\\\"") + "\", ";
                types    += ((int)item.Type).ToString() + ", ";

                if (item.Type == RequestType.SendMessageWithPhoto)
                {
                    //Загружаем изображение
                    MultipartFormDataContent form = new MultipartFormDataContent();
                    form.Add(new ByteArrayContent(item.Photo), "photo", "photo.jpg");
                    responce = await httpClient.PostAsync(uploadImageUrl, form);

                    responceString = responce.Content.ReadAsStringAsync().Result;

                    if (responceString.Contains("error"))
                    {
                        IsError = 1;
                        Logging.Logger.Error($"VK Api Load: NOT OK {responceString}");
                    }

                    json = JObject.Parse(responceString);
                    var photo  = json["photo"];
                    var server = json["server"];
                    var hash   = json["hash"];

                    if (photo.ToString() == "[]")
                    {
                        await SendMessage(item.User_ID, "Опаньки! Мы попали на неудачный сервер. Мы уже на пути к тому, чтобы устранить эту проблему, но пока я не смогу ответить на ваши вопросы 3(");

                        IsError = 1;
                        return(IsError);
                    }

                    photos  += "\"" + photo.ToString().Replace("\"", "\\\"") + "\", ";
                    servers += "\"" + server.ToString() + "\", ";
                    hashs   += "\"" + hash.ToString() + "\", ";
                }
                else
                {
                    photos  += "\"empty\", ";
                    servers += "\"empty\", ";
                    hashs   += "\"empty\", ";
                }
            }
            // передает в скрип "code" параметры
            var code = Properties.Resources.SendMessageWithPhotoSkript;

            code = code.Replace("Pids", ids.Remove(ids.Length - 2));
            code = code.Replace("Pmessages", messages.Remove(messages.Length - 2));
            code = code.Replace("Phashs", hashs.Remove(hashs.Length - 2));
            code = code.Replace("Pphotos", photos.Remove(photos.Length - 2));
            code = code.Replace("Pservers", servers.Remove(servers.Length - 2));
            code = code.Replace("Ptypes", types.Remove(types.Length - 2));
            code = code.Replace("Pcount", Requests.Count.ToString());
            code = BotTextHelper.SmileCodesReplace(code, SocialNetworkType.VK);
            code = HttpUtility.UrlEncode(code);
            //генерим контент для пост запроса
            string        data      = "code=" + code + "&access_token=" + _token + "&v=5.53";
            StringContent parametrs = new StringContent(data, Encoding.UTF8, "application/x-www-form-urlencoded");

            //вызываем метод, параметром которого является скрипт, который выполнится на строне vk.com без лимитов (почти)
            url = $"https://api.vk.com/method/execute";

            using (var client = new HttpClient())
            {
                using (var r = await client.PostAsync(new Uri(url), parametrs))
                {
                    responce       = r;
                    responceString = await r.Content.ReadAsStringAsync();


                    if (responceString.Contains("error"))
                    {
                        IsError = 1;
                        Logging.Logger.Error($"VK Api Execute: NOT OK {responceString}, data {data}");
                    }
                }
            }
            return(IsError);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Рисует все найденные организации на карте этажа
        /// Возвращает структуру с добавленными в нее картинками
        /// </summary>
        /// <returns></returns>
        public FindedInformation DrawFindedShops()
        {
            var groupedOrgs = (List <GroupedOrganization>)answer.GroopedResult; // получает группы огранизаций

            groupedOrgs.OrderByDescending(x => x.AverageRating).ToList();

            foreach (Floor f in dataOfBot.Floors)
            {
                var groupsFromFloor = groupedOrgs.Where(x => x.FloorID == f.FloorID).ToList();
                if (groupsFromFloor.Count != 0)
                {
                    //var bitmap = new BitmapSettings(new Bitmap(Image.FromStream(new MemoryStream(f.File))), f.FloorID);
                    var bitmap = new BitmapSettings(new Bitmap(Image.FromFile(ConfigurationManager.AppSettings["ContentPath"] + $"Floors\\{f.FloorID}.{f.FileExtension}")), f.FloorID);



                    foreach (var group in groupsFromFloor)
                    {
                        foreach (var org in group.Orgs)
                        {
                            Image img;
                            var   mObjofThisOrg = group.MapObjects.Where(x => org.OrganizationMapObject.Select(y => y.MapObjectID).Contains(x.MapObjectID));
                            if (group.MapObjects.Count == 1)
                            {
                                img = Properties.Resources.Shop;
                            }
                            else
                            {
                                img = Properties.Resources.ShopG; // для групп рисуем оранжевую точку
                            }
                            foreach (var mObj in mObjofThisOrg)
                            {
                                var temp = org.CategoryOrganization.Select(x => x.Category).Select(x => x.ServiceCategoryType);
                                if (temp.Contains(ServiceCategoryType.Service) || temp.Contains(ServiceCategoryType.Link))
                                {
                                    img = ImagingHelper.ResizeImage(img, 110, 110);
                                    bitmap.DrawLocation(mObj.LongitudeFixed, mObj.LatitudeFixed, "default", img);
                                    bitmap.DrawLandMarksExtra(dataOfBot, f.Number);
                                }
                                else
                                {
                                    img = ImagingHelper.ResizeImage(img, (int)(img.Width * 4 / 2.5F), (int)(img.Height * 4 / 2.5F));
                                    bitmap.DrawLocation(mObj.LongitudeFixed, mObj.LatitudeFixed, "default", img);
                                }
                            }
                        }
                    }

                    bitmap.DrawLandMarksExtra(dataOfBot, f.FloorID);
                    bitmap.DrawLandMarksOrganizations(dataOfBot, f.FloorID);
                    bitmap.DrawSignPoint(dataOfBot, f.FloorID, dataOfBot.Customers[0].Name);

                    // расставляем балуны для каждой группы
                    char index = 'A';
                    for (int i = 0; i < 5 && i < groupsFromFloor.Count; i++)
                    {
                        var   obj = Properties.Resources.ResourceManager.GetObject(index.ToString());
                        Image img = (Bitmap)obj;
                        bitmap.DrawLocation(BotMapHelper.CenterOfDiagonal(groupsFromFloor[i].MapObjects), "MultyDraw", img);
                        index++;
                    }
                    // подпись картинки
                    var tmp = title.Replace("%floornumber%", f.Number.ToString());
                    bitmap.DrawText(tmp, BotTextHelper.LengthOfString(tmp, bitmap), 5F, 23, Color.DarkSlateGray, true);
                    answer.FloorsPictures.Add(bitmap);
                }
            }
            return(answer);
        }