-
Notifications
You must be signed in to change notification settings - Fork 4
poll-feat #39
base: master
Are you sure you want to change the base?
poll-feat #39
Conversation
|
||
private readonly string[] _emojis = | ||
{ | ||
"", "1️⃣", "2️⃣", "3️⃣","4️⃣","5️⃣","6️⃣","7️⃣", "8️⃣", "9️⃣", "🔟" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@Bibletoon Записывай как работать с эмодзи кекв
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
(это локальный мем, если что, не обращайте внимания)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Кекв
LoggerHolder.Instance.Error("The message wasn't sent by the command " + | ||
"\"{CommandName}\", the length must not be zero", | ||
PollCommand.Descriptor.CommandName); | ||
return Result.Ok(); |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Что за -1?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Я думаю это связано с тем, что на 0 позиции будет название команды, а остальные - это аргументы пула. А он считает именно их кол-во.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Тогда не понял, почему вообще название команды это аргумент команды...
There was a problem hiding this comment.
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], |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
У тебя из метода GetPollArguments
может вернуться пустой лист
private async void ReactWithEmojis(SocketCommandContext context) | ||
{ | ||
for (int i = 1; i < _argsCount; i++) | ||
{ | ||
await context.Message.AddReactionAsync(new Emoji(_emojis[i])) | ||
.ConfigureAwait(false); | ||
} | ||
} |
There was a problem hiding this comment.
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? |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Что-то вообще ничего не понял
public string[] Args { get; } | ||
public List<string> Args { get; } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
В чем суть данного (и пачки ниже) изменения?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Хотел получать переменное кол-во аргументов. Изначально нужно было указывать определенное количество, как я понял. Так же и появилась проблема выше - проверка на полученное количество аргументов и заданное на получение в PollCommand дескрипторе, как args
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Вообще ничего не понял
Что значит переменное кол-во аргументов?
Ты хочешь сам изменять аргументы команды? Ты явно делаешь что-то не так
There was a problem hiding this comment.
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 по логике, поэтому изменил на лист. Может и правда не так понял 😕
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Так тебе приходит запрос уже с каким-то конкретным количеством аргументов, зачем тут лист?
Ну пришло 5 - массив из 5 элементов
7 - из 7
Сам по себе-то массив не меняется
public Task<Result<IBotMessage>> Execute(CommandContainer args) | ||
{ | ||
IBotMessage message = new BotPollMessage(String.Join(" ", args.Arguments)); | ||
return Task.FromResult(Result.Ok(message)); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Не понял, создал ботмесседж и вернул его
А где сама логика Execute
-то?
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
А в чем смысл создавать каждый раз одну и ту же регулярку? Ну сделай ее статичным полем приватным просто
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
- Очень сильно пострадал DiscordProvider, в него добавилось много логики, которая не принадлежит ему
- Ряд замечаний в сторону улучшения объектно-ориентированности кода.
@@ -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; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Это не часть логики DiscordApiProvider.
private readonly string[] _emojis = | ||
{ | ||
"", "1️⃣", "2️⃣", "3️⃣","4️⃣","5️⃣","6️⃣","7️⃣", "8️⃣", "9️⃣", "🔟" | ||
}; |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
- Почему именно PingCommand.Descriptor.CommandName?
- А в чем идея этого изменения?
LoggerHolder.Instance.Error("The message wasn't sent by the command " + | ||
"\"{CommandName}\", the length must not be zero", | ||
PollCommand.Descriptor.CommandName); | ||
return Result.Ok(); |
There was a problem hiding this comment.
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")) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
- Это не должно быть в ApiProvider
- Ты хардкодишь конкретную команду тут, так быть не должно иначе этот метод на каждую команду будет получать новый if
- А мы разве не поддерживаем кастомные префиксы для команд?
@@ -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? |
There was a problem hiding this comment.
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 - значит точно ок".
IBotMessage message = new BotPollMessage(String.Join(" ", args.Arguments)); | ||
return Task.FromResult(Result.Ok(message)); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ничего не понял)
Почему мы на эту команду делаем ничего?
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
- Мне почему-то кажется, что тут более подходящим названием было AddReactionToMessage.
- Имеет смысл вынести логику реакции. Например, сделать класс MessageWithPool, который в конструктор принимал бы message и poolAnswerCount и внутри бы делал вот эту магию с добавлением Emoji.
{ | ||
List<string> arguments = GetPollArguments(text); | ||
|
||
Result<string> result = CheckText(text); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Наверное же сначала нужно делать этот чек, а потом уже GetPoolArgs.
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)) | ||
}; | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Опять же, это выглядит как логика создания какого-то особенного сообщения. Давайте выделим класс PoolInfoMessage, которое будет создаваться от аргументов, внутри вот эти действия делать и ему оставим метод BuildToEmbed.
Ясно, два шакала одновременно накинулись... |
Буди анчоуса, тройничок устроим |
Вообще судя по всему, произошёл какое-то небольшое недопонимание задачи. В моём представлении это должно выглядеть примерно так:
Про варианты ответов в опросе: Ну и хотелось бы сразу сделать создание опроса в Телеграмме, а не оставлять заглушку (там всё будет проще и ограничится вызовом одного-двух методов библиотеки как мне кажется) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Если что - пиши, если неудобно писать, можем устроить митинг в дискорде.
:с |
:сс |
Добавлена возможность создавать простые опросы до 10-ти вариантов ответа.
Пока все довольно шатко работает 🥴 некоторые моменты нужно подправить.
Предложения выделяются в "..." и '...'