Skip to content

Commit

Permalink
v2 Rewrite (#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
Plerx2493 authored Nov 16, 2022
1 parent 3d82b76 commit 4f925fe
Show file tree
Hide file tree
Showing 55 changed files with 2,996 additions and 1,896 deletions.
815 changes: 687 additions & 128 deletions .editorconfig

Large diffs are not rendered by default.

5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -364,4 +364,7 @@ MigrationBackup/
FodyWeavers.xsd

# Rider
.idea/
.idea/

# Config
*.json
15 changes: 15 additions & 0 deletions ModularAssistentForDiscordServer/Commands/CommandUtillity.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using DSharpPlus.Entities;

namespace MADS.Commands;

public class CommandUtility
{
public static DiscordEmbedBuilder GetDiscordEmbed()
{
var standardEmbed = new DiscordEmbedBuilder()
{
Color = new Optional<DiscordColor>(new DiscordColor(0, 255, 194)),
};
return standardEmbed;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using System.Text.RegularExpressions;
using DSharpPlus;
using DSharpPlus.Entities;
using DSharpPlus.SlashCommands;

namespace MADS.Commands.ContextMenu;

public class StealEmojiMessage : ApplicationCommandModule
{
private const string EmojiRegex = @"<a?:(.+?):(\d+)>";

[ContextMenu(ApplicationCommandType.MessageContextMenu, "Steal emoji")]
public async Task YoinkAsync(ContextMenuContext ctx)
{
var matches = Regex.Matches(ctx.TargetMessage.Content, EmojiRegex);

if (matches.Count < 1)
{
await ctx.CreateResponseAsync(new DiscordEmbedBuilder().WithTitle("⚠️ Emoji not found!"), true);
return;
}

var split = matches[0].Groups[2].Value;
var emojiName = matches[0].Groups[1].Value;
var animated = matches[0].Value.StartsWith("<a");

if (ulong.TryParse(split, out var emojiId))
{
await CopyEmoji(ctx, emojiName, emojiId, animated);
}
else
{
await ctx.CreateResponseAsync(new DiscordEmbedBuilder().WithTitle("⚠️ Failed to fetch your new emoji."), true);
}
}

private static async Task CopyEmoji(ContextMenuContext ctx, string name, ulong id, bool animated)
{
using HttpClient httpClient = new();
var downloadedEmoji =
await httpClient.GetStreamAsync($"https://cdn.discordapp.com/emojis/{id}.{(animated ? "gif" : "png")}");
MemoryStream memory = new();
await downloadedEmoji.CopyToAsync(memory);
await downloadedEmoji.DisposeAsync();
var newEmoji = await ctx.Guild.CreateEmojiAsync(name, memory);

await ctx.CreateResponseAsync(new DiscordEmbedBuilder().WithTitle($"✅ Yoink! This emoji has been added to your server: {newEmoji}"), true);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
using DSharpPlus.Exceptions;
using DSharpPlus.SlashCommands;
using Humanizer;

namespace MADS.Commands.ContextMenu;
using DSharpPlus;
using DSharpPlus.Entities;
using Entities;
using Microsoft.EntityFrameworkCore;

public class UserInfoUser : ApplicationCommandModule
{
public MadsServiceProvider CommandService { get; set; }
public IDbContextFactory<MadsContext> DbFactory { get; set; }

[ContextMenu(ApplicationCommandType.UserContextMenu, "Info")]
public async Task GetUserInfo(ContextMenuContext ctx)
{

//await ctx.CreateResponseAsync("Test", true);

var user = ctx.TargetUser;

DiscordMember member = null;

user ??= ctx.User;
try
{
if (!ctx.Channel.IsPrivate)
{
member = await ctx.Guild.GetMemberAsync(user.Id);
}
}
catch (DiscordException e)
{
if (e.GetType() != typeof(NotFoundException))
{
throw;
}
}

DiscordEmbedBuilder embed = new();

string userUrl = "https://discordapp.com/users/" + user.Id;

embed
.WithAuthor($"{user.Username}#{user.Discriminator}", userUrl, user.AvatarUrl)
.WithColor(new DiscordColor(0, 255, 194))
.AddField("Creation:",
$"{user.CreationTimestamp.Humanize()} {Formatter.Timestamp(user.CreationTimestamp, TimestampFormat.ShortDate)}",
true)
.AddField("ID:", user.Id.ToString(), true);

if (member is not null)
{
embed.AddField("Joined at:",
$"{member.JoinedAt.Humanize()} {Formatter.Timestamp(member.JoinedAt, TimestampFormat.ShortDate)}",
true);
if (member.MfaEnabled.HasValue)
{
embed.AddField("2FA:", member.MfaEnabled.ToString());
}

embed.AddField("Permissions:", member.Permissions.Humanize());

embed.AddField("Hierarchy:",
member.Hierarchy != int.MaxValue ? member.Hierarchy.ToString() : "Server owner", true);


if (member.Roles.Any())
{
embed.AddField("Roles", member.Roles.Select(x => x.Name).Humanize());
}
}

await ctx.CreateResponseAsync(embed.Build(), true);

}
}
10 changes: 10 additions & 0 deletions ModularAssistentForDiscordServer/Commands/MadsServiceProvider.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace MADS.Commands;

public class MadsServiceProvider
{
public ModularDiscordBot ModularDiscordBot;
public MadsServiceProvider(ModularDiscordBot modularDiscordBot)
{
ModularDiscordBot = modularDiscordBot;
}
}
47 changes: 47 additions & 0 deletions ModularAssistentForDiscordServer/Commands/Slash/About.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using DSharpPlus;
using DSharpPlus.Entities;
using DSharpPlus.SlashCommands;
using Humanizer;

namespace MADS.Commands.Slash;

public class About : ApplicationCommandModule
{
public MadsServiceProvider CommandService { get; set; }

[SlashCommand("about", "Infos about the bot")]
public async Task AboutCommand(InteractionContext ctx)
{
var discordEmbedBuilder = CommandUtility.GetDiscordEmbed();
var discordMessageBuilder = new DiscordInteractionResponseBuilder();
var inviteUri = ctx.Client.CurrentApplication.GenerateOAuthUri(null, Permissions.Administrator, OAuthScope.Bot,
OAuthScope.ApplicationsCommands);
var addMe = $"[Click here!]({inviteUri.Replace(" ", "%20")})";

var diff = DateTime.Now - CommandService.ModularDiscordBot.StartTime;
var date = $"{diff.Days} days {diff.Hours} hours {diff.Minutes} minutes";

discordEmbedBuilder
.WithTitle("About me")
.WithDescription("A modular designed discord bot for moderation and stuff")
.WithAuthor(ctx.Client.CurrentUser.Username, ctx.Client.CurrentUser.AvatarUrl,
ctx.Client.CurrentUser.AvatarUrl)
.WithColor(new DiscordColor(0, 255, 194))
.AddField("Owner:", "[Plerx#0175](https://github.com/Plerx2493/)", true)
.AddField("Source:", "[Github](https://github.com/Plerx2493/Mads)", true)
.AddField("D#+ Version:", ctx.Client.VersionString)
.AddField("Guilds", ctx.Client.Guilds.Count.ToString(), true)
.AddField("Uptime", date.Humanize(), true)
.AddField("Ping", $"{ctx.Client.Ping} ms", true)
.AddField("Add me", addMe);

discordMessageBuilder.AddEmbed(discordEmbedBuilder.Build());
discordMessageBuilder.AddComponents(new DiscordButtonComponent(ButtonStyle.Success, "feedback-button",
"Feedback"));
discordMessageBuilder.AsEphemeral();

await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, discordMessageBuilder);
var response = await ctx.GetOriginalResponseAsync();
await CommandService.ModularDiscordBot.Logging.LogCommandExecutionAsync(ctx, response);
}
}
37 changes: 37 additions & 0 deletions ModularAssistentForDiscordServer/Commands/Slash/BotStats.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System.Diagnostics;
using DSharpPlus.Entities;
using DSharpPlus.SlashCommands;
using Humanizer;
using Humanizer.Localisation;

namespace MADS.Commands.Slash;

public class BotStats : ApplicationCommandModule
{
[SlashCommand("botstats", "Get statistics about the bot")]
public async Task GetBotStatsAsync(InteractionContext ctx)
{
using var process = Process.GetCurrentProcess();

var members = ctx.Client.Guilds.Values.Select(x => x.MemberCount).Sum();
var guilds = ctx.Client.Guilds.Count;
var ping = ctx.Client.Ping;
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true, true);
var heapMemory = $"{process.PrivateMemorySize64 / 1024 / 1024} MB";

var embed = new DiscordEmbedBuilder();
embed
.WithTitle("Statistics")
.WithColor(new DiscordColor(0, 255, 194))
.AddField("Membercount:", members.ToString("N0"), true)
.AddField("Guildcount:", guilds.ToString("N0"), true)
.AddField("Ping:", ping.ToString("N0"), true)
.AddField("Threads:", $"{ThreadPool.ThreadCount}", true)
.AddField("Memory:", heapMemory, true)
.AddField("Uptime:",
$"{DateTimeOffset.UtcNow.Subtract(process.StartTime).Humanize(2, minUnit: TimeUnit.Millisecond, maxUnit: TimeUnit.Day)}",
true);

await ctx.CreateResponseAsync(embed, true);
}
}
28 changes: 28 additions & 0 deletions ModularAssistentForDiscordServer/Commands/Slash/Jumpad.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using DSharpPlus;
using DSharpPlus.Entities;
using DSharpPlus.SlashCommands;
using MADS.CustomComponents;

namespace MADS.Commands.Slash;

[GuildOnly]
public class Jumppad : ApplicationCommandModule
{
[SlashCommand("jumppad", "Create a jumppad button"), SlashCommandPermissions(Permissions.MoveMembers)]
public async Task Test(InteractionContext ctx,
[Option("originChannel", "Channel where the users will be moved out"), ChannelTypes(ChannelType.Voice)]
DiscordChannel originChannel,
[Option("targetChannel", "Channel where the users will be put in"), ChannelTypes(ChannelType.Voice)]
DiscordChannel targetChannel
)
{
DiscordInteractionResponseBuilder message = new();
DiscordButtonComponent newButton = new(ButtonStyle.Success, "Placeholder", "Jump");
var actionButton = ActionDiscordButton.Build(ActionDiscordButtonEnum.MoveVoiceChannel, newButton, originChannel.Id,
targetChannel.Id);

message.AddComponents(actionButton);
message.Content = "Jumppad";
await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, message);
}
}
30 changes: 30 additions & 0 deletions ModularAssistentForDiscordServer/Commands/Slash/Ping.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using DSharpPlus.SlashCommands;

namespace MADS.Commands.Slash;

public class Ping : ApplicationCommandModule
{
public MadsServiceProvider CommandService { get; set; }

[SlashCommand("ping", "Get the bot's ping")]
public async Task PingCommand(InteractionContext ctx)
{
var diff = DateTime.Now - CommandService.ModularDiscordBot.StartTime;
var date = Humanizer.TimeSpanHumanizeExtensions.Humanize(diff); //$"{diff.Days} days {diff.Hours} hours {diff.Minutes} minutes";

var discordEmbedBuilder = CommandUtility.GetDiscordEmbed();
discordEmbedBuilder
.WithTitle("Status")
.WithTimestamp(DateTime.Now)
.AddField("Uptime", date)
.AddField("Websocket ping", $"{ctx.Client.Ping} ms");

await ctx.CreateResponseAsync(discordEmbedBuilder, true);

var response = await ctx.GetOriginalResponseAsync();
await CommandService.ModularDiscordBot.Logging.LogCommandExecutionAsync(ctx, response);
await Task.Delay(10_000);

await ctx.DeleteResponseAsync();
}
}
46 changes: 46 additions & 0 deletions ModularAssistentForDiscordServer/Commands/Slash/Purge.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using DSharpPlus;
using DSharpPlus.Entities;
using DSharpPlus.SlashCommands;
using DSharpPlus.SlashCommands.Attributes;

namespace MADS.Commands.Slash;

public class Purge : ApplicationCommandModule
{
public MadsServiceProvider CommandService { get; set; }

[SlashCommand("purge","Purges messages"),
SlashRequirePermissions(Permissions.ManageMessages),
SlashRequireGuild]
public async Task PurgeMessages(InteractionContext ctx, [Option("amount", "Delete a bunch of messages")] long amount = 100)
{
if (amount > 100)
{
await ctx.CreateResponseAsync("You cannot purge more than 100 messages at once",true);
return;
}

await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource, new DiscordInteractionResponseBuilder());
var response = await ctx.GetOriginalResponseAsync();

var messagesApi = await ctx.Channel.GetMessagesAsync((int) amount);
List<DiscordMessage> messages = new();
messages.AddRange(messagesApi);

messages.RemoveAll(x => (DateTime.UtcNow - x.Timestamp).TotalDays >= 14);
messages.Remove(response);

await ctx.Channel.DeleteMessagesAsync(messages);
await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent($"{messages.Count} messages deleted"));



await CommandService.ModularDiscordBot.Logging.LogCommandExecutionAsync(ctx, response);



await Task.Delay(10_000);

await ctx.DeleteResponseAsync();
}
}
Loading

0 comments on commit 4f925fe

Please sign in to comment.