Skip to content

Commit 4e2a2ff

Browse files
committed
Improve argument parsing in TextCommandHandler.cs
Refactor the argument parsing logic in TextCommandHandler.cs to use a List<string> for collecting arguments and a string for building the current argument. This new implementation correctly handles quoted arguments by checking if a part starts and ends with a quote, or if it starts or ends with a quote and continues to build the argument until the closing quote is found. It also trims the quotes from the arguments and filters out any empty or whitespace-only arguments.
1 parent 988b048 commit 4e2a2ff

File tree

1 file changed

+26
-19
lines changed

1 file changed

+26
-19
lines changed

Sources/TelegramBot/Handlers/TextCommandHandler.cs

Lines changed: 26 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -27,29 +27,36 @@ public TextCommandHandler(IReadOnlyCollection<MethodInfo> controllerMethods, Upd
2727
return null;
2828
}
2929
var message = update.Message;
30-
// /mail Vadik vadbex@gmail.com Test "Hello! It's me..."
31-
string[] parts = message.Text.Split(' ', System.StringSplitOptions.RemoveEmptyEntries);
32-
if (parts.Length == 0)
33-
{
34-
return null;
35-
}
36-
// if part is quoted, then join it with the next part
37-
for (int i = 0; i < parts.Length; i++)
30+
string[] parts = message.Text.Split(' ');
31+
List<string> arguments = new List<string>();
32+
string currentArgument = string.Empty;
33+
foreach (var part in parts)
3834
{
39-
if (parts[i].StartsWith('"'))
35+
if (part.StartsWith('"') && part.EndsWith('"'))
4036
{
41-
for (int j = i + 1; j < parts.Length; j++)
42-
{
43-
if (parts[j].EndsWith('"'))
44-
{
45-
parts[i] = parts[i][1..] + " " + parts[j][..^1];
46-
parts[j] = string.Empty;
47-
break;
48-
}
49-
}
37+
arguments.Add(part);
38+
}
39+
else if (part.StartsWith('"'))
40+
{
41+
currentArgument = part;
42+
}
43+
else if (part.EndsWith('"'))
44+
{
45+
currentArgument += " " + part;
46+
arguments.Add(currentArgument);
47+
currentArgument = string.Empty;
48+
}
49+
else if (!string.IsNullOrEmpty(currentArgument))
50+
{
51+
currentArgument += " " + part;
52+
}
53+
else
54+
{
55+
arguments.Add(part);
5056
}
5157
}
52-
parts = parts
58+
parts = arguments
59+
.Select(p => p.Trim('"'))
5360
.Where(p => !string.IsNullOrWhiteSpace(p))
5461
.ToArray();
5562
if (parts.Length == 0)

0 commit comments

Comments
 (0)