示例#1
0
        public static void RunBot(string accessToken)
        {
            var bot = new TelegramBot(accessToken);

            var me = bot.MakeRequestAsync(new GetMe()).Result;

            if (me == null)
            {
                Console.WriteLine("GetMe() FAILED. Do you forget to add your AccessToken to App.config?");
                Console.WriteLine("(Press ENTER to quit)");
                Console.ReadLine();
                return;
            }
            Console.WriteLine("{0} (@{1}) connected!", me.FirstName, me.Username);

            Console.WriteLine();
            Console.WriteLine("Find @{0} in Telegram and send him a message - it will be displayed here", me.Username);
            Console.WriteLine("(Press ENTER to stop listening and quit)");
            Console.WriteLine();
            Console.WriteLine("ATENTION! This project uses nuget package, not 'live' project in solution (because 'live' project is vNext now)");
            Console.WriteLine();

            string uploadedPhotoId    = null;
            string uploadedDocumentId = null;
            long   offset             = 0;

            while (!stopMe)
            {
                var updates = bot.MakeRequestAsync(new GetUpdates()
                {
                    Offset = offset
                }).Result;
                if (updates != null)
                {
                    foreach (var update in updates)
                    {
                        offset = update.UpdateId + 1;
                        if (update.Message == null)
                        {
                            continue;
                        }
                        var from   = update.Message.From;
                        var text   = update.Message.Text;
                        var photos = update.Message.Photo;
                        Console.WriteLine(
                            "Msg from {0} {1} ({2}) at {4}: {3}",
                            from.FirstName,
                            from.LastName,
                            from.Username,
                            text,
                            update.Message.Date);

                        if (photos != null)
                        {
                            var webClient = new WebClient();
                            foreach (var photo in photos)
                            {
                                Console.WriteLine("  New image arrived: size {1}x{2} px, {3} bytes, id: {0}", photo.FileId, photo.Height, photo.Width, photo.FileSize);
                                var file         = bot.MakeRequestAsync(new GetFile(photo.FileId)).Result;
                                var tempFileName = System.IO.Path.GetTempFileName();
                                webClient.DownloadFile(file.FileDownloadUrl, tempFileName);
                                Console.WriteLine("    Saved to {0}", tempFileName);
                            }
                        }

                        if (string.IsNullOrEmpty(text))
                        {
                            continue;
                        }
                        if (text == "/photo")
                        {
                            if (uploadedPhotoId == null)
                            {
                                var reqAction = new SendChatAction(update.Message.Chat.Id, "upload_photo");
                                bot.MakeRequestAsync(reqAction).Wait();
                                System.Threading.Thread.Sleep(500);
                                using (var photoData = Assembly.GetExecutingAssembly().GetManifestResourceStream("TelegramBotDemo.t_logo.png"))
                                {
                                    var req = new SendPhoto(update.Message.Chat.Id, new FileToSend(photoData, "Telegram_logo.png"))
                                    {
                                        Caption = "Telegram_logo.png"
                                    };
                                    var msg = bot.MakeRequestAsync(req).Result;
                                    uploadedPhotoId = msg.Photo.Last().FileId;
                                }
                            }
                            else
                            {
                                var req = new SendPhoto(update.Message.Chat.Id, new FileToSend(uploadedPhotoId))
                                {
                                    Caption = "Resending photo id=" + uploadedPhotoId
                                };
                                bot.MakeRequestAsync(req).Wait();
                            }
                            continue;
                        }
                        if (text == "/doc")
                        {
                            if (uploadedDocumentId == null)
                            {
                                var reqAction = new SendChatAction(update.Message.Chat.Id, "upload_document");
                                bot.MakeRequestAsync(reqAction).Wait();
                                System.Threading.Thread.Sleep(500);
                                using (var docData = Assembly.GetExecutingAssembly().GetManifestResourceStream("TelegramBotDemo.Telegram_Bot_API.htm"))
                                {
                                    var req = new SendDocument(update.Message.Chat.Id, new FileToSend(docData, "Telegram_Bot_API.htm"));
                                    var msg = bot.MakeRequestAsync(req).Result;
                                    uploadedDocumentId = msg.Document.FileId;
                                }
                            }
                            else
                            {
                                var req = new SendDocument(update.Message.Chat.Id, new FileToSend(uploadedDocumentId));
                                bot.MakeRequestAsync(req).Wait();
                            }
                            continue;
                        }
                        if (text == "/docutf8")
                        {
                            var reqAction = new SendChatAction(update.Message.Chat.Id, "upload_document");
                            bot.MakeRequestAsync(reqAction).Wait();
                            System.Threading.Thread.Sleep(500);
                            using (var docData = Assembly.GetExecutingAssembly().GetManifestResourceStream("TelegramBotDemo.Пример UTF8 filename.txt"))
                            {
                                var req = new SendDocument(update.Message.Chat.Id, new FileToSend(docData, "Пример UTF8 filename.txt"));
                                var msg = bot.MakeRequestAsync(req).Result;
                                uploadedDocumentId = msg.Document.FileId;
                            }
                            continue;
                        }
                        if (text == "/help")
                        {
                            var keyb = new ReplyKeyboardMarkup()
                            {
                                Keyboard = new[] {
                                    new[] { new KeyboardButton("/photo"), new KeyboardButton("/doc"), new KeyboardButton("/docutf8") },
                                    new[] { new KeyboardButton("/help") }
                                },
                                OneTimeKeyboard = true,
                                ResizeKeyboard  = true
                            };
                            var reqAction = new SendMessage(update.Message.Chat.Id, "Here is all my commands")
                            {
                                ReplyMarkup = keyb
                            };
                            bot.MakeRequestAsync(reqAction).Wait();
                            continue;
                        }
                        if (update.Message.Text.Length % 2 == 0)
                        {
                            bot.MakeRequestAsync(new SendMessage(
                                                     update.Message.Chat.Id,
                                                     "You wrote: \r\n_" + update.Message.Text.MarkdownEncode() + "_")
                            {
                                ParseMode = SendMessage.ParseModeEnum.Markdown
                            }).Wait();
                        }
                        else
                        {
                            bot.MakeRequestAsync(new ForwardMessage(update.Message.Chat.Id, update.Message.Chat.Id, update.Message.MessageId)).Wait();
                        }
                    }
                }
            }
        }
示例#2
0
        public static void RunBot(string accessToken)
        {
            var bot = new TelegramBot(accessToken);

            var me = bot.MakeRequestAsync(new GetMe()).Result;
            if (me == null)
            {
                Console.WriteLine("GetMe() FAILED. Do you forget to add your AccessToken to App.config?");
                Console.WriteLine("(Press ENTER to quit)");
            }
            Console.WriteLine("{0} (@{1}) connected!", me.FirstName, me.Username);

            Console.WriteLine();
            Console.WriteLine("Find @{0} in Telegram and send him a message - it will be displayed here", me.Username);
            Console.WriteLine("(Press ENTER to stop listening and quit)");
            Console.WriteLine();

            string uploadedPhotoId = null;
            string uploadedDocumentId = null;
            long offset = 0;
            while (!stopMe)
            {
                var updates = bot.MakeRequestAsync(new GetUpdates() { Offset = offset }).Result;
                if (updates != null)
                {
                    foreach (var update in updates)
                    {
                        offset = update.UpdateId + 1;
                        if (update.Message == null)
                        {
                            continue;
                        }
                        var from = update.Message.From;
                        var text = update.Message.Text;
                        Console.WriteLine(
                            "Msg from {0} {1} ({2}) at {4}: {3}",
                            from.FirstName,
                            from.LastName,
                            from.Username,
                            text,
                            update.Message.Date);

                        if (string.IsNullOrEmpty(text))
                        {
                            continue;
                        }
                        if (text == "/photo")
                        {
                            if (uploadedPhotoId == null)
                            {
                                var reqAction = new SendChatAction(update.Message.Chat.Id, "upload_photo");
                                bot.MakeRequestAsync(reqAction).Wait();
                                System.Threading.Thread.Sleep(500);
                                using (var photoData = Assembly.GetExecutingAssembly().GetManifestResourceStream("TelegramBotDemo.t_logo.png"))
                                {
                                    var req = new SendPhoto(update.Message.Chat.Id, new FileToSend(photoData, "Telegram_logo.png"))
                                    {
                                        Caption = "Telegram_logo.png"
                                    };
                                    var msg = bot.MakeRequestAsync(req).Result;
                                    uploadedPhotoId = msg.Photo.Last().FileId;
                                }
                            }
                            else
                            {
                                var req = new SendPhoto(update.Message.Chat.Id, new FileToSend(uploadedPhotoId))
                                {
                                    Caption = "Resending photo id=" + uploadedPhotoId
                                };
                                bot.MakeRequestAsync(req).Wait();
                            }
                            continue;
                        }
                        if (text == "/doc")
                        {
                            if (uploadedDocumentId == null)
                            {
                                var reqAction = new SendChatAction(update.Message.Chat.Id, "upload_document");
                                bot.MakeRequestAsync(reqAction).Wait();
                                System.Threading.Thread.Sleep(500);
                                using (var docData = Assembly.GetExecutingAssembly().GetManifestResourceStream("TelegramBotDemo.Telegram_Bot_API.htm"))
                                {
                                    var req = new SendDocument(update.Message.Chat.Id, new FileToSend(docData, "Telegram_Bot_API.htm"));
                                    var msg = bot.MakeRequestAsync(req).Result;
                                    uploadedDocumentId = msg.Document.FileId;
                                }
                            }
                            else
                            {
                                var req = new SendDocument(update.Message.Chat.Id, new FileToSend(uploadedDocumentId));
                                bot.MakeRequestAsync(req).Wait();
                            }
                            continue;
                        }
                        if (text == "/docutf8")
                        {
                            var reqAction = new SendChatAction(update.Message.Chat.Id, "upload_document");
                            bot.MakeRequestAsync(reqAction).Wait();
                            System.Threading.Thread.Sleep(500);
                            using (var docData = Assembly.GetExecutingAssembly().GetManifestResourceStream("TelegramBotDemo.Пример UTF8 filename.txt"))
                            {
                                var req = new SendDocument(update.Message.Chat.Id, new FileToSend(docData, "Пример UTF8 filename.txt"));
                                var msg = bot.MakeRequestAsync(req).Result;
                                uploadedDocumentId = msg.Document.FileId;
                            }
                            continue;
                        }
                        if (text == "/help")
                        {
                            var keyb = new ReplyKeyboardMarkup()
                            {
                                Keyboard = new[] { new[] { "/photo", "/doc", "/docutf8" }, new[] { "/help" } },
                                OneTimeKeyboard = true,
                                ResizeKeyboard = true
                            };
                            var reqAction = new SendMessage(update.Message.Chat.Id, "Here is all my commands") { ReplyMarkup = keyb };
                            bot.MakeRequestAsync(reqAction).Wait();
                            continue;
                        }
                        if (update.Message.Text.Length % 2 == 0)
                        {
                            bot.MakeRequestAsync(new SendMessage(update.Message.Chat.Id, "You wrote " + update.Message.Text.Length + " characters")).Wait();
                        }
                        else
                        {
                            bot.MakeRequestAsync(new ForwardMessage(update.Message.Chat.Id, update.Message.Chat.Id, update.Message.MessageId)).Wait();
                        }
                    }
                }
            }
        }
示例#3
0
        public static void RunBot(string accessToken)
        {
            var bot = new TelegramBot(accessToken);

            var me = bot.MakeRequestAsync(new GetMe()).Result;
            if (me == null)
            {
                Console.WriteLine("GetMe() FAILED. Do you forget to add your AccessToken to config.json?");
                Console.WriteLine("(Press ENTER to quit)");
                Console.ReadLine();
                return;
            }
            Console.WriteLine("{0} (@{1}) connected!", me.FirstName, me.Username);

            Console.WriteLine();
            Console.WriteLine("Find @{0} in Telegram and send him a message - it will be displayed here", me.Username);
            Console.WriteLine("(Press ENTER to stop listening and quit)");
            Console.WriteLine();

            string uploadedPhotoId = null;
            string uploadedDocumentId = null;
            long offset = 0;
            while (!stopMe)
            {
                var updates = bot.MakeRequestAsync(new GetUpdates() { Offset = offset }).Result;
                if (updates != null)
                {
                    foreach (var update in updates)
                    {
                        offset = update.UpdateId + 1;
                        if (update.Message == null)
                        {
                            continue;
                        }
                        var from = update.Message.From;
                        var text = update.Message.Text;
                        var photos = update.Message.Photo;
                        Console.WriteLine(
                            "Msg from {0} {1} ({2}) at {4}: {3}",
                            from.FirstName,
                            from.LastName,
                            from.Username,
                            text,
                            update.Message.Date);

                        if (photos != null)
                        {
                            var webClient = new WebClient();
                            foreach (var photo in photos)
                            {
                                Console.WriteLine("  New image arrived: size {1}x{2} px, {3} bytes, id: {0}", photo.FileId, photo.Height, photo.Width, photo.FileSize);
                                var file = bot.MakeRequestAsync(new GetFile(photo.FileId)).Result;
                                var tempFileName = System.IO.Path.GetTempFileName();
                                webClient.DownloadFile(file.FileDownloadUrl, tempFileName);
                                Console.WriteLine("    Saved to {0}", tempFileName);
                            }
                        }

                        if (string.IsNullOrEmpty(text))
                        {
                            continue;
                        }
                        if (text == "/photo")
                        {
                            if (uploadedPhotoId == null)
                            {
                                var reqAction = new SendChatAction(update.Message.Chat.Id, "upload_photo");
                                bot.MakeRequestAsync(reqAction).Wait();
                                System.Threading.Thread.Sleep(500);
                                using (var photoData = typeof(Program).Assembly.GetManifestResourceStream("TelegramBotDemo-vNext.t_logo.png"))
                                {
                                    var req = new SendPhoto(update.Message.Chat.Id, new FileToSend(photoData, "Telegram_logo.png"))
                                    {
                                        Caption = "Telegram_logo.png"
                                    };
                                    var msg = bot.MakeRequestAsync(req).Result;
                                    uploadedPhotoId = msg.Photo.Last().FileId;
                                }
                            }
                            else
                            {
                                var req = new SendPhoto(update.Message.Chat.Id, new FileToSend(uploadedPhotoId))
                                {
                                    Caption = "Resending photo id=" + uploadedPhotoId
                                };
                                bot.MakeRequestAsync(req).Wait();
                            }
                            continue;
                        }
                        if (text == "/doc")
                        {
                            if (uploadedDocumentId == null)
                            {
                                var reqAction = new SendChatAction(update.Message.Chat.Id, "upload_document");
                                bot.MakeRequestAsync(reqAction).Wait();
                                System.Threading.Thread.Sleep(500);
                                using (var docData = typeof(Program).Assembly.GetManifestResourceStream("TelegramBotDemo-vNext.Telegram_Bot_API.htm"))
                                {
                                    var req = new SendDocument(update.Message.Chat.Id, new FileToSend(docData, "Telegram_Bot_API.htm"));
                                    var msg = bot.MakeRequestAsync(req).Result;
                                    uploadedDocumentId = msg.Document.FileId;
                                }
                            }
                            else
                            {
                                var req = new SendDocument(update.Message.Chat.Id, new FileToSend(uploadedDocumentId));
                                bot.MakeRequestAsync(req).Wait();
                            }
                            continue;
                        }
                        if (text == "/docutf8")
                        {
                            var reqAction = new SendChatAction(update.Message.Chat.Id, "upload_document");
                            bot.MakeRequestAsync(reqAction).Wait();
                            System.Threading.Thread.Sleep(500);
                            using (var docData = typeof(Program).Assembly.GetManifestResourceStream("TelegramBotDemo-vNext.Пример UTF8 filename.txt"))
                            {
                                var req = new SendDocument(update.Message.Chat.Id, new FileToSend(docData, "Пример UTF8 filename.txt"));
                                var msg = bot.MakeRequestAsync(req).Result;
                                uploadedDocumentId = msg.Document.FileId;
                            }
                            continue;
                        }
                        if (text == "/help")
                        {
                            var keyb = new ReplyKeyboardMarkup()
                            {
                                Keyboard = new[] { new[] { "/photo", "/doc", "/docutf8" }, new[] { "/help" } },
                                OneTimeKeyboard = true,
                                ResizeKeyboard = true
                            };
                            var reqAction = new SendMessage(update.Message.Chat.Id, "Here is all my commands") { ReplyMarkup = keyb };
                            bot.MakeRequestAsync(reqAction).Wait();
                            continue;
                        }
                        if (update.Message.Text.Length % 2 == 0)
                        {
                            bot.MakeRequestAsync(new SendMessage(
                                update.Message.Chat.Id,
                                "You wrote *" + update.Message.Text.Length + " characters*")
                            {
                                ParseMode = SendMessage.ParseModeEnum.Markdown
                            }).Wait();
                        }
                        else
                        {
                            bot.MakeRequestAsync(new ForwardMessage(update.Message.Chat.Id, update.Message.Chat.Id, update.Message.MessageId)).Wait();
                        }
                    }
                }
            }
        }
示例#4
0
        public static async Task RunBot()
        {
            try
            {
                int lev = 0;

                var bot = new TelegramBot(ApiToken);
                var me  = await bot.MakeRequestAsync(new GetMe());

                Console.WriteLine($"UserName : {me.Username}");
                long offset     = 0;
                int  whileCount = 0;
                while (true)
                {
                    var updates = await bot.MakeRequestAsync(new GetUpdates()
                    {
                        Offset = offset
                    });

                    try
                    {
                        foreach (var update in updates)
                        {
                            offset = update.UpdateId + 1;
                            var text = update.Message.Text;
                            if (text.ToLower() == "/start" || text.ToLower() == "/new")
                            {
                                var chat = update.Message.Chat;
                                InsertLogedIn(chat.Username, chat.FirstName, chat.LastName);
                                var resp = new SendMessage(0, "");
                                resp = new SendMessage(update.Message.Chat.Id, $"درودبر شما به ربات انجمن علمی کامپیوتر خوش آمدید.{Environment.NewLine}لطفا یکی ار سرویس های زیر را انتخاب کنید")
                                {
                                    ReplyMarkup = serviceKeyboard
                                };
                                await bot.MakeRequestAsync(resp);
                            }
                            else if (text != null)
                            {
                                if (text.ToLower().Contains("دریافت چارت دروس رشته".Trim()))
                                {
                                    var resp = new SendMessage(update.Message.Chat.Id, "در کدام گرایش مشغول به تحصیل هستید؟")
                                    {
                                        ReplyMarkup = fieldsKeyboard
                                    };
                                    await bot.MakeRequestAsync(resp);

                                    lev = lev + 1;
                                    continue;
                                }
                                if (text.ToLower().Contains("نرم افزار".TrimEnd()))
                                {
                                    var resp1 = new SendMessage(update.Message.Chat.Id, "صبور باشید...");
                                    await bot.MakeRequestAsync(resp1);

                                    string path = AppDomain.CurrentDomain.BaseDirectory + @"\Images\Soft.jpg";
                                    path = path.Replace(@"\bin\Debug", "");
                                    using (var stream = System.IO.File.Open(path, FileMode.Open))
                                    {
                                        var resp = new SendPhoto(update.Message.Chat.Id, new FileToSend(stream, "Soft.jpg"));
                                        await bot.MakeRequestAsync(resp);

                                        continue;
                                    }
                                }
                                else if (text.ToLower().Contains("معماری سیستمهای کامپیوتری".TrimEnd()))
                                {
                                    var resp1 = new SendMessage(update.Message.Chat.Id, "صبور باشید...");
                                    await bot.MakeRequestAsync(resp1);

                                    string path = AppDomain.CurrentDomain.BaseDirectory + @"Images\Arch.jpg";
                                    path = path.Replace(@"\bin\Debug", "");
                                    using (var stream = System.IO.File.Open(path, FileMode.Open))
                                    {
                                        var resp = new SendPhoto(update.Message.Chat.Id, new FileToSend(stream, "Arch.jpg"));
                                        await bot.MakeRequestAsync(resp);

                                        continue;
                                    }
                                }
                                else if (text.ToLower().Contains("فناوری اطلاعات".ToLower()))
                                {
                                    var resp1 = new SendMessage(update.Message.Chat.Id, "صبور باشید...");
                                    await bot.MakeRequestAsync(resp1);

                                    string path = AppDomain.CurrentDomain.BaseDirectory + @"Images\IT.jpg";
                                    path = path.Replace(@"\bin\Debug", "");
                                    using (var stream = System.IO.File.Open(path, FileMode.Open))
                                    {
                                        var resp = new SendPhoto(update.Message.Chat.Id, new FileToSend(stream, "IT.jpg"));
                                        await bot.MakeRequestAsync(resp);

                                        continue;
                                    }
                                }
                                else
                                {
                                    var resp = new SendMessage(update.Message.Chat.Id, "دستور نامفهوم بود!");
                                    await bot.MakeRequestAsync(resp);

                                    continue;
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error : " + ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error : " + ex.Message);
            }
        }
示例#5
0
        public static void RunBot(string accessToken)
        {
            var bot = new TelegramBot(accessToken, new HttpClient());

            var me = bot.MakeRequestAsync(new GetMe()).Result;

            if (me == null)
            {
                Console.WriteLine("GetMe() FAILED. Do you forget to add your AccessToken to config.json?");
                Console.WriteLine("(Press ENTER to quit)");
                Console.ReadLine();
                return;
            }
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            Console.WriteLine("{0} (@{1}) connected!", me.FirstName, me.Username);

            Console.WriteLine();
            Console.WriteLine("Find @{0} in Telegram and send him a message - it will be displayed here", me.Username);
            Console.WriteLine("(Press ENTER to stop listening and quit)");
            Console.WriteLine();

            string uploadedPhotoId    = null;
            string uploadedDocumentId = null;
            long   offset             = 0;

            while (!stopMe)
            {
                var updates = bot.MakeRequestAsync(new GetUpdates()
                {
                    Offset = offset
                }).Result;
                if (updates != null)
                {
                    foreach (var update in updates)
                    {
                        offset = update.UpdateId + 1;
                        if (update.Message == null)
                        {
                            continue;
                        }
                        var from     = update.Message.From;
                        var text     = update.Message.Text;
                        var photos   = update.Message.Photo;
                        var contact  = update.Message.Contact;
                        var location = update.Message.Location;
                        Console.WriteLine(
                            "Msg from {0} {1} ({2}) at {4}: {3}",
                            from.FirstName,
                            from.LastName,
                            from.Username,
                            text,
                            update.Message.Date);

                        if (photos != null)
                        {
                            var webClient = new HttpClient();
                            foreach (var photo in photos)
                            {
                                Console.WriteLine("  New image arrived: size {1}x{2} px, {3} bytes, id: {0}", photo.FileId, photo.Height, photo.Width, photo.FileSize);
                                var file         = bot.MakeRequestAsync(new GetFile(photo.FileId)).Result;
                                var tempFileName = System.IO.Path.GetTempFileName();
                                var bytes        = webClient.GetByteArrayAsync(file.FileDownloadUrl).Result;
                                System.IO.File.WriteAllBytes(tempFileName, bytes);
                                Console.WriteLine("    Saved to {0}", tempFileName);
                            }
                        }
                        if (contact != null)
                        {
                            var req = new SendContact(update.Message.Chat.Id, contact.PhoneNumber, contact.FirstName)
                            {
                                LastName = contact.LastName
                            };
                            bot.MakeRequestAsync(req).Wait();
                        }
                        if (location != null)
                        {
                            var req = new SendLocation(update.Message.Chat.Id, location.Latitude, location.Longitude);
                            bot.MakeRequestAsync(req).Wait();
                        }

                        if (string.IsNullOrEmpty(text))
                        {
                            continue;
                        }
                        if (text == "/photo")
                        {
                            if (uploadedPhotoId == null)
                            {
                                var reqAction = new SendChatAction(update.Message.Chat.Id, "upload_photo");
                                bot.MakeRequestAsync(reqAction).Wait();
                                System.Threading.Thread.Sleep(500);
                                using var photoData = typeof(Program).GetTypeInfo().Assembly.GetManifestResourceStream("TelegramBotDemo-vNext.t_logo.png");
                                var req = new SendPhoto(update.Message.Chat.Id, new FileToSend(photoData, "Telegram_logo.png"))
                                {
                                    Caption = "Telegram_logo.png"
                                };
                                var msg = bot.MakeRequestAsync(req).Result;
                                uploadedPhotoId = msg.Photo.Last().FileId;
                            }
                            else
                            {
                                var req = new SendPhoto(update.Message.Chat.Id, new FileToSend(uploadedPhotoId))
                                {
                                    Caption = "Resending photo id=" + uploadedPhotoId
                                };
                                bot.MakeRequestAsync(req).Wait();
                            }
                            continue;
                        }
                        if (text == "/doc")
                        {
                            if (uploadedDocumentId == null)
                            {
                                var reqAction = new SendChatAction(update.Message.Chat.Id, "upload_document");
                                bot.MakeRequestAsync(reqAction).Wait();
                                System.Threading.Thread.Sleep(500);
                                using var docData = typeof(Program).GetTypeInfo().Assembly.GetManifestResourceStream("TelegramBotDemo-vNext.Telegram_Bot_API.htm");
                                var req = new SendDocument(update.Message.Chat.Id, new FileToSend(docData, "Telegram_Bot_API.htm"));
                                var msg = bot.MakeRequestAsync(req).Result;
                                uploadedDocumentId = msg.Document.FileId;
                            }
                            else
                            {
                                var req = new SendDocument(update.Message.Chat.Id, new FileToSend(uploadedDocumentId));
                                bot.MakeRequestAsync(req).Wait();
                            }
                            continue;
                        }
                        if (text == "/docutf8")
                        {
                            var reqAction = new SendChatAction(update.Message.Chat.Id, "upload_document");
                            bot.MakeRequestAsync(reqAction).Wait();
                            System.Threading.Thread.Sleep(500);
                            using var docData = typeof(Program).GetTypeInfo().Assembly.GetManifestResourceStream("TelegramBotDemo-vNext.Пример_UTF8_filename.txt");
                            var req = new SendDocument(update.Message.Chat.Id, new FileToSend(docData, "Пример_UTF8_filename.txt"));
                            var msg = bot.MakeRequestAsync(req).Result;
                            uploadedDocumentId = msg.Document.FileId;
                            continue;
                        }
                        if (text == "/help")
                        {
                            var keyb = new ReplyKeyboardMarkup()
                            {
                                Keyboard = new[] {
                                    new[] { new KeyboardButton("/photo"), new KeyboardButton("/doc"), new KeyboardButton("/docutf8") },
                                    new[] { new KeyboardButton("/contact")
                                            {
                                                RequestContact = true
                                            }, new KeyboardButton("/location")
                                            {
                                                RequestLocation = true
                                            } },
                                    new[] { new KeyboardButton("/help") }
                                },
                                OneTimeKeyboard = true,
                                ResizeKeyboard  = true
                            };
                            var reqAction = new SendMessage(update.Message.Chat.Id, "Here is all my commands")
                            {
                                ReplyMarkup = keyb
                            };
                            bot.MakeRequestAsync(reqAction).Wait();
                            continue;
                        }
                        if (text == "/longmsg")
                        {
                            var msg = new string('X', 10240);
                            bot.MakeRequestAsync(new SendMessage(update.Message.Chat.Id, msg)).Wait();
                            continue;
                        }
                        if (update.Message.Text.Length % 2 == 0)
                        {
                            bot.MakeRequestAsync(new SendMessage(
                                                     update.Message.Chat.Id,
                                                     "You wrote: \r\n" + update.Message.Text.MarkdownEncode())
                            {
                                ParseMode = SendMessage.ParseModeEnum.Markdown
                            }).Wait();
                        }
                        else
                        {
                            bot.MakeRequestAsync(new ForwardMessage(update.Message.Chat.Id, update.Message.Chat.Id, update.Message.MessageId)).Wait();
                        }
                    }
                }
            }
        }
 public static ValidationResult <SendPhoto> CreateValidation(this SendPhoto value) => new ValidationResult <SendPhoto>(value)
 .ValidateRequired(x => x.ChatId)
 .ValidateRequired(x => x.Photo);
示例#7
0
        private void SocketConnection_OnMessage(object sender, MessageEventArgs e)
        {
            var ws = (WebSocket)sender;

            if (e.IsText)
            {
                ws.Log.Info("Text Message");
                WriteLog(e.Data);

                JObject baleObject = JObject.Parse(e.Data);
                var     mainType   = baleObject["$type"].Value <string>();
                var     subType    = "NO-BODY";
                var     date       = "NO-DATE";

                //detect body type
                if (baleObject["body"] != null && baleObject["body"]["$type"] != null)
                {
                    subType = baleObject["body"]["$type"].Value <string>();
                }

                //detect date main code
                if (baleObject["body"] != null && baleObject["body"]["date"] != null)
                {
                    date = baleObject["body"]["date"].Value <string>();
                }

                //detect date main code
                if (baleObject["body"] != null && baleObject["body"]["startDate"] != null)
                {
                    date = baleObject["body"]["startDate"].Value <string>();
                }

                //detect peer شناسایی کاربر
                if (baleObject["body"] != null && baleObject["body"]["peer"] != null)
                {
                    LastUser = new Peer()
                    {
                        accessHash = baleObject["body"]["peer"]["accessHash"].Value <string>(),
                        id         = baleObject["body"]["peer"]["id"].Value <string>(),
                        type       = baleObject["body"]["peer"]["$type"].Value <string>()
                    };

                    WriteLog("LastUserId:\t" + LastUser.id);
                }

                txtRec.Text += mainType + "\t" + subType + "\t" + date + "\r\n";

                //این یک پیام است
                if (mainType == "FatSeqUpdate" && subType == "Message")
                {
                    //این پیام متنی است
                    if (baleObject["body"]["message"]["$type"].Value <string>() == "Text")
                    {
                        var message = baleObject["body"]["message"]["text"].Value <string>();
                        txtRec.Text += message + "\r\n";

                        if (isFirstMessage)
                        {
                            isFirstMessage = false;
                            var welcomeSticker = SendMessageTools.GetStickerMessage(new SendSticker()
                            {
                                Type        = "Sticker",
                                FastPreview = null,
                                Image256    = new Model.Image()
                                {
                                    FileLocation = new FileLocation()
                                    {
                                        FileStorageVersion = 1,
                                        AccessHash         = "549755813890",
                                        FileId             = "7415072606480367873"
                                    },
                                    Height   = 256,
                                    Width    = 256,
                                    FileSize = 4924
                                },
                                Image512 = new Model.Image()
                                {
                                    FileLocation = new FileLocation()
                                    {
                                        FileStorageVersion = 1,
                                        AccessHash         = "549755813890",
                                        FileId             = "-8656471477048966910"
                                    },
                                    Height   = 512,
                                    Width    = 512,
                                    FileSize = 11356
                                },
                                StickerCollectionId         = 265723345,
                                StickerCollectionAccessHash = "-8925386374726878396",
                                StickerId = 1345218
                            }, LastUser);


                            //var welcomeSticker = SendMessageTools.GetStickerMessage(new SendSticker()
                            //{
                            //    Type = "Sticker",
                            //    FastPreview = null,
                            //    Image256 = new Model.Image()
                            //    {
                            //        FileLocation = new FileLocation()
                            //        {
                            //            FileStorageVersion = 1,
                            //            AccessHash = "1884281475",
                            //            FileId = "5894772107577788931"
                            //        },
                            //        Height = 256,
                            //        Width = 256,
                            //        FileSize = 4924
                            //    },
                            //    Image512 = new Model.Image()
                            //    {
                            //        FileLocation = new FileLocation()
                            //        {
                            //            FileStorageVersion = 1,
                            //            AccessHash = "1884281475",
                            //            FileId = "5894772107577788931"
                            //        },
                            //        Height = 512,
                            //        Width = 512,
                            //        FileSize = 11356
                            //    },
                            //    StickerCollectionId = 265723345,
                            //    StickerCollectionAccessHash = "-8925386374726878396",
                            //    StickerId = 1345218
                            //}, LastUser);

                            socketConnection.Send(welcomeSticker);
                        }
                    }
                    else
                    {
                        var msgType = baleObject["body"]["message"]["$type"].Value <string>();
                        if (msgType == "TemplateMessageResponse")
                        {
                            //این دستور از یک دکمه اومده
                            var textMessage = baleObject["body"]["message"]["textMessage"].Value <string>();
                            txtRec.Text += msgType + "\tBTN:" + textMessage + "\r\n";
                        }
                        else if (baleObject["body"]["message"]["mimeType"] != null)
                        {
                            //این پیام حاوی فایل یا سند یا عکس است
                            var mimeType = baleObject["body"]["message"]["mimeType"].Value <string>();
                            txtRec.Text += msgType + "\t" + mimeType + "\r\n";
                        }
                        else
                        {
                            txtRec.Text += msgType;
                        }
                    }
                }

                if (mainType == "Response")
                {
                    if (baleObject["body"]["url"] != null)
                    {
                        //دریافت پاسخ برای آپلود فایل و ارسال فایل
                        var id          = baleObject["id"].Value <long>();
                        var receivedUrl = baleObject["body"]["url"].Value <string>();

                        if (SendMessageTools.IsDownloadPending(id))
                        {
                            var fileName = SendMessageTools.GetDownloadFilename(id);
                            var dlUrl    = receivedUrl + "?filename=" + fileName;
                            socketConnection.Log.Info("Download File");
                            socketConnection.Log.Info(dlUrl);
                            SendMessageTools.DownloadFile(dlUrl, socketConnection, fileName);
                            SendMessageTools.DeleteDownload(id);
                        }
                        else if (SendMessageTools.IsUploadPending(id))
                        {
                            FileCache.FileInfoModel fileInfoModel;
                            if (SendMessageTools.UploadFile(id, receivedUrl, socketConnection, out fileInfoModel))
                            {
                                //send Info
                                var fileId = baleObject["body"]["fileId"].Value <string>();
                                var hash   = baleObject["body"]["userId"].Value <long>();

                                string msg = null;

                                //تشخیص ارسال عکس
                                if (fileInfoModel.UploadType == UploadTypeEnum.Document)
                                {
                                    msg = SendMessageTools.GetDocumentMessage(new SendDocument()
                                    {
                                        Type       = "Document",
                                        AccessHash = hash,
                                        Algorithm  = "algorithm",
                                        CheckSum   = "checkSum",
                                        Caption    = new Caption()
                                        {
                                            Text = txtPayam.Text, Type = "Text"
                                        },
                                        Ext                = null,
                                        FileId             = fileId,
                                        FileSize           = fileInfoModel.Size,
                                        FileStorageVersion = 1,
                                        MimeType           = "application/document",
                                        Name               = fileInfoModel.Name,
                                        Thumb              = null
                                    }, LastUser);
                                }
                                else if (fileInfoModel.UploadType == UploadTypeEnum.Photo)
                                {
                                    LastPhoto = new SendPhoto()
                                    {
                                        Type       = "Document",
                                        AccessHash = hash,
                                        Algorithm  = "algorithm",
                                        CheckSum   = "checkSum",
                                        Caption    = new Caption()
                                        {
                                            Text = txtPayam.Text, Type = "Text"
                                        },
                                        FileId             = fileId,
                                        FileSize           = fileInfoModel.Size,
                                        FileStorageVersion = 1,
                                        Name     = fileInfoModel.Name,
                                        MimeType = "image/jpeg",
                                        Ext      = new Ext()
                                        {
                                            Type   = "Photo",
                                            Width  = fileInfoModel.Width,
                                            Height = fileInfoModel.Height
                                        },
                                        Thumb = new Thumb()
                                        {
                                            ThumbThumb = "None",
                                            Width      = fileInfoModel.Width,
                                            Height     = fileInfoModel.Height
                                        }
                                    };
                                    msg = SendMessageTools.GetPhotoMessage(LastPhoto, LastUser);
                                }
                                else if (fileInfoModel.UploadType == UploadTypeEnum.Voice)
                                {
                                    msg = SendMessageTools.GetSendVoice(new SendVoice()
                                    {
                                        Type       = "Document",
                                        AccessHash = hash,
                                        Algorithm  = "algorithm",
                                        CheckSum   = "checkSum",
                                        Caption    = new Caption()
                                        {
                                            Text = txtPayam.Text, Type = "Text"
                                        },
                                        FileId             = fileId,
                                        FileSize           = fileInfoModel.Size,
                                        FileStorageVersion = 1,
                                        Name     = fileInfoModel.Name,
                                        MimeType = "audio/mp3",
                                        Ext      = new Ext()
                                        {
                                            Type     = "Voice",
                                            Duration = (int)(Convert.ToDouble(fileInfoModel.Duration) * 1000)
                                        }
                                    }, LastUser);
                                }

                                if (msg != null)
                                {
                                    socketConnection.Send(msg);
                                }

                                SendMessageTools.DeleteCacheUpload(id);
                            }
                        }
                    }
                }

                txtRec.SelectionStart = txtRec.TextLength;
                txtRec.ScrollToCaret();
            }
            else
            {
                ws.Log.Info("Binary Message");
                WriteLog(Convert.ToBase64String(e.RawData));
            }
        }