Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions Remora.Discord.Commands/Parsers/SnowflakeParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//

using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
Expand All @@ -38,9 +39,26 @@
[PublicAPI]
public class SnowflakeParser : AbstractTypeParser<Snowflake>
{
private static readonly Regex _channelLinkRegex = new
(
@"^https://(canary\.|ptb\.)?discord\.com/channels/(?<guild_id>@me|[0-9]*)/(?<channel_id>[0-9]*)(/(?<message_id>[0-9]*))?/?$",
RegexOptions.Compiled | RegexOptions.CultureInvariant
);

/// <inheritdoc />
public override ValueTask<Result<Snowflake>> TryParseAsync(string value, CancellationToken ct = default)
{
var channelLinkMatch = _channelLinkRegex.Match(value);
if (channelLinkMatch.Success)

Check warning

Code scanning / InspectCode

Invert 'if' statement to reduce nesting Warning

Invert 'if' statement to reduce nesting
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I don't get this tbh.

{
value = channelLinkMatch.Groups["message_id"].Value;

if (string.IsNullOrEmpty(value))
{
value = channelLinkMatch.Groups["channel_id"].Value;
}
}

return new
(
!DiscordSnowflake.TryParse(value.Unmention(), out var snowflake)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,24 @@ public async Task CanParseSnowflakeByNumber()
Assert.Equal(snowflakeValue, tryParse.Entity.Value);
}

/// <summary>
/// Tests whether the parser can parse snowflake value given by url.
/// </summary>
/// <param name="value">Mention that should be parsed correctly.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[InlineData("https://discord.com/channels/690919691404967977/765178263517397033")]
[InlineData("https://discord.com/channels/690919691404967977/1389600463250260019/765178263517397033")]
[InlineData("https://canary.discord.com/channels/690919691404967977/1389600463250260019/765178263517397033")]
[InlineData("https://ptb.discord.com/channels/690919691404967977/1389600463250260019/765178263517397033")]
[Theory]
public async Task CanParseSnowflakeByUrl(string value)
{
ulong snowflakeValue = 765178263517397033;
var tryParse = await _parser.TryParseAsync(value);
ResultAssert.Successful(tryParse);
Assert.Equal(snowflakeValue, tryParse.Entity.Value);
}

/// <summary>
/// Tests whether the parser can parse snowflake value given by mentions.
/// </summary>
Expand Down
Loading