예제 #1
0
파일: VkSender.cs 프로젝트: equuskk/Goblin
    public async Task SendToMany(IEnumerable <long> chatIds, string message, CoreKeyboard keyboard = null,
                                 IEnumerable <string> attachments = null)
    {
        message = TrimText(message);

        foreach (var chunk in chatIds.Chunk(ChunkLimit))
        {
            try
            {
                await _vkApi.Messages.SendToUserIdsAsync(new MessagesSendParams
                {
                    UserIds     = chunk,
                    Message     = message,
                    Keyboard    = KeyboardConverter.FromCoreToVk(keyboard, true),
                    Attachments = ConvertAttachments(attachments),
                    RandomId    = GetRandomId()
                });

                await Task.Delay(100);
            }
            catch (Exception e)
            {
                _logger.Error(e, "Ошибка при отправке сообщения");
            }
        }
    }
예제 #2
0
    public Task Send(long chatId, string message, CoreKeyboard keyboard = null, IEnumerable <string> attachments = null)
    {
        message = TrimText(message);
        var replyMarkup = KeyboardConverter.FromCoreToTg(keyboard);

        return(_botClient.SendTextMessageAsync(chatId, message, replyMarkup: replyMarkup));
    }
예제 #3
0
    public static CoreKeyboard GetMailingKeyboard(BotUser user)
    {
        const string mailingKey = "mailing";
        var          isSchedule = user.HasScheduleSubscription;
        var          isWeather  = user.HasWeatherSubscription;

        var scheduleColor = isSchedule
                                    ? CoreKeyboardButtonColor.Negative
                                    : CoreKeyboardButtonColor.Positive;
        var weatherColor = isWeather
                                   ? CoreKeyboardButtonColor.Negative
                                   : CoreKeyboardButtonColor.Positive;

        var scheduleText = isSchedule
                                   ? "❌Отписаться от рассылки расписания"
                                   : "✔Подписаться на рассылку расписания";
        var weatherText = isWeather
                                  ? "❌Отписаться от рассылки погоды"
                                  : "✔Подписаться на рассылку погоды";

        var kb = new CoreKeyboard
        {
            IsInline = true
        };

        kb.AddButton(scheduleText, scheduleColor, mailingKey, "schedule")
        .AddLine()
        .AddButton(weatherText, weatherColor, mailingKey, "weather")
        .AddReturnToMenuButton();

        return(kb);
    }
예제 #4
0
    public static IReplyMarkup FromCoreToTg(CoreKeyboard coreKeyboard)
    {
        if (coreKeyboard is null)
        {
            return(null);
        }

        coreKeyboard.RemoveReturnToMenuButton();

        return(coreKeyboard.IsInline ? GenerateInlineKeyboard() : GenerateReplyKeyboard());

        IReplyMarkup GenerateReplyKeyboard()
        {
            var tgButtonsList = new List <List <KeyboardButton> >();
            var currentLine   = new List <KeyboardButton>();

            foreach (var line in coreKeyboard.Buttons)
            {
                foreach (var button in line)
                {
                    currentLine.Add(new KeyboardButton(button.Title));
                }

                tgButtonsList.Add(currentLine);
                currentLine = new List <KeyboardButton>();
            }

            var keyboard = new ReplyKeyboardMarkup(tgButtonsList)
            {
                OneTimeKeyboard = coreKeyboard.IsOneTime,
                ResizeKeyboard  = true
            };

            return(keyboard);
        }

        IReplyMarkup GenerateInlineKeyboard()
        {
            var tgButtonsList = new List <List <InlineKeyboardButton> >();
            var currentLine   = new List <InlineKeyboardButton>();

            foreach (var line in coreKeyboard.Buttons)
            {
                foreach (var button in line)
                {
                    currentLine.Add(InlineKeyboardButton.WithCallbackData(button.Title, button.Payload));
                }

                tgButtonsList.Add(currentLine);
                currentLine = new List <InlineKeyboardButton>();
            }

            var keyboard = new InlineKeyboardMarkup(tgButtonsList);

            return(keyboard);
        }
    }
예제 #5
0
    public Task <IResult> Execute(Message msg, BotUser user)
    {
        var kb = new CoreKeyboard();

        return(Task.FromResult <IResult>(new SuccessfulResult
        {
            Message = "Окей",
            Keyboard = kb
        }));
    }
예제 #6
0
파일: VkSender.cs 프로젝트: equuskk/Goblin
    public Task Send(long chatId, string message, CoreKeyboard keyboard = null, IEnumerable <string> attachments = null)
    {
        message = TrimText(message);

        return(_vkApi.Messages.SendAsync(new MessagesSendParams
        {
            PeerId = chatId,
            Message = message,
            Keyboard = KeyboardConverter.FromCoreToVk(keyboard, true),
            Attachments = ConvertAttachments(attachments),
            RandomId = GetRandomId()
        }));
    }
예제 #7
0
    public async Task <IResult> Execute(Message msg, BotUser user)
    {
        var teacherName = string.Join(' ', msg.CommandParameters);

        if (string.IsNullOrWhiteSpace(teacherName))
        {
            return(new FailedResult("Укажите имя и фамилию преподавателя."));
        }

        try
        {
            var findResult = await _narfuApi.Teachers.FindByName(teacherName);

            if (!findResult.Any())
            {
                return(new FailedResult("Преподаватель с такими данными не найден."));
            }

            if (findResult.Length > 9)
            {
                return(new FailedResult("Найдено слишком много преподавателей. Укажите более точные данные."));
            }

            var keyboard = new CoreKeyboard
            {
                IsInline = true
            };
            foreach (var teacher in findResult)
            {
                keyboard.AddButton(teacher.Name, CoreKeyboardButtonColor.Primary,
                                   "teacherSchedule", teacher.Id.ToString());
                keyboard.AddLine();
            }

            keyboard.AddReturnToMenuButton(false);
            return(new SuccessfulResult
            {
                Message = "Выберите преподавателя из списка:",
                Keyboard = keyboard
            });
        }
        catch (HttpRequestException)
        {
            return(new FailedResult(DefaultErrors.NarfuSiteIsUnavailable));
        }
        catch (Exception ex)
        {
            Log.ForContext <FindTeacherCommand>().Fatal(ex, "Ошибка при поиске преподавателя");
            return(new FailedResult(DefaultErrors.NarfuUnexpectedError));
        }
    }
예제 #8
0
    public static MessageKeyboard FromCoreToVk(CoreKeyboard coreKeyboard, bool isInlineKeyboardAllowed = false)
    {
        if (coreKeyboard is null)
        {
            return(null);
        }
        var kb = new KeyboardBuilder();
        var inlineKeyboardEnabled = coreKeyboard.IsInline && isInlineKeyboardAllowed;

        if (!isInlineKeyboardAllowed)
        {
            if (coreKeyboard.IsOneTime)
            {
                kb.SetOneTime();
            }
        }
        else
        {
            coreKeyboard.RemoveReturnToMenuButton();
        }

        kb.SetInline(inlineKeyboardEnabled);

        var isFirst = true;

        foreach (var line in coreKeyboard.Buttons)
        {
            if (!isFirst)
            {
                kb.AddLine();
            }

            foreach (var button in line)
            {
                var color = FromCoreColorToVk(button.Color);
                kb.AddButton(new MessageKeyboardButtonAction()
                {
                    Label   = button.Title,
                    Payload = button.Payload,
                    Type    = inlineKeyboardEnabled ? KeyboardButtonActionType.Callback : KeyboardButtonActionType.Text,
                }, color);
                // kb.AddButton(button.Title, button.PayloadValue, color, button.PayloadKey);
            }

            isFirst = false;
        }

        return(kb.Build());
    }
예제 #9
0
    public static CoreKeyboard GetDefaultKeyboard()
    {
        var kb = new CoreKeyboard(false);

        kb.AddButton("Расписание", CoreKeyboardButtonColor.Primary, "scheduleKeyboard", string.Empty)
        .AddButton("Экзамены", CoreKeyboardButtonColor.Primary, "exams", string.Empty)
        .AddLine()
        .AddButton("Погода", CoreKeyboardButtonColor.Primary, "weatherNow", string.Empty)
        .AddButton("Ежедневная погода", CoreKeyboardButtonColor.Primary, "weatherDailyKeyboard", string.Empty)
        .AddLine()
        .AddButton("Рассылка", CoreKeyboardButtonColor.Primary, "mailingKeyboard", string.Empty)
        .AddButton("Напоминания", CoreKeyboardButtonColor.Default, "reminds", string.Empty)
        .AddButton("Справка", CoreKeyboardButtonColor.Primary, "help", string.Empty);

        return(kb);
    }
예제 #10
0
    public static CoreKeyboard GetDailyWeatherKeyboard()
    {
        const string defaultFormat = "dd.MM.yyyy";
        var          today         = DateTime.Now;
        var          tomorrow      = today.AddDays(1);

        var kb = new CoreKeyboard
        {
            IsInline = true
        };

        kb.AddButton("На сегодня", CoreKeyboardButtonColor.Primary,
                     "weatherDaily", today.ToString(defaultFormat))
        .AddLine()
        .AddButton("На завтра", CoreKeyboardButtonColor.Primary,
                   "weatherDaily", tomorrow.ToString(defaultFormat))
        .AddReturnToMenuButton();

        return(kb);
    }
예제 #11
0
    public static CoreKeyboard GetScheduleKeyboard()
    {
        const string defaultFormat = "dd.MM.yyyy";
        var          today         = DateTime.Now;

        var keyboard = new CoreKeyboard
        {
            IsInline = true
        };

        keyboard.AddButton($"На сегодня ({today:dd.MM - dddd})", CoreKeyboardButtonColor.Primary,
                           "schedule", today.ToString(defaultFormat));
        keyboard.AddLine();

        var tomorrow = today.AddDays(1);

        if (tomorrow.DayOfWeek != DayOfWeek.Sunday)
        {
            keyboard.AddButton($"На завтра ({tomorrow:dd.MM - dddd})", CoreKeyboardButtonColor.Primary,
                               "schedule", tomorrow.ToString(defaultFormat));
            keyboard.AddLine();
        }

        for (var i = 1; i < 7; i++)
        {
            var date = tomorrow.AddDays(i);
            if (date.DayOfWeek == DayOfWeek.Sunday)
            {
                continue;
            }

            keyboard.AddButton($"На {date:dd.MM (dddd)}", CoreKeyboardButtonColor.Primary,
                               "schedule", date.ToString(defaultFormat));
            if (i % 2 == 0)
            {
                keyboard.AddLine();
            }
        }

        return(keyboard.AddReturnToMenuButton(false));
    }
예제 #12
0
    public async Task SendToMany(IEnumerable <long> chatIds, string message, CoreKeyboard keyboard = null,
                                 IEnumerable <string> attachments = null)
    {
        message = TrimText(message);
        foreach (var chunk in chatIds.Chunk(25))
        {
            foreach (var id in chunk)
            {
                try
                {
                    await Send(id, message, keyboard, attachments);
                }
                catch (Exception e)
                {
                    _logger.Error(e, "Ошибка при отправке сообщения");
                }
            }

            await Task.Delay(1500);
        }
    }