Skip to content

Commit

Permalink
Dev/overhaul (#34)
Browse files Browse the repository at this point in the history
  • Loading branch information
Plerx2493 authored Feb 18, 2024
1 parent 70f7e21 commit 11dfd81
Show file tree
Hide file tree
Showing 61 changed files with 1,556 additions and 525 deletions.
48 changes: 48 additions & 0 deletions .github/workflows/containerImages.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
name: Publish Docker image
on:
push:

jobs:
push_to_registry:
name: Publish Docker image
runs-on: ubuntu-latest
steps:
- name: Check out the repo
uses: actions/checkout@v4

- name: Set up QEMU
uses: docker/setup-qemu-action@v3

- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3

- name: Login to DockerHub
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}

- name: Build and Push ModularAssistentForDiscordServer
uses: docker/build-push-action@v3
with:
context: .
file: ./ModularAssistentForDiscordServer/Dockerfile
push: true
tags: |
ghcr.io/plerx2493/mads:latest
ghcr.io/plerx2493/mads:${{ github.sha }}
build-args: |
"BUILD_VER=${{ github.sha }}"
- name: Build and Push QuartzDB
uses: docker/build-push-action@v3
with:
context: .
file: ./QuartzNetDocker/Dockerfile
push: true
tags: |
ghcr.io/plerx2493/quartz-db-mysql:latest
ghcr.io/plerx2493/quartz-db-mysql:${{ github.sha }}
build-args: |
"BUILD_VER=${{ github.sha }}"
2 changes: 1 addition & 1 deletion .github/workflows/dotnet.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ jobs:
- name: Setup .NET
uses: actions/setup-dotnet@v2
with:
dotnet-version: 7.0.x
dotnet-version: 8.0.x
- name: Restore dependencies
run: dotnet restore
- name: Build
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ namespace MADS.Commands.AutoCompletion;

public class ReminderAutoCompletion : IAutocompleteProvider
{
private IDbContextFactory<MadsContext> _factory;
private readonly IDbContextFactory<MadsContext> _factory;

public ReminderAutoCompletion(IServiceProvider services)
{
Expand All @@ -31,11 +31,22 @@ public ReminderAutoCompletion(IServiceProvider services)

public async Task<IEnumerable<DiscordAutoCompleteChoice>> Provider(AutocompleteContext ctx)
{
//TODO Userinput is not working (The input string '' was not in a correct format.)
/*long currentInput = (long?) ctx.OptionValue ?? 0;
string currentInputString = currentInput.ToString();
if (currentInputString == "0")
{
currentInputString = "";
}
*/

await using var db = await _factory.CreateDbContextAsync();
var choices = db.Reminders
.Where(x => x.UserId == ctx.User.Id)
.Select(x => new DiscordAutoCompleteChoice(x.Id.ToString(), x.Id.ToString()))
.ToList();
.Select(x => x.Id.ToString())
.ToList()
//.Where(x => x.StartsWith(currentInputString))
.Select(x => new DiscordAutoCompleteChoice(x, x));
return choices;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,27 @@
// See the License for the specific language governing permissions and
// limitations under the License.

using DeepL;
using DSharpPlus.Entities;
using DSharpPlus.SlashCommands;
using MADS.Extensions;

namespace MADS.Commands.Slash;
namespace MADS.Commands.AutoCompletion;

public sealed class NoBtches : MadsBaseApplicationCommand
public class TargetLanguageAutoCompletion : IAutocompleteProvider
{
[SlashCommand("nobtches", "nobtches api")]
public async Task PingCommand
(
InteractionContext ctx,
[Option("imageText", "Text on image")] string imageText
)
private readonly Translator _translator;

public TargetLanguageAutoCompletion(Translator translator)
{
imageText = imageText.Replace(" ", "%20").Replace("?", "%3F");
await ctx.CreateResponseAsync("https://api.no-bitch.es/" + imageText);
_translator = translator;
}

public async Task<IEnumerable<DiscordAutoCompleteChoice>> Provider(AutocompleteContext ctx)
{
var sourceLangs = await _translator.GetTargetLanguagesAsync();
var choices = sourceLangs
.Select(x => new DiscordAutoCompleteChoice(x.Name, x.Code))
.Take(25);
return choices;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,14 @@

using DSharpPlus.Entities;
using DSharpPlus.SlashCommands;
using MADS.Entities;
using MADS.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace MADS.Commands.AutoCompletion;

public class VoiceAlertAutoCompletion : IAutocompleteProvider
{
private VoiceAlertService _voiceAlertService;
private readonly VoiceAlertService _voiceAlertService;

public VoiceAlertAutoCompletion(IServiceProvider services)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public static DiscordEmbedBuilder GetDiscordEmbed()
{
var standardEmbed = new DiscordEmbedBuilder
{
Color = new Optional<DiscordColor>(new DiscordColor(0, 255, 194))
Color = new DiscordColor(0, 255, 194)
};
return standardEmbed;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,28 @@

namespace MADS.Commands.ContextMenu;

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

private HttpClient _httpClient;

public StealEmojiMessage(HttpClient httpClient)
{
_httpClient = httpClient;
}

[ContextMenu(ApplicationCommandType.MessageContextMenu, "Steal emoji(s)"),
SlashRequirePermissions(Permissions.ManageEmojis)]
public async Task YoinkAsync(ContextMenuContext ctx)
{
await ctx.DeferAsync(true);

if (ctx.TargetMessage.Content is null)
{
await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("⚠️ Message has not content!"));
return;
}

var matches = Regex.Matches(ctx.TargetMessage.Content.Replace("><", "> <"), EmojiRegex, RegexOptions.Compiled);
var matches = EmojiRegex().Matches(ctx.TargetMessage.Content.Replace("><", "> <"));

if (matches.Count < 1)
{
Expand Down Expand Up @@ -63,7 +74,7 @@ await ctx.EditResponseAsync(
// ignored
}

await IntendedWait(1000);
await IntendedWait(500);
}

var message = newEmojis.Aggregate("✅ Yoink! These emoji(s) have been added to your server: ",
Expand All @@ -76,11 +87,10 @@ await ctx.EditResponseAsync(
await ctx.EditResponseAsync(discordWebhook);
}

private static async Task<DiscordEmoji> CopyEmoji(ContextMenuContext ctx, string name, ulong id, bool animated)
private async Task<DiscordEmoji> 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")}");
await _httpClient.GetStreamAsync($"https://cdn.discordapp.com/emojis/{id}.{(animated ? "gif" : "png")}");

MemoryStream memory = new();

Expand All @@ -91,4 +101,7 @@ private static async Task<DiscordEmoji> CopyEmoji(ContextMenuContext ctx, string

return newEmoji;
}

[GeneratedRegex("<a?:(.+?):(\\d+)>", RegexOptions.Compiled)]
private static partial Regex EmojiRegex();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// Copyright 2023 Plerx2493
//
// Licensed under the Apache License, Version 2.0 (the "License")
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using DeepL;
using DSharpPlus;
using DSharpPlus.Entities;
using DSharpPlus.SlashCommands;
using MADS.CustomComponents;
using MADS.Extensions;
using MADS.Services;
using Quartz.Util;

namespace MADS.Commands.ContextMenu;

public class TranslateMessage : MadsBaseApplicationCommand
{
private readonly TranslateInformationService _translateInformationService;
private readonly Translator _translator;

public TranslateMessage(TranslateInformationService translateInformationService, Translator translator)
{
_translateInformationService = translateInformationService;
_translator = translator;
}

[ContextMenu(ApplicationCommandType.MessageContextMenu, "Translate message")]
public async Task TranslateAsync(ContextMenuContext ctx)
{
await ctx.DeferAsync(true);

var preferredLanguage = await _translateInformationService.GetPreferredLanguage(ctx.User.Id);
bool isPreferredLanguageSet = !preferredLanguage.IsNullOrWhiteSpace();

if(!isPreferredLanguageSet) preferredLanguage = "en-US";

var messageId = ctx.TargetMessage.Id;
var message = await ctx.Channel.GetMessageAsync(messageId);
var messageContent = message.Content;

if (messageContent.IsNullOrWhiteSpace() || messageContent is null)
{
await ctx.CreateResponseAsync("⚠️ Message is empty!");
return;
}

if (preferredLanguage is null)
{
await ctx.CreateResponseAsync("⚠️ No language set!");
return;
}

var transaltedMessage =
await _translator.TranslateTextAsync(messageContent, null, preferredLanguage);

var embed = new DiscordEmbedBuilder()
.WithAuthor(message.Author?.Username,
message.Author?.AvatarUrl)
.WithDescription(transaltedMessage.Text)
.WithColor(new DiscordColor(0, 255, 194))
.WithFooter($"Translated from {transaltedMessage.DetectedSourceLanguageCode} to {preferredLanguage}")
.WithTimestamp(DateTime.Now);

await ctx.CreateResponseAsync(embed);

if (isPreferredLanguageSet) return;

var followUpMessage = new DiscordFollowupMessageBuilder()
.WithContent("⚠️ You haven't set a preferred language yet. Default is english.")
.AddComponents(new DiscordButtonComponent(ButtonStyle.Primary, "setLanguage", "Set language").AsActionButton(ActionDiscordButtonEnum.SetTranslationLanguage))
.AddComponents(new DiscordButtonComponent(ButtonStyle.Primary, "setLanguage", "Set your language to en-US").AsActionButton(ActionDiscordButtonEnum.SetTranslationLanguage, "en-US"))
.AsEphemeral();


await ctx.FollowUpAsync(followUpMessage);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,8 @@ public async Task GetUserInfo(ContextMenuContext ctx)
{
var user = ctx.TargetUser;

DiscordMember member = null;

user ??= ctx.User;
DiscordMember? member = null;

try
{
if (!ctx.Channel.IsPrivate) member = await ctx.Guild.GetMemberAsync(user.Id);
Expand All @@ -57,7 +56,7 @@ public async Task GetUserInfo(ContextMenuContext ctx)
embed.AddField("Joined at:",
$"{member.JoinedAt.Humanize()} {Formatter.Timestamp(member.JoinedAt, TimestampFormat.ShortDate)}",
true);
if (member.MfaEnabled.HasValue) embed.AddField("2FA:", member.MfaEnabled.ToString());
if (member.MfaEnabled.HasValue) embed.AddField("2FA:", member.MfaEnabled.ToString()!);

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

Expand Down
4 changes: 2 additions & 2 deletions ModularAssistentForDiscordServer/Commands/Slash/About.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ 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 inviteUri = ctx.Client.CurrentApplication.GenerateOAuthUri(null, Permissions.Administrator, DiscordOAuthScope.Bot,
DiscordOAuthScope.ApplicationsCommands);
var addMe = $"[Click here!]({inviteUri.Replace(" ", "%20")})";

var diff = DateTime.Now - CommandService.StartTime;
Expand Down
17 changes: 9 additions & 8 deletions ModularAssistentForDiscordServer/Commands/Slash/BotStats.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,13 @@
using MADS.Entities;
using MADS.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace MADS.Commands.Slash;

public sealed class BotStats : MadsBaseApplicationCommand
{
private IDbContextFactory<MadsContext> _contextFactory;
private DiscordRestClient _discordRestClient;
private readonly IDbContextFactory<MadsContext> _contextFactory;
private readonly DiscordRestClient _discordRestClient;

public BotStats(IDbContextFactory<MadsContext> contextFactory, DiscordRestClient discordRestClient)
{
Expand All @@ -43,18 +42,20 @@ public async Task GetBotStatsAsync(InteractionContext ctx)
var swDb = new Stopwatch();
var swRest = new Stopwatch();

var _ = await db.Users.FirstOrDefaultAsync();
swDb.Start();
var _ = await db.Guilds.FirstAsync();
var __ = await db.Guilds.FirstOrDefaultAsync();
swDb.Stop();

var ___ = await _discordRestClient.GetChannelAsync(ctx.Guild.Channels.Values.First().Id);
swRest.Start();
var __ = await _discordRestClient.GetChannelAsync(ctx.Channel.Id);
var ____ = await _discordRestClient.GetChannelAsync(ctx.Channel.Id);
swRest.Stop();

using var process = Process.GetCurrentProcess();

var members = ctx.Client.Guilds.Values.Select(x => x.MemberCount).Sum();
var guilds = ctx.Client.Guilds.Count;
var members = db.Users.Count();
var guilds = db.Guilds.Count();
var ping = ctx.Client.Ping;
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true, true);
var heapMemory = $"{process.PrivateMemorySize64 / 1024 / 1024} MB";
Expand All @@ -71,7 +72,7 @@ public async Task GetBotStatsAsync(InteractionContext ctx)
.AddField("Rest Latency:", swRest.ElapsedMilliseconds.ToString("N0") + " ms", true)
.AddField("Memory:", heapMemory, true)
.AddField("Uptime:",
$"{DateTimeOffset.UtcNow.Subtract(process.StartTime).Humanize(2, minUnit: TimeUnit.Millisecond, maxUnit: TimeUnit.Day)}",
$"{DateTimeOffset.UtcNow.Subtract(process.StartTime).Humanize(3, minUnit: TimeUnit.Millisecond, maxUnit: TimeUnit.Day)}",
true);

await ctx.CreateResponseAsync(embed, true);
Expand Down
Loading

0 comments on commit 11dfd81

Please sign in to comment.