Пример #1
0
        public static async void TimerHandler(object obj, MessageEventArgs args)
        {
            var text = args.Message?.Text;

            if (!(obj is TelegramBotClient client))
            {
                return;
            }

            if (string.IsNullOrEmpty(text))
            {
                return;
            }

            if (text == StartCommand)
            {
                await client.SendTextMessageIgnoreAPIErrorsAsync(args.GetChatId(), StartAnswer);

                return;
            }

            if (!TimeSpan.TryParseExact(text, TimeSpanFormat, CultureInfo.InvariantCulture, out var timeSpan))
            {
                return;
            }

            var sec = timeSpan.TotalSeconds;

            var infoMsg = await client.SendTextMessageAsync(args.GetChatId(),
                                                            $@"The timer for {timeSpan.ToString(TimeSpanFormat)} is being started...");

            DateTime startTime = DateTime.Now;

            while (true)
            {
                var delayTask = Task.Delay(1000);

                var leftSeconds = (DateTime.Now - startTime).TotalSeconds;

                if (leftSeconds >= sec)
                {
                    break;
                }

                var editTask =
                    client.EditMessageTextAsync(
                        args.GetChatId(),
                        infoMsg.MessageId,
                        $"Timer for {timeSpan.ToString(TimeSpanFormat)} is running! {Environment.NewLine}" +
                        $"Current remaining time: {timeSpan - new TimeSpan(0, 0, seconds: (int)leftSeconds)}");

                Task.WaitAll(editTask, delayTask);
            }

            var editAfterRunTask =
                client.EditMessageTextAsync(
                    args.GetChatId(),
                    infoMsg.MessageId,
                    $"Timer for {timeSpan.ToString(TimeSpanFormat)} has run out!"
                    );

            var sendTask =
                client.SendTextMessageAsync(
                    args.GetChatId(),
                    $"@{args.GetSenderUserName()} The timer has ran out!");

            await Task.WhenAll(editAfterRunTask, sendTask);
        }