Skip to content

Commit

Permalink
Implement feature to embed jumplinks
Browse files Browse the repository at this point in the history
  • Loading branch information
Naamloos committed Feb 13, 2024
1 parent 3d1565d commit 66a62b2
Show file tree
Hide file tree
Showing 4 changed files with 198 additions and 0 deletions.
113 changes: 113 additions & 0 deletions ModCore/Components/AutoEmbedComponents.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
using DSharpPlus.EventArgs;
using DSharpPlus;
using ModCore.Extensions.Abstractions;
using ModCore.Extensions.Attributes;
using System.Collections.Generic;
using System.Threading.Tasks;
using DSharpPlus.Entities;
using ModCore.Database;
using ModCore.Extensions;
using ModCore.Utils.Extensions;
using ModCore.Database.JsonEntities;
using System.Linq;
using ModCore.Entities;

namespace ModCore.Components
{
public class AutoEmbedComponents : BaseComponentModule
{
private DatabaseContextBuilder database;

public AutoEmbedComponents(DatabaseContextBuilder database)
{
this.database = database;
}

[Component("ae.select", ComponentType.StringSelect)]
public async Task AutoRoleConfig(ComponentInteractionCreateEventArgs e)
{
await e.Interaction.CreateResponseAsync(InteractionResponseType.DeferredMessageUpdate, new DiscordInteractionResponseBuilder().AsEphemeral(true));

EmbedMessageLinksMode mode;

switch(e.Interaction.Data.Values[0])
{
default:
mode = EmbedMessageLinksMode.Disabled; break;
case "prefix":
mode = EmbedMessageLinksMode.Prefixed; break;
case "always":
mode = EmbedMessageLinksMode.Always; break;
}

await using (var db = database.CreateContext())
{
var guild = db.GuildConfig.First(x => x.GuildId == (long)e.Guild.Id);
var settings = guild.GetSettings();

settings.EmbedMessageLinks = mode;
guild.SetSettings(settings);
db.GuildConfig.Update(guild);
await db.SaveChangesAsync();
}

string state;
switch (mode)
{
default:
state = "Disabled";
break;
case EmbedMessageLinksMode.Prefixed:
state = "Only when prefixed with `!`";
break;
case EmbedMessageLinksMode.Always:
state = "Always embed";
break;
}

await e.Interaction.EditOriginalResponseAsync(new DiscordWebhookBuilder().WithContent($"👍 New state for Auto Jump Link Embed: {state}.")
.AddComponents(new DiscordButtonComponent(ButtonStyle.Secondary, "ae", "Back to Jump Link Embed config", emoji: new DiscordComponentEmoji("🏃"))));
}

public static async Task PostMenuAsync(DiscordInteraction interaction, InteractionResponseType responseType, DatabaseContext db)
{
await using (db)
{
var settings = interaction.Guild.GetGuildSettings(db);

string state;
var mode = settings.EmbedMessageLinks;

switch(mode)
{
default:
state = "Disabled";
break;
case EmbedMessageLinksMode.Prefixed:
state = "Only when prefixed with `!`";
break;
case EmbedMessageLinksMode.Always:
state = "Always embed";
break;
}

var embed = new DiscordEmbedBuilder()
.WithTitle("🖇️ Jump Link Embed Configuration")
.WithDescription("Jump Link Embed allows ModCore to automatically post embeds for jump links.")
.AddField("Current State", state);

await interaction.CreateResponseAsync(responseType, new DiscordInteractionResponseBuilder()
.AddEmbed(embed)
.WithContent("")
.AddComponents(new DiscordSelectComponent("ae.select", "Change state", new List<DiscordSelectComponentOption>()
{
new DiscordSelectComponentOption("Disable", "off", "Disables jump link embeds", mode == EmbedMessageLinksMode.Disabled, new DiscordComponentEmoji("")),
new DiscordSelectComponentOption("Prefixed with !", "prefix", "Create embeds when prefixed with !",
mode == EmbedMessageLinksMode.Prefixed, new DiscordComponentEmoji("")),
new DiscordSelectComponentOption("Always", "always", "Always create jump link embeds", mode == EmbedMessageLinksMode.Always, new DiscordComponentEmoji(""))
}))
.AddComponents(new DiscordButtonComponent(ButtonStyle.Secondary, "cfg", "Back to Config", emoji: new DiscordComponentEmoji("🏃"))));
}
}
}
}
5 changes: 5 additions & 0 deletions ModCore/Components/ConfigComponents.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ public async Task NicknameAsync(ComponentInteractionCreateEventArgs e)
public async Task RoleMenuAsync(ComponentInteractionCreateEventArgs e)
=> await RoleMenuConfigComponents.PostMenuAsync(e.Interaction, InteractionResponseType.UpdateMessage, database.CreateContext());

[Component("ae", ComponentType.Button)]
public async Task AutoEmbedAsync(ComponentInteractionCreateEventArgs e)
=> await AutoEmbedComponents.PostMenuAsync(e.Interaction, InteractionResponseType.UpdateMessage, database.CreateContext());

[Component("cfg.dump", ComponentType.Button)]
public async Task DumpConfigAsync(ComponentInteractionCreateEventArgs e)
{
Expand Down Expand Up @@ -130,6 +134,7 @@ public static async Task PostMenuAsync(DiscordInteraction interaction, Interacti
})
.AddComponents(new DiscordComponent[]
{
new DiscordButtonComponent(ButtonStyle.Primary, "ae", "Jump Link Embed", emoji: new DiscordComponentEmoji("🖇️")),
new DiscordButtonComponent(ButtonStyle.Secondary, "cfg.reset", "Reset Server Configuration", emoji: new DiscordComponentEmoji("🗑")),
new DiscordButtonComponent(ButtonStyle.Secondary, "cfg.dump", "Dump JSON (Advanced)", emoji: new DiscordComponentEmoji("📩"))
})
Expand Down
9 changes: 9 additions & 0 deletions ModCore/Database/JsonEntities/GuildSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,15 @@ public partial class GuildSettings

[JsonProperty("role_menus")]
public List<GuildRoleMenu> RoleMenus = new List<GuildRoleMenu>();

public EmbedMessageLinksMode EmbedMessageLinks = EmbedMessageLinksMode.Disabled;
}

public enum EmbedMessageLinksMode
{
Disabled = 0,
Prefixed = 1,
Always = 2
}

public class GuildRoleMenu
Expand Down
71 changes: 71 additions & 0 deletions ModCore/Listeners/EmbedMessageLinks.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
using DSharpPlus.EventArgs;
using DSharpPlus;
using Microsoft.Extensions.Caching.Memory;
using ModCore.Database;
using ModCore.Extensions.Attributes;
using ModCore.Extensions.Enums;
using System.Threading.Tasks;
using ModCore.Database.JsonEntities;
using ModCore.Utils.Extensions;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System;
using DSharpPlus.Entities;
using Humanizer;

namespace ModCore.Listeners
{
public class EmbedMessageLinks
{
public static Regex AlwaysEmbedRegex = new Regex(@"https?:\/\/.*?discord.com\/channels\/([0-9]+)\/([0-9]+)\/([0-9]+)", RegexOptions.Compiled);
public static Regex PrefixedEmbedRegex = new Regex(@"!https?:\/\/.*?discord.com\/channels\/([0-9]+)\/([0-9]+)\/([0-9]+)", RegexOptions.Compiled);

[AsyncListener(EventType.MessageCreated)]
public static async Task ReactionAddedAsync(MessageCreateEventArgs eventargs, DatabaseContextBuilder database,
DiscordClient client, IMemoryCache cache)
{
using (DatabaseContext ctx = database.CreateContext())
{
GuildSettings settings;
settings = eventargs.Guild.GetGuildSettings(ctx);

if (settings == null)
return; // No guild settings so starboard is disabled.

if (settings.EmbedMessageLinks == EmbedMessageLinksMode.Disabled)
return;// embedding is disabled.

Regex rex = settings.EmbedMessageLinks == EmbedMessageLinksMode.Always? AlwaysEmbedRegex : PrefixedEmbedRegex;
var matches = rex.Matches(eventargs.Message.Content);

var embeds = new List<DiscordEmbed>();

foreach(Match match in matches)
{
var guildId = ulong.Parse(match.Groups[1].Value);
var channelId = ulong.Parse(match.Groups[2].Value);
var messageId = ulong.Parse(match.Groups[3].Value);

if (guildId != eventargs.Guild.Id) return; // not same guild
if (!eventargs.Guild.Channels.ContainsKey(channelId)) return; // channel not found

var channel = eventargs.Guild.Channels[channelId];
try
{
var message = await channel.GetMessageAsync(messageId);
// no exception = exists
var truncatedText = message.Content.Length > 250? message.Content.Truncate(250) + "..." : message.Content;
embeds.Add(new DiscordEmbedBuilder()
.WithDescription($"{truncatedText}\n\n[Jump to message]({match.Value.Replace("!", "")})")
.WithAuthor(message.Author.GetDisplayUsername(), iconUrl: message.Author.GetAvatarUrl(ImageFormat.Png))
.Build());
}
catch (Exception) { }
}

if(embeds.Count > 0)
await eventargs.Channel.SendMessageAsync(x => x.AddEmbeds(embeds));
}
}
}
}

0 comments on commit 66a62b2

Please sign in to comment.