Esempio n. 1
0
 private static void PrintReceiveScreenInteractive()
 {
     Console.Clear();
     WriteMessageSlowly("Switching to message view");
     Console.Clear();
     Console.WriteLine("Press <ESC> if you want to return to main menu");
     bot.StartReceiving();
     while (Console.ReadKey().Key != ConsoleKey.Escape)
     {
         Console.ReadKey();
     }
     bot.StopReceiving();
     Console.Clear();
     DrawMainMenue();
 }
Esempio n. 2
0
        public Bottu(string Token, string baseApiAddress)
        {
            AutoResetEvent are = new AutoResetEvent(false);

            client       = new Telegram.Bot.TelegramBotClient(Token);
            MediaWikiApi = new HttpClient
            {
                BaseAddress = new Uri(baseApiAddress)
            };

            var InlineObservable = Observable.FromEventPattern <InlineQueryEventArgs>(c => client.OnInlineQuery += c, c => client.OnInlineQuery -= c);

            InlineObservable
            .Throttle(TimeSpan.FromMilliseconds(100))
            .Where(c => c?.EventArgs?.InlineQuery != null && !string.IsNullOrWhiteSpace(c.EventArgs.InlineQuery.Query))
            .Select(c => c.EventArgs.InlineQuery)
            .Select(c => Observable.FromAsync(async() => await ProcessInline(c)))
            .Concat()
            .Subscribe();

            client.StartReceiving(new[] { UpdateType.InlineQuery });

            Console.WriteLine("Started.");

            are.WaitOne();

            client.StopReceiving();
            Console.WriteLine("Stopped.");
        }
Esempio n. 3
0
        async void BotInit()
        {
            await _bot.SetWebhookAsync("");

            _bot.OnUpdate += async(object su, Telegram.Bot.Args.UpdateEventArgs evu) =>
            {
                if (evu.Update.CallbackQuery != null || evu.Update.InlineQuery != null)
                {
                    return;
                }
                var update  = evu.Update;
                var message = update.Message;
                if (message == null)
                {
                    return;
                }
                if (message.Type == Telegram.Bot.Types.Enums.MessageType.TextMessage)
                {
                    HandleCommand(message.Text, message.Chat.Id, message.MessageId);
                }
            };

            _bot.OnCallbackQuery += async(object sc, Telegram.Bot.Args.CallbackQueryEventArgs ev) =>
            {
                var message = ev.CallbackQuery.Message;
                HandleCallback(ev.CallbackQuery.Data, message.Chat.Id, message.MessageId);
                await _bot.AnswerCallbackQueryAsync(ev.CallbackQuery.Id); // отсылаем пустое, чтобы убрать "частики" на кнопке
            };
            _bot.StartReceiving();
        }
Esempio n. 4
0
 private void button1_Click(object sender, EventArgs e)
 {
     BOT            = new Telegram.Bot.TelegramBotClient("657941583:AAGXlkhYUY6v9q71eCHb1BejDDY8Yq0yk1Y");
     BOT.OnMessage += BotOnMessageReceived;
     BOT.StartReceiving(new UpdateType[] { UpdateType.Message });
     button1.Enabled = false;
 }
Esempio n. 5
0
 private void button1_Click(object sender, EventArgs e)
 {
     BOT            = new Telegram.Bot.TelegramBotClient("508495921:AAHbY2MwO1Gmh6SSOkVO-YoM6oL_vqTTuKY");
     BOT.OnMessage += BotOnMassageReceived;
     BOT.StartReceiving(new UpdateType[] { UpdateType.Message });
     button1.Enabled = false;
 }
Esempio n. 6
0
 public void startBot()
 {
     botTelegram.OnMessage += BotTelegram_OnMessage;
     botTelegram.StartReceiving();
     Console.ReadLine();
     botTelegram.StopReceiving();
 }
Esempio n. 7
0
 void Button1Click(object sender, EventArgs e)
 {
     BOT            = new Telegram.Bot.TelegramBotClient("565638539:AAEBhReNYzHgTMFvhiC-OYECXjlLY4g3Xto");
     BOT.OnMessage += BotOnMessageReceived;
     BOT.StartReceiving(new UpdateType[] { UpdateType.Message });
     button1.Enabled = false;
 }
        public static async Task Main()
        {
            try
            {
                while (true)
                {
                    try
                    {
                        Bot = new Telegram.Bot.TelegramBotClient("place_your_BOT_API_Token_Here");
                        BOTAuthentication = new TelegramAuthentication();

                        Bot.OnMessage       += BotOnMessageReceived;
                        Bot.OnMessageEdited += BotOnMessageReceived;
                        Bot.OnReceiveError  += BotOnReceiveError;

                        Bot.StartReceiving(Array.Empty <UpdateType>());

                        Console.ReadLine();
                    }
                    catch (Exception e)
                    {
                        Thread.Sleep(1000);
                    }
                }
            }
            catch (Exception e)
            {
                Thread.Sleep(2000);
            }
        }
Esempio n. 9
0
 void Button1Click(object sender, EventArgs e)
 {
     BOT            = new Telegram.Bot.TelegramBotClient("455535082:AAGeMMob7ty-q_QFSN4kV2icxt-L7_7PGr0"); //"вставь сюда свой токен");
     BOT.OnMessage += BotOnMessageReceived;
     BOT.StartReceiving(new UpdateType[] { UpdateType.MessageUpdate });
     button1.Enabled = false;
     l1 = label1;
 }
Esempio n. 10
0
        public void Start()
        {
            botClient.StartReceiving();

            while (true)
            {
            }
        }
Esempio n. 11
0
 public Worker(ILogger <Worker> logger, TelegramWorkerOptions telegramWorkerOptions)
 {
     _logger    = logger;
     _botClient = new Telegram.Bot.TelegramBotClient(telegramWorkerOptions.APIKey);
     _cards     = JsonImporter.JsonImporter.ReadCardsFromJson();
     _botClient.OnInlineQuery += _botClient_OnInlineQuery;
     _botClient.StartReceiving();
 }
Esempio n. 12
0
 private void StartBot(object sender, RoutedEventArgs e)
 {
     if (TokenLabel.Content.Equals("Token received"))
     {
         TokenLabel.Content = "Bot alive";
     }
     BOT            = new Telegram.Bot.TelegramBotClient(Token);
     BOT.OnMessage += BotOnMessageReceived;
     BOT.StartReceiving(new UpdateType[] { UpdateType.Message });
 }
Esempio n. 13
0
        static void Main(string[] args)
        {
            Bot.OnMessage += BotOnTextReceived;
            var me = Bot.GetMeAsync().Result;

            Console.Title = me.Username;

            Bot.StartReceiving();
            Console.ReadLine();
            Bot.StopReceiving();
        }
Esempio n. 14
0
        private static async Task MainAsync()
        {
            botClient = new Telegram.Bot.TelegramBotClient(Properties.Settings.Default.BotAccessToken);

            var me = await botClient.GetMeAsync();

            botClient.OnMessage += MessageReceived;
            botClient.StartReceiving(new[] {
                UpdateType.Message
            });
        }
Esempio n. 15
0
        public static void Main()
        {
            var me = Bot.GetMeAsync().Result;

            Console.Title        = me.Username;
            Bot.OnMessage       += BotOnMessageReceived;
            Bot.OnMessageEdited += BotOnMessageReceived;
            Bot.OnCallbackQuery += BotOnCallbackQueryReceived;
            Bot.StartReceiving(Array.Empty <UpdateType>());
            Console.WriteLine($"Start listening for @{me.Username}");
            Console.ReadLine();
            Bot.StopReceiving();
        }
Esempio n. 16
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            ////var req = Request.InputStream;
            ////var responsString = new StreamReader(req).ReadToEnd();
            ////var e = JsonConvert.DeserializeObject<Update>(responsString);
            ////Telegram.Bot.TelegramBotClient bot = new Telegram.Bot.TelegramBotClient("425489173:AAG2esoDKjjSwT4LSGJCDMD7WnTDbjNhBRk"); //testony
            ////var x = await bot.SendTextMessageAsync(e.Message.Chat.Id, "succeed");

            bot.OnMessage += Bot_OnMessage;
            bot.StartReceiving();
        }
Esempio n. 17
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                BOT            = new Telegram.Bot.TelegramBotClient("{КЛЮЧ_API}");
                BOT.OnMessage += BotOnMessageReceived;
                BOT.StartReceiving(new UpdateType[] { UpdateType.MessageUpdate });
                button1.Enabled = false;

                this.Visible = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 18
0
        static void Main(string[] args)
        {
            Console.WriteLine("# Welcome to bot settings");
            Console.Write("# Please provider your token (or press enter): ");
            var token = Console.ReadLine();

            if (string.IsNullOrEmpty(token))
            {
                token = ConfigurationManager.AppSettings["token"];
                Console.WriteLine($"# Token from config file: {token}");
            }
            var client = new Telegram.Bot.TelegramBotClient(token);
            var task   = client.GetMeAsync();

            task.Wait();
            if (task.IsCompleted)
            {
                var user = task.Result;
                Console.WriteLine($"{user.FirstName} {user.LastName} is greeting you here!");
            }

            try
            {
                var stream = new FileStream("C:\\Users\\tsmirnov\\ssl\\fpublic.pem", FileMode.Open);

                var cert = new FileToSend()
                {
                    Content  = stream,
                    Filename = "felix"
                };
                client.SetWebhookAsync("https://cloundwin.westeurope.cloudapp.azure.com/api/webhooks/update", cert).Wait();
                client.StartReceiving();

                var message = new Message()
                {
                };
            }
            catch (Exception e)
            {
                throw;
            }
        }
Esempio n. 19
0
        static void Main()
        {
            bot = new Telegram.Bot.TelegramBotClient("723889901:AAFSFuCmJI62q876qMXOnrZxjGssu6EhI00");

            // загрузка базы курьеров
            Courier.Load();
            Console.WriteLine("База загружена");

            // события TelegramAPI и их обработчики
            bot.OnMessage            += BotOnMessageReceived;
            bot.OnMessageEdited      += BotOnMessageReceived;
            bot.OnCallbackQuery      += BotOnCallbackQueryReceived;
            bot.OnInlineQuery        += BotOnInlineQueryReceived;
            bot.OnInlineResultChosen += BotOnChosenInlineResultReceived;
            bot.OnReceiveError       += BotOnReceiveError;

            bot.StartReceiving(Array.Empty <UpdateType>());


            while (true)
            {
                var input = Console.ReadLine().Trim().ToLower();
                switch (input)
                {
                case "cours":
                    Console.WriteLine(U.StrCol(Environment.NewLine, Courier.Couriers));
                    break;

                case "end":
                case "exit":
                    bot.StopReceiving();
                    return;

                default:
                    break;
                }
            }
        }
Esempio n. 20
0
        static Dictionary <int, string> dict = new Dictionary <int, string>(); //создание словаря

        static void Main(string[] args)
        {
            dict.Add(-1, "Тест"); //добавление к словару по цифре вызова
            dict.Add(0, "Ураган");
            dict.Add(1, "Извержение вулкана");
            dict.Add(2, "Падение метеорита");
            dict.Add(3, "Потоп");
            dict.Add(4, "Нашествие саранчи");
            dict.Add(5, "Землетрясение");

            dict.Remove(-1); //удаление из словаря

            if (dict.TryGetValue(3, out string value))
            {
                Console.WriteLine(value);
            }

            _bot            = new Telegram.Bot.TelegramBotClient("Наш токен от Botfather");
            _bot.OnMessage += _bot_OnMessage;
            _bot.StartReceiving();

            Console.ReadKey();
        }
Esempio n. 21
0
        /// <summary>
        /// "-nopreload" - prevents loading shedules on start
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            JsonData.ReadData();


            KeyboardInit();
            WeekInitPlanned();
            TeachersInit();
            GradeInit();
            if (!(Environment.GetCommandLineArgs().Length > 1 && Environment.GetCommandLineArgs()[1] == "-nopreload"))
            {
                TeachersShedInit();
                GroupShedListInit();
            }
            GetElectives();


            Scheduler.RunNotifier().GetAwaiter().GetResult();


            BOT = new Telegram.Bot.TelegramBotClient(ReadToken());
            logger.Info("Подключен бот Telegram.");
            BOT.OnMessage += BotOnMessageReceived;
            BOT.StartReceiving(new UpdateType[] { UpdateType.Message });
            logger.Info("Ожидает сообщений...");


            vkBot = new VkBot(ReadTokenVK(), GetGroupUrl());
            vkBot.OnMessageReceived += BotOnMessageReceived;
            logger.Info("Подключен бот VK.");
            vkBot.StartAsync();
            logger.Info("Ожидает сообщений...");


            Console.CancelKeyPress += OnExit;
            _closing.WaitOne();
        }
Esempio n. 22
0
        /// <summary>
        /// "-nopreload" - prevents loading shedules on start
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            using (StreamReader file = File.OpenText("markov.json"))
            {
                JsonSerializer serializer = new JsonSerializer();
                Markov = (NodeChain)serializer.Deserialize(file, typeof(NodeChain));
            }
            //Markov = System.Text.Json.JsonSerializer.Deserialize<NodeChain>(File.ReadAllText("markov.json"));

            Json_Data.ReadData();
            KeyboardInit();


            BOT = new Telegram.Bot.TelegramBotClient(ReadToken());
            logger.Info("Bot connected.");
            BOT.OnMessage += BotOnMessageReceived;

            BOT.StartReceiving(new UpdateType[] { UpdateType.Message });
            //Scheduler.RunNotifier().GetAwaiter().GetResult();
            logger.Info("Waiting for messages...");

            Console.CancelKeyPress += OnExit;
            _closing.WaitOne();
        }
Esempio n. 23
0
        async void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            var worker = sender as BackgroundWorker;
            var key    = e.Argument as String;

            try
            {
                var Bot = new Telegram.Bot.TelegramBotClient(key);
                await Bot.SetWebhookAsync("");

                Bot.OnInlineQuery += async(object si, Telegram.Bot.Args.InlineQueryEventArgs ei) =>
                {
                    var query = ei.InlineQuery.Query;

                    var msg = new Telegram.Bot.Types.InputMessageContents.InputTextMessageContent
                    {
                        ParseMode = Telegram.Bot.Types.Enums.ParseMode.Html,
                    };

                    Telegram.Bot.Types.InlineQueryResults.InlineQueryResult[] results =
                    {
                        new Telegram.Bot.Types.InlineQueryResults.InlineQueryResultArticle
                        {
                        },
                        new Telegram.Bot.Types.InlineQueryResults.InlineQueryResultAudio
                        {
                        },
                        new Telegram.Bot.Types.InlineQueryResults.InlineQueryResultPhoto
                        {
                        },
                        new Telegram.Bot.Types.InlineQueryResults.InlineQueryResultVideo
                        {
                        }
                    };


                    await Bot.AnswerInlineQueryAsync(ei.InlineQuery.Id, results);
                };

                Bot.OnUpdate += async(object su, Telegram.Bot.Args.UpdateEventArgs evu) =>
                {
                    if (evu.Update.CallbackQuery != null || evu.Update.InlineQuery != null)
                    {
                        return;
                    }
                    var update  = evu.Update;
                    var message = update.Message;
                    //пусть будут чрезвычайно длинные строки, мне лень делать что-то умное, ключ апи раздают всем подряд, палить его не боюсь
                    var randomRestaurantUrl =
                        "https://search-maps.yandex.ru/v1/?apikey=0d7404f4-957c-4116-b9a3-efe9fc40fbc7&results=500&text=Куда сходить пообедать баумана казань&lang=ru_RU&type=biz";
                    var buhichUrl = "https://search-maps.yandex.ru/v1/?apikey=0d7404f4-957c-4116-b9a3-efe9fc40fbc7&results=500&text=Куда сходить выпить пива баумана казань&lang=ru_RU&type=biz";
                    if (message == null)
                    {
                        return;
                    }
                    if (message.Type == Telegram.Bot.Types.Enums.MessageType.TextMessage)
                    {
                        if (message.Text == "/кудакушац")
                        {
                            string[] restaurants = { "Арома", "The Woods", "Brownbear", "ТЫ ПИДОР", "Big Butcher Grill", "OmNomNom", "Rock'n'Roll'ы", "Черный ящик", "Wok and Go", "Agafredo", "Твин Пикс", "KFC", "Тринити", "МАКДАК", "Бивень", "Соль", "The Тёлки", "Бинхартс" };
                            //хотел отправлять фотки, но потом стало лень их заливать
                            //string[] restaurantsPhotos = { "AgADAgAD5KkxG-nNgUsmW5IeJEGSBBIySw0ABA_maPNgEFdds1gRAAEC"};
                            //var randomPhoto = restaurantsPhotos[new Random().Next(0, restaurantsPhotos.Length)];
                            var randomCommand = restaurants[new Random().Next(0, restaurants.Length)];
                            //var photos = new Telegram.Bot.Types.FileToSend { FileId = randomPhoto };
                            string outputText = randomCommand + " - это место куда ты сегодня пойдешь обедать";
                            await Bot.SendTextMessageAsync(message.Chat.Id, outputText, replyToMessageId : message.MessageId);

                            //await Bot.SendPhotoAsync(message.Chat.Id, photos, replyToMessageId: message.MessageId);
                        }

                        if (message.Text == "/кудахавать")
                        {
                            await Bot.SendTextMessageAsync(message.Chat.Id, YandexRandomiser.GetRandomSearchResult(randomRestaurantUrl).Result, replyToMessageId : message.MessageId);
                        }

                        if (message.Text == "/кудабухать")
                        {
                            await Bot.SendTextMessageAsync(message.Chat.Id, YandexRandomiser.GetRandomSearchResult(buhichUrl).Result, replyToMessageId : message.MessageId);
                        }
                    }
                };

                // запускаем прием обновлений
                Bot.StartReceiving();
            }
            catch (Telegram.Bot.Exceptions.ApiRequestException ex)
            {
                Console.WriteLine(ex.Message); // если ключ не подошел - пишем об этом в консоль отладки
            }
        }
Esempio n. 24
0
        async void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            var worker = sender as BackgroundWorker;
            var key    = e.Argument as String; // получаем ключ из аргументов

            try
            {
                var Bot = new Telegram.Bot.TelegramBotClient(key); // инициализируем API
                await Bot.SetWebhookAsync("");                     // Обязательно! убираем старую привязку к вебхуку для бота

                // Inlin'ы
                Bot.OnInlineQuery += async(object si, Telegram.Bot.Args.InlineQueryEventArgs ei) =>
                {
                    var query = ei.InlineQuery.Query;

                    var msg = new Telegram.Bot.Types.InputMessageContents.InputTextMessageContent
                    {
                        MessageText = @"Это супер крутой текст статьи
с переносами
и <b>html</b> <i>тегами!</i>",
                        ParseMode   = Telegram.Bot.Types.Enums.ParseMode.Html,
                    };

                    Telegram.Bot.Types.InlineQueryResults.InlineQueryResult[] results =
                    {
                        new Telegram.Bot.Types.InlineQueryResults.InlineQueryResultArticle
                        {
                            Id                  = "1",
                            Title               = "Тестовый тайтл",
                            Description         = "Описание статьи тут",
                            InputMessageContent = msg,
                        },
                        new Telegram.Bot.Types.InlineQueryResults.InlineQueryResultAudio
                        {
                            Url    = "http://aftamat4ik.ru/wp-content/uploads/2017/05/mongol-shuudan_-_kozyr-nash-mandat.mp3",
                            Id     = "2",
                            FileId = "123423433",
                            Title  = "Монгол Шуудан - Козырь наш Мандат!",
                        },
                        new Telegram.Bot.Types.InlineQueryResults.InlineQueryResultPhoto
                        {
                            Id          = "3",
                            Url         = "http://aftamat4ik.ru/wp-content/uploads/2017/05/14277366494961.jpg",
                            ThumbUrl    = "http://aftamat4ik.ru/wp-content/uploads/2017/05/14277366494961-150x150.jpg",
                            Caption     = "Текст под фоткой",
                            Description = "Описание",
                        },
                        new Telegram.Bot.Types.InlineQueryResults.InlineQueryResultVideo
                        {
                            Id       = "4",
                            Url      = "http://aftamat4ik.ru/wp-content/uploads/2017/05/bb.mp4",
                            ThumbUrl = "http://aftamat4ik.ru/wp-content/uploads/2017/05/joker_5-150x150.jpg",
                            Title    = "демо видеоролика",
                            MimeType = "video/mp4",
                        }
                    };


                    await Bot.AnswerInlineQueryAsync(ei.InlineQuery.Id, results);
                };

                // Callback'и от кнопок
                Bot.OnCallbackQuery += async(object sc, Telegram.Bot.Args.CallbackQueryEventArgs ev) =>
                {
                    var message = ev.CallbackQuery.Message;
                    if (ev.CallbackQuery.Data == "callback1")
                    {
                        await Bot.AnswerCallbackQueryAsync(ev.CallbackQuery.Id, "You hav choosen " + ev.CallbackQuery.Data, true);
                    }
                    else
                    if (ev.CallbackQuery.Data == "callback2")
                    {
                        await Bot.SendTextMessageAsync(message.Chat.Id, "тест", replyToMessageId : message.MessageId);

                        await Bot.AnswerCallbackQueryAsync(ev.CallbackQuery.Id); // отсылаем пустое, чтобы убрать "частики" на кнопке
                    }
                };

                Bot.OnUpdate += async(object su, Telegram.Bot.Args.UpdateEventArgs evu) =>
                {
                    if (evu.Update.CallbackQuery != null || evu.Update.InlineQuery != null)
                    {
                        return;                                                                     // в этом блоке нам келлбэки и инлайны не нужны
                    }
                    var update  = evu.Update;
                    var message = update.Message;
                    if (message == null)
                    {
                        return;
                    }
                    if (message.Type == Telegram.Bot.Types.Enums.MessageType.TextMessage)
                    {
                        if (message.Text == "/hello")
                        {
                            // в ответ на команду /saysomething выводим сообщение
                            await Bot.SendTextMessageAsync(message.Chat.Id, "Ну здарова! Как сам? :)", replyToMessageId : message.MessageId);
                        }
                        if (message.Text == "/help")
                        {
                            string txt = "Сори, я сам тут новенький :)\n /help - помощь\n /hello - поздароваться\n /getimg - получи картинку\n /rbuttons - Reply - кнопки\n /ibuttons - Inline кнопки";
                            // в ответ на команду /saysomething выводим сообщение
                            await Bot.SendTextMessageAsync(message.Chat.Id, txt, replyToMessageId : message.MessageId);
                        }
                        if (message.Text == "/getimg")
                        {
                            // в ответ на команду /getimage выводим картинку
                            await Bot.SendPhotoAsync(message.Chat.Id, "http://aftamat4ik.ru/wp-content/uploads/2017/03/photo_2016-12-13_23-21-07.jpg", "Revolution!");
                        }

                        // inline buttons
                        if (message.Text == "/ibuttons")
                        {
                            var keyboard = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(
                                new Telegram.Bot.Types.InlineKeyboardButton[][]
                            {
                                // First row
                                new [] {
                                    // First column
                                    new Telegram.Bot.Types.InlineKeyboardButton("раз", "callback1"),

                                    // Second column
                                    new Telegram.Bot.Types.InlineKeyboardButton("два", "callback2"),
                                },
                            }
                                );

                            await Bot.SendTextMessageAsync(message.Chat.Id, "Давай накатим, товарищ, по одной!", false, false, 0, keyboard, Telegram.Bot.Types.Enums.ParseMode.Default);
                        }

                        // reply buttons
                        if (message.Text == "/rbuttons")
                        {
                            var keyboard = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup
                            {
                                Keyboard = new[] {
                                    new[]             // row 1
                                    {
                                        new Telegram.Bot.Types.KeyboardButton("Накатим!"),
                                        new Telegram.Bot.Types.KeyboardButton("Рря!")
                                    },
                                },
                                ResizeKeyboard = true
                            };

                            await Bot.SendTextMessageAsync(message.Chat.Id, "Давай накатим, товарищ, мой!", false, false, 0, keyboard, Telegram.Bot.Types.Enums.ParseMode.Default);
                        }
                        // обработка reply кнопок
                        if (message.Text.ToLower() == "накатим!")
                        {
                            await Bot.SendTextMessageAsync(message.Chat.Id, "Ну, за здоровье!", replyToMessageId : message.MessageId);
                        }
                        if (message.Text.ToLower() == "рря!")
                        {
                            await Bot.SendTextMessageAsync(message.Chat.Id, "Ну, за демократию!", replyToMessageId : message.MessageId);
                        }
                    }
                };

                // запускаем прием обновлений
                Bot.StartReceiving();
            }
            catch (Telegram.Bot.Exceptions.ApiRequestException ex)
            {
                Console.WriteLine(ex.Message); // если ключ не подошел - пишем об этом в консоль отладки
            }
        }
Esempio n. 25
0
        static async void DoWork()
        {
            var Bot = new Telegram.Bot.TelegramBotClient("412328897:AAFFYLJ8W1JjRrY5oQk3dwlNE_O4qLynZhA");
            await Bot.SetWebhookAsync("");

            Bot.OnUpdate += async(object su, Telegram.Bot.Args.UpdateEventArgs evu) =>
            {
                if (evu.Update.CallbackQuery != null || evu.Update.InlineQuery != null)
                {
                    return;
                }
                var update  = evu.Update;
                var message = update.Message;
                if (message == null)
                {
                    return;
                }
                if (message.Type == Telegram.Bot.Types.Enums.MessageType.TextMessage)
                {
                    if (message.Text.ToLower() == "/start")
                    {
                        await Bot.SendTextMessageAsync(message.Chat.Id, "Здравствуйте, что вам от меня надо?", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, Keyboard());
                    }
                }
            };

            Bot.OnCallbackQuery += async(object sc, Telegram.Bot.Args.CallbackQueryEventArgs ev) =>
            {
                var message = ev.CallbackQuery.Message;
                if (ev.CallbackQuery.Data == "a")
                {
                    await Bot.SendTextMessageAsync(message.Chat.Id, @"@dvachannel
@mudak
@ftp_dank_memes
@LaQeque
@ruOvsyanochan
@mudaks
                               ");
                }
                else

                if (ev.CallbackQuery.Data == "r")
                {
                    await Bot.SendContactAsync(message.Chat.Id, "+79601206458", "Ostap", "Kit");
                }
                else
                if (ev.CallbackQuery.Data == "b")
                {
                    await Bot.SendTextMessageAsync(message.Chat.Id, "@meduzalive");
                }
                else
                if (ev.CallbackQuery.Data == "d")
                {
                    await Bot.SendTextMessageAsync(message.Chat.Id, "@sticker");
                }

                string[] represent = { "Мож ещё чего?", "Ещё чего надо?", "Что-нибудь ещё?", "Ещё что-нибудь?", "Что то ещё?", "Мож ещё чего ?" };

                await Bot.SendTextMessageAsync(message.Chat.Id, represent[new Random().Next(0, 6)], Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, Keyboard());
            };

            Bot.StartReceiving();
        }
Esempio n. 26
0
        async void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            var worker = sender as BackgroundWorker;
            var key    = e.Argument as String; // получаем ключ из аргументов

            try
            {
                var Bot = new Telegram.Bot.TelegramBotClient(key); // инициализируем API
                await Bot.SetWebhookAsync("");                     // Обязательно! убираем старую привязку к вебхуку для бота

                //TEST

                try
                {
                    Bot.OnUpdate += async(object su, Telegram.Bot.Args.UpdateEventArgs evu) =>
                    {
                        if (evu.Update.CallbackQuery != null || evu.Update.InlineQuery != null)
                        {
                            return;                                                                     // в этом блоке нам келлбэки и инлайны не нужны
                        }
                        var update  = evu.Update;
                        var message = update.Message;

                        string txt = Properties.Settings.Default.solo;
                        if (message == null)
                        {
                            return;
                        }

                        if (message.Type == Telegram.Bot.Types.Enums.MessageType.Text)
                        {
                            var chtid    = message.Chat.Id;
                            int chtidi   = (int)chtid;
                            var username = message.From.Username;
                            var name     = message.From.FirstName;
                            var surname  = message.From.LastName;
                            var chatname = message.Chat.Title;

                            InputOnlineFile vzhuh     = new InputOnlineFile("CAADAgADKwADCpgGDM8eYp6xnBJwAg");
                            InputOnlineFile stick     = new InputOnlineFile("CAADAgADjAAD2kJgEdHmJbf9LcNAAg");
                            InputOnlineFile kickstick = new InputOnlineFile("CAADAgADFwADCpgGDPT5dlQ90N3vAg");
                            InputOnlineFile gogo      = new InputOnlineFile("CAADAgADIgADCpgGDP2DujSOYxb2Ag");
                            InputOnlineFile stb_1     = new InputOnlineFile("CAADAgADKAADCpgGDAlPwj3jog11Ag");
                            InputOnlineFile pipi      = new InputOnlineFile("MEDIA/bolt.jpg");
                            string          offlist   = System.IO.File.ReadAllText("offlist.txt");



                            try
                            {
                                if (message.Text.ToLower().Equals("987"))
                                {
                                    string tempz = Properties.Settings.Default.SettingsKey;
                                    await Bot.SendTextMessageAsync(message.Chat.Id, tempz);

                                    return;
                                }
                                //ВЫЗОВ ИЗ ЧАТА


                                if (message.Text.ToLower().Contains("ридонли"))
                                {
                                    int iserid = message.ReplyToMessage.From.Id;
                                    //string usrid = iserid.ToString();

                                    if (offlist.Contains(username))
                                    {
                                        var      RoS        = message.Text.ToString();
                                        Regex    my_reg     = new Regex(@"\D");
                                        string   out_string = my_reg.Replace(RoS, "");
                                        int      RoTime     = Convert.ToInt32(out_string);
                                        DateTime untilDate  = DateTime.Now.AddMinutes(RoTime);
                                        await Bot.RestrictChatMemberAsync(message.Chat.Id, iserid, untilDate);

                                        await Bot.SendStickerAsync(message.Chat.Id, vzhuh);

                                        await Bot.SendTextMessageAsync(message.Chat.Id, message.ReplyToMessage.From.FirstName + ", поздравляю!  В качестве бонуса, ты получаешь РО на " + RoTime.ToString() + " минут.", replyToMessageId : message.ReplyToMessage.MessageId);

                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                    if (message.From.Id == iserid)
                                    {
                                        var      RoS        = message.Text.ToString();
                                        Regex    my_reg     = new Regex(@"\D");
                                        string   out_string = my_reg.Replace(RoS, "");
                                        int      RoTime     = Convert.ToInt32(out_string);
                                        DateTime untilDate  = DateTime.Now.AddMinutes(RoTime);
                                        await Bot.RestrictChatMemberAsync(message.Chat.Id, iserid, untilDate);

                                        await Bot.SendStickerAsync(message.Chat.Id, vzhuh);

                                        await Bot.SendTextMessageAsync(message.Chat.Id, message.ReplyToMessage.From.FirstName + ", очень жаль, но это было твое решение :(  Ты получаешь РО на " + RoTime.ToString() + " минут.", replyToMessageId : message.ReplyToMessage.MessageId);

                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                    return;
                                }

                                //ДЛЯ ЕВЫ
                                if (message.Text.Contains("Ева, "))
                                {
                                    //В чате Кантины
                                    if (message.Chat.Id.Equals(-1001033483774))
                                    {
                                        List <string> lstT  = new List <string>();
                                        Random        randT = new Random();
                                        var           inxT  = System.IO.File.ReadAllLines(tost);
                                        string[]      str   = new string[1]; // здесь будут храниться n случаные неповторяющиеся строки из inxT
                                        int           k;

                                        for (int i = 0; i < str.Length; i++)
                                        {
                                            while (true)
                                            {
                                                k = randT.Next(inxT.Length);

                                                if (!lstT.Any(x => x.Equals(inxT[k])))
                                                {
                                                    lstT.Add(inxT[k]);

                                                    str[i] = inxT[k];

                                                    break;
                                                }
                                            }
                                        }
                                        //await Bot.SendTextMessageAsync(message.Chat.Id, "Тут этого делать нельзя.");
                                        string lls = string.Join("\r\n", lstT.ToArray());
                                        await Bot.SendTextMessageAsync(message.Chat.Id, "Я просто скажу тост:" + "\r\n" + lls);

                                        return;
                                    }

                                    //Во всех остальных чатах
                                    else
                                    {
                                        string inmess = message.Text.ToLower();
                                        //TEST CHAT ID
                                        System.IO.File.AppendAllText(all_msg, DateTime.Now + " " + chatname + " " + username + " " + name + " " + surname + "\r\n" + message.Text + "\r\n");
                                        string[] readText = System.IO.File.ReadAllLines(logs_path, Encoding.Default);

                                        if (inmess.Contains("hooba") && username.Equals("kanier"))
                                        {
                                            //string last_ten = System.IO.File.ReadAllText("123.txt");
                                            //string n = readText[i];
                                            await Bot.SendTextMessageAsync(message.Chat.Id, System.IO.File.ReadAllText("LOGS/123.txt"));

                                            return;
                                        }
                                        if (inmess.Contains("покажи всё") && username.Equals("kanier"))
                                        {
                                            //string last_ten = System.IO.File.ReadAllText("123.txt");
                                            //string n = readText[i];
                                            await Bot.SendTextMessageAsync(message.Chat.Id, System.IO.File.ReadAllText(logs_path));

                                            return;
                                        }
                                        if (inmess.Contains("срейд"))
                                        {
                                            string srtext = System.IO.File.ReadAllText(sreid_path);
                                            //await Bot.SendTextMessageAsync(message.Chat.Id, "[Тестовая ссылка из бота](https://t.me/iv?url=https%3A%2F%2Fyavin4.ru%2Fother%2Fthe-sith-triumvirate%2F&rhash=a6a7d09d8d0768)");
                                            await Bot.SendTextMessageAsync(message.Chat.Id, "Я просто оставлю это здесь...\n" + srtext);

                                            return;
                                        }
                                        if (inmess.Contains("взвод"))
                                        {
                                            await Bot.SendTextMessageAsync(message.Chat.Id, "https://yavin4.ru/other/tb-platoons/" + "\r\n" + "^^^^^^^^^^^^^^^^^^^^^^^^" + "\r\n" + "https://t.me/iv?url=https://yavin4.ru/other/tb-platoons/&rhash=a6a7d09d8d0768");

                                            return;
                                        }

                                        if (inmess.Contains("экстерминатус") && username.Equals("kanier") || inmess.Contains("экстерминатус") && username.Equals("vlad_o_v"))
                                        {
                                            InputOnlineFile stream = new InputOnlineFile("MEDIA/flu.mp4");
                                            //InputOnlineFile  fts = new InputOnlineFile(stream);

                                            //Stream stream_flu = null;
                                            //fts.Content = stream;
                                            stream.FileName = "FLU";

                                            //ТЕСТОВЫЙ КУСОК
                                            DateTime old_ticker_dt = Properties.Settings.Default.ticker_start;
                                            DateTime now_ticker_dt = DateTime.Now;
                                            TimeSpan alltime       = Properties.Settings.Default.best_try;
                                            TimeSpan nowalltime    = now_ticker_dt - old_ticker_dt;
                                            if (nowalltime > alltime)
                                            {
                                                Properties.Settings.Default.best_try = nowalltime;
                                                Properties.Settings.Default.Save();
                                            }
                                            else
                                            {
                                                Properties.Settings.Default.best_try = alltime;
                                                Properties.Settings.Default.Save();
                                            }


                                            ///Запомнить===>>//DateTime rec_time = Properties.Settings.Default.ticker_start;
                                            DateTime ticker = DateTime.Now;
                                            Properties.Settings.Default.ticker_start = ticker;
                                            Properties.Settings.Default.Save();
                                            string txt_ticker = ticker.ToString();
                                            //await Bot.SendTextMessageAsync(message.Chat.Id, "Мне очень печально это говорить но, ПРИНЕСИТЕ FLUGGEGECHEIMEN!!!", replyToMessageId: message.MessageId);
                                            //await Bot.SendDocumentAsync(message.Chat.Id, stream, "Мне очень печально это говорить но, ПРИНЕСИТЕ FLUGGEGECHEIMEN!!!");
                                            await Bot.SendVideoAsync(message.Chat.Id, stream);

                                            return;
                                        }
                                        if (inmess.Contains("счетчик") || inmess.Contains("счётчик"))
                                        {
                                            string   old_ticker    = Properties.Settings.Default.ticker_start.ToString();
                                            DateTime old_ticker_dt = Properties.Settings.Default.ticker_start;
                                            DateTime now_ticker_dt = DateTime.Now;
                                            TimeSpan alltime       = now_ticker_dt - old_ticker_dt;
                                            //Properties.Settings.Default.best_try = alltime;
                                            //string final_count_full = alltime.ToString();
                                            //string final_count_short = final_count_full.Substring(0, final_count_full.LastIndexOf("."));
                                            //string final_count_wo_days = alltime.ToString("DD:MM:SS");
                                            //await Bot.SendTextMessageAsync(message.Chat.Id, "Новый отсчёт был запущен: " + old_ticker);
                                            await Bot.SendTextMessageAsync(message.Chat.Id, "На Явине всё спокойно уже: " + string.Format("\nДней: {0:%d} \nЧасов: {0:%h} \nМинут: {0:%m} \nСекунд: {0:%s}", alltime) + "\nОтсчёт был запущен: " + old_ticker);

                                            string for_lbl = "На Явине всё спокойно уже: " + string.Format("\nДней: {0:%d} \nЧасов: {0:%h} \nМинут: {0:%m} \nСекунд: {0:%s}", alltime) + "\nОтсчёт был запущен: " + old_ticker;
                                            Properties.Settings.Default.out_txt = for_lbl;
                                            Properties.Settings.Default.Save();
                                            TimeSpan best_try = Properties.Settings.Default.best_try;
                                            await Bot.SendTextMessageAsync(message.Chat.Id, string.Format("Лучшее время: Дней: {0:%d} Часов: {0:%h} Минут: {0:%m} Секунд: {0:%s}", best_try));

                                            //await Bot.SendTextMessageAsync(message.Chat.Id, "Дней: " + final_count_short.Substring(0, final_count_short.LastIndexOf(".")));
                                            return;
                                        }
                                        if (inmess.Contains("обнули 900") && username.Equals("kanier"))
                                        {
                                            Properties.Settings.Default.best_try = new TimeSpan(0, 0, 0, 0);
                                            Properties.Settings.Default.Save();
                                            return;
                                        }

                                        if (inmess.Contains("пришло время"))
                                        {
                                            await Bot.SendStickerAsync(message.Chat.Id, kickstick);

                                            return;
                                        }


                                        if (inmess.Contains("chatid") && username.Equals("kanier"))
                                        {
                                            await Bot.SendTextMessageAsync(message.Chat.Id, chtid.ToString());

                                            return;
                                        }

                                        //TEST MESSAGE TO OTHER CHAT
                                        if (inmess.Contains("отправь") && offlist.Contains(username))
                                        {
                                            if (inmess.Contains("в кантину кота"))
                                            {
                                                await Bot.SendStickerAsync("-1001033483774", vzhuh);

                                                return;
                                            }
                                            if (inmess.Contains("стикер кик"))
                                            {
                                                await Bot.SendStickerAsync("-1001119850321", kickstick);

                                                return;
                                            }
                                            ////Properties.Settings.Default.buffer = inmess;
                                            //string sendinmess = inmess.Replace("Ева, ", "");
                                            //Properties.Settings.Default.buffer = sendinmess;
                                            //Properties.Settings.Default.Save();
                                            //string smess = Properties.Settings.Default.buffer;
                                            await Bot.SendTextMessageAsync("-1001119850321", message.Text.Replace("Ева, отправь ", ""));

                                            return;
                                        }
                                        //if (inmess.Contains("гого")&& offlist.Contains(username))
                                        //   {
                                        //       try
                                        //       {



                                        //           //await Bot.SendDocumentAsync("-1001119850321", fts, "Все на ТБ!!!");
                                        //           await Bot.SendStickerAsync("-1001119850321", gogo);
                                        //           await Bot.SendStickerAsync("-1001121566331 ", gogo);
                                        //           //            //await Bot.SendDocumentAsync(message.Chat.Id, new InputOnlineFile("GP.xlsx"));
                                        //           return;
                                        //       }
                                        //       catch (Exception ex)
                                        //       {
                                        //           System.IO.File.WriteAllText("LOGS/errorall.txt", ex.Message);
                                        //           //await Bot.SendTextMessageAsync(message.Chat.Id, "Что-то не так");
                                        //           return;

                                        //       }


                                        //   }
                                        if (inmess.Contains("привет") || inmess.Contains("как дела") || inmess.Contains("здрав"))
                                        {
                                            await Bot.SendTextMessageAsync(message.Chat.Id, "Привет, " + name + "." + "\r\n" + "Что ты хочешь знать?" + "\r\n" + "Я могу напомнить тебе правила Ямы или ААТ, показать список солистов или памятку по ТБ. Могу напомнить, кто закрывает соло следующую Яму-0. И многое другое ;) Достаточно обратиться ко мне по имени. К примеру: \"Ева, кто закрывает соло?\"", replyToMessageId : message.MessageId);

                                            return;
                                        }
                                        if (inmess.Contains("соло") || inmess.Contains("закрывает"))

                                        {
                                            if (offlist.Contains(username))
                                            {
                                                // в ответ на команду выводим сообщение
                                                await Bot.SendTextMessageAsync(message.Chat.Id, txt);

                                                return;
                                            }
                                            else
                                            {
                                                string ntxt  = Properties.Settings.Default.short_solo;
                                                string wotxt = ntxt.Replace("@", "");
                                                await Bot.SendTextMessageAsync(message.Chat.Id, "Для закрытия следующей Ямы-0, Колесом Фортуны избран " + wotxt + " !");

                                                return;
                                            }
                                        }

                                        //ТЕСТ РИДОНЛИ



                                        if (inmess.Contains("накати") || inmess.Contains("рря") || inmess.Contains("тост"))
                                        {
                                            List <string> lstT  = new List <string>();
                                            Random        randT = new Random();
                                            var           inxT  = System.IO.File.ReadAllLines(tost);
                                            string[]      str   = new string[1]; // здесь будут храниться n случаные неповторяющиеся строки из inxT
                                            int           k;

                                            for (int i = 0; i < str.Length; i++)
                                            {
                                                while (true)
                                                {
                                                    k = randT.Next(inxT.Length);

                                                    if (!lstT.Any(x => x.Equals(inxT[k])))
                                                    {
                                                        lstT.Add(inxT[k]);

                                                        str[i] = inxT[k];

                                                        break;
                                                    }
                                                }
                                            }

                                            string lls = string.Join("\r\n", lstT.ToArray());

                                            await Bot.SendTextMessageAsync(message.Chat.Id, lls);

                                            return;
                                        }

                                        if (inmess.Contains("стб"))
                                        {
                                            string          f1text  = System.IO.File.ReadAllText("TEXT/STB/f1.txt");
                                            string          f2text  = System.IO.File.ReadAllText("TEXT/STB/f2.txt");
                                            string          f3text  = System.IO.File.ReadAllText("TEXT/STB/f3.txt");
                                            string          f4text  = System.IO.File.ReadAllText("TEXT/STB/f4.txt");
                                            string          f5text  = System.IO.File.ReadAllText("TEXT/STB/f5.txt");
                                            string          f6text  = System.IO.File.ReadAllText("TEXT/STB/f6.txt");
                                            var             stream1 = System.IO.File.Open("MEDIA/STB.jpg", FileMode.Open);
                                            InputOnlineFile pipi1   = new InputOnlineFile(stream1)
                                            {
                                                //pipi1.ContentContent = stream1,
                                                //pipi1.FileName = "MEDIA/STB.jpg"
                                            };

                                            if (inmess.Contains("1"))
                                            {
                                                await Bot.SendPhotoAsync(message.Chat.Id, photo : pipi1);

                                                await Bot.SendTextMessageAsync(message.Chat.Id, f1text);

                                                return;
                                            }

                                            if (inmess.Contains("2"))
                                            {
                                                await Bot.SendPhotoAsync(message.Chat.Id, photo : pipi1);

                                                await Bot.SendTextMessageAsync(message.Chat.Id, f2text);

                                                return;
                                            }

                                            if (inmess.Contains("3"))
                                            {
                                                await Bot.SendPhotoAsync(message.Chat.Id, photo : pipi1);

                                                await Bot.SendTextMessageAsync(message.Chat.Id, f3text);

                                                return;
                                            }

                                            if (inmess.Contains("4"))
                                            {
                                                await Bot.SendPhotoAsync(message.Chat.Id, photo : pipi1);

                                                await Bot.SendTextMessageAsync(message.Chat.Id, f4text);

                                                return;
                                            }

                                            if (inmess.Contains("5"))
                                            {
                                                await Bot.SendPhotoAsync(message.Chat.Id, photo : pipi1);

                                                await Bot.SendTextMessageAsync(message.Chat.Id, f5text);

                                                return;
                                            }

                                            if (inmess.Contains("6"))
                                            {
                                                await Bot.SendPhotoAsync(message.Chat.Id, photo : pipi1);

                                                await Bot.SendTextMessageAsync(message.Chat.Id, f6text);

                                                return;
                                            }


                                            string tbfile = System.IO.File.ReadAllText("TEXT/STB/tb.txt");
                                            await Bot.SendTextMessageAsync(message.Chat.Id, tbfile);

                                            return;
                                        }
                                        if (inmess.Contains("ттб"))
                                        {
                                            await Bot.SendTextMessageAsync(message.Chat.Id, "К сожалению, мне пока ничего об этом не известно. Посмотрим, что там нахерачили ЕА.", replyToMessageId : message.MessageId);

                                            return;
                                        }
                                        if (inmess.Contains("прости") || inmess.Contains("извин"))
                                        {
                                            await Bot.SendTextMessageAsync(message.Chat.Id, "Ничего страшного! Но я это запомню...", replyToMessageId : message.MessageId);

                                            return;
                                        }
                                        if (inmess.Contains("ям") || inmess.Contains("ранкор"))
                                        {
                                            List <string> lstR = new List <string>();
                                            var           inxR = System.IO.File.ReadAllLines(rancor_path);
                                            string        llsR = string.Join("\r\n", inxR.ToArray());
                                            await Bot.SendTextMessageAsync(message.Chat.Id, "Я напомню тебе правила)))" + "\r\n" + llsR);

                                            return;
                                        }
                                        if (inmess.Contains("чудо") || inmess.Contains("хорошая") || inmess.Contains("умни") || inmess.Contains("умна") || inmess.Contains("крас"))
                                        {
                                            await Bot.SendTextMessageAsync(message.Chat.Id, "Спасибо, мне очень приятно!");

                                            return;
                                        }
                                        if (inmess.Contains("список"))
                                        {
                                            try
                                            {
                                                List <string> lstL   = new List <string>();
                                                string        lstall = System.IO.File.ReadAllText(solo_path);
                                                string        newlst = lstall.Replace("@", "");
                                                await Bot.SendTextMessageAsync(message.Chat.Id, newlst, replyToMessageId : message.MessageId);

                                                return;
                                            }
                                            catch
                                            {
                                                await Bot.SendTextMessageAsync(message.Chat.Id, "Список солистов пуст. Надо бы обновить.");

                                                return;
                                            }
                                        }
                                        if (inmess.Contains("аат") || inmess.Contains("танк"))
                                        {
                                            List <string> lstR = new List <string>();
                                            var           inxR = System.IO.File.ReadAllLines(aat_path);
                                            string        llsR = string.Join("\r\n", inxR.ToArray());
                                            await Bot.SendTextMessageAsync(message.Chat.Id, llsR, replyToMessageId : message.MessageId);

                                            return;
                                        }

                                        if (inmess.Contains("думаешь"))
                                        {
                                            await Bot.SendTextMessageAsync(message.Chat.Id, name + ", у меня просто нет слов.", replyToMessageId : message.MessageId);

                                            return;
                                        }

                                        if (inmess.Contains("выбери нового солиста"))
                                        {
                                            if (offlist.Contains(username))
                                            {
                                                //var checksolo = System.IO.File.ReadAllLines("solo.txt");
                                                //if (checksolo.Length == 0)
                                                //{
                                                //    MessageBox.Show("Файл пуст!");
                                                //}
                                                string lastsolo = Properties.Settings.Default.short_solo;
                                                var    soloL    = System.IO.File.ReadAllText(solo_path);
                                                var    soloX    = soloL.Replace(lastsolo, "");
                                                //var soloF = soloX.Replace("\n\n", "\n");
                                                //var lines = System.IO.File.ReadAllLines("solo.txt");
                                                //string[] linesX = lines.re
                                                //System.IO.File.WriteAllLines("solo.txt", lines);
                                                //MessageBox.Show(lastsolo);
                                                //MessageBox.Show(soloF);
                                                System.IO.File.WriteAllText(solo_path, soloX);

                                                string fileName       = solo_path;
                                                string outputFileName = "TEXT/solotemp.txt";
                                                string inputLine;

                                                System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
                                                System.IO.StreamWriter sw = new System.IO.StreamWriter(outputFileName);

                                                inputLine = sr.ReadLine();
                                                while (inputLine != null)
                                                {
                                                    if (inputLine.Length > 0)
                                                    {
                                                        sw.WriteLine(inputLine);
                                                    }
                                                    // read the next line
                                                    inputLine = sr.ReadLine();
                                                }
                                                sr.Close();
                                                sw.Close();

                                                var transf = System.IO.File.ReadAllText("TEXT/solotemp.txt");
                                                System.IO.File.WriteAllText(solo_path, transf);
                                                try
                                                {
                                                    List <string> lst = new List <string>();

                                                    Random rand = new Random();

                                                    var inx = System.IO.File.ReadAllLines(solo_path);

                                                    string[] str = new string[1]; // здесь будут храниться n случаные неповторяющиеся строки из inx

                                                    int k;

                                                    for (int i = 0; i < str.Length; i++)
                                                    {
                                                        while (true)
                                                        {
                                                            k = rand.Next(inx.Length);
                                                            if (!lst.Any(x => x.Equals(inx[k])))
                                                            {
                                                                lst.Add(inx[k]);
                                                                str[i] = inx[k];
                                                                break;
                                                            }
                                                        }
                                                    }


                                                    string lls = string.Join("\r\n", lst.ToArray());
                                                    Properties.Settings.Default.short_solo = lls;
                                                    Properties.Settings.Default.solo       = "Для закрытия следующей Ямы-0, Колесом Фортуны избран " + lls + " !";
                                                    Properties.Settings.Default.Save();
                                                    await Bot.SendTextMessageAsync(message.Chat.Id, "В этот раз Фортуна избрала " + lls, replyToMessageId : message.MessageId);

                                                    return;
                                                }
                                                catch
                                                {
                                                    await Bot.SendTextMessageAsync(message.Chat.Id, "Список солистов пуст. Надо бы обновить");

                                                    return;
                                                }
                                            }

                                            else
                                            {
                                                await Bot.SendTextMessageAsync(message.Chat.Id, name + " , мне не говорили, что тебе можно это делать. Извини.", replyToMessageId : message.MessageId);

                                                return;
                                            }
                                        }


                                        if (inmess.Contains("спасибо") || inmess.Contains("благодар"))
                                        {
                                            await Bot.SendTextMessageAsync(message.Chat.Id, name + ", не стоит. Мне было даже немного приятно)))");

                                            return;
                                        }

                                        await Bot.SendTextMessageAsync(message.Chat.Id, name + ", что за ересь? Я не понимаю, что ты имеешь в виду(((");

                                        return;
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                System.IO.File.AppendAllText(logs_path, "\r\n" + DateTime.Now + "\r\n" + ex.Message + "\r\n");
                                return;
                            }

                            try
                            {
                                if (message.Text.Equals("Ева") || message.Text.Equals("/info") || message.Text.Equals("/info@YavinIV_rollbot"))
                                {
                                    await Bot.SendTextMessageAsync(message.Chat.Id, "Слушаю тебя, " + name + "." + "\r\n" + "Что ты хочешь знать?" + "\r\n" + "Я могу напомнить тебе правила Ямы или ААТ, показать список солистов или памятку по ТБ. Могу напомнить, кто закрывает соло следующую Яму-0. И многое другое ;) Достаточно обратиться ко мне по имени. К примеру: \"Ева, кто закрывает соло?\"", replyToMessageId : message.MessageId);

                                    return;
                                }
                            }
                            catch (Exception ex)
                            {
                                System.IO.File.AppendAllText(logs_path, "\r\n" + DateTime.Now + "\r\n" + ex.Message + "\r\n");
                                System.IO.File.WriteAllText("LOGS/123.txt", "\r\n" + DateTime.Now + "\r\n" + ex.Message + "\r\n");
                                return;
                            }
                        }
                    };

                    // запускаем прием обновлений
                    Bot.StartReceiving();
                }
                catch (Telegram.Bot.Exceptions.ApiRequestException ex)
                {
                    System.IO.File.WriteAllText("LOGS/error.log", "\r\n" + DateTime.Now + "\r\n" + ex.Message + "\r\n"); // если ключ не подошел - пишем об этом в консоль отладки
                }
            }
            catch (Exception ex)
            {
                System.IO.File.AppendAllText(logs_path, "\r\n" + DateTime.Now + "\r\n" + ex.Message + "\r\n");
                System.IO.File.WriteAllText("LOGS/123.txt", "\r\n" + DateTime.Now + "\r\n" + ex.Message + "\r\n");
            }
        }
Esempio n. 27
0
 public void setTelegramEvent()
 {
     Bot.OnMessage += Bot_OnMessage; // 이벤트를 추가해줍니다.
     Bot.StartReceiving();           // 이 함수가 실행이 되어야 사용자로부터 메세지를 받을 수 있습니다.
 }
Esempio n. 28
0
        async void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            var worker = sender as BackgroundWorker;

            try
            {
                int admin_id = Convert.ToInt32(admin_textbox.Text);
                var key_bot  = "952377344:AAGav52g97Q7WtvXyXxbMkyexx3Aj7WuV7s";
                var Bot      = new Telegram.Bot.TelegramBotClient(key_bot); // инициализируем API

                try
                {
                    await Bot.SetWebhookAsync(""); // !!!!!!!!!!!!!!!!!!!!!!ЦИКЛ ПЕРЕЗАПУСКА
                }
                catch
                {
                    await Bot.SetWebhookAsync("");
                }


                // Inlin'ы
                Bot.OnInlineQuery += async(object si, Telegram.Bot.Args.InlineQueryEventArgs ei) =>
                {
                    var query = ei.InlineQuery.Query;
                };



                Bot.OnUpdate += async(object su, Telegram.Bot.Args.UpdateEventArgs evu) =>
                {
                    var update  = evu.Update;
                    var message = update.Message;
                    var id_mess = message.MessageId;
                    var id_chat = message.Chat.Id;
                    // 670031730



                    if (message == null)
                    {
                        return;
                    }
                    try
                    {
                        string          connStr    = "server=localhost;user=root;database=tron;password="******";";
                        MySqlConnection connection = new MySqlConnection(connStr);
                        connection.Open();


                        //// получение айди поста из базы Русския

                        string Kryp_win_sql = "SELECT `Post_number` FROM `tron`.`post` WHERE(`idPost` = 1)";
                        string O_nas_sql    = "SELECT `Post_number` FROM `tron`.`post`  WHERE(`idPost` = 2)";
                        string News_sql     = "SELECT `Post_number` FROM `tron`.`post`  WHERE(`idPost` = 3)";
                        string Event_sql    = "SELECT `Post_number` FROM `tron`.`post`  WHERE(`idPost` = 4)";
                        string Social_sql   = "SELECT `Post_number` FROM `tron`.`post`  WHERE(`idPost` = 5)";
                        string Help_sql     = "SELECT `Post_number` FROM `tron`.`post` WHERE(`idPost` = 6)";

                        MySqlCommand Kryp_win_sql_ = new MySqlCommand(Kryp_win_sql, connection);
                        Kryp_win_sql_.ExecuteNonQuery();
                        Kryp_win_rus = Convert.ToInt32(Kryp_win_sql_.ExecuteScalar());

                        MySqlCommand O_nas_sql_ = new MySqlCommand(O_nas_sql, connection);
                        O_nas_sql_.ExecuteNonQuery();
                        O_nas_rus = Convert.ToInt32(O_nas_sql_.ExecuteScalar());

                        MySqlCommand News_sql_ = new MySqlCommand(News_sql, connection);
                        News_sql_.ExecuteNonQuery();
                        News_rus = Convert.ToInt32(News_sql_.ExecuteScalar());

                        MySqlCommand Event_sql_ = new MySqlCommand(Event_sql, connection);
                        Event_sql_.ExecuteNonQuery();
                        Event_rus = Convert.ToInt32(Event_sql_.ExecuteScalar());

                        MySqlCommand Social_sql_ = new MySqlCommand(Social_sql, connection);
                        Social_sql_.ExecuteNonQuery();
                        Social_rus = Convert.ToInt32(Social_sql_.ExecuteScalar());

                        MySqlCommand Help_sql_ = new MySqlCommand(Help_sql, connection);
                        Help_sql_.ExecuteNonQuery();
                        Help_rus = Convert.ToInt32(Help_sql_.ExecuteScalar());

                        /////
                        string Kryp_win_sql_eng = "SELECT `Post_number` FROM `tron`.`post_eng` WHERE(`idPost` = 1)";
                        string O_nas_sql_eng    = "SELECT `Post_number` FROM `tron`.`post_eng`  WHERE(`idPost` = 2)";
                        string News_sql_eng     = "SELECT `Post_number` FROM `tron`.`post_eng`  WHERE(`idPost` = 3)";
                        string Event_sql_eng    = "SELECT `Post_number` FROM `tron`.`post_eng`  WHERE(`idPost` = 4)";
                        string Social_sql_eng   = "SELECT `Post_number` FROM `tron`.`post_eng`  WHERE(`idPost` = 5)";
                        string Help_sql_eng     = "SELECT `Post_number` FROM `tron`.`post_eng` WHERE(`idPost` = 6)";

                        MySqlCommand Kryp_win_sql__eng = new MySqlCommand(Kryp_win_sql_eng, connection);
                        Kryp_win_sql__eng.ExecuteNonQuery();
                        Kryp_win_eng = Convert.ToInt32(Kryp_win_sql__eng.ExecuteScalar());

                        MySqlCommand O_nas_sql__eng = new MySqlCommand(O_nas_sql_eng, connection);
                        O_nas_sql__eng.ExecuteNonQuery();
                        O_nas_eng = Convert.ToInt32(O_nas_sql__eng.ExecuteScalar());

                        MySqlCommand News_sql__eng = new MySqlCommand(News_sql_eng, connection);
                        News_sql__eng.ExecuteNonQuery();
                        News_eng = Convert.ToInt32(News_sql__eng.ExecuteScalar());

                        MySqlCommand Event_sql__eng = new MySqlCommand(Event_sql_eng, connection);
                        Event_sql__eng.ExecuteNonQuery();
                        Event_eng = Convert.ToInt32(Event_sql__eng.ExecuteScalar());

                        MySqlCommand Social_sql__eng = new MySqlCommand(Social_sql_eng, connection);
                        Social_sql__eng.ExecuteNonQuery();
                        Social_eng = Convert.ToInt32(Social_sql__eng.ExecuteScalar());

                        MySqlCommand Help_sql__eng = new MySqlCommand(Help_sql_eng, connection);
                        Help_sql__eng.ExecuteNonQuery();
                        Help_eng = Convert.ToInt32(Help_sql__eng.ExecuteScalar());

                        string name = message.Chat.FirstName;
                        // запрос на добавление в базу языка
                        string language_sql_rus = @"UPDATE `tron`.`telegram`SET`Language` =""RUS"" WHERE (`Chat_id`)=" + message.Chat.Id;
                        string language_sql_eng = @"UPDATE `tron`.`telegram`SET`Language` =""ENG"" WHERE (`Chat_id`)=" + message.Chat.Id;
                        //sql Запрос на ввод данных Id
                        string id_sql = "INSERT INTO `tron`.`telegram`(`Chat_id`)VALUES(" + message.Chat.Id + ")";
                        //проверка наличия записи в бд
                        string id_proverka = "SELECT `Chat_id` FROM `tron`.`telegram` WHERE `Chat_id`=" + message.Chat.Id;
                        //запрос на язык
                        string Language = "SELECT `Language` FROM `tron`.`telegram` WHERE `Chat_id`=" + message.Chat.Id;

                        MySqlCommand Language_sql = new MySqlCommand(Language, connection);
                        Language_sql.ExecuteNonQuery();
                        string s         = Convert.ToString(Language_sql.ExecuteScalar());
                        var    main      = new ReplyKeyboardMarkup();
                        var    key_ru    = new ReplyKeyboardMarkup();
                        var    key_eng   = new ReplyKeyboardMarkup();
                        var    skip      = new ReplyKeyboardMarkup();
                        var    admin     = new ReplyKeyboardMarkup();
                        var    admin_eng = new ReplyKeyboardMarkup();
                        admin.Keyboard =
                            new KeyboardButton[][]
                        {
                            new KeyboardButton[]
                            {
                                new KeyboardButton(button11)
                            },
                            new KeyboardButton[]
                            {
                                new KeyboardButton(button2),
                                new KeyboardButton(button3),
                                new KeyboardButton(button4)
                            },
                            new KeyboardButton[]
                            {
                                new KeyboardButton(button6),
                                new KeyboardButton(button7)
                            },

                            new KeyboardButton[]
                            {
                                new KeyboardButton(@"Отправить оповещение")
                            }
                        };
                        admin.ResizeKeyboard  = true;
                        admin.OneTimeKeyboard = true;



                        admin_eng.Keyboard =
                            new KeyboardButton[][]
                        {
                            new KeyboardButton[]
                            {
                                new KeyboardButton(button1_eng)
                            },
                            new KeyboardButton[]
                            {
                                new KeyboardButton(button2_eng),
                                new KeyboardButton(button3_eng),
                                new KeyboardButton(button4_eng)
                            },
                            new KeyboardButton[]
                            {
                                new KeyboardButton(button6_eng),
                                new KeyboardButton(button7_eng)
                            },

                            new KeyboardButton[]
                            {
                                new KeyboardButton(@"Send message")
                            }
                        };
                        admin_eng.ResizeKeyboard  = true;
                        admin_eng.OneTimeKeyboard = true;



                        key_ru.Keyboard =
                            new KeyboardButton[][]
                        {
                            new KeyboardButton[]
                            {
                                new KeyboardButton(button11)
                            },
                            new KeyboardButton[]
                            {
                                new KeyboardButton(button2),
                                new KeyboardButton(button3),
                                new KeyboardButton(button4)
                            },
                            new KeyboardButton[]
                            {
                                new KeyboardButton(button5),
                                new KeyboardButton(button6),
                                new KeyboardButton(button7)
                            },
                            new KeyboardButton[]
                            {
                                new KeyboardButton(button8)
                            }
                        };
                        key_ru.ResizeKeyboard = true;



                        key_eng.Keyboard =
                            new KeyboardButton[][]
                        {
                            new KeyboardButton[]
                            {
                                new KeyboardButton(button1_eng)
                            },
                            new KeyboardButton[]
                            {
                                new KeyboardButton(button2_eng),
                                new KeyboardButton(button3_eng),
                                new KeyboardButton(button4_eng)
                            },
                            new KeyboardButton[]
                            {
                                new KeyboardButton(button5_eng),
                                new KeyboardButton(button6_eng),
                                new KeyboardButton(button7_eng)
                            },
                            new KeyboardButton[]
                            {
                                new KeyboardButton(button8_eng)
                            }
                        };
                        key_eng.ResizeKeyboard = true;


                        if (message.Text == "/start")
                        {
                            //Sql запрос проверка есть ли пользователь в базе.
                            MySqlCommand command1 = new MySqlCommand(id_proverka, connection);
                            command1.ExecuteNonQuery();
                            if (Convert.ToInt32(command1.ExecuteScalar()) == 0)
                            {
                                MySqlCommand command = new MySqlCommand(id_sql, connection);
                                command.ExecuteNonQuery();
                            }
                            //конец проверки
                            var language = new ReplyKeyboardMarkup();
                            language.Keyboard =
                                new KeyboardButton[][]
                            {
                                new KeyboardButton[]
                                {
                                    new KeyboardButton("🇷🇺 Russian"),
                                    new KeyboardButton("🇬🇧󠁧󠁢󠁥󠁮󠁧󠁿 English")
                                }
                            };
                            language.ResizeKeyboard  = true;
                            language.OneTimeKeyboard = true;
                            await Bot.SendTextMessageAsync(message.Chat.Id, "Hello!", ParseMode.Html, false, true, 0, language);
                        }


                        if (message.From.Id == admin_id)
                        {
                            /*
                             * if (message.Text == "/admin")
                             * {
                             *
                             *
                             *  ///админка
                             *  //
                             *
                             * }
                             */
                            var mes = message.From.Id;



                            if (message.Text == "/eng")
                            {
                                await Bot.SendTextMessageAsync(message.Chat.Id, "Admin", ParseMode.Html, false, true, 0, admin_eng);
                            }
                            if (message.Text == "/rus")
                            {
                                await Bot.SendTextMessageAsync(message.Chat.Id, "Админ", ParseMode.Html, false, true, 0, admin);
                            }
                            if (message.Text == button11)
                            {
                                int          da       = message_id;
                                string       post     = @"UPDATE `tron`.`post` SET `Post_number` = '" + da + "' WHERE(`idPost` = '1')";
                                MySqlCommand command1 = new MySqlCommand(post, connection);
                                command1.ExecuteNonQuery();

                                await Bot.SendTextMessageAsync(message.Chat.Id, "Готово!", ParseMode.Html, false, true, 0, admin);
                            }

                            if (message.Text == button2)
                            {
                                int          da       = message_id;
                                string       post     = @"UPDATE `tron`.`post` SET `Post_number` = '" + da + "' WHERE(`idPost` = '2')";
                                MySqlCommand command1 = new MySqlCommand(post, connection);
                                command1.ExecuteNonQuery();

                                await Bot.SendTextMessageAsync(message.Chat.Id, "Готово!", ParseMode.Html, false, true, 0, admin);
                            }
                            if (message.Text == button3)
                            {
                                int          da       = message_id;
                                string       post     = @"UPDATE `tron`.`post` SET `Post_number` = '" + da + "' WHERE(`idPost` = '3')";
                                MySqlCommand command1 = new MySqlCommand(post, connection);
                                command1.ExecuteNonQuery();
                                await Bot.SendTextMessageAsync(message.Chat.Id, "Готово!", ParseMode.Html, false, true, 0, admin);
                            }
                            if (message.Text == button4)
                            {
                                int          da       = message_id;
                                string       post     = @"UPDATE `tron`.`post` SET `Post_number` = '" + da + "' WHERE(`idPost` = '4')";
                                MySqlCommand command1 = new MySqlCommand(post, connection);
                                command1.ExecuteNonQuery();
                                await Bot.SendTextMessageAsync(message.Chat.Id, "Готово!", ParseMode.Html, false, true, 0, admin);
                            }
                            if (message.Text == button6)
                            {
                                int          da       = message_id;
                                string       post     = @"UPDATE `tron`.`post` SET `Post_number` = '" + da + "' WHERE(`idPost` = '5')";
                                MySqlCommand command1 = new MySqlCommand(post, connection);
                                command1.ExecuteNonQuery();
                                await Bot.SendTextMessageAsync(message.Chat.Id, "Готово!", ParseMode.Html, false, true, 0, admin);
                            }
                            if (message.Text == button7)
                            {
                                int          da       = message_id;
                                string       post     = @"UPDATE `tron`.`post` SET `Post_number` = '" + da + "' WHERE(`idPost` = '6')";
                                MySqlCommand command1 = new MySqlCommand(post, connection);
                                command1.ExecuteNonQuery();
                                await Bot.SendTextMessageAsync(message.Chat.Id, "Готово!", ParseMode.Html, false, true, 0, admin);
                            }



                            if (message.Text == button1_eng)
                            {
                                int          da       = message_id;
                                string       post     = @"UPDATE `tron`.`post_eng` SET `Post_number` = '" + da + "' WHERE(`idPost` = '1')";
                                MySqlCommand command1 = new MySqlCommand(post, connection);
                                command1.ExecuteNonQuery();

                                await Bot.SendTextMessageAsync(message.Chat.Id, "Succes!", ParseMode.Html, false, true, 0, admin_eng);
                            }

                            if (message.Text == button2_eng)
                            {
                                int          da       = message_id;
                                string       post     = @"UPDATE `tron`.`post_eng` SET `Post_number` = '" + da + "' WHERE(`idPost` = '2')";
                                MySqlCommand command1 = new MySqlCommand(post, connection);
                                command1.ExecuteNonQuery();

                                await Bot.SendTextMessageAsync(message.Chat.Id, "Succes!", ParseMode.Html, false, true, 0, admin_eng);
                            }
                            if (message.Text == button3_eng)
                            {
                                int          da       = message_id;
                                string       post     = @"UPDATE `tron`.`post_eng` SET `Post_number` = '" + da + "' WHERE(`idPost` = '3')";
                                MySqlCommand command1 = new MySqlCommand(post, connection);
                                command1.ExecuteNonQuery();
                                await Bot.SendTextMessageAsync(message.Chat.Id, "Succes!", ParseMode.Html, false, true, 0, admin_eng);
                            }
                            if (message.Text == button4_eng)
                            {
                                int          da       = message_id;
                                string       post     = @"UPDATE `tron`.`post_eng` SET `Post_number` = '" + da + "' WHERE(`idPost` = '4')";
                                MySqlCommand command1 = new MySqlCommand(post, connection);
                                command1.ExecuteNonQuery();
                                await Bot.SendTextMessageAsync(message.Chat.Id, "Succes!", ParseMode.Html, false, true, 0, admin_eng);
                            }
                            if (message.Text == button6_eng)
                            {
                                int          da       = message_id;
                                string       post     = @"UPDATE `tron`.`post_eng` SET `Post_number` = '" + da + "' WHERE(`idPost` = '5')";
                                MySqlCommand command1 = new MySqlCommand(post, connection);
                                command1.ExecuteNonQuery();
                                await Bot.SendTextMessageAsync(message.Chat.Id, "Succes!", ParseMode.Html, false, true, 0, admin_eng);
                            }
                            if (message.Text == button7_eng)
                            {
                                int          da       = message_id;
                                string       post     = @"UPDATE `tron`.`post_eng` SET `Post_number` = '" + da + "' WHERE(`idPost` = '6')";
                                MySqlCommand command1 = new MySqlCommand(post, connection);
                                command1.ExecuteNonQuery();
                                await Bot.SendTextMessageAsync(message.Chat.Id, "Succes!", ParseMode.Html, false, true, 0, admin_eng);
                            }



                            if (message.Text == @"Send message")
                            {
                                MySqlCommand  command = new MySqlCommand("SELECT `Chat_id` FROM `tron`.`telegram`  WHERE(`Language` = 'ENG')", connection);
                                List <string> id      = new List <string>();
                                using (MySqlDataReader reader = command.ExecuteReader())
                                {
                                    while (reader.Read())
                                    {
                                        id.Add(reader[0].ToString());
                                    }
                                }
                                for (int i = 0; id.Count >= 0; i++)
                                {
                                    await Bot.SendTextMessageAsync(Convert.ToString(id[i]), message_text, ParseMode.Html, false, true, 0, key_eng);
                                }
                            }
                            if (message.Text == @"Отправить оповещение")
                            {
                                MySqlCommand  command = new MySqlCommand("SELECT `Chat_id` FROM `tron`.`telegram` WHERE(`Language` = 'RUS')", connection);
                                List <string> id      = new List <string>();
                                using (MySqlDataReader reader = command.ExecuteReader())
                                {
                                    while (reader.Read())
                                    {
                                        id.Add(reader[0].ToString());
                                    }
                                }
                                for (int i = 0; id.Count >= 0; i++)
                                {
                                    await Bot.SendTextMessageAsync(Convert.ToString(id[i]), message_text, ParseMode.Html, false, true, 0, key_ru);
                                }
                            }
                            message_text = message.Text;
                            if (message.From.IsBot == true || message.IsForwarded == true || message.ForwardFrom.IsBot == true)
                            {
                                message_id = message.MessageId;
                            }
                        }

                        if (message.Text == "🇷🇺 Russian")
                        {
                            skip.Keyboard =
                                new KeyboardButton[][]
                            {
                                new KeyboardButton[]
                                {
                                    new KeyboardButton("Пропустить")
                                }
                            };
                            skip.ResizeKeyboard  = true;
                            skip.OneTimeKeyboard = true;
                            await Bot.SendTextMessageAsync(message.Chat.Id, "Привет, чтобы продолжить тебе нужно ввести свой TRON (TRX) кошелек.", ParseMode.Html, false, true, 0, skip);

                            MySqlCommand command = new MySqlCommand(language_sql_rus, connection);
                            command.ExecuteNonQuery();
                        }
                        if (message.Text == "🇬🇧󠁧󠁢󠁥󠁮󠁧󠁿 English")
                        {
                            skip.Keyboard =
                                new KeyboardButton[][]
                            {
                                new KeyboardButton[]
                                {
                                    new KeyboardButton("Skip")
                                }
                            }; skip.ResizeKeyboard = true;
                            skip.OneTimeKeyboard   = true;
                            await Bot.SendTextMessageAsync(message.Chat.Id, "Hello, send me your TRON (TRX) wallet.", ParseMode.Html, false, true, 0, skip);

                            MySqlCommand command = new MySqlCommand(language_sql_eng, connection);
                            command.ExecuteNonQuery();
                        }



                        if (s == "RUS")
                        {
                            main.Keyboard =
                                new KeyboardButton[][]
                            {
                                new KeyboardButton[]
                                {
                                    new KeyboardButton(button11)
                                },
                                new KeyboardButton[]
                                {
                                    new KeyboardButton(button2),
                                    new KeyboardButton(button3),
                                    new KeyboardButton(button4)
                                },
                                new KeyboardButton[]
                                {
                                    new KeyboardButton(button5),
                                    new KeyboardButton(button6),
                                    new KeyboardButton(button7)
                                },
                                new KeyboardButton[]
                                {
                                    new KeyboardButton(button8)
                                }
                            };
                            main.ResizeKeyboard = true;
                        }
                        else
                        {
                            skip.Keyboard =
                                new KeyboardButton[][]
                            {
                                new KeyboardButton[]
                                {
                                    new KeyboardButton("Skip")
                                }
                            };

                            main.Keyboard =
                                new KeyboardButton[][]
                            {
                                new KeyboardButton[]
                                {
                                    new KeyboardButton(button1_eng)
                                },
                                new KeyboardButton[]
                                {
                                    new KeyboardButton(button2_eng),
                                    new KeyboardButton(button3_eng),
                                    new KeyboardButton(button4_eng)
                                },
                                new KeyboardButton[]
                                {
                                    new KeyboardButton(button5_eng),
                                    new KeyboardButton(button6_eng),
                                    new KeyboardButton(button7_eng)
                                },
                                new KeyboardButton[]
                                {
                                    new KeyboardButton(button8_eng)
                                }
                            };
                            main.ResizeKeyboard = true;
                        }
                        if (message.Type == Telegram.Bot.Types.Enums.MessageType.Text & message.From.Id != admin_id)
                        {
                            string patertn = @"T+\w{33}";


                            foreach (Match match in Regex.Matches(message.Text, patertn))
                            {
                                //запрос языка

                                if (s == "RUS")
                                {
                                    await Bot.SendTextMessageAsync(message.Chat.Id, "Адресс добавлен в БД", ParseMode.Html, false, true, 0, main);
                                }
                                else
                                {
                                    await Bot.SendTextMessageAsync(message.Chat.Id, "Success", ParseMode.Html, false, true, 0, main);
                                }



                                string da = message.Text;

                                //Добавление trx кошелька
                                string Wallet = @"UPDATE `tron`.`telegram` SET `Wallet` = '" + da + "' WHERE(`Chat_id` = '" + message.Chat.Id + "')";

                                MySqlCommand command = new MySqlCommand(Wallet, connection);
                                command.ExecuteNonQuery();
                            }

                            if (message.Text == @"Пропустить")
                            {
                                await Bot.SendTextMessageAsync(message.Chat.Id, "Добро пожаловать в бота 888TRON!", ParseMode.Html, false, true, 0, main);
                            }
                            if (message.Text == @"Skip")
                            {
                                await Bot.SendTextMessageAsync(message.Chat.Id, "Welcome to the 888TRON bot!", ParseMode.Html, false, true, 0, main);
                            }



                            //// eng
                            ///
                            if (message.Text == button1_eng)
                            {
                                await Bot.ForwardMessageAsync(message.Chat.Id, admin_id, Kryp_win_eng);
                            }
                            if (message.Text == button2_eng)
                            {
                                await Bot.ForwardMessageAsync(message.Chat.Id, admin_id, O_nas_eng);
                            }

                            if (message.Text == button3_eng)
                            {
                                await Bot.ForwardMessageAsync(message.Chat.Id, admin_id, News_eng);
                            }
                            if (message.Text == button4_eng)
                            {
                                await Bot.ForwardMessageAsync(message.Chat.Id, admin_id, Event_eng);
                            }

                            if (message.Text == button6_eng)
                            {
                                await Bot.ForwardMessageAsync(message.Chat.Id, admin_id, Social_eng);
                            }
                            if (message.Text == button7_eng)
                            {
                                await Bot.ForwardMessageAsync(message.Chat.Id, admin_id, Help_eng);
                            }



                            if (message.Text == button11)
                            {
                                await Bot.ForwardMessageAsync(message.Chat.Id, admin_id, Kryp_win_rus);
                            }
                            if (message.Text == button2)
                            {
                                await Bot.ForwardMessageAsync(message.Chat.Id, admin_id, O_nas_rus);
                            }

                            if (message.Text == button3)
                            {
                                await Bot.ForwardMessageAsync(message.Chat.Id, admin_id, News_rus);
                            }
                            if (message.Text == button4)
                            {
                                await Bot.ForwardMessageAsync(message.Chat.Id, admin_id, Event_rus);
                            }

                            if (message.Text == button6)
                            {
                                await Bot.ForwardMessageAsync(message.Chat.Id, admin_id, Social_rus);
                            }
                            if (message.Text == button7)
                            {
                                await Bot.ForwardMessageAsync(message.Chat.Id, admin_id, Help_rus);
                            }

                            if (message.Text == button8)
                            {
                                string lastPrice;
                                string _24change;
                                string high;
                                string full;
                                string low;
                                string volume;

                                string json = @"{""operationName"":null,""variables"":{},""query"":""{\n exchange(id: 12) {\n stats {\n lastPrice\n h24_change\n high\n low\n volume\n    }\n  }\n}\n""}";

                                var httpRequest = (HttpWebRequest)WebRequest.Create("https://trontrade.io/graphql");
                                httpRequest.Method      = "POST";
                                httpRequest.ContentType = "application/json; charset=utf-8";
                                using (var requestStream = httpRequest.GetRequestStream())
                                    using (var writer = new StreamWriter(requestStream))
                                    {
                                        writer.Write(json);
                                    }
                                using (var httpResponse = httpRequest.GetResponse())
                                    using (var responseStream = httpResponse.GetResponseStream())
                                        using (var reader = new StreamReader(responseStream))
                                        {
                                            string response = reader.ReadToEnd();
                                            full = response;
                                        }
                                MatchCollection matchList = Regex.Matches(full, @"([0-9])+?(.[0-9]+)");
                                var             list      = matchList.Cast <Match>().Select(match => match.Value).ToList();



                                lastPrice = Convert.ToString(Convert.ToDouble(list[0]) / 1000000);
                                _24change = Convert.ToString(list[1]);
                                high      = Convert.ToString(Convert.ToDouble(list[2]) / 1000000);
                                low       = Convert.ToString(Convert.ToDouble(list[3]) / 1000000);
                                volume    = Convert.ToString(Convert.ToDouble(list[4]) / 1000000);

                                volume = volume.Substring(0, volume.Length - 4);
                                volume = Convert.ToString(volume);

                                WebRequest send = WebRequest.Create("https://888tron.com/api1/getDividends");
                                send.Method = "POST";

                                string divedent_bad;
                                using (WebResponse result = send.GetResponse())
                                {
                                    StreamReader reader = new StreamReader(result.GetResponseStream());
                                    divedent_bad = reader.ReadToEnd();
                                }
                                string divedent = System.Text.RegularExpressions.Regex.Match(divedent_bad, @"(-)?[0-9]+").Groups[0].Value;

                                divedent = divedent.Substring(0, divedent.Length - 6);
                                double divedent_good = Convert.ToDouble(divedent);
                                divedent = divedent_good.ToString("#,#", CultureInfo.InvariantCulture);

                                // tron888 =date - DateTime.Now;
                                //string time = Convert.ToString(date.Hour + ":" + tron888.Minutes + ":" + tron888.Seconds);
                                await Bot.SendTextMessageAsync(message.Chat.Id, "Доступные Дивиденды: " + divedent + " TRX" + "\nВыплата через: " + Times.Days + ":" + Times.Hours + ":" + Times.Minutes + ":" + Times.Seconds + "\nPrice: " + lastPrice + " TRX (" + _24change + "%)" + "\n24H High: " + high + " TRX" + "\n24H Low: " + low + " TRX" + "\n24H Volume: " + volume + " 888", ParseMode.Html, false, true, 0, main);
                            }

                            if (message.Text == button8_eng)
                            {
                                string lastPrice;
                                string _24change;
                                string high;
                                string full;
                                string low;
                                string volume;

                                string json = @"{""operationName"":null,""variables"":{},""query"":""{\n exchange(id: 12) {\n stats {\n lastPrice\n h24_change\n high\n low\n volume\n    }\n  }\n}\n""}";

                                var httpRequest = (HttpWebRequest)WebRequest.Create("https://trontrade.io/graphql");
                                httpRequest.Method      = "POST";
                                httpRequest.ContentType = "application/json; charset=utf-8";
                                using (var requestStream = httpRequest.GetRequestStream())
                                    using (var writer = new StreamWriter(requestStream))
                                    {
                                        writer.Write(json);
                                    }
                                using (var httpResponse = httpRequest.GetResponse())
                                    using (var responseStream = httpResponse.GetResponseStream())
                                        using (var reader = new StreamReader(responseStream))
                                        {
                                            string response = reader.ReadToEnd();
                                            full = response;
                                        }
                                MatchCollection matchList    = Regex.Matches(full, @"([0-9])+?(.[0-9]+)");
                                var             list         = matchList.Cast <Match>().Select(match => match.Value).ToList();
                                CultureInfo     temp_culture = Thread.CurrentThread.CurrentCulture;
                                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");


                                lastPrice = (Convert.ToDouble(list[0]) / 1000000).ToString();
                                _24change = list[1];
                                high      = ((Convert.ToDouble(list[2]) / 1000000)).ToString();
                                low       = ((Convert.ToDouble(list[3]) / 1000000)).ToString();
                                volume    = ((Convert.ToDouble(list[4]) / 1000000)).ToString();

                                volume = volume.Substring(0, volume.Length - 4);

                                WebRequest send = WebRequest.Create("https://888tron.com/api1/getDividends");
                                send.Method = "POST";

                                string divedent_bad;
                                using (WebResponse result = send.GetResponse())
                                {
                                    StreamReader reader = new StreamReader(result.GetResponseStream());
                                    divedent_bad = reader.ReadToEnd();
                                }
                                string divedent = System.Text.RegularExpressions.Regex.Match(divedent_bad, @"(-)?[0-9]+").Groups[0].Value;

                                divedent = divedent.Substring(0, divedent.Length - 6);
                                double divedent_good = Convert.ToDouble(divedent);
                                string divedent222   = divedent_good.ToString("#,#", CultureInfo.InvariantCulture);


                                // tron888 =date - DateTime.Now;
                                //string time = Convert.ToString(date.Hour + ":" + tron888.Minutes + ":" + tron888.Seconds);
                                await Bot.SendTextMessageAsync(message.Chat.Id, "Available Dividends: " + divedent222 + " TRX" + "\nDividends Countdown: " + Times.Days + ":" + Times.Hours + ":" + Times.Minutes + ":" + Times.Seconds + "\nPrice: " + lastPrice + " TRX (" + _24change + "%)" + "\n24H High: " + high + " TRX" + "\n24H Low: " + low + " TRX" + "\n24H Volume: " + volume + " 888", ParseMode.Html, false, true, 0, main);
                            }

                            if (message.Text == button5_eng)
                            {
                                var button = new InlineKeyboardButton {
                                    Url = "https://t.me/tron888 ", Text = "🇬🇧󠁧󠁢󠁥󠁮󠁧󠁿 English chat"
                                };
                                var markup = new InlineKeyboardMarkup(button);
                                await Bot.SendTextMessageAsync(message.Chat.Id, "Press the button 👇", replyMarkup : markup);
                            }
                            if (message.Text == button5)
                            {
                                var button = new InlineKeyboardButton {
                                    Url = "https://t.me/Tron888rus", Text = "🇷🇺 Русский чат"
                                };
                                var markup = new InlineKeyboardMarkup(button);
                                await Bot.SendTextMessageAsync(message.Chat.Id, "Нажмите на кнопку 👇", replyMarkup : markup);
                            }
                        }
                    }
                    catch
                    {
                    }
                };

                Bot.StartReceiving();

                // запускаем прием обновлений
            }

            catch (Telegram.Bot.Exceptions.ApiRequestException ex)
            {
                Console.WriteLine(ex.Message); // если ключ не подошел - пишем об этом в консоль отладки
            }
        }
Esempio n. 29
0
        async void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            var worker = sender as BackgroundWorker;
            var key    = e.Argument as String; // получаем ключ из аргументов

            try
            {
                var Bot = new Telegram.Bot.TelegramBotClient(key); // инициализируем API

                try
                {
                    await Bot.SetWebhookAsync(""); // !!!!!!!!!!!!!!!!!!!!!!ЦИКЛ ПЕРЕЗАПУСКА
                }
                catch
                {
                    await Bot.SetWebhookAsync("");
                }


                // Inlin'ы
                Bot.OnInlineQuery += async(object si, Telegram.Bot.Args.InlineQueryEventArgs ei) =>
                {
                    var query = ei.InlineQuery.Query;
                };

                Bot.OnCallbackQuery += async(object sc, Telegram.Bot.Args.CallbackQueryEventArgs ev) =>
                {
                    var message = ev.CallbackQuery.Message;
                    if (ev.CallbackQuery.Data == "CallDaily")
                    {
                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                        await Bot.SendTextMessageAsync(message.Chat.Id, "CallDaily", ParseMode.Html, false, false, 0, null);
                    }

                    if (ev.CallbackQuery.Data == "PutDaily")
                    {
                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                        await Bot.SendTextMessageAsync(message.Chat.Id, "PutDaily", ParseMode.Html, false, false, 0, null);
                    }

                    if (ev.CallbackQuery.Data == "Call6Hr")
                    {
                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                        await Bot.SendTextMessageAsync(message.Chat.Id, "Call6Hr", ParseMode.Html, false, false, 0, null);
                    }

                    if (ev.CallbackQuery.Data == "Put6Hr")
                    {
                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                        await Bot.SendTextMessageAsync(message.Chat.Id, "Put6Hr", ParseMode.Html, false, false, 0, null);
                    }
                };

                Bot.OnUpdate += async(object su, Telegram.Bot.Args.UpdateEventArgs evu) =>
                {
                    try
                    {
                        var update  = evu.Update;
                        var message = update.Message;
                        if (message == null)
                        {
                            return;
                        }



                        if (message.Type == Telegram.Bot.Types.Enums.MessageType.Text)
                        {
                            for (; ;)
                            {
                                TronScan.tronscan();
                                for (int i = 0; i < TronScan.message.Count; i++)
                                {
                                    await Bot.SendTextMessageAsync(message.Chat.Id = 460657014, TronScan.message[i], ParseMode.Html, false, false, 0, null);
                                }
                                Thread.Sleep(60000);
                            }



                            if (message.Text == "/price_option@TestTestTestTestTest111_bot")
                            {
                                try
                                {
                                    var inlineMainKeyboard = new InlineKeyboardMarkup(new[]
                                    {
                                        new []
                                        {
                                            new InlineKeyboardButton  {
                                                Text = "Call Daily Options ", CallbackData = "CallDaily"
                                            },

                                            new   InlineKeyboardButton {
                                                Text = "Put Daily Options ", CallbackData = "PutDaily"
                                            }
                                        },
                                        new []
                                        {
                                            new InlineKeyboardButton  {
                                                Text = "Call 6Hr Daily Options ", CallbackData = "Call6Hr"
                                            },

                                            new   InlineKeyboardButton {
                                                Text = "Put 6Hr Daily Options ", CallbackData = "Put6Hr"
                                            }
                                        }
                                    });


                                    string Current_price, Exercise_Price, Change, Potential, Contracts;
                                    await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                    await Bot.SendTextMessageAsync(message.Chat.Id, "<b>Цена на опционы!</b>", ParseMode.Html, false, false, 0, inlineMainKeyboard);
                                }
                                catch
                                {
                                }
                            }
                        }



                        if (message.Type == MessageType.ChatMemberLeft)
                        {
                            try
                            {
                                await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);
                            }
                            catch
                            {
                            }
                            return;
                        }
                        if (Data.HI == 1 & message.Type == MessageType.ChatMembersAdded)
                        {
                            try
                            {
                                await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);
                            }
                            catch
                            {
                            }
                            return;
                        }
                        if (message.Text == "/stop_hello_func@TestTestTestTestTest111_bot")
                        {
                            try
                            {
                                Data.HI = 1;
                            }


                            catch
                            {
                            }
                        }
                        if (message.Text == "/start_hello_func@TestTestTestTestTest111_bot")
                        {
                            try
                            {
                                Data.HI = 0;
                            }


                            catch
                            {
                            }
                        }

                        if (Data.HI == 0 & message.Type == MessageType.ChatMembersAdded)
                        {
                            try
                            {
                                var inlineKeyboardMarkup = new InlineKeyboardMarkup(new[]
                                {
                                    new  [] { new InlineKeyboardButton {
                                                  Text = "Скачать мобильное приложение!", CallbackData = "demo", Url = "https://medium.com/@abcc.com/our-mobile-app-is-ready-41fdd6663869 "
                                              } }
                                });
                                if (Hi.one == null)
                                {
                                    if (update.Message.From.Username != null)
                                    {
                                        string one = update.Message.From.Username;
                                        Hi.one = "@" + one;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                    else
                                    {
                                        string one = update.Message.From.FirstName + " " + update.Message.From.LastName;
                                        Hi.one = one;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                }

                                if (Hi.two == null)
                                {
                                    if (update.Message.From.Username != null)
                                    {
                                        string two = update.Message.From.Username;
                                        Hi.two = "@" + two;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                    else
                                    {
                                        string two = update.Message.From.FirstName + " " + update.Message.From.LastName;
                                        Hi.two = two;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                }
                                if (Hi.three == null)
                                {
                                    if (update.Message.From.Username != null)
                                    {
                                        string three = update.Message.From.Username;
                                        Hi.three = "@" + three;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                    else
                                    {
                                        string three = update.Message.From.FirstName + " " + update.Message.From.LastName;
                                        Hi.three = three;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                }
                                if (Hi.four == null)
                                {
                                    if (update.Message.From.Username != null)
                                    {
                                        string four = update.Message.From.Username;
                                        Hi.four = "@" + four;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                    else
                                    {
                                        string four = update.Message.From.FirstName + " " + update.Message.From.LastName;
                                        Hi.four = four;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                }
                                if (Hi.five == null)
                                {
                                    if (update.Message.From.Username != null)
                                    {
                                        string five = update.Message.From.Username;
                                        Hi.five = "@" + five;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                    else
                                    {
                                        string five = update.Message.From.FirstName + " " + update.Message.From.LastName;
                                        Hi.five = five;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                }
                                if (Hi.six == null)
                                {
                                    if (update.Message.From.Username != null)
                                    {
                                        string six = update.Message.From.Username;
                                        Hi.six = "@" + six;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                    else
                                    {
                                        string six = update.Message.From.FirstName + " " + update.Message.From.LastName;
                                        Hi.six = six;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                }
                                if (Hi.seven == null)
                                {
                                    if (update.Message.From.Username != null)
                                    {
                                        string seven = update.Message.From.Username;
                                        Hi.seven = "@" + seven;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                    else
                                    {
                                        string seven = update.Message.From.FirstName + " " + update.Message.From.LastName;
                                        Hi.seven = seven;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                }
                                if (Hi.eight == null)
                                {
                                    if (update.Message.From.Username != null)
                                    {
                                        string eight = update.Message.From.Username;
                                        Hi.eight = "@" + eight;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                    else
                                    {
                                        string eight = update.Message.From.FirstName + " " + update.Message.From.LastName;
                                        Hi.eight = eight;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                }
                                if (Hi.nine == null)
                                {
                                    if (update.Message.From.Username != null)
                                    {
                                        string nine = update.Message.From.Username;
                                        Hi.nine = "@" + nine;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                    else
                                    {
                                        string nine = update.Message.From.FirstName + " " + update.Message.From.LastName;
                                        Hi.nine = nine;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                }
                                if (Hi.ten == null)
                                {
                                    if (update.Message.From.Username != null)
                                    {
                                        string ten = update.Message.From.Username;
                                        Hi.ten = "@" + ten;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                    else
                                    {
                                        string ten = update.Message.From.FirstName + " " + update.Message.From.LastName;
                                        Hi.ten = ten;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                }
                                if (Hi.H11 == null)
                                {
                                    if (update.Message.From.Username != null)
                                    {
                                        string H11 = update.Message.From.Username;
                                        Hi.H11 = "@" + H11;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                    else
                                    {
                                        string H11 = update.Message.From.FirstName + " " + update.Message.From.LastName;
                                        Hi.H11 = H11;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                }
                                if (Hi.H12 == null)
                                {
                                    if (update.Message.From.Username != null)
                                    {
                                        string H12 = update.Message.From.Username;
                                        Hi.H12 = "@" + H12;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                    else
                                    {
                                        string H12 = update.Message.From.FirstName + " " + update.Message.From.LastName;
                                        Hi.H12 = H12;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                }
                                if (Hi.H13 == null)
                                {
                                    if (update.Message.From.Username != null)
                                    {
                                        string H13 = update.Message.From.Username;
                                        Hi.H13 = "@" + H13;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                    else
                                    {
                                        string H13 = update.Message.From.FirstName + " " + update.Message.From.LastName;
                                        Hi.H13 = H13;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                }
                                if (Hi.H14 == null)
                                {
                                    if (update.Message.From.Username != null)
                                    {
                                        string H14 = update.Message.From.Username;
                                        Hi.H14 = "@" + H14;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                    else
                                    {
                                        string H14 = update.Message.From.FirstName + " " + update.Message.From.LastName;
                                        Hi.H14 = H14;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                }
                                if (Hi.H15 == null)
                                {
                                    if (update.Message.From.Username != null)
                                    {
                                        string H15 = update.Message.From.Username;
                                        Hi.H15 = "@" + H15;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                    else
                                    {
                                        string H15 = update.Message.From.FirstName + " " + update.Message.From.LastName;
                                        Hi.H15 = H15;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                }
                                if (Hi.H16 == null)
                                {
                                    if (update.Message.From.Username != null)
                                    {
                                        string H16 = update.Message.From.Username;
                                        Hi.H16 = "@" + H16;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                    else
                                    {
                                        string H16 = update.Message.From.FirstName + " " + update.Message.From.LastName;
                                        Hi.H16 = H16;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                }
                                if (Hi.H17 == null)
                                {
                                    if (update.Message.From.Username != null)
                                    {
                                        string H17 = update.Message.From.Username;
                                        Hi.H17 = "@" + H17;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                    else
                                    {
                                        string H17 = update.Message.From.FirstName + " " + update.Message.From.LastName;
                                        Hi.H17 = H17;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                }
                                if (Hi.H17 == null)
                                {
                                    if (update.Message.From.Username != null)
                                    {
                                        string H17 = update.Message.From.Username;
                                        Hi.H17 = "@" + H17;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                    else
                                    {
                                        string H17 = update.Message.From.FirstName + " " + update.Message.From.LastName;
                                        Hi.H17 = H17;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                }
                                if (Hi.H18 == null)
                                {
                                    if (update.Message.From.Username != null)
                                    {
                                        string H18 = update.Message.From.Username;
                                        Hi.H18 = "@" + H18;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                    else
                                    {
                                        string H18 = update.Message.From.FirstName + " " + update.Message.From.LastName;
                                        Hi.H18 = H18;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                }
                                if (Hi.H19 == null)
                                {
                                    if (update.Message.From.Username != null)
                                    {
                                        string H19 = update.Message.From.Username;
                                        Hi.H19 = "@" + H19;

                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                    else
                                    {
                                        string H19 = update.Message.From.FirstName + " " + update.Message.From.LastName;
                                        Hi.H19 = H19;

                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        return;
                                    }
                                }
                                if (Hi.H20 == null)
                                {
                                    if (update.Message.From.Username != null)
                                    {
                                        string H20 = update.Message.From.Username;
                                        Hi.H20 = "@" + H20;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        await Bot.SendTextMessageAsync(message.Chat.Id, $"{Hi.one + ", " + Hi.two + ", " + Hi.three + ", " + Hi.four + ", " + Hi.five + ", " + Hi.six + ", " + Hi.seven + ", " + Hi.eight + ", " + Hi.nine + ", " + Hi.ten + ", " + Hi.H11 + ", " + Hi.H12 + ", " + Hi.H13 + ", " + Hi.H14 + ", " + Hi.H15 + ", " + Hi.H16 + ", " + Hi.H17 + ", " + Hi.H18 + ", " + Hi.H19 + ", " + Hi.H20  } \n<b>Добро пожаловать в наш уютный чат ABCC СНГ \nМы всегда рады тебе в нашем чате!😉\n" + "Воспользуйся нашим ботом</b> @TestTestTestTestTest111_bot <b>с множеством полезных команд!\n</b><b>Последний блок</b> /last_block@TestTestTestTestTest111_bot \n<b>Цена АТ</b> /at_usdt@TestTestTestTestTest111_bot \n<b>Цена BTC</b> /btc_usdt@TestTestTestTestTest111_bot \n<b>Цена ETH</b> /eth_usdt@TestTestTestTestTest111_bot \n<b>А также множество других команд! Нажми / и действуй!</b> \n<b>Обучающий ролик!</b>" + "\n" + @" <a href=""https://www.youtube.com/watch?v=shzrEeLKZWU"">📈📈📈</a>", ParseMode.Html, false, false, 0, inlineKeyboardMarkup);

                                        //https://www.youtube.com/watch?v=shzrEeLKZWU&t=1s
                                        Hi.one   = null;
                                        Hi.two   = null;
                                        Hi.three = null;
                                        Hi.four  = null;
                                        Hi.five  = null;
                                        Hi.six   = null;
                                        Hi.seven = null;
                                        Hi.eight = null;
                                        Hi.nine  = null;
                                        Hi.ten   = null;
                                        Hi.H11   = null;
                                        Hi.H12   = null;
                                        Hi.H13   = null;
                                        Hi.H14   = null;
                                        Hi.H15   = null;
                                        Hi.H16   = null;
                                        Hi.H17   = null;
                                        Hi.H18   = null;
                                        Hi.H19   = null;
                                        Hi.H20   = null;

                                        return;
                                    }
                                    else
                                    {
                                        string H20 = update.Message.From.FirstName + " " + update.Message.From.LastName;
                                        Hi.H20 = H20;
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        await Bot.SendTextMessageAsync(message.Chat.Id, $"{Hi.one + ", " + Hi.two + ", " + Hi.three + ", " + Hi.four + ", " + Hi.five + ", " + Hi.six + ", " + Hi.seven + ", " + Hi.eight + ", " + Hi.nine + ", " + Hi.ten + ", " + Hi.H11 + ", " + Hi.H12 + ", " + Hi.H13 + ", " + Hi.H14 + ", " + Hi.H15 + ", " + Hi.H16 + ", " + Hi.H17 + ", " + Hi.H18 + ", " + Hi.H19 + ", " + Hi.H20  } \n<b>Добро пожаловать в наш уютный чат ABCC СНГ \nМы всегда рады тебе в нашем чате!😉\n" + "Воспользуйся нашим ботом</b> @TestTestTestTestTest111_bot <b>с множеством полезных команд!\n</b><b>Последний блок</b> /last_block@TestTestTestTestTest111_bot \n<b>Цена АТ</b> /at_usdt@TestTestTestTestTest111_bot \n<b>Цена BTC</b> /btc_usdt@TestTestTestTestTest111_bot \n<b>Цена ETH</b> /eth_usdt@TestTestTestTestTest111_bot \n<b>А также множество других команд! Нажми / и действуй!</b> \n<b>Обучающий ролик!</b>" + "\n" + @" <a href=""https://www.youtube.com/watch?v=shzrEeLKZWU"">!</a>", ParseMode.Html, false, false, 0, inlineKeyboardMarkup);

                                        Hi.one   = null;
                                        Hi.two   = null;
                                        Hi.three = null;
                                        Hi.four  = null;
                                        Hi.five  = null;
                                        Hi.six   = null;
                                        Hi.seven = null;
                                        Hi.eight = null;
                                        Hi.nine  = null;
                                        Hi.ten   = null;
                                        Hi.H11   = null;
                                        Hi.H12   = null;
                                        Hi.H13   = null;
                                        Hi.H14   = null;
                                        Hi.H15   = null;
                                        Hi.H16   = null;
                                        Hi.H17   = null;
                                        Hi.H18   = null;
                                        Hi.H19   = null;
                                        Hi.H20   = null;

                                        return;
                                    }
                                }
                                return;
                            }
                            catch
                            {
                            }
                        }

                        var entities = message.Entities.Where(t => t.Type == MessageEntityType.Url ||
                                                              t.Type == MessageEntityType.Mention);
                        foreach (var entity in entities)
                        {
                            if (entity.Type == MessageEntityType.Url)
                            {
                                try
                                {
                                    //40103694 - @off_fov
                                    //571522545 -  @ProAggressive
                                    //320968789 - @timcheg1
                                    //273228404 - @hydranik
                                    //435567580 - Никита
                                    //352345393 - @i_am_zaytsev
                                    //430153320 - @KingOfMlnD
                                    //579784 - @kamiyar
                                    //536915847 - @m1Bean
                                    //460657014 - @DenisSenatorov

                                    if (message.From.Username == @"off_fov" || message.From.Username == @"LindaMao" || message.From.Username == @"XiniW" || message.From.Username == @"ProAggressive" || message.From.Username == @"timcheg1" || message.From.Username == @"hydranik" || message.From.Username == @"i_am_zaytsev" || message.From.Username == @"KingOfMlnD" || message.From.Username == @"kamiyar" || message.From.Username == @"m1Bean" || message.From.Username == @"DenisSenatorov" || message.From.Id == 435567580)
                                    {
                                        return;
                                    }
                                    else
                                    {
                                        await Bot.DeleteMessageAsync(message.Chat.Id, message.MessageId);

                                        if (update.Message.From.Username != null)
                                        {
                                            await Bot.SendTextMessageAsync(message.Chat.Id, "@" + message.From.Username + ", Ссылки запрещены!");

                                            return;
                                        }
                                        else
                                        {
                                            await Bot.SendTextMessageAsync(message.Chat.Id, message.From.FirstName + ", Ссылки запрещены!");

                                            return;
                                        }
                                    }
                                }
                                catch
                                {
                                }
                                return;
                            }
                        }
                    }
                    catch
                    {
                    }
                };

                Bot.StartReceiving();

                // запускаем прием обновлений
            }

            catch (Telegram.Bot.Exceptions.ApiRequestException ex)
            {
                Console.WriteLine(ex.Message); // если ключ не подошел - пишем об этом в консоль отладки
            }
        }
Esempio n. 30
0
        async void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            var    worker = sender as BackgroundWorker;
            string key    = "622335668:AAEv62L9dRi4BH6JVyW8gfEg-tCmd-qTRXo";

            try
            {
                var Bot = new Telegram.Bot.TelegramBotClient(key);
                await Bot.SetWebhookAsync("");

                // Callback'и от кнопок
                Bot.OnCallbackQuery += async(object sc, Telegram.Bot.Args.CallbackQueryEventArgs ev) =>
                {
                    var message = ev.CallbackQuery.Message;
                    if (ev.CallbackQuery.Data == "callback0")
                    {
                        await Bot.AnswerCallbackQueryAsync(ev.CallbackQuery.Id, "You hav choosen " + ev.CallbackQuery.Data, true);
                    }

                    else if (ev.CallbackQuery.Data.Contains("correctAnswer"))
                    {
                        await Bot.SendTextMessageAsync(message.Chat.Id, "Вірно!", replyToMessageId : message.MessageId);

                        await Bot.AnswerCallbackQueryAsync(ev.CallbackQuery.Id);                        // видаляє очікування (годинник)

                        GetQuestion(Bot, ev, message);
                        string tCountry = ev.CallbackQuery.Data.Replace("correctAnswer", "");
                        BotAs.RightAnswer(tCountry);
                    }

                    else if (ev.CallbackQuery.Data == "wrongAnswer")
                    {
                        await Bot.SendTextMessageAsync(message.Chat.Id, "Емм..Ні. Йдем далі...", replyToMessageId : message.MessageId);

                        await Bot.AnswerCallbackQueryAsync(ev.CallbackQuery.Id);                        // видаляє очікування (годинник)

                        GetQuestion(Bot, ev, message);
                        BotAs.WrongAnswer();
                    }

                    else
                    if (ev.CallbackQuery.Data.Contains("Continent:"))
                    {
                        string tContinent = ev.CallbackQuery.Data.Replace("Continent:", "");
                        await Bot.SendTextMessageAsync(message.Chat.Id, "Хмм, сміливо!", replyToMessageId : message.MessageId);

                        BotAs.ChooseContinent(tContinent);
                        GetQuestion(Bot, ev, message);
                    }
                };

                Bot.OnUpdate += async(object su, Telegram.Bot.Args.UpdateEventArgs evu) =>
                {
                    if (evu.Update.CallbackQuery != null || evu.Update.InlineQuery != null)
                    {
                        return;
                    }
                    var update  = evu.Update;
                    var message = update.Message;
                    if (message == null)
                    {
                        return;
                    }
                    if (message.Type == Telegram.Bot.Types.Enums.MessageType.Text)
                    {
                        if (message.Text == "/hello")
                        {
                            await Bot.SendTextMessageAsync(message.Chat.Id, "Хелова", replyToMessageId : message.MessageId);
                        }
                        if (message.Text == "/getimage")
                        {
                            await Bot.SendPhotoAsync(message.Chat.Id, "https://static.365info.kz/uploads/2019/03/a346a3729504594579883eeb12a38d80.jpg", "Та й таке!");
                        }

                        if (message.Text == "/stopgame")
                        {
                            await Bot.SendTextMessageAsync(message.Chat.Id, "Гру завершено! Правильних: " + BotAs.RightAnswers + " з " + (BotAs.WrongAnswers + BotAs.RightAnswers), replyToMessageId : message.MessageId);

                            BotAs.OverGame();
                        }

                        if (message.Text == "/capitals")
                        {
                            BotAs.StartGame();
                            List <string> continents = BotAs.GetContinents();
                            continents.Add("Все");

                            Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton[] Keys = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton[continents.Count];

                            int i = 0;

                            foreach (string continent in continents)
                            {
                                Keys[i] = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton {
                                    Text = continent, CallbackData = "Continent:" + continent
                                };
                                i++;
                            }

                            var keyboard = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(
                                new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton[][]
                            {
                                Keys
                            }
                                );

                            await Bot.SendTextMessageAsync(message.Chat.Id, "З чого розпочнемо гру?", replyMarkup : keyboard);
                        }
                    }
                };

                Bot.StartReceiving();
            }
            catch (Telegram.Bot.Exceptions.ApiRequestException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }