Skip to content

Commit

Permalink
modernisation
Browse files Browse the repository at this point in the history
  • Loading branch information
Pannoniae committed Sep 3, 2024
1 parent 6f4f9e9 commit 6eb1e90
Show file tree
Hide file tree
Showing 6 changed files with 137 additions and 6 deletions.
2 changes: 1 addition & 1 deletion CommandHandlers/MusicModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ public async Task PlayJazzAsync(CommandContext ctx,
var interactivity = ctx.Client.GetInteractivity();

var results = (await GuildMusic.getJazz("*" + term + "*")).ToList();
if (!results.Any()) {
if (results.Count == 0) {
await common.respond(ctx, "Nothing was found.");
return;
}
Expand Down
6 changes: 6 additions & 0 deletions Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ public static class Constants {
public static string? redditappsecret;
public static string? apikey;
public static string? apikey_huggingface;
public static string? apikey_cloudflareAI;
public static string? apikey_cloudflareAIaccount;
public static string? spotifytoken;
public static string? spotifytoken2;
public static string? detectlanguagetoken;
Expand All @@ -42,6 +44,10 @@ public static void init() {
if (apikey is null || apikey_huggingface is null) {
logger.warn("Google/Perspective tokens not found.");
}
(apikey_cloudflareAI, apikey_cloudflareAIaccount) = (json["cloudflareAI"]?.Value<string>(), json["cloudflareAIaccount"]?.Value<string>());
if (apikey_cloudflareAI is null || apikey_cloudflareAIaccount is null) {
logger.warn("CloudFlare AI token not found.");
}
(spotifytoken, spotifytoken2) = (json["spotify1"]?.Value<string>(), json["spotify2"]?.Value<string>());
if (spotifytoken is null || spotifytoken2 is null) {
logger.warn("Spotify token not found.");
Expand Down
2 changes: 2 additions & 0 deletions EconomyBot.sln.DotSettings.user
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ABooruOnRails_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2024_002E2_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F9ceea25afff845d4bf74cdc572e60dc310e00_003F9f_003F9a508cfd_003FBooruOnRails_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ACommandsNextExtension_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2024_002E2_003Fresharper_002Dhost_003FSourcesCache_003Fa38c7f18ffbb3bc05a9cc8954e6c76460cd756159506a29ad25c9224e2158_003FCommandsNextExtension_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ADanbooruDonmai_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2024_002E2_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F9ceea25afff845d4bf74cdc572e60dc310e00_003F2b_003F750fc07b_003FDanbooruDonmai_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ADirectory_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2024_002E2_003Fresharper_002Dhost_003FSourcesCache_003F822394c8ab83955ac4f023cd5a4a8d2064f5f7e18291dd2e785015d510dbf063_003FDirectory_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AExtensionMethods_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2024_002E2_003Fresharper_002Dhost_003FSourcesCache_003Fb4b5cdcfd168e613645574352e23955936185196fa4b2e7f8dcd8d7853c54_003FExtensionMethods_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AFileAttribute_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2024_002E2_003Fresharper_002Dhost_003FSourcesCache_003Fbff59440f5a011d3ba618656ced572f4ef404db0f0a64807cd193c4f4a0e112_003FFileAttribute_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
Expand Down
4 changes: 3 additions & 1 deletion Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -333,13 +333,15 @@ private static async Task setup(DiscordClient client, LavalinkExtension lavalink

hasSetup = true;

await setupB(client, lavalink, lavalinkConfig);

logger.info("Setup done!");
}

private static async Task setupB(DiscordClient client, LavalinkExtension lavalink,
LavalinkConfiguration lavalinkConfig) {
foreach (var guild in client.Guilds) {
logger.debug($"{guild.Value.Name}, {guild.Value.JoinedAt.ToString()}");
logger.info($"{guild.Value.Name}, {guild.Value.JoinedAt.ToString()}");
}
}

Expand Down
127 changes: 124 additions & 3 deletions Text/WilteryHandler.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
using DisCatSharp;
using System.Net;
using System.Text;
using System.Web;
using DisCatSharp;
using DisCatSharp.Entities;
using EconomyBot.Logging;
using Newtonsoft.Json.Linq;

namespace EconomyBot;

Expand All @@ -14,6 +18,7 @@ public class WilteryHandler {
public GuildMusicData GuildMusic { get; set; }

public DiscordClient client;
public HttpClient httpClient = new();

private List<MessageHandler> messageHandlers = new();

Expand All @@ -25,6 +30,17 @@ public WilteryHandler(DiscordClient client) {
"basket"));
messageHandlers.Add(new WordMessageHandler("hrt", "hurt"));
messageHandlers.Add(new ResponseWordMessageHandler("anal", "Have fun getting HIV"));

// stop the stupidity
// replace every gendered pronoun with neutral ones
messageHandlers.Add(new AIWordMessageHandler("hers "));
messageHandlers.Add(new AIWordMessageHandler("her "));
messageHandlers.Add(new AIWordMessageHandler("him "));
messageHandlers.Add(new AIWordMessageHandler("his "));
messageHandlers.Add(new AIWordMessageHandler("she "));
messageHandlers.Add(new AIWordMessageHandler("he "));
messageHandlers.Add(new AIWordMessageHandler("herself "));
messageHandlers.Add(new AIWordMessageHandler("himself "));
}

public async Task sendWebhookToChannel(DiscordChannel channel, string message) {
Expand Down Expand Up @@ -84,7 +100,90 @@ public async Task handleMessage(DiscordClient client, DiscordMessage message) {
foreach (var handler in messageHandlers) {
if (handler.shouldProcess(message)) {
handler.process(this, message);
// if processed, don't bother with the rest
break;
}
}
}

/// <summary>
/// Transforms messages so they are neutral.
/// </summary>
public async Task replaceMessageAINeutral(DiscordMessage message) {
string contents = message.Content;
DiscordChannel channel = message.Channel;
DiscordMember user = (DiscordMember)message.Author;

const string API_URL =
"https://api.cloudflare.com/client/v4/accounts/2498ecc574e198ccf65813d2aa3af4ca/ai/run/";

var h_json = $$"""
{
"messages": [
{
"role": "system",
"content": "Replace all the gendered pronouns in the following sentence with neutral ones. For example, replace 'she' with 'they'. Only output the modified sentence and nothing else.
If the sentence is not gendered, output 'nothing'."
},
{
"role": "user",
"content": "{{HttpUtility.JavaScriptStringEncode(message.Content)}}"
}
]
}
""";
var httpRequestMessage = new HttpRequestMessage {
Method = HttpMethod.Post,
RequestUri = new Uri(API_URL + "@cf/meta/llama-3-8b-instruct"),
Headers = {
{ HttpRequestHeader.Authorization.ToString(), $"Bearer {Constants.apikey_cloudflareAI}" },
},
Content = new StringContent(h_json, Encoding.UTF8, "application/json")
};
var h_response = await httpClient.SendAsync(httpRequestMessage);
var h_responseString = await h_response.Content.ReadAsStringAsync();
JObject h_responseJson;
var labels = new Dictionary<string, double>();
try {
h_responseJson = JObject.Parse(h_responseString);
}
catch {

logger.error(h_responseString);
return;
}

try {
var success = h_responseJson["success"];
// if not success, return
if (success?.Value<bool>() == false) {
logger.error(h_responseString);
return;
}
// get the response from the json
var response = h_responseJson["result"]?["response"]?.Value<string>();
if (response == null) {
logger.error(h_responseString);
return;
}
// if nothing (bot detected neutral message), don't change
if (response == "nothing") {
return;
}
// send the response
try {
// yeet
await message.DeleteAsync();
string newMessage = response;
await sendWebhookToChannelAsUser(channel, newMessage, user);
}
catch (Exception e) {
logger.error(e);
}

}
catch (Exception e) {
logger.error(e);
}
}

Expand Down Expand Up @@ -120,8 +219,30 @@ public virtual async void process(WilteryHandler handler, DiscordMessage message
}
}

public class WordExceptionMessageHandler
(string target, string replacement, params string[] exceptions) : MessageHandler {
public class ExactWordMessageHandler(string target, string replacement) : WordMessageHandler(target, replacement) {
private readonly string target = target;
private readonly string replacement = replacement;
public override bool shouldProcess(DiscordMessage message) {
return message.Content.Contains($"{target} ", StringComparison.CurrentCultureIgnoreCase);
}

public override async void process(WilteryHandler handler, DiscordMessage message) {
await handler.replaceMessage(message, target, replacement);
}
}

public class AIWordMessageHandler(string target) : WordMessageHandler(target, "") {
private readonly string target = target;
public override bool shouldProcess(DiscordMessage message) {
return message.Content.Contains(target, StringComparison.CurrentCultureIgnoreCase) && !message.Author.IsBot;
}

public override async void process(WilteryHandler handler, DiscordMessage message) {
await handler.replaceMessageAINeutral(message);
}
}

public class WordExceptionMessageHandler(string target, string replacement, params string[] exceptions) : MessageHandler {
public virtual bool shouldProcess(DiscordMessage message) {
return message.Content.Contains(target, StringComparison.CurrentCultureIgnoreCase)
&& exceptions.All(e => !message.Content.Contains(e, StringComparison.CurrentCultureIgnoreCase));
Expand Down
2 changes: 1 addition & 1 deletion application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ lavalink:
gc-warnings: true
plugins:
# Replace VERSION with the current version as shown by the Releases tab or a long commit hash for snapshots.
- dependency: "dev.lavalink.youtube:youtube-plugin:1.5.2"
- dependency: "dev.lavalink.youtube:youtube-plugin:1.7.2"
snapshot: false # Set to true if you want to use a snapshot version.

plugins:
Expand Down

0 comments on commit 6eb1e90

Please sign in to comment.