Skip to content

Commit

Permalink
Fix Discord Webhook issue (DevBetterCom#1035)
Browse files Browse the repository at this point in the history
Discord changed their API so that the `username` property on the request object can no longer be an empty string. We need to make that property a null or not include it at all
  • Loading branch information
snowfrogdev authored Mar 10, 2023
1 parent f21c294 commit 4dfe3e4
Show file tree
Hide file tree
Showing 3 changed files with 110 additions and 50 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ Head over to [devBetter.com](https://devbetter.com) to see the live site. Scroll

### Prerequisite

- [.NET 7 SDK](https://dotnet.microsoft.com/en-us/download)
- [The command-line interface (CLI) tools for Entity Framework Core](https://docs.microsoft.com/en-us/ef/core/cli/dotnet)

### Building and Running the App Locally
Expand All @@ -61,7 +62,7 @@ Some actions, such as registering a member, send email notifications. You should

You should create an **appsettings.development.json** file to hold your other connection strings such as for Azure Storage. You can use [Azurite](https://github.com/Azure/Azurite) as a local emulator for this.

You will need to set up a Discord server - see [here](https://ardalis.com/add-discord-notifications-to-asp-net-core-apps/) for a walkthrough - and add the url to appsettings.development.json in the Discord Webhooks section that you can copy from appsettings.json. Alternatively you can create a mock server which will provide you with a url to use - an example is mocky.io
For the Discord web hook integration, you can use the `dev-test` channel in devBetter's Discord server. The web hook url is in the channel description on Discord. You can use that in you appsettings.development.json. Alternatively, you can set up your own Discord server - see [here](https://ardalis.com/add-discord-notifications-to-asp-net-core-apps/) for a walkthrough - and add the url to appsettings.development.json in the Discord Webhooks section that you can copy from appsettings.json. You could also create a mock server which will provide you with a url to use - an example is mocky.io

## EF Migrations Commands

Expand Down
101 changes: 52 additions & 49 deletions src/DevBetterWeb.Infrastructure/DiscordWebhooks/BaseWebhook.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,59 +18,62 @@ namespace DevBetterWeb.Infrastructure.DiscordWebooks;
[JsonObject]
public abstract class BaseWebhook
{
private readonly HttpClient _httpClient = new HttpClient();
protected string _webhookUrl;
private readonly IAppLogger<BaseWebhook> _logger;
private readonly HttpClient _httpClient = new HttpClient();
protected string _webhookUrl;
private readonly IAppLogger<BaseWebhook> _logger;

public BaseWebhook(string webhookUrl, IAppLogger<BaseWebhook> logger)
{
Guard.Against.NullOrEmpty(webhookUrl, nameof(webhookUrl));
_webhookUrl = webhookUrl;
_logger = logger;
}
public BaseWebhook(string webhookUrl, IAppLogger<BaseWebhook> logger)
{
Guard.Against.NullOrEmpty(webhookUrl, nameof(webhookUrl));
_webhookUrl = webhookUrl;
_logger = logger;
}

public BaseWebhook(ulong id, string token, IAppLogger<BaseWebhook> logger) : this($"https://discordapp.com/api/webhooks/{id}/{token}", logger)
{
}
public BaseWebhook(ulong id, string token, IAppLogger<BaseWebhook> logger) : this($"https://discordapp.com/api/webhooks/{id}/{token}", logger)
{
}

[JsonProperty("content")]
public string Content { get; set; } = "";
[JsonProperty("username")]
public string Username { get; set; } = "";
[JsonProperty("avatar_url")]
public string AvatarUrl { get; set; } = "";
// ReSharper disable once InconsistentNaming
[JsonProperty("tts")]
public bool IsTTS { get; set; }
[JsonProperty("embeds")]
public List<Embed> Embeds { get; set; } = new List<Embed>();
[JsonProperty("content")]
public string Content { get; set; } = "";
[JsonProperty("username")]
public string? Username { get; set; }
[JsonProperty("avatar_url")]
public string AvatarUrl { get; set; } = "";
// ReSharper disable once InconsistentNaming
[JsonProperty("tts")]
public bool IsTTS { get; set; }
[JsonProperty("embeds")]
public List<Embed> Embeds { get; set; } = new List<Embed>();

public virtual async Task<HttpResponseMessage> Send()
{
var content = new StringContent(JsonConvert.SerializeObject(this), Encoding.UTF8, "application/json");
try
{
return await _httpClient.PostAsync(_webhookUrl, content);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error sending webhook", _webhookUrl, content);
return new HttpResponseMessage();
}
}
public virtual async Task<HttpResponseMessage> Send()
{
var content = new StringContent(JsonConvert.SerializeObject(this), Encoding.UTF8, "application/json");
try
{
var response = await _httpClient.PostAsync(_webhookUrl, content);
var responseContent = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
return response;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error sending webhook", _webhookUrl, content);
return new HttpResponseMessage();
}
}

public Task<HttpResponseMessage> Send(string content, string username = "", string avatarUrl = "", bool isTTS = false, IEnumerable<Embed>? embeds = null)
{
Content = content;
Username = username;
AvatarUrl = avatarUrl;
IsTTS = isTTS;
Embeds.Clear();
if (embeds != null)
{
Embeds.AddRange(embeds);
}
public Task<HttpResponseMessage> Send(string content, string? username = null, string avatarUrl = "", bool isTTS = false, IEnumerable<Embed>? embeds = null)
{
Content = content;
Username = username;
AvatarUrl = avatarUrl;
IsTTS = isTTS;
Embeds.Clear();
if (embeds != null)
{
Embeds.AddRange(embeds);
}

return Send();
}
return Send();
}
}
56 changes: 56 additions & 0 deletions src/DevBetterWeb.Web/appsettings.Template.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
{
"googleReCaptcha:SiteKey": "6LcEwN4ZAAAAAC-_UfJ0dmdU8bRxLLJ4FwjXyE1R",
"googleReCaptcha:SecretKey": "YOUR_SECRET_KEY",
"storageconnectionstring": "[connection string goes here]",
"VIMEO_TOKEN": "[vimeo token string goes here]",
"videoUrlPrefix": "https://devbetter2storage.blob.core.windows.net/videos/",
"GoogleMapsAPIKey": "GOOGLE_MAPS_API_KEY",
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=DevBetterWeb.App;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"ApiSettings": {
"ApiKey": "[api key string goes here]"
},
"Logging": {
"ApplicationInsights": {
"LogLevel": {
"Default": "Debug",
"Microsoft": "Error"
}
},
"IncludeScopes": {},
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
},
"AzureAppServicesFile": {
"IncludeScopes": true,
"LogLevel": {
"Default": "Information"
}
}
},
"DiscordWebhookUrls": {
"AdminUpdates": "(test url goes here)",
"BookDiscussion": "(test url goes here)",
"CoachingSessionsNotifications": "(test url goes here)",
"DevBetterComNotifications": "(test url goes here)"
},
"StripeOptions": {
"StripeInvoicePaidWebHookSecretKey": "WebHook key goes here",
"StripePaymentIntentSucceededWebHookSecretKey": "WebHook key goes here",
"StripeCustomerSubscriptionUpdatedWebHookSecretKey": "WebHook key goes here",
"StripeCustomerSubscriptionDeletedWebHookSecretKey": "WebHook key goes here",
"StripePublishableKey": "publishable key",
"StripeSecretKey": "secret key",
"YearlyPlanId": "yearly plan price id",
"MonthlyPlanId": "monthly plan price id"
},
"SubscriptionPlanOptions": {
"expectedNumberOfSubscriptionPlansNotInPaymentProvider": 0
},
"ApplicationInsights": {
"ConnectionString": "(appinsights connection string goes here)"
}
}

0 comments on commit 4dfe3e4

Please sign in to comment.