コード例 #1
0
ファイル: ImportCSVBot.cs プロジェクト: LuxuryDev/LuxuryBot
        private int InsertToAttachmentFs(byte[] stream)
        {
            try
            {
                if (stream != null)
                {
                    AttachmentFs attachmentFs = new AttachmentFs
                    {
                        Fs   = stream,
                        GuId = Guid.NewGuid()
                    };

                    using (MarketBotDbContext db = new MarketBotDbContext())
                    {
                        db.AttachmentFs.Add(attachmentFs);
                        db.SaveChanges();
                        return(attachmentFs.Id);
                    }
                }

                else
                {
                    return(-1);
                }
            }

            catch (Exception exp)
            {
                return(-1);
            }
        }
コード例 #2
0
        private async Task <int> CreateProduct(Product SaveProduct, IFormFile image = null, int balance = 0)
        {
            AttachmentFs attachmentFs = null;

            SaveProduct = ProductFunc.InsertProduct(SaveProduct.Name,
                                                    Convert.ToInt32(SaveProduct.CategoryId),
                                                    Convert.ToInt32(SaveProduct.UnitId),
                                                    SaveProduct.CurrentPrice.Value,
                                                    Convert.ToInt32(SaveProduct.CurrentPrice.CurrencyId),
                                                    SaveProduct.Enable,
                                                    SaveProduct.Text,
                                                    SaveProduct.TelegraphUrl);

            ///добавляем остатки
            if (SaveProduct.Stock != null && balance > 0)
            {
                ProductFunc.InsertStock(SaveProduct.Id, balance, balance, "добавление нового товара");
            }


            if (image != null && SaveProduct != null) // загружаем фотографию в базу данных
            {
                attachmentFs = ProductFunc.InsertMainPhoto(SaveProduct.Id, image.OpenReadStream(), image.FileName);
            }

            if (attachmentFs != null) // обновляем id фотографии  у продукта
            {
                ProductFunc.UpdateMainPhoto(SaveProduct.Id, attachmentFs.Id);

                //отправляем эту фотографию в телеграм и вытаскивваем FileId. Далее этот FileID присваеваем этой картинке
                await SendPhotoAndSaveFileId(attachmentFs);
            }

            return(SaveProduct.Id);
        }
コード例 #3
0
        private AttachmentFs InsertAttachmentFs(byte[] PhotoByte,
                                                int AttachmentTypeId = ConstantVariable.MediaTypeVariable.Photo,
                                                string Caption       = "",
                                                string Name          = "Photo.jpg")
        {
            try
            {
                AttachmentFs attachmentFs = new AttachmentFs
                {
                    AttachmentTypeId = AttachmentTypeId,
                    GuId             = Guid.NewGuid(),
                    Caption          = Caption,
                    Fs   = PhotoByte,
                    Name = Name
                };

                db.AttachmentFs.Add(attachmentFs);
                db.SaveChanges();
                return(attachmentFs);
            }

            catch
            {
                return(null);
            }
        }
コード例 #4
0
        public AttachmentFs InsertMainPhoto(int ProductId, Stream image, string Name = "Photo.jpg")
        {
            try
            {
                MemoryStream memoryStream = new MemoryStream();
                image.CopyTo(memoryStream);

                AttachmentFs attachmentFs = new AttachmentFs
                {
                    AttachmentTypeId = ConstantVariable.MediaTypeVariable.Photo,
                    Name             = Name,
                    Fs   = memoryStream.ToArray(),
                    GuId = Guid.NewGuid()
                };

                db.AttachmentFs.Add(attachmentFs);

                db.SaveChanges();

                return(attachmentFs);
            }

            catch
            {
                return(null);
            }
        }
コード例 #5
0
        public ProductPhoto InsertAdditionallPhoto(int ProductId, Telegram.Bot.Types.File Photo, string Caption = null)
        {
            byte[] PhotoByte = null;

            AttachmentFs attachmentFs = null;

            ProductPhoto productPhoto = null;

            try
            {
                if (ProductId > 0 && Photo != null)
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        Photo.FileStream.CopyTo(ms);
                        PhotoByte = ms.ToArray();
                    }

                    if (PhotoByte != null)
                    {
                        attachmentFs = InsertAttachmentFs(PhotoByte, Caption: Caption);
                    }

                    if (attachmentFs != null)
                    {
                        productPhoto = new ProductPhoto
                        {
                            AttachmentFsId = attachmentFs.Id,
                            ProductId      = ProductId
                        };

                        db.ProductPhoto.Add(productPhoto);

                        db.SaveChanges();
                    }

                    return(productPhoto);
                }

                return(null);
            }

            catch
            {
                return(null);
            }
        }
コード例 #6
0
        private async Task <string> SendPhotoAndSaveFileId(AttachmentFs attachmentFs)
        {
            if (BotInfo == null)
            {
                BotInfo = Bot.GeneralFunction.GetBotInfo();
            }


            try
            {
                string token = BotInfo.Token;

                TelegramBotClient = new Telegram.Bot.TelegramBotClient(token);

                System.IO.Stream stream = new MemoryStream(attachmentFs.Fs);

                Telegram.Bot.Types.FileToSend fileToSend = new Telegram.Bot.Types.FileToSend
                {
                    Content  = stream,
                    Filename = "Photo.jpg"
                };

                var Message = await TelegramBotClient.SendPhotoAsync(BotInfo.OwnerChatId, fileToSend);

                string Fileid = Message.Photo[Message.Photo.Length - 1].FileId;

                AttachmentTelegramFunction.AddAttachmentTelegram(attachmentFs.Id, BotInfo.Id, Fileid);

                return(Fileid);
            }

            catch
            {
                return(null);
            }
        }
コード例 #7
0
        private async Task <int> UpdateProduct(Product SaveProduct, IFormFile image = null)
        {
            AttachmentFs attachmentFs = null;


            if (image != null) // загружаем фотографию в базу данных
            {
                attachmentFs = ProductFunc.InsertMainPhoto(SaveProduct.Id, image.OpenReadStream(), image.FileName);
            }


            if (attachmentFs != null) // обновляем id фотографии  у продукта
            {
                SaveProduct.MainPhoto = attachmentFs.Id;

                //отправляем эту фотографию в телеграм и вытаскивваем FileId. Далее этот FileID присваеваем этой картинке
                await SendPhotoAndSaveFileId(attachmentFs);
            }


            ProductFunc.UpdateProduct(SaveProduct);

            return(SaveProduct.Id);
        }
コード例 #8
0
        /// <summary>
        /// Вытаскивам с сервера телеграм этот файл и записываем его в БД бота. Нам нужно хранить эти файлы, т.к если бота заблокируют или
        /// мы подключим допольнительных ботов, то мы не сможем отправить FileId другого бота. Поэтому мы храним в бд эти файлы
        /// </summary>
        /// <param name="id">FileId файл на сервере телеграм</param>
        /// <returns>Возращает id записи из таблицы AttachmentFS</returns>
        protected async Task <int> InsertToAttachmentFs(string id = null, string Caption = "")
        {
            if (id == null)
            {
                id = FileId;
            }
            Db.BotMngmntDbContext db = new Db.BotMngmntDbContext();

            try
            {
                var file = await TelegramClient.GetFileAsync(id);

                System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();

                await file.FileStream.CopyToAsync(memoryStream);

                // Довавбляем в БД
                AttachmentFs attachmentFs = new AttachmentFs
                {
                    Fs               = memoryStream.ToArray(),
                    GuId             = Guid.NewGuid(),
                    Caption          = Caption,
                    AttachmentTypeId = MediaFileTypeId
                };

                db.AttachmentFs.Add(attachmentFs);

                int type = HowMediaType(Update.Message); // узнаем какой типа файла. Фото, Аудио и тд

                //Когда оператора будет смотреть заявку через того же бота, через коготого пользователь
                //оформлял заявку, мы отправим ему ID файла на сервере телеграм вместо целой картинки. Это будет быстрее.
                //А если оператор будет смотреть заявку из другого бота (например старого удалят), то мы сможем отрпавить файл картинки

                //максимальный размер файла 15 мб
                if (file != null && file.FileSize <= 15 * 1024 * 1024 && memoryStream != null && await db.SaveChangesAsync() > 0 && type > 0)
                {
                    AttachmentTelegram attachment = new AttachmentTelegram();
                    attachment.FileId         = id;
                    attachment.AttachmentFsId = attachmentFs.Id;
                    attachment.BotInfoId      = BotInfo.Id;

                    db.AttachmentTelegram.Add(attachment);

                    if (await db.SaveChangesAsync() > 0)
                    {
                        return(Convert.ToInt32(attachment.AttachmentFsId));
                    }

                    else
                    {
                        return(-1);
                    }
                }

                if (file.FileSize > 15 * 1024 * 1024)
                {
                    await SendMessage(new BotMessage { TextMessage = "Ошибка. Файл не может быть больше 15 мб!" });

                    return(-1);
                }

                else
                {
                    return(-1);
                }
            }


            catch (Exception exp)
            {
                return(-1);
            }

            finally
            {
                db.Dispose();
            }
        }