Exemplo n.º 1
0
        private void HandleCallbackQuery(Update update)
        {
            var parts = update.CallbackQuery.Data.Split(':');

            var isAdmin = StoreAdminRepo.GetAdmin(update.CallbackQuery.Message.Chat.Id) != null;

            if (parts.Length == 2 && parts[0] == "reset" && int.TryParse(parts[1], out var productId))
            {
                using (var db = Db)
                {
                    var product = db.StoreProductRecords.SingleOrDefault(x => x.Id == productId);

                    var rows = new List <List <InlineKeyboardButton> >
                    {
                        new List <InlineKeyboardButton>
                        {
                            InlineKeyboardButton.WithCallbackData($"تصاویر ({product.ImageFileRecords.Count})", "images:" + product.Id)
                        }
                    };

                    if (isAdmin)
                    {
                        rows.Add(GetAdminRow(product));
                    }

                    TelegramClient.EditMessageReplyMarkupAsync(update.CallbackQuery.Message.Chat.Id, update.CallbackQuery.Message.MessageId, new InlineKeyboardMarkup(rows));
                }
            }
            else if (parts.Length == 2 && parts[0] == "edit" && int.TryParse(parts[1], out productId))
            {
                if (!isAdmin)
                {
                    TelegramClient.AnswerCallbackQueryAsync(update.CallbackQuery.Id, "متاسفانه مجوز اجرای این دستور را ندارید.");
                    return;
                }

                using (var db = Db)
                {
                    var product = db.StoreProductRecords.Include(x => x.ImageFileRecords).AsNoTracking().SingleOrDefault(x => x.Id == productId);
                    var chatId  = update.CallbackQuery.Message.Chat.Id;

                    if (!NewProductStates.TryGetValue(chatId, out _))
                    {
                        NewProductStates.Add(chatId, null);
                    }

                    NewProductStates[chatId]               = new NewProductInState();
                    NewProductStates[chatId].IsEdit        = true;
                    NewProductStates[chatId].ProductRecord = product;

                    HandleNewProductMessage(update, new SubscriberRecord {
                        ChatId = chatId
                    });
                }
            }
            else if (parts.Length == 2 && parts[0] == "delete_approve" && int.TryParse(parts[1], out productId))
            {
                if (!isAdmin)
                {
                    TelegramClient.AnswerCallbackQueryAsync(update.CallbackQuery.Id, "متاسفانه مجوز اجرای این دستور را ندارید.");
                    return;
                }

                var optionButtons = new[]
                {
                    InlineKeyboardButton.WithCallbackData("بیخیال", "reset:" + productId),
                    InlineKeyboardButton.WithCallbackData("نه، اصلا", "reset:" + productId),
                    InlineKeyboardButton.WithCallbackData("مطمئنم، حذفش کن", "delete:" + productId)
                };
                var rows = optionButtons.OrderBy(x => Guid.NewGuid()).Select(x => new List <InlineKeyboardButton> {
                    x
                });

                TelegramClient.EditMessageReplyMarkupAsync(update.CallbackQuery.Message.Chat.Id, update.CallbackQuery.Message.MessageId, new InlineKeyboardMarkup(rows));
            }
            else if (parts.Length == 2 && parts[0] == "delete" && int.TryParse(parts[1], out productId))
            {
                using (var db = Db)
                {
                    var product = db.StoreProductRecords.SingleOrDefault(x => x.Id == productId);

                    if (product != null)
                    {
                        db.StoreProductRecords.Remove(product);
                        db.SaveChanges();
                    }

                    TelegramClient.AnswerCallbackQueryAsync(update.CallbackQuery.Id, "محصول با موفقیت حذف شد.");
                    TelegramClient.DeleteMessageAsync(update.CallbackQuery.Message.Chat.Id, update.CallbackQuery.Message.MessageId);
                }
            }
            else if (parts.Length == 2 && parts[0] == "images" && int.TryParse(parts[1], out productId))
            {
                using (var db = Db)
                {
                    var product           = db.StoreProductRecords.Single(x => x.Id == productId);
                    var total             = product.ImageFileRecords.Count;
                    var secondImageFileId = product.ImageFileRecords.Skip(total > 1 ? 1 : 0).First().ImageFileId;
                    var currentIndex      = product.ImageFileRecords.Select(x => x.ImageFileId).ToList().IndexOf(secondImageFileId) + 1;

                    var rows = new List <InlineKeyboardButton>
                    {
                        InlineKeyboardButton.WithCallbackData("<<", $"images_prev:{currentIndex},{productId}"),
                        InlineKeyboardButton.WithCallbackData($"تصویر {currentIndex} از {total}"),
                        InlineKeyboardButton.WithCallbackData(">>", $"images_next:{currentIndex},{productId}")
                    };

                    TelegramClient.SendPhotoAsync(update.CallbackQuery.Message.Chat.Id, secondImageFileId, replyMarkup: new InlineKeyboardMarkup(rows));
                }
            }
            else if (parts.Length == 2 && parts[0] == "images_next")
            {
                using (var db = Db)
                {
                    var currentIndex = int.Parse(parts[1].Split(',')[0]);
                    productId = int.Parse(parts[1].Split(',')[1]);

                    var product = db.StoreProductRecords.Single(x => x.Id == productId);
                    var total   = product.ImageFileRecords.Count;

                    if (currentIndex < total)
                    {
                        currentIndex++;
                    }

                    var rows = new List <InlineKeyboardButton>
                    {
                        InlineKeyboardButton.WithCallbackData("<<", $"images_prev:{currentIndex}," + productId),
                        InlineKeyboardButton.WithCallbackData($"تصویر {currentIndex} از {total}", "images_nav_hide:" + productId),
                        InlineKeyboardButton.WithCallbackData(">>", $"images_next:{currentIndex}," + productId)
                    };

                    var imageFileId = product.ImageFileRecords.Skip(total > 1 ? currentIndex - 1 : 0).First().ImageFileId;
                    TelegramClient.EditMessageMediaAsync(
                        update.CallbackQuery.Message.Chat.Id,
                        update.CallbackQuery.Message.MessageId,
                        new InputMediaPhoto(imageFileId),
                        new InlineKeyboardMarkup(rows)
                        );
                }
            }
            else if (parts.Length == 2 && parts[0] == "images_prev")
            {
                using (var db = Db)
                {
                    var currentIndex = int.Parse(parts[1].Split(',')[0]);
                    productId = int.Parse(parts[1].Split(',')[1]);

                    var product = db.StoreProductRecords.Single(x => x.Id == productId);
                    var total   = product.ImageFileRecords.Count;

                    if (currentIndex > 1)
                    {
                        currentIndex--;
                    }

                    var rows = new List <InlineKeyboardButton>
                    {
                        InlineKeyboardButton.WithCallbackData("<<", $"images_prev:{currentIndex}," + productId),
                        InlineKeyboardButton.WithCallbackData($"تصویر {currentIndex} از {total}", "images_nav_hide:" + productId),
                        InlineKeyboardButton.WithCallbackData(">>", $"images_next:{currentIndex}," + productId)
                    };

                    var imageFileId = product.ImageFileRecords.Skip(total > 1 ? currentIndex - 1 : 0).First().ImageFileId;
                    TelegramClient.EditMessageMediaAsync(
                        update.CallbackQuery.Message.Chat.Id,
                        update.CallbackQuery.Message.MessageId,
                        new InputMediaPhoto(imageFileId),
                        new InlineKeyboardMarkup(rows)
                        );
                }
            }
            else if (parts.Length == 2 && parts[0] == "delete_image")
            {
                var imageRecord = NewProductStates[update.CallbackQuery.Message.Chat.Id].ProductRecord.ImageFileRecords.SingleOrDefault(x => x.Id == int.Parse(parts[1]));

                if (imageRecord != null)
                {
                    NewProductStates[update.CallbackQuery.Message.Chat.Id].ProductRecord.ImageFileRecords.Remove(imageRecord);
                    TelegramClient.DeleteMessageAsync(update.CallbackQuery.Message.Chat.Id, update.CallbackQuery.Message.MessageId);
                    TelegramClient.AnswerCallbackQueryAsync(update.CallbackQuery.Id, "عکس مورد نظر از محصول حذف شد.");
                    return;
                }
            }

            TelegramClient.AnswerCallbackQueryAsync(update.CallbackQuery.Id);
        }
Exemplo n.º 2
0
        public void Update(Update update, SubscriberRecord subscriberRecord)
        {
            if (update.Type == UpdateType.CallbackQuery)
            {
                HandleCallbackQuery(update);
                return;
            }

            if (update.Type != UpdateType.Message)
            {
                return;
            }

            var isAdmin = StoreAdminRepo.GetAdmin(subscriberRecord.ChatId) != null;

            switch (update.Message.Text)
            {
            case StateManager.Keyboards.StartCommand:
                TelegramClient.SendTextMessageAsync(subscriberRecord.ChatId, SettingRepo.Load <Setting>().WelcomeMessage, parseMode: ParseMode.Markdown, replyMarkup: isAdmin ? StateManager.Keyboards.StartAdmin : StateManager.Keyboards.StartUser);
                break;

            case StateManager.Keyboards.NewProductCommand:
                if (!isAdmin)
                {
                    TelegramClient.SendTextMessageAsync(update.Message.Chat.Id, "متاسفانه مجوز اجرای این دستور را ندارید.");
                    return;
                }

                if (!NewProductStates.TryGetValue(subscriberRecord.ChatId, out _))
                {
                    NewProductStates.Add(subscriberRecord.ChatId, null);
                }

                NewProductStates[subscriberRecord.ChatId] = new NewProductInState();
                NewProductStates[subscriberRecord.ChatId].ProductRecord.BotInstanceRecordId = BotInstanceId;

                HandleNewProductMessage(update, subscriberRecord);
                break;

            case StateManager.Keyboards.ListProductsCommand:
                using (var db = Db)
                {
                    var products = db.StoreProductRecords.Include(x => x.ImageFileRecords).AsNoTracking().Where(x => x.BotInstanceRecordId == BotInstanceId);

                    if (!products.Any())
                    {
                        TelegramClient.SendTextMessageAsync(subscriberRecord.ChatId, "محصولی برای نمایش وجود ندارد.");
                        return;
                    }

                    var i = 0;
                    var productDetailTemplate = SettingRepo.Load <Setting>().ProductDetailTemplate;

                    foreach (var product in products)
                    {
                        var detail = productDetailTemplate
                                     .Replace("[Index]", (++i).ToString())
                                     .Replace("[Name]", product.Name)
                                     .Replace("[Code]", product.Code)
                                     .Replace("[Price]", product.Price.ToCurrency())
                                     .Replace("[Description]", product.Description);

                        var buttons = new List <List <InlineKeyboardButton> >
                        {
                            new List <InlineKeyboardButton>
                            {
                                InlineKeyboardButton.WithCallbackData($"تصاویر ({product.ImageFileRecords.Count})", "images:" + product.Id)
                            }
                        };

                        if (isAdmin)
                        {
                            buttons.Add(GetAdminRow(product));
                        }

                        Task.Delay(i * 500)
                        .ContinueWith(task =>
                        {
                            TelegramClient.SendPhotoAsync(
                                subscriberRecord.ChatId,
                                product.ImageFileRecords.First().ImageFileId,
                                detail,
                                parseMode: ParseMode.Markdown,
                                replyMarkup: new InlineKeyboardMarkup(buttons));
                        })
                        .ContinueWith(task =>
                        {
                            Logger.LogError("Delayed Message Exception: {Message}", task.Exception?.GetBaseException().Message);
                        }, TaskContinuationOptions.OnlyOnFaulted);
                    }
                }
                break;

            case StateManager.Keyboards.CancelCommand:
                if (NewProductStates.TryGetValue(subscriberRecord.ChatId, out _))
                {
                    NewProductStates.Remove(subscriberRecord.ChatId);
                }

                TelegramClient.SendTextMessageAsync(subscriberRecord.ChatId, "عملیات فعلی لغو شد", replyMarkup: StateManager.Keyboards.StartAdmin);
                break;

            default:
                if (NewProductStates.TryGetValue(subscriberRecord.ChatId, out _))
                {
                    if (!isAdmin)
                    {
                        TelegramClient.SendTextMessageAsync(update.Message.Chat.Id, "متاسفانه مجوز اجرای این دستور را ندارید.");
                        return;
                    }

                    HandleNewProductMessage(update, subscriberRecord);
                }
                else
                {
                    TelegramClient.SendTextMessageAsync(subscriberRecord.ChatId, "متوجه پیام نشدم..");
                }
                break;
            }
        }