Skip to content
This repository has been archived by the owner on May 12, 2024. It is now read-only.

poll-feat #39

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

poll-feat #39

wants to merge 1 commit into from

Conversation

callbackcat
Copy link
Contributor

Добавлена возможность создавать простые опросы до 10-ти вариантов ответа.
Пока все довольно шатко работает 🥴 некоторые моменты нужно подправить.
Предложения выделяются в "..." и '...'

Added poll feature (raw)

private readonly string[] _emojis =
{
"", "1️⃣", "2️⃣", "3️⃣","4️⃣","5️⃣","6️⃣","7️⃣", "8️⃣", "9️⃣", "🔟"

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Bibletoon Записывай как работать с эмодзи кекв

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(это локальный мем, если что, не обращайте внимания)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Кекв

Comment on lines +145 to +148
LoggerHolder.Instance.Error("The message wasn't sent by the command " +
"\"{CommandName}\", the length must not be zero",
PollCommand.Descriptor.CommandName);
return Result.Ok();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Залогировали ошибку и вернули ок?

@@ -150,15 +176,22 @@ private Task ClientOnMessage(SocketMessage arg)
}

var context = new SocketCommandContext(_client, message);
if (!context.User.IsBot && context.Message.Content.Contains("!Poll"))
{
_argsCount = GetPollArguments(message.Content).Count() - 1;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Что за -1?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я думаю это связано с тем, что на 0 позиции будет название команды, а остальные - это аргументы пула. А он считает именно их кол-во.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тогда не понял, почему вообще название команды это аргумент команды...

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

На 0-й позиции будет заголовок опроса. -1 поправлю, глупый момент, согласен


var embed = new EmbedBuilder
{
Title = arguments[0],

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

У тебя из метода GetPollArguments может вернуться пустой лист

Comment on lines +376 to +383
private async void ReactWithEmojis(SocketCommandContext context)
{
for (int i = 1; i < _argsCount; i++)
{
await context.Message.AddReactionAsync(new Emoji(_emojis[i]))
.ConfigureAwait(false);
}
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Да откуда вы все берете ConfigureAwait? Вам кто-то о нем рассказал или что?
async void не используй, без понимания как, почему и зачем просто сделай async Task

@@ -24,7 +25,7 @@ public Result CheckArgsCount(CommandContainer args)
return commandTask.ToResult<CommandContainer>();
}

return commandTask.Value.Args.Length == args.Arguments.Count
return (commandTask.Value.Args.Count == args.Arguments.Count) || (args.CommandName == "Poll") // Better way to check for Poll?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Что-то вообще ничего не понял

Comment on lines -11 to +12
public string[] Args { get; }
public List<string> Args { get; }

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В чем суть данного (и пачки ниже) изменения?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Хотел получать переменное кол-во аргументов. Изначально нужно было указывать определенное количество, как я понял. Так же и появилась проблема выше - проверка на полученное количество аргументов и заданное на получение в PollCommand дескрипторе, как args

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вообще ничего не понял
Что значит переменное кол-во аргументов?
Ты хочешь сам изменять аргументы команды? Ты явно делаешь что-то не так

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ну нам нужно получать !Poll + args и непонятно как действовать с string[ ], т.к. он просит указать точное количество args, а их может быть от 1 до 10 по логике, поэтому изменил на лист. Может и правда не так понял 😕

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Так тебе приходит запрос уже с каким-то конкретным количеством аргументов, зачем тут лист?
Ну пришло 5 - массив из 5 элементов
7 - из 7
Сам по себе-то массив не меняется

Comment on lines +19 to +23
public Task<Result<IBotMessage>> Execute(CommandContainer args)
{
IBotMessage message = new BotPollMessage(String.Join(" ", args.Arguments));
return Task.FromResult(Result.Ok(message));
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не понял, создал ботмесседж и вернул его
А где сама логика Execute-то?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А она внутри IBotMessage и вызывается BotManager'ом


private List<string> GetPollArguments(string args)
{
var regex = new Regex(@"[^\s""']+|""([^""]*)""|'([^']*)'"); // Splits into "..." '...' a b c

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А в чем смысл создавать каждый раз одну и ту же регулярку? Ну сделай ее статичным полем приватным просто

Copy link
Member

@FrediKats FrediKats left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Очень сильно пострадал DiscordProvider, в него добавилось много логики, которая не принадлежит ему
  2. Ряд замечаний в сторону улучшения объектно-ориентированности кода.

@@ -21,6 +27,12 @@ public class DiscordApiProvider : IBotApiProvider, IDisposable
private readonly object _lock = new object();
private readonly DiscordSettings _settings;
private DiscordSocketClient _client;
private int _argsCount;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это не часть логики DiscordApiProvider.

Comment on lines +32 to +35
private readonly string[] _emojis =
{
"", "1️⃣", "2️⃣", "3️⃣","4️⃣","5️⃣","6️⃣","7️⃣", "8️⃣", "9️⃣", "🔟"
};
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это не часть логики DiscordApiProvider.

@@ -118,12 +130,26 @@ public Result<string> SendTextMessage(string text, SenderInfo sender)
if (text.Length == 0)
{
LoggerHolder.Instance.Error("The message wasn't sent by the command " +
$"\"{PingCommand.Descriptor.CommandName}\", the length must not be zero.");
"\"{CommandName}\", the length must not be zero",
PingCommand.Descriptor.CommandName);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Почему именно PingCommand.Descriptor.CommandName?
  2. А в чем идея этого изменения?

LoggerHolder.Instance.Error("The message wasn't sent by the command " +
"\"{CommandName}\", the length must not be zero",
PollCommand.Descriptor.CommandName);
return Result.Ok();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А почему тут Result.Ok, если это возвращение при ошибке - не валидном наборе аргументов.

@@ -150,15 +176,22 @@ private Task ClientOnMessage(SocketMessage arg)
}

var context = new SocketCommandContext(_client, message);
if (!context.User.IsBot && context.Message.Content.Contains("!Poll"))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Это не должно быть в ApiProvider
  2. Ты хардкодишь конкретную команду тут, так быть не должно иначе этот метод на каждую команду будет получать новый if
  3. А мы разве не поддерживаем кастомные префиксы для команд?

@@ -24,7 +25,7 @@ public Result CheckArgsCount(CommandContainer args)
return commandTask.ToResult<CommandContainer>();
}

return commandTask.Value.Args.Length == args.Arguments.Count
return (commandTask.Value.Args.Count == args.Arguments.Count) || (args.CommandName == "Poll") // Better way to check for Poll?
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если есть кастомная логика проверки валидности размера, то предлагаю сделать базовый класс для команд, где будет виртуальный метод IsValidArgumentCount, который проверяет commandTask.Value.Args.Count == args.Arguments.Count, а PollCommand будет наследоваться и оверрайдить со своей кастомной логикой (в идеале там должен быть парсинг и какая-то проверка, а не "если poll - значит точно ок".

Comment on lines +21 to +22
IBotMessage message = new BotPollMessage(String.Join(" ", args.Arguments));
return Task.FromResult(Result.Ok(message));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ничего не понял)
Почему мы на эту команду делаем ничего?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В предыдущих сериях pr'ах была добавлена возможность отправлять не только текст, поэтому команда отвечает только за то, что бы создать сообщение, а вызовом метода отправки занимается BotManager (так как сообщению нужен api provider, что бы отправиться)

return options;
}

private async void ReactWithEmojis(SocketCommandContext context)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Мне почему-то кажется, что тут более подходящим названием было AddReactionToMessage.
  2. Имеет смысл вынести логику реакции. Например, сделать класс MessageWithPool, который в конструктор принимал бы message и poolAnswerCount и внутри бы делал вот эту магию с добавлением Emoji.

{
List<string> arguments = GetPollArguments(text);

Result<string> result = CheckText(text);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Наверное же сначала нужно делать этот чек, а потом уже GetPoolArgs.

Comment on lines +317 to +328
for (int i = 1; i < arguments.Count; i++)
{
arguments[i] = _emojis[i] + "\t" + arguments[i];
}

var embed = new EmbedBuilder
{
Title = arguments[0],
Color = Color.Purple,
Description = String.Join("\n", arguments.Skip(1))
};

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Опять же, это выглядит как логика создания какого-то особенного сообщения. Давайте выделим класс PoolInfoMessage, которое будет создаваться от аргументов, внутри вот эти действия делать и ему оставим метод BuildToEmbed.

@FrediKats
Copy link
Member

Ясно, два шакала одновременно накинулись...

@hrrrrustic
Copy link

hrrrrustic commented Aug 15, 2021

Ясно, два шакала одновременно накинулись...

Буди анчоуса, тройничок устроим

@Bibletoon
Copy link
Member

Bibletoon commented Aug 16, 2021

Вообще судя по всему, произошёл какое-то небольшое недопонимание задачи. В моём представлении это должно выглядеть примерно так:

  • Есть какая-то отдельная сущность для опроса, имеющая в себе заголовок опроса и варианты ответов
  • BotPollMessage как раз таки содержит в себе эту сущность
  • Пользователь в любой команде может создать опрос и вернуть BotPollMessage

Про варианты ответов в опросе:
Это шаманство с проверкой того, является ли команда опросом (во время проверки количества аргументов) супер лишняя. Во-первых, это костыль. Во-вторых, нам пока не нужно уметь получать переменное количество вариантов ответов от пользователя. То, какие у опроса будут варианты ответов должна решать команда, его вызывающая: там может быть как постоянные варианты (типа да/нет), так и варианты зависящие от переданных аргументов (оставим принятие решения на создателя команды)

Ну и хотелось бы сразу сделать создание опроса в Телеграмме, а не оставлять заглушку (там всё будет проще и ограничится вызовом одного-двух методов библиотеки как мне кажется)

Copy link
Member

@Bibletoon Bibletoon left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если что - пиши, если неудобно писать, можем устроить митинг в дискорде.

@FrediKats
Copy link
Member

@FrediKats
Copy link
Member

:сс

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Реализовать возможность отправлять опросы
4 participants