-
Notifications
You must be signed in to change notification settings - Fork 71
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Integration] Discord integration (#244)
* Fix updating the user preferences * Fix adding user properties to UserInfo context * Fix adding user properties to UserInfo context * Make the dictionaries merge code more imperative * Create Discord integration * Fix invalid status on Discord integration * Add tests for Discord integration * Change appSettings indentation to match the previous one * Update appSettings for tests * Add empty line at the end of the file to match the convention * Apply code review advice * Add integration image * Apply code refactoring * Add a new line at the end of file
- Loading branch information
Showing
15 changed files
with
594 additions
and
65 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
36 changes: 36 additions & 0 deletions
36
backend/src/Notifo.Domain.Integrations/Discord/DiscordBotClientPool.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
// ========================================================================== | ||
// Notifo.io | ||
// ========================================================================== | ||
// Copyright (c) Sebastian Stehle | ||
// All rights reserved. Licensed under the MIT license. | ||
// ========================================================================== | ||
|
||
using Discord; | ||
using Microsoft.Extensions.Caching.Memory; | ||
|
||
namespace Notifo.Domain.Integrations.Discord; | ||
|
||
public class DiscordBotClientPool : CachePool<IDiscordClient> | ||
{ | ||
public DiscordBotClientPool(IMemoryCache memoryCache) | ||
: base(memoryCache) | ||
{ | ||
} | ||
|
||
public async Task<IDiscordClient> GetDiscordClient(string botToken, CancellationToken ct) | ||
{ | ||
var cacheKey = $"{nameof(IDiscordClient)}_{botToken}"; | ||
|
||
var found = await GetOrCreateAsync(cacheKey, TimeSpan.FromMinutes(5), async () => | ||
{ | ||
var client = new DiscordClient(); | ||
|
||
// Method provides no option to pass CancellationToken | ||
await client.LoginAsync(TokenType.Bot, botToken); | ||
|
||
return client; | ||
}); | ||
|
||
return found; | ||
} | ||
} |
19 changes: 19 additions & 0 deletions
19
backend/src/Notifo.Domain.Integrations/Discord/DiscordClient.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
// ========================================================================== | ||
// Notifo.io | ||
// ========================================================================== | ||
// Copyright (c) Sebastian Stehle | ||
// All rights reserved. Licensed under the MIT license. | ||
// ========================================================================== | ||
|
||
using Discord.Rest; | ||
|
||
namespace Notifo.Domain.Integrations.Discord; | ||
|
||
public class DiscordClient : DiscordRestClient, IAsyncDisposable | ||
{ | ||
public async new ValueTask DisposeAsync() | ||
{ | ||
await LogoutAsync(); | ||
await base.DisposeAsync(); | ||
} | ||
} |
108 changes: 108 additions & 0 deletions
108
backend/src/Notifo.Domain.Integrations/Discord/DiscordIntegration.Messaging.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,108 @@ | ||
// ========================================================================== | ||
// Notifo.io | ||
// ========================================================================== | ||
// Copyright (c) Sebastian Stehle | ||
// All rights reserved. Licensed under the MIT license. | ||
// ========================================================================== | ||
|
||
using Discord; | ||
using Discord.Net; | ||
|
||
namespace Notifo.Domain.Integrations.Discord; | ||
|
||
public sealed partial class DiscordIntegration : IMessagingSender | ||
{ | ||
private const int Attempts = 5; | ||
public const string DiscordChatId = nameof(DiscordChatId); | ||
|
||
public void AddTargets(IDictionary<string, string> targets, UserInfo user) | ||
{ | ||
var userId = GetUserId(user); | ||
|
||
if (!string.IsNullOrWhiteSpace(userId)) | ||
{ | ||
targets[DiscordChatId] = userId; | ||
} | ||
} | ||
|
||
public async Task<DeliveryResult> SendAsync(IntegrationContext context, MessagingMessage message, | ||
CancellationToken ct) | ||
{ | ||
if (!message.Targets.TryGetValue(DiscordChatId, out var chatId)) | ||
{ | ||
return DeliveryResult.Skipped(); | ||
} | ||
|
||
return await SendMessageAsync(context, message, chatId, ct); | ||
} | ||
|
||
private async Task<DeliveryResult> SendMessageAsync(IntegrationContext context, MessagingMessage message, string chatId, | ||
CancellationToken ct) | ||
{ | ||
var botToken = BotToken.GetString(context.Properties); | ||
|
||
for (var i = 1; i <= Attempts; i++) | ||
{ | ||
try | ||
{ | ||
var client = await discordBotClientPool.GetDiscordClient(botToken, ct); | ||
var requestOptions = new RequestOptions { CancelToken = ct }; | ||
|
||
if (!ulong.TryParse(chatId, out var chatIdParsed)) | ||
{ | ||
throw new InvalidOperationException("Invalid Discord DM chat ID."); | ||
} | ||
|
||
var user = await client.GetUserAsync(chatIdParsed, CacheMode.AllowDownload, requestOptions); | ||
if (user is null) | ||
{ | ||
throw new InvalidOperationException("User not found."); | ||
} | ||
|
||
EmbedBuilder builder = new EmbedBuilder(); | ||
|
||
builder.WithTitle(message.Text); | ||
builder.WithDescription(message.Body); | ||
|
||
if (!string.IsNullOrWhiteSpace(message.ImageSmall)) | ||
{ | ||
builder.WithThumbnailUrl(message.ImageSmall); | ||
} | ||
|
||
if (!string.IsNullOrWhiteSpace(message.ImageLarge)) | ||
{ | ||
builder.WithImageUrl(message.ImageLarge); | ||
} | ||
|
||
if (!string.IsNullOrWhiteSpace(message.LinkUrl)) | ||
{ | ||
builder.WithFields(new EmbedFieldBuilder().WithName(message.LinkText ?? message.LinkUrl).WithValue(message.LinkUrl)); | ||
} | ||
|
||
builder.WithFooter("Sent with Notifo"); | ||
|
||
// Throws HttpException if the user has some privacy settings that make it impossible to text them. | ||
await user.SendMessageAsync(string.Empty, false, builder.Build(), requestOptions); | ||
break; | ||
} | ||
catch (HttpException ex) when (ex.DiscordCode == DiscordErrorCode.CannotSendMessageToUser) | ||
{ | ||
return DeliveryResult.Failed("User has privacy settings that prevent sending them DMs on Discord."); | ||
} | ||
catch | ||
{ | ||
if (i == Attempts) | ||
{ | ||
return DeliveryResult.Failed("Unknown error when sending Discord DM to user."); | ||
} | ||
} | ||
} | ||
|
||
return DeliveryResult.Handled; | ||
} | ||
|
||
private static string? GetUserId(UserInfo user) | ||
{ | ||
return UserId.GetString(user.Properties); | ||
} | ||
} |
73 changes: 73 additions & 0 deletions
73
backend/src/Notifo.Domain.Integrations/Discord/DiscordIntegration.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
// ========================================================================== | ||
// Notifo.io | ||
// ========================================================================== | ||
// Copyright (c) Sebastian Stehle | ||
// All rights reserved. Licensed under the MIT license. | ||
// ========================================================================== | ||
|
||
using Discord; | ||
using Notifo.Domain.Integrations.Resources; | ||
using Notifo.Infrastructure.Validation; | ||
|
||
namespace Notifo.Domain.Integrations.Discord; | ||
|
||
public sealed partial class DiscordIntegration : IIntegration | ||
{ | ||
private readonly DiscordBotClientPool discordBotClientPool; | ||
|
||
public static readonly IntegrationProperty UserId = new IntegrationProperty("discordUserId", PropertyType.Text) | ||
{ | ||
EditorLabel = Texts.Discord_UserIdLabel, | ||
EditorDescription = Texts.Discord_UserIdDescription | ||
}; | ||
|
||
public static readonly IntegrationProperty BotToken = new IntegrationProperty("discordBotToken", PropertyType.Text) | ||
{ | ||
EditorLabel = Texts.Discord_BotTokenLabel, | ||
EditorDescription = Texts.Discord_BotTokenDescription, | ||
IsRequired = true | ||
}; | ||
|
||
public IntegrationDefinition Definition { get; } = | ||
new IntegrationDefinition( | ||
"Discord", | ||
Texts.Discord_Name, | ||
"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 127.14 96.36\"><path fill=\"#5865f2\" d=\"M107.7,8.07A105.15,105.15,0,0,0,81.47,0a72.06,72.06,0,0,0-3.36,6.83A97.68,97.68,0,0,0,49,6.83,72.37,72.37,0,0,0,45.64,0,105.89,105.89,0,0,0,19.39,8.09C2.79,32.65-1.71,56.6.54,80.21h0A105.73,105.73,0,0,0,32.71,96.36,77.7,77.7,0,0,0,39.6,85.25a68.42,68.42,0,0,1-10.85-5.18c.91-.66,1.8-1.34,2.66-2a75.57,75.57,0,0,0,64.32,0c.87.71,1.76,1.39,2.66,2a68.68,68.68,0,0,1-10.87,5.19,77,77,0,0,0,6.89,11.1A105.25,105.25,0,0,0,126.6,80.22h0C129.24,52.84,122.09,29.11,107.7,8.07ZM42.45,65.69C36.18,65.69,31,60,31,53s5-12.74,11.43-12.74S54,46,53.89,53,48.84,65.69,42.45,65.69Zm42.24,0C78.41,65.69,73.25,60,73.25,53s5-12.74,11.44-12.74S96.23,46,96.12,53,91.08,65.69,84.69,65.69Z\"/></svg>", | ||
new List<IntegrationProperty> | ||
{ | ||
BotToken | ||
}, | ||
new List<IntegrationProperty> | ||
{ | ||
UserId | ||
}, | ||
new HashSet<string> | ||
{ | ||
Providers.Messaging, | ||
}) | ||
{ | ||
Description = Texts.Discord_Description | ||
}; | ||
|
||
public DiscordIntegration(DiscordBotClientPool discordBotClientPool) | ||
{ | ||
this.discordBotClientPool = discordBotClientPool; | ||
} | ||
|
||
public Task<IntegrationStatus> OnConfiguredAsync(IntegrationContext context, IntegrationConfiguration? previous, | ||
CancellationToken ct) | ||
{ | ||
var botToken = BotToken.GetString(context.Properties); | ||
|
||
try | ||
{ | ||
TokenUtils.ValidateToken(TokenType.Bot, botToken); | ||
} | ||
catch | ||
{ | ||
throw new ValidationException("The Discord bot token is invalid."); | ||
} | ||
|
||
return Task.FromResult(IntegrationStatus.Verified); | ||
} | ||
} |
25 changes: 25 additions & 0 deletions
25
backend/src/Notifo.Domain.Integrations/Discord/DiscordServiceExtensions.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
// ========================================================================== | ||
// Notifo.io | ||
// ========================================================================== | ||
// Copyright (c) Sebastian Stehle | ||
// All rights reserved. Licensed under the MIT license. | ||
// ========================================================================== | ||
|
||
using Notifo.Domain.Integrations; | ||
using Notifo.Domain.Integrations.Discord; | ||
|
||
namespace Microsoft.Extensions.DependencyInjection; | ||
|
||
public static class DiscordServiceExtensions | ||
{ | ||
public static IServiceCollection AddIntegrationDiscord(this IServiceCollection services) | ||
{ | ||
services.AddSingletonAs<DiscordIntegration>() | ||
.As<IIntegration>(); | ||
|
||
services.AddSingletonAs<DiscordBotClientPool>() | ||
.AsSelf(); | ||
|
||
return services; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.