public void SendMessage(TelegramBotClient botClient)
        {
            InlineButton inlineButton = new InlineButton();

            if (user.IsAdmin == 3)
            {
                botClient.EditMessage(_message.From.Id, user.MessageID, "Пользователь забанен на 2 дня!", "36 - LimitedUser", replyMarkup: inlineButton.InteractionUsers(userTwo, db._featuredUserNews.Any(p => p.UserId == userTwo.ID && p.UserWhoAddedId == user.ID), db.GetFeaturedUsers(user, userTwo), isAdmin: true));
            }
            else if (userTwo.IsAdmin != 3 && userTwo.IsAdmin != 2)
            {
                botClient.EditMessage(_message.From.Id, user.MessageID, "Пользователь забанен на 2 дня!", "36 - LimitedUser", replyMarkup: inlineButton.InteractionUsers(userTwo, db._featuredUserNews.Any(p => p.UserId == userTwo.ID && p.UserWhoAddedId == user.ID), db.GetFeaturedUsers(user, userTwo), isAdmin: true));
            }
            else
            {
                user.IsAdmin    = 0;
                userTwo.BanDate = System.DateTime.Today;
                if (user.BanDate.Date < System.DateTime.Today)
                {
                    user.BanDate = System.DateTime.Now;
                }
                user.BanDate = user.BanDate.AddDays(30);
                db.Save();
                Settings settings = db.GetSettings();
                IsBanUser.ThisBan(botClient, _message, user, settings);

                System.String temp = "Администратор " + user.IsAdmin + " уровня: @" + user.Username + " пытался забанить другого администратора " + "\nID: " + userTwo.ID + "\nФИО: " + userTwo.FIO + "\nНомер: " + user.Number + "\nС данного администратора снята админка, так же он был забанен во всех чатах! Если бан был выдан случайно пропишите /UbBan " + user.ID;

                Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup answer = inlineButton.AdminPanelAppeal(_message, user.ID, _message.Data);
                botClient.SendText(settings.ChannelAdmin, temp, replyMarkup: answer);
            }
        }
Пример #2
0
        private async void OnBotMessageReceived(object sender, MessageEventArgs e)
        {
            var message = e.Message;

            if (message.Type != MessageType.TextMessage)
            {
                return;
            }

            if (message.Text == "/start")
            {
                var keyboard = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(
                    new InlineKeyboardButton[]
                {
                    new InlineKeyboardCallbackButton(
                        "Добавить заказ", "AddOrderCallback"),
                    new InlineKeyboardCallbackButton(
                        "Список заказов", "GetOrdersCallback")
                }
                    );

                await _bot.SendTextMessageAsync(message.Chat.Id, "Выберите необходимое Вам действие",
                                                replyMarkup : keyboard);

                return;
            }

            await OrderBuilder(message);
        }
Пример #3
0
        public async void ShowItem(TelegramBotClient BotClient, System.Object message, InlineButton inlineButton, DataBaseContext baseContext)
        {
            CallbackQuery _message = message as CallbackQuery;

            Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup answer = inlineButton.CookingShow(message, baseContext);
            await BotClient.EditMessageTextAsync(_message.From.Id, _message.Message.MessageId, "Выберете статью: ", replyMarkup : answer);
        }
Пример #4
0
        static Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup Keyboard()
        {
            var keyboard = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(
                new Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardCallbackButton[][]
            {
                new [] {
                    new Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardCallbackButton("Мемов!", "a"),
                },
                new[]
                {
                    new Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardCallbackButton("Стикеров!", "d")
                },
                new[]
                {
                    new Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardCallbackButton("Норм СМИ!", "b"),
                },
                new[]
                {
                    new Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardCallbackButton("Контакты создателя!", "r")
                }
            }
                );

            return(keyboard);
        }
Пример #5
0
        private void TaskListCallback(Update update)
        {
            string envs = null;

            var commands = new List <string> {
                "RunBuild", "RunDeploy", "Stop", "Status"
            };
            var lines = new List <List <Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton> >();

            int j = 1;

            for (int i = 0; i < commands.Count; i++)
            {
                if (lines.Count < j)
                {
                    lines.Add(new List <Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton>());
                }

                lines[j - 1].Add(Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton
                                 .WithCallbackData(commands[i]));

                if (lines[j - 1].Count == 2)
                {
                    j++;
                }
            }

            var keyboard = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(lines);

            _bot.SendTextMessageAsync(update.CallbackQuery.Message.Chat.Id, update.CallbackQuery.Data + ":",
                                      parseMode: Telegram.Bot.Types.Enums.ParseMode.Default,
                                      replyMarkup: keyboard);
        }
Пример #6
0
        internal override async Task Reply(Message message, TelegramBotClient botClient)
        {
            var inlineKeyboarButtons = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton[BloodTestIndicatorsCommand.InlineKeyboardRowsCount][];

            for (int i = 0, j = 0, k = 1; i < BloodTestIndicatorsCommand.InlineKeyboardRowsCount; i++, j += BloodTestIndicatorsCommand.InlineKeyboardColumnsCount, k += BloodTestIndicatorsCommand.InlineKeyboardColumnsCount)
            {
                // row i
                inlineKeyboarButtons[i] =
                    new[]
                {
                    // column 1
                    Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData(BloodTestIndicatorsCommand.IndicatorsList[j], $"{BloodTestIndicatorsCommand.IndicatorsList[j]}{BloodTestIndicatorsCommand.CallbackData}"),
                    // column 2
                    Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData(BloodTestIndicatorsCommand.IndicatorsList[k], $"{BloodTestIndicatorsCommand.IndicatorsList[k]}{BloodTestIndicatorsCommand.CallbackData}")
                };
            }

            var inlineKeyboar = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(inlineKeyboarButtons);
            var chatId        = message.Chat.Id;

            string newBotMessage = "Выберете интересующий Вас показатель:";
            var    media         = new InputMediaPhoto("https://raw.githubusercontent.com/OnofreichukRoman/MedicalTelegramBot/master/Images/Bloodtestindicators.jpg");

            await botClient.EditMessageMediaAsync(chatId, message.MessageId, media, replyMarkup : inlineKeyboar);

            await botClient.EditMessageCaptionAsync(chatId, message.MessageId, newBotMessage, replyMarkup : inlineKeyboar, parseMode : Telegram.Bot.Types.Enums.ParseMode.Markdown);
        }
 private void SendOneInlineMessage(long id, String s, Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup keyboardMarkup)
 {
     try
     {
         bot.SendTextMessageAsync(id, s, true, true, 0, keyboardMarkup, Telegram.Bot.Types.Enums.ParseMode.Default);
     }
     catch (Telegram.Bot.Exceptions.ApiRequestException ex) { }
 }
Пример #8
0
        private static void ListenerTaskSend(WebLancer.Objects.Task task)
        {
            string text     = $"📝 <b>{task.Title}</b> 📝\n\n{task.Discription}\n\n💰 {task.Price}\n\n👩‍💻 <i>{task.Applications}</i> 👨‍💻";
            var    keyboard = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithUrl("Открыть проект в браузере", task.Link));

            bot.SendMessage(text, keyboard);

            Log.GoodMessage(text);
        }
Пример #9
0
        private void SendMessagAll(String s, Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup keyboardMarkup)
        {
            List <UserDB> people = modelUser.GetObjects();

            foreach (UserDB person in people)
            {
                SendOneInlineMessage(person.id, s, keyboardMarkup);
            }
        }
Пример #10
0
 /// <summary>
 /// Отправляет кнопки в част
 /// </summary>
 /// <param name="chatId">ID чата</param>
 /// <returns></returns>
 private async Task ShowFuncButton(long chatId)
 {
     var keyboard = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(new[]
     {
         new[] { Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData("Заархивировать") },
         new[] { Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData("Сделать фото черно-белым") },
         //new[]{ Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData("Найти песню по названию") }
     });
     await bot.SendTextMessageAsync(chatId, start, replyMarkup : keyboard);
 }
Пример #11
0
        private async void OnBotCallbackQuery(object sender, CallbackQueryEventArgs e)
        {
            var message         = e.CallbackQuery.Message;
            var callbackData    = e.CallbackQuery.Data;
            var keyboardButtons = new List <InlineKeyboardButton>();

            switch (callbackData)
            {
            case "AddOrderCallback":
                _templateForms = await _httpClient.GetTemplateFormsAsync();

                foreach (var form in _templateForms)
                {
                    _callbackNames.Add(form.Id.ToString());
                    keyboardButtons.Add(new InlineKeyboardCallbackButton(form.Name, form.Id.ToString()));
                }

                var keyboard = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(keyboardButtons.ToArray());

                await _bot.SendTextMessageAsync(message.Chat.Id, "Что хотите заказать?",
                                                replyMarkup : keyboard);

                break;

            case "GetOrdersCallback":
                var orders = await _httpClient.GetOrderAsync();

                var ordersMessage = MakeOrdersMessage(orders);
                await _bot.SendTextMessageAsync(message.Chat.Id, ordersMessage, ParseMode.Html);

                break;
            }

            var indexOfData = _callbackNames.IndexOf(callbackData);

            if (indexOfData > -1)
            {
                var templateFormId = Convert.ToInt32(_callbackNames[indexOfData]);
                _templateForm = GetTemplateFormById(templateFormId);
                if (_templateForm.Id != null)
                {
                    _order = await _httpClient.PostTemplateFormIntoOrderAsync((int)_templateForm.Id);
                }

                await _bot.SendTextMessageAsync(message.Chat.Id, _templateForm.Fields?[_templateFieldId].Name);

                _lastBotRequest = LastBotRequest.TemplateField;
            }
        }
        public static Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup createInlineKeyboard(List <string> buttonNames)
        {
            var buttonsRow = new List <Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton>();

            foreach (var b in buttonNames)
            {
                var button = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton();
                button.Text = b;
                buttonsRow.Add(button);
            }

            var inlineKeyboard = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(buttonsRow);

            return(inlineKeyboard);
        }
Пример #13
0
        private void SubscribeCommand(Update update)
        {
            var envs = _dataAccess.SubscribesDataAccess.GetEnvsByChatId(update.Message.Chat.Id.ToString());

            var envsList = !string.IsNullOrEmpty(envs)
                ? envs.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList()
                : new List <string>();

            var lines = new List <List <Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton> >();

            var max = 23;
            int j   = 1;

            for (int i = 10; i <= max + 2; i++)
            {
                if (i == 14 || i == 15)
                {
                    continue;
                }

                var name = i <= max ? "crm" + i.ToString() : (i == max + 1 ? "preprod" : "all");

                if (!envsList.Contains(name))
                {
                    if (lines.Count < j)
                    {
                        lines.Add(new List <Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton>());
                    }

                    var text = name; // == "preprod" ? "\U0001F699" + name : "\U0001F697" + name;

                    lines[j - 1].Add(Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton
                                     .WithCallbackData(text, name));

                    if (lines[j - 1].Count == 4)
                    {
                        j++;
                    }
                }
            }

            var keyboard = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(lines);

            _bot.SendTextMessageAsync(update.Message.Chat.Id, "Subscribe envs:",
                                      parseMode: Telegram.Bot.Types.Enums.ParseMode.Default,
                                      replyMarkup: keyboard);
        }
Пример #14
0
        public override void Execute(TelegramBotClient botClient, System.Object message)
        {
            DataBase db       = Singleton.GetInstance().Context;
            Message  _Message = message as Message;

            System.Int32 FromId = _Message.ReplyToMessage.From.Id;
            System.Int32 ban    = 10;
            System.Int32.TryParse(_Message.Text.ToLower().Replace(Name, "").Replace(" ", "").Replace(".", ","), out ban);
            Settings settings = db.GetSettings();

            botClient.DeleteMessage(_Message.Chat.Id, _Message.MessageId, "20");

            User Admin = db.GetUser(_Message.From.Id);
            User user  = db.GetUser(_Message.ReplyToMessage.From.Id);

            try
            {
                if (Admin.IsAdmin > 0)
                {
                    if (user.IsAdmin != 2 && user.IsAdmin != 3)
                    {
                        user.BanDate     = System.DateTime.Now.AddDays(ban);
                        user.BanDescript = "Вы были забанены администратором группы!";
                        db.Save();

                        System.String text = "Пользователь " + user.FIO + "\nID: " + user.ID + "\nНомер: " + user.Number + "\nБыл забанен администратором " + Admin.IsAdmin + " урованя " + Admin.FIO;
                        botClient.SendText(settings.ChannelAdmin, text, user, true);

                        IsBanUser.ThisBan(botClient, _Message, user, settings);
                    }
                    else
                    {
                        Admin.BanDate = System.DateTime.Now.AddDays(ban);
                        Admin.IsAdmin = 0;
                        db.Save();
                        IsBanUser.ThisBan(botClient, _Message, Admin, settings);
                        System.String temp         = "Администратор " + Admin.IsAdmin + " уровня: @" + Admin.Username + " пытался забанить 2 уровня администратора на " + ban + " дней!" + "\nФИО: " + user.FIO + "\nС данного администратора снята админка, так же он был забанен во всех чатах! Если бан был выдан случайно пропишите /UbBan " + user.ID;
                        InlineButton  inlineButton = new InlineButton();
                        Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup answer = inlineButton.AdminPanelAppeal(message, user.ID, _Message.Text);
                        botClient.SendText(settings.ChannelAdmin, temp, Admin, true, replyMarkup: answer);
                    }
                }
            }
            catch (System.Exception Ex) { Log.Logging(Ex); }
            return;
        }
Пример #15
0
        private async void CallBackNewMessage(object sender, Telegram.Bot.Args.MessageEventArgs msg)
        {
            Message message = msg.Message;

            if (message.Text != null)
            {
                if (message.Text == "/start")
                {
                    await Bot.SendTextMessageAsync(message.Chat.Id, "Здрастей", replyMarkup : startButtons);
                }
                if (message.Text.ToLower() == "оплатить складчину")
                {
                    var payOrNot = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(
                        new Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardButton[][]
                    {
                        new [] {
                            new Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardCallbackButton("Я оплатил", "userPaid"),
                            new Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardCallbackButton("назад", "back"),
                        }
                    }
                        );
                    await Bot.SendTextMessageAsync(message.Chat.Id, "Оплатите пожалуйста N btc или N etc на счет", replyMarkup : payOrNot);
                }
                if (message.Text.ToLower() == "вип доступ")
                {
                    await Bot.SendTextMessageAsync(message.Chat.Id, "вип доступа пока нет, расскажешь что тут надо не помню уже", replyMarkup : startButtons);
                }
                if (message.Text.ToLower() == "личный кабинет")
                {
                    var lobby = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(
                        new Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardButton[][]
                    {
                        new [] {
                            new Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardCallbackButton("Мой статус", "showStatus"),
                            new Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardCallbackButton("Настроить пересылку", "showChannel"),
                        }
                    }
                        );
                    await Bot.SendTextMessageAsync(message.Chat.Id, "Это ваш личный кабинет " + message.From.Username, replyMarkup : lobby);
                }
            }
        }
Пример #16
0
        private static void BotOnMessageReceived(object sender, MessageEventArgs messageEventArgs)
        {
            message = messageEventArgs.Message;

            if (message == null || message.Type != MessageType.TextMessage)
            {
                return;
            }

            if (message.Text.StartsWith("/help"))
            {
                Bot.SendTextMessageAsync(message.Chat.Id, WalletKeeper.Constants.HELP_MESSAGE);
            }


            if (message.Text.StartsWith("/spending"))
            {
                var keyboard2 = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup();
                keyboard2.InlineKeyboard = new Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardButton[][]
                {
                    new Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardButton[]
                    {
                        Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardButton.WithCallbackData("по категориям"),
                        Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardButton.WithCallbackData("по датам"),
                    },
                };

                Bot.SendTextMessageAsync(message.Chat.Id, "Выбери вид отчетности", replyMarkup: keyboard2);
            }

            if (message.Text.StartsWith("/start"))
            {
                DataBaseCon.InsertUser((int)message.Chat.Id, message.Chat.FirstName);
                Bot.SendTextMessageAsync(message.Chat.Id, $"Привет, {message.Chat.FirstName}" + WalletKeeper.Constants.START_MESSAGE);
            }
            if (message.Text.StartsWith("/delete"))
            {
                DataBaseCon.DeleteRows((int)message.Chat.Id);
                Bot.SendTextMessageAsync(message.Chat.Id, WalletKeeper.Constants.DELETE_DONE);
            }
        }
Пример #17
0
        internal override async Task Execute(Message message, TelegramBotClient botClient)
        {
            var keyboardButtons = new[]
            {
                new [] // row 1
                {
                    //column 1
                    new Telegram.Bot.Types.ReplyMarkups.KeyboardButton("🔙 На главную"),
                    //column 2
                    new Telegram.Bot.Types.ReplyMarkups.KeyboardButton("🔬 Общий анализ крови")
                },
                new [] // row 2
                {
                    //column 1
                    new Telegram.Bot.Types.ReplyMarkups.KeyboardButton("🔬 Общий анализ мочи")
                }
            };
            var inlineKeyboardSearchButton = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton[][]
            {
                // row 1
                new []
                {
                    // column 1
                    Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("🔍 Поиск")
                }
            };

            var keyboard = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup(keyboardButtons)
            {
                ResizeKeyboard = true
            };
            var inlineKeyboardSearch = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(inlineKeyboardSearchButton);
            var chatId = message.Chat.Id;

            string botMessage       = "Выберете интересующий Вас анализ: ↕️";
            string botSearchMessage = "Или воспользуйтесь кнопкой поиска по другим анализам и показателям";

            await botClient.SendTextMessageAsync(chatId, botMessage, replyToMessageId : message.MessageId, replyMarkup : keyboard);

            await botClient.SendTextMessageAsync(chatId, botSearchMessage, replyMarkup : inlineKeyboardSearch);
        }
Пример #18
0
        internal override async Task Reply(Message message, TelegramBotClient botClient)
        {
            var inlineKeyboardButtons = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton[][]
            {
                // row 1
                new []
                {
                    // column 1
                    Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData("<< Назад", "Показатели анализа крови")
                }
            };

            var inlineKeyboar = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(inlineKeyboardButtons);

            string newBotMessage = "*Нейтрофилы* – самая многочисленная разновидность лейкоцитов. Зрелые сегментоядерные нейтрофилы у здорового взрослого человека составляют 47-72% всех лейкоцитов крови; в анализе крови определяются также незрелые палочкоядерные нейтрофилы, доля которых в норме составляет 1-6%. Повышенное содержание нейтрофилов в крови называется нейтрофилией; пониженное – нейтропенией. Нейтрофилы играют огромную роль в защите организма от инфекционных заболеваний, особенно бактериальных и грибковых. Нейтрофилы способны покидать кровяное русло и устремляться к очагу инфекции, принимая активное участие в развитии воспаления. Они также обладают способностью поглощать и разрушать чужеродные частицы – бактерии и грибы. Этот процесс называется фагоцитозом. Повышенная продукция нейтрофилов и их миграция к очагу инфекции часто являются первым ответом организма на инфекционное заболевание.";
            var    chatId        = message.Chat.Id;
            var    media         = new InputMediaPhoto("https://raw.githubusercontent.com/OnofreichukRoman/MedicalTelegramBot/master/Images/neutrophils.jpg");

            await botClient.EditMessageMediaAsync(chatId, message.MessageId, media, replyMarkup : inlineKeyboar);

            await botClient.EditMessageCaptionAsync(chatId, message.MessageId, newBotMessage, replyMarkup : inlineKeyboar, parseMode : Telegram.Bot.Types.Enums.ParseMode.Markdown);
        }
        internal override async Task Reply(Message message, TelegramBotClient botClient)
        {
            var inlineKeyboardButtons = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton[][]
            {
                // row 1
                new []
                {
                    // column 1
                    Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData("<< Назад", "Показатели анализа крови")
                }
            };

            var inlineKeyboar = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(inlineKeyboardButtons);

            string newBotMessage = "*Эозинофилы* — один из видов лейкоцитов, клеток иммунной системы, защищающих человеческий организм от паразитов и участвующих в развитии аллергических реакций. \nЭозинофилия крови — это состояние, характеризующееся абсолютным или относительным повышением числа эозинофилов. \nАнализ крови на эозинофилы свидетельствует о наличии различных заболеваний и помогает своевременно начать их лечение.";
            var    chatId        = message.Chat.Id;
            var    media         = new InputMediaPhoto("https://raw.githubusercontent.com/OnofreichukRoman/MedicalTelegramBot/master/Images/eosinophils.jpg");

            await botClient.EditMessageMediaAsync(chatId, message.MessageId, media, replyMarkup : inlineKeyboar);

            await botClient.EditMessageCaptionAsync(chatId, message.MessageId, newBotMessage, replyMarkup : inlineKeyboar, parseMode : Telegram.Bot.Types.Enums.ParseMode.Markdown);
        }
        internal override async Task Reply(Message message, TelegramBotClient botClient)
        {
            var inlineKeyboardButtons = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton[][]
            {
                // row 1
                new []
                {
                    // column 1
                    Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData("<< Назад", "Показатели анализа крови")
                }
            };

            var inlineKeyboar = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(inlineKeyboardButtons);

            string newBotMessage = "*Лейкоциты* – клетки крови, которые образуются в костном мозге. Основная их функция – бороться с инфекцией и повреждением тканей. Выделяют пять типов лейкоцитов, которые отличаются по внешнему виду и выполняемым функциям: эозинофилы, базофилы, нейтрофилы, лимфоциты и моноциты. Они присутствуют в организме в относительно стабильных пропорциях и, хотя их численность может значительно изменяться в течение дня, в норме обычно остаются в пределах референсных значений. \nЛейкоциты образуются из стволовых клеток костного мозга и в процессе созревания проходят ряд промежуточных стадий, в ходе которых клетка и содержащееся в ней ядро уменьшаются. В кровоток должны попадать только зрелые лейкоциты.Они живут недолго, так что происходит их постоянное обновление. Производство лейкоцитов в костном мозге возрастает в ответ на любое повреждение тканей, это часть нормального воспалительного ответа. Цель воспалительного ответа – отграничение повреждения, удаление вызвавшего его причинного фактора и восстановление ткани.";
            var    chatId        = message.Chat.Id;
            var    media         = new InputMediaPhoto("https://raw.githubusercontent.com/OnofreichukRoman/MedicalTelegramBot/master/Images/leukocytes.jpg");

            await botClient.EditMessageMediaAsync(chatId, message.MessageId, media, replyMarkup : inlineKeyboar);

            await botClient.EditMessageCaptionAsync(chatId, message.MessageId, newBotMessage, replyMarkup : inlineKeyboar, parseMode : Telegram.Bot.Types.Enums.ParseMode.Markdown);
        }
        internal override async Task Reply(Message message, TelegramBotClient botClient)
        {
            var inlineKeyboardButtons = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton[][]
            {
                // row 1
                new []
                {
                    // column 1
                    Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData("<< Назад", "Показатели анализа крови")
                }
            };

            var inlineKeyboar = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(inlineKeyboardButtons);

            string newBotMessage = "*Базофилы* являются разновидностью лейкоцитов. Они представляют собой самую малую группу и составляют не более 1 % от общей массы лейкоцитов. При обнаружении антигена(аллергена) в базофилах происходит дегрануляция. Другими словами, они выпускают свое содержимое наружу, благодаря чему блокируют аллергены, усиливают кровоток и увеличивают проницаемость сосудов. В результате создается очаг воспаления, к которому устремляются другие гранулоциты(моноциты и эозинофилы) на борьбу с чужеродным элементом. Это и есть главная функция базофилов — вовремя обнаружить и подавить аллергены, не дать им распространиться по всему организму и призвать остальных гранулоцитов к месту воспаления.  Кроме своей главной функции базофилы, благодаря наличию гепарина, участвуют в процессах свертываемости крови, препятствуют образованию тромбов в мелких сосудах легких и печени. Также они осуществляют питание тканей, поддерживают нормальный кровоток в малых кровеносных сосудах и рост новых капилляров.";
            var    chatId        = message.Chat.Id;
            var    media         = new InputMediaPhoto("https://raw.githubusercontent.com/OnofreichukRoman/MedicalTelegramBot/master/Images/basophils.jpg");

            await botClient.EditMessageMediaAsync(chatId, message.MessageId, media, replyMarkup : inlineKeyboar);

            await botClient.EditMessageCaptionAsync(chatId, message.MessageId, newBotMessage, replyMarkup : inlineKeyboar, parseMode : Telegram.Bot.Types.Enums.ParseMode.Markdown);
        }
Пример #22
0
        internal override async Task Reply(Message message, TelegramBotClient botClient)
        {
            var inlineKeyboardButtons = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton[][]
            {
                // row 1
                new []
                {
                    // column 1
                    Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData("<< Назад", "Показатели анализа крови")
                }
            };

            var inlineKeyboar = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(inlineKeyboardButtons);

            string newBotMessage = "*Лимфоциты* – это один из видов лейкоцитов, особых клеток, которые циркулируют в крови человека и являются главными клетками иммунной системы. \nРазные виды лимфоцитов способны вырабатывать антитела, уничтожать чужеродные агенты(в первую очередь – вирусы, а также бактерии, грибки и простейшие) и пораженные клетки собственного организма, обуславливать развитие аллергических реакций. В детском возрасте происходит распределение и обучение в органах иммунной системы исходно недифференцированных лимфоцитов, это является основой формирования иммунитета. \nВсе лейкоциты, а значит лимфоциты в том числе, образуются в костном мозге, а затем «дозревают» в других органах в зависимости от назначения.Существуют несколько видов лимфоцитов: Т - клетки, В - клетки и NK-клетки.";
            var    chatId        = message.Chat.Id;
            var    media         = new InputMediaPhoto("https://raw.githubusercontent.com/OnofreichukRoman/MedicalTelegramBot/master/Images/lymphocytes.jpg");

            await botClient.EditMessageMediaAsync(chatId, message.MessageId, media, replyMarkup : inlineKeyboar);

            await botClient.EditMessageCaptionAsync(chatId, message.MessageId, newBotMessage, replyMarkup : inlineKeyboar, parseMode : Telegram.Bot.Types.Enums.ParseMode.Markdown);
        }
Пример #23
0
        internal override async Task Execute(Message message, TelegramBotClient botClient)
        {
            var keyboardButtons = new[]
            {
                new [] // row 1
                {
                    //column 1
                    new Telegram.Bot.Types.ReplyMarkups.KeyboardButton("🧾 Показатели анализа крови"),
                },
                new [] // row 2
                {
                    //column 1
                    new Telegram.Bot.Types.ReplyMarkups.KeyboardButton("🔙 Назад к анализам")
                }
            };
            var inlineKeyboardSearchButton = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton[][]
            {
                // row 1
                new []
                {
                    // column 1
                    Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("🔍 Поиск")
                }
            };

            var keyboard = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup(keyboardButtons)
            {
                ResizeKeyboard = true
            };
            var inlineKeyboardSearch = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(inlineKeyboardSearchButton);
            var chatId = message.Chat.Id;

            string botMessage       = "#Общийанализкрови #ОАК \n🔬🩸 *Общий анализ крови (ОАК)* – это наиболее доступный метод первичной оценки состояния организма, результаты которого, наряду с общим анализом мочи и биохимическим анализом крови, входят в алгоритмы диагностики большинства заболеваний. У здорового человека кровь по своему составу относительно постоянна, но   реагирует практически на любые патологические изменения в организме. Поэтому, чтобы понять, что происходит с человеком, какие исследования назначить в дальнейшем или определиться с лечением, врач, в первую очередь, всегда назначает ОАК. \nЭто исследование также используется в виде профилактического обследования даже при отсутствии каких-либо симптомов и отражает изменения состояния здоровья. Кроме того, ОАК позволяет оценить успешность проведенного лечения.";
            string botSearchMessage = "Не нашли то что искали? Воспользуйтесь кнопкой поиска по другим анализам и показателям";

            await botClient.SendPhotoAsync(chatId, "https://raw.githubusercontent.com/OnofreichukRoman/MedicalTelegrammBot/master/Images/bloodanalysis.jpg", botMessage, replyToMessageId : message.MessageId, parseMode : Telegram.Bot.Types.Enums.ParseMode.Markdown, replyMarkup : keyboard);

            await botClient.SendTextMessageAsync(chatId, botSearchMessage, replyMarkup : inlineKeyboardSearch);
        }
Пример #24
0
        internal override async Task Reply(Message message, TelegramBotClient botClient)
        {
            var inlineKeyboardButtons = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton[][]
            {
                // row 1
                new []
                {
                    // column 1
                    Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData("<< Назад", "Показатели анализа крови")
                }
            };

            var inlineKeyboar = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(inlineKeyboardButtons);

            string newBotMessage = "*Моноциты* – немногочисленные, но по размеру наиболее крупные иммунные клетки организма. \nЭти лейкоциты принимают участие в распознавании чужеродных веществ и обучению других лейкоцитов к их распознаванию.Могут мигрировать из крови в ткани организма.Вне кровеносного русла моноциты изменяют свою форму и преобразуются в макрофаги.Макрофаги могут активно мигрировать к очагу воспаления для того, чтобы принять участие в очищении воспаленной ткани от погибших клеток, лейкоцитов, бактерий. Благодаря такой работе макрофагов создаются все условия для восстановления поврежденных тканей.";
            var    chatId        = message.Chat.Id;
            var    media         = new InputMediaPhoto("https://raw.githubusercontent.com/OnofreichukRoman/MedicalTelegramBot/master/Images/monocytes.jpg");

            await botClient.EditMessageMediaAsync(chatId, message.MessageId, media, replyMarkup : inlineKeyboar);

            await botClient.EditMessageCaptionAsync(chatId, message.MessageId, newBotMessage, replyMarkup : inlineKeyboar, parseMode : Telegram.Bot.Types.Enums.ParseMode.Markdown);
        }
Пример #25
0
        public Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup GetInlineKeyboard(string[][] buttons, string[][] callback_data)
        {
            int rows = buttons.Length;

            Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton[][] keyboardButtons = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton[rows][];

            for (int row = 0; row < rows; row++)
            {
                keyboardButtons[row] = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton[buttons[row].Length];

                for (int column = 0; column < buttons[row].Length; column++)
                {
                    keyboardButtons[row][column] = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton {
                        Text = buttons[row][column], CallbackData = callback_data[row][column]
                    };
                }
            }


            var keyboard = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(keyboardButtons);

            return(keyboard);
        }
Пример #26
0
        internal override async Task Execute(Message message, TelegramBotClient botClient)
        {
            var inlineKeyboarButtons = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton[InlineKeyboardRowsCount][];

            for (int i = 0, j = 0, k = 1; i < InlineKeyboardRowsCount; i++, j += InlineKeyboardColumnsCount, k += InlineKeyboardColumnsCount)
            {
                // row i
                inlineKeyboarButtons[i] =
                    new[]
                {
                    // column 1
                    Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData(IndicatorsList[j], $"{IndicatorsList[j]}{CallbackData}"),
                    // column 2
                    Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData(IndicatorsList[k], $"{IndicatorsList[k]}{CallbackData}")
                };
            }

            var inlineKeyboar = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(inlineKeyboarButtons);
            var chatId        = message.Chat.Id;

            string botMessage = "Выберете интересующий Вас показатель:";

            await botClient.SendPhotoAsync(chatId, "https://raw.githubusercontent.com/OnofreichukRoman/MedicalTelegramBot/master/Images/Bloodtestindicators.jpg", botMessage, parseMode : Telegram.Bot.Types.Enums.ParseMode.Markdown, replyMarkup : inlineKeyboar);
        }
Пример #27
0
        private static async void OnMessageHandler(object sender, Telegram.Bot.Args.MessageEventArgs e)
        {
            var text   = e.Message.Text;
            var userId = e.Message.Chat.Id;

            if (text == null)
            {
                return;
            }
            try
            {
                //logging messages
                File.AppendAllText(logPath, $"{userId}({e.Message.Chat.FirstName} {e.Message.Chat.LastName}): {text}, {e.Message.Date}\n");
            }
            catch
            {
                File.AppendAllText(logPath, $"{userId}({e.Message.Chat.FirstName}): {text}, {e.Message.Date}\n");
            }
            Console.WriteLine($"User {userId}({e.Message.Chat.FirstName}) sent {text}");
            if (!states.ContainsKey(userId))
            {
                states.Add(userId, State.CommandReciever);
            }

            if (!tempEvents.ContainsKey(userId))
            {
                tempEvents[userId] = new Tuple <Event, int>(new Event(), 0);
            }
            switch (states[userId])
            {
            case State.CommandReciever:
                switch (text)
                {
                case "/start":
                    Send(userId, "This bot helps you to plan your businesses!\n" +
                         "Press /add to start planning!\nPress /help to read more about commands");
                    break;

                case "/help":
                    Send(userId, "This bot helps you to plan your businesses!\n" +
                         "/add adds new plan" +
                         "\n/show shows all records\n" +
                         "/mark then choose a bussiness to mark it done\n" +
                         "/delay then choose a different time for your business\n" +
                         "/remove then choose a record to remove\n" +
                         "(You'll receive notifications and daily statistics)");
                    break;

                case "/show":
                    if (!planner.Contains(userId) || planner.Get(userId).Count() == 0)
                    {
                        Send(userId, "You have no plans!");
                    }
                    else
                    {
                        var    plans = planner.Get(userId);
                        string res   = $"You have planned {plans.Count()} things!\n";
                        for (int i = 0; i < plans.Count(); ++i)
                        {
                            res += $"{i + 1}. {plans[i].name} {plans[i].time} {plans[i].importance}\n";
                        }
                        Send(userId, res);
                    }
                    break;

                case "/add":
                    states[userId] = State.AddName;
                    Send(userId, "Type business name");
                    break;

                case "/mark":
                    states[userId] = State.MarkName;
                    var userEventsMarkName = planner.Get(userId);
                    List <List <Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton> > listMarkName = new List <List <Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton> >();
                    for (int i = 0; i < userEventsMarkName.Count(); ++i)
                    {
                        string cur        = $"{userEventsMarkName[i].name} {userEventsMarkName[i].time} {userEventsMarkName[i].importance}";
                        var    addingList = new List <Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton>
                        {
                            Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData($"{cur}", $"{i}")
                        };
                        listMarkName.Add(addingList);
                    }
                    var markupMarkName = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(listMarkName);
                    try
                    {
                        await bot.SendTextMessageAsync(userId, "Choose a deal you want to mark:", replyMarkup : markupMarkName);
                    }
                    catch
                    {
                        Console.WriteLine($"Error: forbidden user {userId}");
                        planner.DeleteUser(userId);
                        states.Remove(userId);
                        tempEvents.Remove(userId);
                        break;
                    }
                    break;

                case "/delay":
                    states[userId] = State.DelayName;
                    var userEvnts = planner.Get(userId);
                    List <List <Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton> > listDelay = new List <List <Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton> >();
                    for (int i = 0; i < userEvnts.Count(); ++i)
                    {
                        string cur        = $"{userEvnts[i].name} {userEvnts[i].time} {userEvnts[i].importance}";
                        var    addingList = new List <Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton>
                        {
                            Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData($"{cur}", $"{i}")
                        };
                        listDelay.Add(addingList);
                    }
                    var markupDelay = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(listDelay);
                    try
                    {
                        await bot.SendTextMessageAsync(userId, "Choose a deal you want to delay:", replyMarkup : markupDelay);
                    }
                    catch
                    {
                        Console.WriteLine($"Error: forbidden user {userId}");
                        planner.DeleteUser(userId);
                        states.Remove(userId);
                        tempEvents.Remove(userId);
                        break;
                    }
                    break;

                case "/remove":
                    states[userId] = State.RemoveName;
                    var usrEvnts = planner.Get(userId);
                    List <List <Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton> > listRemove = new List <List <Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton> >();
                    for (int i = 0; i < usrEvnts.Count(); ++i)
                    {
                        string cur        = $"{usrEvnts[i].name} {usrEvnts[i].time} {usrEvnts[i].importance}";
                        var    addingList = new List <Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton>
                        {
                            Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData($"{cur}", $"{i}")
                        };
                        listRemove.Add(addingList);
                    }
                    var markupRemove = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(listRemove);
                    try
                    {
                        await bot.SendTextMessageAsync(userId, "Choose a deal you want to delay:", replyMarkup : markupRemove);
                    }
                    catch
                    {
                        Console.WriteLine($"Error: forbidden user {userId}");
                        planner.DeleteUser(userId);
                        states.Remove(userId);
                        tempEvents.Remove(userId);
                        break;
                    }
                    break;

                default:
                    Send(userId, "Enter a proper command! Type /help to get more info");
                    break;
                }
                break;

            case State.AddName:
                tempEvents[userId].Item1.name = text;
                if (tempEvents[userId].Item1.name == "")
                {
                    Send(userId, "Enter non empty name!");
                }
                else
                {
                    var TimeMarkup = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup(new[]
                    {
                        new []
                        {
                            new Telegram.Bot.Types.ReplyMarkups.KeyboardButton("Today"),
                            new Telegram.Bot.Types.ReplyMarkups.KeyboardButton("Tomorrow"),
                            new Telegram.Bot.Types.ReplyMarkups.KeyboardButton("No Term")
                        }
                    })
                    {
                        OneTimeKeyboard = true
                    };
                    try
                    {
                        await bot.SendTextMessageAsync(userId, "Choose Time below!", replyMarkup : TimeMarkup);
                    }
                    catch
                    {
                        Console.WriteLine($"Error: forbidden user {userId}");
                        planner.DeleteUser(userId);
                        states.Remove(userId);
                        tempEvents.Remove(userId);
                        break;
                    }
                }
                states[userId] = State.AddTime;
                break;

            case State.AddTime:
                switch (text)
                {
                case "Today":
                    tempEvents[userId].Item1.time = Time.Today;
                    break;

                case "Tomorrow":
                    tempEvents[userId].Item1.time = Time.Tomorrow;
                    break;

                case "No Term":
                    tempEvents[userId].Item1.time = Time.NoTerm;
                    break;

                default:
                    Send(userId, "Push the buttons!");
                    return;
                }
                var ImpMarkup = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup(new[]
                {
                    new[]
                    {
                        new Telegram.Bot.Types.ReplyMarkups.KeyboardButton("Important"),
                        new Telegram.Bot.Types.ReplyMarkups.KeyboardButton("Medium"),
                        new Telegram.Bot.Types.ReplyMarkups.KeyboardButton("Casual")
                    }
                })
                {
                    OneTimeKeyboard = true
                };
                try
                {
                    await bot.SendTextMessageAsync(userId, "Choose importance below!", replyMarkup : ImpMarkup);
                }
                catch
                {
                    Console.WriteLine($"Error: forbidden user {userId}");
                    planner.DeleteUser(userId);
                    states.Remove(userId);
                    tempEvents.Remove(userId);
                    break;
                }
                states[userId] = State.AddImportance;
                break;

            case State.AddImportance:
                switch (text)
                {
                case "Important":
                    tempEvents[userId].Item1.importance = Importance.Important;
                    break;

                case "Medium":
                    tempEvents[userId].Item1.importance = Importance.Medium;
                    break;

                case "Casual":
                    tempEvents[userId].Item1.importance = Importance.Casual;
                    break;

                default:
                    Send(userId, "Push the buttons!");
                    return;
                }
                tempEvents[userId].Item1.owner = userId;
                planner.Add(userId, new Event(tempEvents[userId].Item1.name, tempEvents[userId].Item1.time, tempEvents[userId].Item1.importance, tempEvents[userId].Item1.owner));
                tempEvents[userId] = new Tuple <Event, int>(new Event(), 0);

                var markup = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardRemove();
                try
                {
                    await bot.SendTextMessageAsync(e.Message.Chat.Id, "Record added!", replyMarkup : markup);
                }
                catch
                {
                    Console.WriteLine($"Error: forbidden user {userId}");
                    planner.DeleteUser(userId);
                    states.Remove(userId);
                    tempEvents.Remove(userId);
                    break;
                }
                states[userId] = State.CommandReciever;
                break;

            case State.MarkDone:
                switch (text)
                {
                case "Done":
                    tempEvents[userId].Item1.done = true;
                    break;

                case "Not done":
                    tempEvents[userId].Item1.done = false;
                    break;

                default:
                    Send(userId, "Push the buttons!");
                    return;
                }
                var markupMarkDone = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardRemove();
                try
                {
                    await bot.SendTextMessageAsync(e.Message.Chat.Id, $"State was successfully changed!", replyMarkup : markupMarkDone);
                }
                catch
                {
                    Console.WriteLine($"Error: forbidden user {userId}");
                    planner.DeleteUser(userId);
                    states.Remove(userId);
                    tempEvents.Remove(userId);
                    break;
                }
                planner.Mark(e.Message.Chat.Id, tempEvents[userId].Item2, tempEvents[userId].Item1.done);
                tempEvents[userId] = new Tuple <Event, int>(new Event(), 0);
                states[userId]     = State.CommandReciever;
                break;

            case State.DelayTime:
                switch (text)
                {
                case "Today":
                    tempEvents[userId].Item1.time = Time.Today;
                    break;

                case "Tomorrow":
                    tempEvents[userId].Item1.time = Time.Tomorrow;
                    break;

                case "No Term":
                    tempEvents[userId].Item1.time = Time.NoTerm;
                    break;

                default:
                    Send(userId, "Push the buttons!");
                    return;
                }
                var markupDelayTime = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardRemove();
                try
                {
                    await bot.SendTextMessageAsync(userId, $"Changes saved!", replyMarkup : markupDelayTime);
                }
                catch
                {
                    Console.WriteLine($"Error: forbidden user {userId}");
                    planner.DeleteUser(userId);
                    states.Remove(userId);
                    tempEvents.Remove(userId);
                    break;
                }
                planner.Delay(userId, tempEvents[userId].Item2, tempEvents[userId].Item1.time);
                tempEvents[userId] = new Tuple <Event, int>(new Event(), 0);
                states[userId]     = State.CommandReciever;
                break;

            default:
                tempEvents[userId] = new Tuple <Event, int>(new Event(), 0);
                //Send(userId, "Something went wrong! Code: Message");
                Send(userId, "Try to push the buttons! Try again");
                states[userId] = State.CommandReciever;
                return;
            }
        }
Пример #28
0
        public IActionResult SetExternalCommand([FromBody] ExtenvBot.Models.ExternalCommandResult result)
        {
            if (result != null && !string.IsNullOrEmpty(result.Id))
            {
                var command = _dataAccess.ExternalCommandDataAccess.GetExternalCommand(result.Id);
                if (command != null)
                {
                    try
                    {
                        _dataAccess.ExternalCommandDataAccess.SetResponseExternalCommand(result.Id, result.Response);

                        if (string.Equals(command.Command, "tasks", StringComparison.OrdinalIgnoreCase))
                        {
                            /*_bot.SendTextMessageAsync(command.ChatId,
                             *  "Your request id = '" + result.Id + "' processed. [Show](" +
                             *  "http://extenvbot.azurewebsites.net/api/telegram/externalcommand/" + result.Id
                             + ").",
                             +  parseMode: Telegram.Bot.Types.Enums.ParseMode.Markdown);*/
                            _bot.SendTextMessageAsync(command.ChatId,
                                                      "Tasks received. [Show](" +
                                                      "http://extenvbot.azurewebsites.net/api/telegram/externalcommand/" + result.Id
                                                      + ")",
                                                      parseMode: Telegram.Bot.Types.Enums.ParseMode.Markdown);
                        }
                        else if (string.Equals(command.Command, "tasklist", StringComparison.OrdinalIgnoreCase))
                        {
                            var buildsList = !string.IsNullOrEmpty(result.Response)
                                ? result.Response.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList()
                                : new List <string>();

                            var lines = new List <List <Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton> >();

                            int j = 1;
                            for (int i = 0; i < buildsList.Count; i++)
                            {
                                if (lines.Count < j)
                                {
                                    lines.Add(new List <Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton>());
                                }

                                lines[j - 1].Add(Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton
                                                 .WithCallbackData(buildsList[i]));

                                if (lines[j - 1].Count == 2)
                                {
                                    j++;
                                }
                            }

                            var keyboard = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(lines);

                            _bot.SendTextMessageAsync(command.ChatId, "Task list:",
                                                      parseMode: Telegram.Bot.Types.Enums.ParseMode.Default,
                                                      replyMarkup: keyboard);
                        }
                        else
                        {
                            if (string.Equals(command.Command, "status", StringComparison.OrdinalIgnoreCase))
                            {
                                _bot.SendTextMessageAsync(command.ChatId, "Status is " + result.Response + ".");
                            }
                            else
                            {
                                _bot.SendTextMessageAsync(command.ChatId, command.Command + " is complete.");
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        //Console.WriteLine(e);
                        _dataAccess.ExternalCommandDataAccess.SetResponseExternalCommand(result.Id, e.ToString());
                    }
                    finally
                    {
                        _dataAccess.ExternalCommandDataAccess.SetProcessedExternalCommand(result.Id);
                    }
                }
            }

            return(Ok());
        }
        public async void Execute(TelegramBotClient botClient, System.Object message)
        {
            Message      _message     = message as Message;
            InlineButton inlineButton = new InlineButton();

            try
            {
                DataBase db   = Singleton.GetInstance().Context;
                User     user = db.GetUser(_message.From.Id); if (IsNullDataBase.IsNull(botClient, _message, user))
                {
                    return;
                }

                botClient.DeleteMessage(_message.Chat.Id, _message.MessageId, "135");

                if (Text != null && user.IsAdmin > 0)
                {
                    User     userTwo = db.GetUser(System.Convert.ToInt32(Text));
                    Settings setting = db.GetSettings();

                    if (userTwo != null)
                    {
                        if (user.IsAdmin == 3)
                        {
                            if (userTwo.BanDate.Date < System.DateTime.Today)
                            {
                                userTwo.BanDate = System.DateTime.Now;
                            }
                            userTwo.BanDate     = userTwo.BanDate.AddDays(Count);
                            userTwo.BanDescript = "Вы были забанены администрацией UBC!";
                            userTwo.PayConfirm  = false;
                            userTwo.PayDate     = System.DateTime.Today;

                            IsBanUser.ThisBan(botClient, _message, userTwo, setting);

                            System.String temp = "Администратор " + user.IsAdmin + " уровня: @" + user.Username + " забанил пользователя на " + Count + " дней!" + "\nID: " + userTwo.ID + "\nФИО: " + userTwo.FIO + "\nНомер: " + user.Number;

                            await botClient.SendTextMessageAsync(setting.ChannelAdmin, temp);
                        }
                        else if (userTwo.IsAdmin != 2 && userTwo.IsAdmin != 3)
                        {
                            if (userTwo.BanDate.Date < System.DateTime.Today)
                            {
                                userTwo.BanDate = System.DateTime.Now;
                            }
                            userTwo.BanDate     = userTwo.BanDate.AddDays(Count);
                            userTwo.BanDescript = "Вы были забанены администрацией UBC!";
                            userTwo.PayConfirm  = false;
                            userTwo.PayDate     = System.DateTime.Today;

                            IsBanUser.ThisBan(botClient, _message, userTwo, setting);

                            System.String temp = "Администратор " + user.IsAdmin + " уровня: @" + user.Username + " забанил пользователя на " + Count + " дней!" + "\nID: " + userTwo.ID + "\nФИО: " + userTwo.FIO + "\nНомер: " + user.Number;

                            await botClient.SendTextMessageAsync(setting.ChannelAdmin, temp);
                        }
                        else
                        {
                            user.IsAdmin = 0;
                            if (user.BanDate.Date < System.DateTime.Today)
                            {
                                user.BanDate = System.DateTime.Now;
                            }
                            user.BanDate = user.BanDate.AddDays(Count);
                            IsBanUser.ThisBan(botClient, _message, user, setting);

                            System.String temp = "Администратор " + user.IsAdmin + " уровня: @" + user.Username + " пытался забанить другого администратора на " + Count + " дней!" + "\nID: " + userTwo.ID + "\nФИО: " + userTwo.FIO + "\nНомер: " + user.Number + "\nС данного администратора снята админка, так же он был забанен во всех чатах! Если бан был выдан случайно пропишите /UbBan " + user.ID;

                            Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup answer = inlineButton.AdminPanelAppeal(message, user.ID, _message.Text);
                            await botClient.SendTextMessageAsync(setting.ChannelAdmin, temp, replyMarkup : answer);
                        }

                        db.Save();
                    }
                    else
                    {
                        try
                        {
                            Message mes = await botClient.EditMessageTextAsync(user.ID, user.MessageID, "Пользователь не найден!", replyMarkup : inlineButton.BackToSettingAdmin);

                            user.MessageID = mes.MessageId;
                        }
                        catch
                        {
                            Message mes = await botClient.SendTextMessageAsync(user.ID, "Пользователь не найден!", replyMarkup : inlineButton.BackToSettingAdmin);

                            user.MessageID = mes.MessageId;
                        }
                        db.Save();
                    }
                }
                else if (Name == "/Ban" && user.IsAdmin > 0)
                {
                    try
                    {
                        Message mes = await botClient.EditMessageTextAsync(user.ID, user.MessageID, "Перешлите сообщения от пользователя которого хотите забанить!", replyMarkup : inlineButton.BackToSettingAdmin);

                        user.Chain     = 1050;
                        user.MessageID = mes.MessageId;
                    }
                    catch
                    {
                        Message mes = await botClient.SendTextMessageAsync(user.ID, "Перешлите сообщения от пользователя которого хотите забанить!", replyMarkup : inlineButton.BackToSettingAdmin);

                        user.Chain     = 1050;
                        user.MessageID = mes.MessageId;
                    }

                    db.Save();
                }
            }
            catch (System.Exception ex)
            {
                Log.Logging(ex);
            }
        }
Пример #30
0
        public AView()
        {
            keyboardHome = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup
            {
                Keyboard = new[]
                {
                    new[]
                    {
                        new Telegram.Bot.Types.KeyboardButton("\U0001F482 Hero"),
                        new Telegram.Bot.Types.KeyboardButton("\U0001F528 Work \U0001F33E")
                    },
                    new[]
                    {
                        new Telegram.Bot.Types.KeyboardButton("\U0001F3F0 Town"),
                        new Telegram.Bot.Types.KeyboardButton(" Back ")
                    },
                },
                ResizeKeyboard = true
            };

            keyboardStart = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(new Telegram.Bot.Types.InlineKeyboardButton[][]
            {
                new []
                {
                    new Telegram.Bot.Types.InlineKeyboardButton("a special Person", "Person"),
                },
                new []
                {
                    new Telegram.Bot.Types.InlineKeyboardButton("a rich Gnome", "Gnome"),
                },
                new []
                {
                    new Telegram.Bot.Types.InlineKeyboardButton("a terrible Orc", "Orc"),
                },
                new []
                {
                    new Telegram.Bot.Types.InlineKeyboardButton("a strong Elf", "Elf"),
                },
            });

            keyboardLvlUp = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(new Telegram.Bot.Types.InlineKeyboardButton[][]
            {
                new []
                {
                    new Telegram.Bot.Types.InlineKeyboardButton(" Attack ", "attack"),
                    new Telegram.Bot.Types.InlineKeyboardButton(" Defence ", "def"),
                },
            });

            keyboardChouseFraction = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(new Telegram.Bot.Types.InlineKeyboardButton[][]
            {
                new []
                {
                    new Telegram.Bot.Types.InlineKeyboardButton(" Alliance ", "Alliance"),
                    new Telegram.Bot.Types.InlineKeyboardButton(" Republic ", "Republic"),
                },
            });

            createNewUser = "******" +
                            "Please visit our group to have more info. https://t.me/WWGlobalChat \n" +
                            " And chouse who you are ...";
            createNewUserEmptyUsername = "******";
            chooseStates       = "\U00002B50 Congratulation! You have become more powerful! And you stand stronger in ";
            upStatesOK         = " You feel the power!";
            upStatesFalse      = " You need to grow more...";
            chooseFraction     = "Please, chose you fraction! Brave Republic or eternal Alliance?";
            setFractionSuccses = "We knew that you would choose the best!";
            setFractionFail    = "Huston we have problems";
            errorMessage       = "Gods dont understand what do you whant to do";
        }