From dc114e3eb18e43615b4c8b1c8d8afb7efbce32b0 Mon Sep 17 00:00:00 2001 From: Chris Johnston Date: Fri, 8 Feb 2019 12:25:47 -0800 Subject: [PATCH] Add webhook url overload for DiscordWebhookClient Adds an overloaded constructor for `DiscordWebhookClient` which accepts the webhook URL. This URL is parsed using a regex for the id and token. If the token is invalid an `ArgumentException` is thrown. --- .../DiscordWebhookClient.cs | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/src/Discord.Net.Webhook/DiscordWebhookClient.cs b/src/Discord.Net.Webhook/DiscordWebhookClient.cs index 16841e936..2a0de5ef7 100644 --- a/src/Discord.Net.Webhook/DiscordWebhookClient.cs +++ b/src/Discord.Net.Webhook/DiscordWebhookClient.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Text.RegularExpressions; using System.Threading.Tasks; using Discord.Logging; using Discord.Rest; @@ -26,6 +27,12 @@ namespace Discord.Webhook /// Creates a new Webhook Discord client. public DiscordWebhookClient(ulong webhookId, string webhookToken) : this(webhookId, webhookToken, new DiscordRestConfig()) { } + /// Creates a new Webhook Discord client. + public DiscordWebhookClient(string webhookUrl) + : this(webhookUrl, new DiscordRestConfig()) { } + + // regex pattern to match webhook urls + private const string WebhookUrlRegex = @"^.+.com\/api\/webhooks\/([\d]+)\/([A-Za-z0-9_-]+)$"; /// Creates a new Webhook Discord client. public DiscordWebhookClient(ulong webhookId, string webhookToken, DiscordRestConfig config) @@ -43,6 +50,36 @@ namespace Discord.Webhook _webhookId = Webhook.Id; } + /// + /// Creates a new Webhook Discord client. + /// + /// The url of the webhook. + /// The configuration options to use for this client. + /// Thrown if the is an invalid format. + public DiscordWebhookClient(string webhookUrl, DiscordRestConfig config) : this(config) + { + // thrown when groups are not populated/valid, or when there is no match + ArgumentException ex() + => new ArgumentException(paramName: nameof(webhookUrl), message: "The given webhook Url was not in a valid format."); + var re = new Regex(WebhookUrlRegex); + var match = re.Match(webhookUrl); + if (match != null) + { + // ensure that the first group is a ulong, set the _webhookId + // 0th group is always the entire match, so start at index 1 + if (!(match.Groups[1].Success && ulong.TryParse(match.Groups[1].Value, out _webhookId))) + throw ex(); + + if (!match.Groups[2].Success) + throw ex(); + + ApiClient.LoginAsync(TokenType.Webhook, match.Groups[2].Value).GetAwaiter().GetResult(); + Webhook = WebhookClientHelper.GetWebhookAsync(this, _webhookId).GetAwaiter().GetResult(); + } + else + throw ex(); + } + private DiscordWebhookClient(DiscordRestConfig config) { ApiClient = CreateApiClient(config);