i think we're back to where discord left off?

This commit is contained in:
Adam R Grey 2023-06-15 23:29:07 -04:00
parent d2aa1f46cc
commit f23474ad51
10 changed files with 331 additions and 211 deletions

View File

@ -8,15 +8,14 @@ using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Collections.Generic;
//TODO: better name
public class thingmanagementdoer
public class Behaver
{
internal thingmanagementdoer() { }
static thingmanagementdoer() { }
internal Behaver() { }
static Behaver() { }
private static readonly thingmanagementdoer _instance = new thingmanagementdoer();
private static readonly Behaver _instance = new Behaver();
public static thingmanagementdoer Instance
public static Behaver Instance
{
get { return _instance; }
}
@ -24,49 +23,41 @@ public class thingmanagementdoer
public async Task<bool> ActOn(Message message)
{
var didThing = false;
//TODO: get combined permissions for author and channel
var contentWithoutMention = message.Content;
// if (message.Author.Id == 159985870458322944) //MEE6
///behavior exists
// var wordLikes = message.Content.Split(' ', StringSplitOptions.TrimEntries);
// var links = wordLikes?.Where(wl => Uri.IsWellFormedUriString(wl, UriKind.Absolute)).Select(wl => new Uri(wl));
// if (links != null && links.Count() > 0)
// {
// if (message.Content?.Contains("you just advanced") == true)
// foreach (var link in links)
// {
// var newText = Regex.Replace(message.Content, "<[^>]*>", message.Author.Username);
// newText = Regex.Replace(newText, "level [\\d]+", "level -1");
// Features.mock(newText, message);
// didThing = true;
// if (link.Host.EndsWith(".tiktok.com"))
// {
// Features.detiktokify(link, message);
// didThing = true;
// }
// }
// }
// if (message.Attachments?.Count() > 0)
// {
// Console.WriteLine($"{message.Attachments.Count()} attachments");
// var appleReactions = false;
// foreach (var att in message.Attachments)
// {
// if (att.Filename?.EndsWith(".heic") == true)
// {
// Features.deheic(message, att);
// appleReactions = true;
// didThing = true;
// }
// }
// if (appleReactions)
// {
// message.React("\U0001F34F");
// }
// }
var wordLikes = message.Content.Split(' ', StringSplitOptions.TrimEntries);
var links = wordLikes?.Where(wl => Uri.IsWellFormedUriString(wl, UriKind.Absolute)).Select(wl => new Uri(wl));
if (links != null && links.Count() > 0)
{
foreach (var link in links)
{
if (link.Host.EndsWith(".tiktok.com"))
{
Features.detiktokify(link, message);
didThing = true;
}
}
}
if (message.Attachments?.Count() > 0)
{
Console.WriteLine($"{message.Attachments.Count()} attachments");
var appleReactions = false;
foreach (var att in message.Attachments)
{
if (att.Filename?.EndsWith(".heic") == true)
{
Features.deheic(message, att);
appleReactions = true;
didThing = true;
}
}
if (appleReactions)
{
message.React("\U0001F34F");
}
}
var msgText = message.Content?.ToLower();
if (!string.IsNullOrWhiteSpace(msgText))
@ -125,11 +116,11 @@ public class thingmanagementdoer
message.Channel.SendMessage("that's not what gaslight means. Did you mean \"say something that (you believe) is wrong\"?");
didThing = true;
}
if (msgText.Contains("!qrplz "))
{
Features.qrify(message.Content.Substring("!qrplz ".Length + msgText.IndexOf("!qrplz ")), message);
didThing = true;
}
// if (msgText.Contains("!qrplz "))
// {
// Features.qrify(message.Content.Substring("!qrplz ".Length + msgText.IndexOf("!qrplz ")), message);
// didThing = true;
// }
if (msgText.Contains("!freedomunits "))
{
Features.Convert(message, contentWithoutMention);

24
Behavior/Behavior.cs Normal file
View File

@ -0,0 +1,24 @@
namespace vassago.Behavior;
using vassago.Models;
using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Collections.Generic;
//expect a behavior to be created per mesage
public abstract class Behavior
{
public abstract Task<bool> ActOn(PermissionSettings permissions, Message message);
public virtual bool ShouldAct(PermissionSettings permissions, Message message)
{
return Regex.IsMatch(message.Content, $"{Trigger}\\b");
}
public abstract string Name { get; }
public abstract string Trigger { get; }
public abstract string Description { get; }
}

83
Behavior/Deheic.cs Normal file
View File

@ -0,0 +1,83 @@
namespace vassago.Behavior;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using vassago.Models;
public class Deheic : Behavior
{
public override string Name => "deheic";
public override string Trigger => "post an heic image";
public override string Description => "convert heic images to jpg";
private List<Attachment> heics = new List<Attachment>();
public override bool ShouldAct(PermissionSettings permissions, Message message)
{
if (message.Attachments?.Count() > 0)
{
foreach (var att in message.Attachments)
{
if (att.Filename?.EndsWith(".heic") == true)
{
heics.Add(att);
}
}
}
return heics.Any();
}
public override async Task<bool> ActOn(PermissionSettings permissions, Message message)
{
if (!Directory.Exists("tmp"))
{
Directory.CreateDirectory("tmp");
}
var conversions = new List<Task<bool>>();
foreach (var att in heics)
{
conversions.Add(actualDeheic(att, message));
}
Task.WaitAll(conversions.ToArray());
await message.React("\U0001F34F");
return true;
}
private async Task<bool> actualDeheic(Attachment att, Message message)
{
try
{
var cancellationTokenSource = new CancellationTokenSource();
CancellationToken token = cancellationTokenSource.Token;
using (Stream output = File.OpenWrite("tmp/" + att.Filename))
{
(await Shared.HttpClient.GetAsync(att.Source))
.Content.CopyTo(output, null, token);
}
if (ExternalProcess.GoPlz("convert", $"tmp/{att.Filename} tmp/{att.Filename}.jpg"))
{
await message.Channel.SendFile($"tmp/{att.Filename}.jpg", "converted from jpeg-but-apple to jpeg");
File.Delete($"tmp/{att.Filename}");
File.Delete($"tmp/{att.Filename}.jpg");
}
else
{
await message.Channel.SendMessage("convert failed :(");
Console.Error.WriteLine("convert failed :(");
}
}
catch (Exception e)
{
await message.Channel.SendMessage($"something failed. aaaadam! {JsonConvert.SerializeObject(e, Formatting.Indented)}");
Console.Error.WriteLine(JsonConvert.SerializeObject(e, Formatting.Indented));
return false;
}
return true;
}
}

101
Behavior/Detiktokify.cs Normal file
View File

@ -0,0 +1,101 @@
namespace vassago.Behavior;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using vassago.Models;
public class Detiktokify : Behavior
{
public override string Name { get => "Detiktokify"; }
public override string Trigger { get => "post a link below vm.tiktok.com"; }
public override string Description { get => "re-host tiktok content"; }
private List<Uri> tiktokLinks = new List<Uri>();
private YoutubeDLSharp.YoutubeDL ytdl;
public Detiktokify()
{
ytdl = new YoutubeDLSharp.YoutubeDL();
ytdl.YoutubeDLPath = "yt-dlp";
ytdl.FFmpegPath = "ffmpeg";
ytdl.OutputFolder = "";
ytdl.OutputFileTemplate = "tiktokbad.%(ext)s";
}
public override bool ShouldAct(PermissionSettings permissions, Message message)
{
if(permissions.MaxAttachmentBytes == 0)
return false;
var wordLikes = message.Content.Split(' ', StringSplitOptions.TrimEntries);
var possibleLinks = wordLikes?.Where(wl => Uri.IsWellFormedUriString(wl, UriKind.Absolute)).Select(wl => new Uri(wl));
if (possibleLinks != null && possibleLinks.Count() > 0)
{
foreach (var link in possibleLinks)
{
if (link.Host.EndsWith(".tiktok.com"))
{
tiktokLinks.Add(link);
}
}
}
return tiktokLinks.Any();
}
public override async Task<bool> ActOn(PermissionSettings permissions, Message message)
{
foreach(var link in tiktokLinks)
{
#pragma warning disable 4014
message.React("tiktokbad");
#pragma warning restore 4014
try
{
var res = await ytdl.RunVideoDownload(link.ToString());
if (!res.Success)
{
Console.Error.WriteLine("tried to dl, failed. \n" + string.Join('\n', res.ErrorOutput));
await message.React("problemon");
await message.Channel.SendMessage("tried to dl, failed. \n" + string.Join('\n', res.ErrorOutput));
}
else
{
string path = res.Data;
if (File.Exists(path))
{
var bytesize = new System.IO.FileInfo(path).Length;
if (bytesize < permissions.MaxAttachmentBytes - 256)
{
try
{
await message.Channel.SendFile(path, null);
}
catch (Exception e)
{
System.Console.Error.WriteLine(e);
await message.Channel.SendMessage($"aaaadam!\n{e}");
}
}
else
{
Console.WriteLine($"file appears too big ({bytesize} bytes ({bytesize / (1024 * 1024)}MB)), not posting");
}
File.Delete(path);
}
else
{
Console.Error.WriteLine("idgi but something happened.");
await message.React("problemon");
}
}
}
catch (Exception e)
{
Console.Error.WriteLine(e);
await message.React("problemon");
return false;
}
}
return true;
}
}

View File

@ -14,100 +14,6 @@ using vassago.Models;
public static class Features
{
public static Random r = new Random();
public static async void detiktokify(Uri link, Message message)
{
//yes, even if there is a problem later.
#pragma warning disable 4014
message.React("tiktokbad");
#pragma warning restore 4014
var ytdl = new YoutubeDLSharp.YoutubeDL();
ytdl.YoutubeDLPath = "yt-dlp";
ytdl.FFmpegPath = "ffmpeg";
ytdl.OutputFolder = "";
ytdl.OutputFileTemplate = "tiktokbad.%(ext)s";
try
{
var res = await ytdl.RunVideoDownload(link.ToString());
if (!res.Success)
{
Console.Error.WriteLine("tried to dl, failed. \n" + string.Join('\n', res.ErrorOutput));
await message.React("problemon");
await message.Channel.SendMessage("tried to dl, failed. \n" + string.Join('\n', res.ErrorOutput));
}
else
{
string path = res.Data;
if (File.Exists(path))
{
var bytesize = new System.IO.FileInfo(path).Length;
if (bytesize < 1024 * 1024 * 10)
{
try
{
await message.Channel.SendFile(path, null);
}
catch (Exception e)
{
System.Console.Error.WriteLine(e);
await message.Channel.SendMessage($"aaaadam!\n{e}");
}
}
else
{
Console.WriteLine($"file appears too big ({bytesize} bytes ({bytesize / (1024 * 1024)}MB)), not posting");
}
File.Delete(path);
}
else
{
Console.Error.WriteLine("idgi but something happened.");
await message.React("problemon");
}
}
}
catch (Exception e)
{
Console.Error.WriteLine(e);
await message.React("problemon");
}
}
public static async void deheic(Message message, Attachment att)
{
try
{
if (!Directory.Exists("tmp"))
{
Directory.CreateDirectory("tmp");
}
var cancellationTokenSource = new CancellationTokenSource();
CancellationToken token = cancellationTokenSource.Token;
using (Stream output = File.OpenWrite("tmp/" + att.Filename))
{
(await Shared.HttpClient.GetAsync(att.Source))
.Content.CopyTo(output, null, token);
}
if (ExternalProcess.GoPlz("convert", $"tmp/{att.Filename} tmp/{att.Filename}.jpg"))
{
await message.Channel.SendFile($"tmp/{att.Filename}.jpg", "converted from jpeg-but-apple to jpeg");
File.Delete($"tmp/{att.Filename}");
File.Delete($"tmp/{att.Filename}.jpg");
}
else
{
await message.Channel.SendMessage("convert failed :(");
Console.Error.WriteLine("convert failed :(");
}
}
catch (Exception e)
{
await message.Channel.SendMessage($"something failed. aaaadam! {JsonConvert.SerializeObject(e, Formatting.Indented)}");
Console.Error.WriteLine(JsonConvert.SerializeObject(e, Formatting.Indented));
}
}
internal static async void mock(string contentWithoutMention, Message message)
{
var toPost = new StringBuilder();
@ -125,31 +31,6 @@ public static class Features
await message.Reply(toPost.ToString());
}
public static async void qrify(string qrContent, Message message)
{
Console.WriteLine($"qring: {qrContent}");
QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeData qrCodeData = qrGenerator.CreateQrCode(qrContent, QRCodeGenerator.ECCLevel.Q);
SvgQRCode qrCode = new SvgQRCode(qrCodeData);
string qrCodeAsSvg = qrCode.GetGraphic(20);
int todaysnumber = Shared.r.Next();
if (!Directory.Exists("tmp"))
{
Directory.CreateDirectory("tmp");
}
File.WriteAllText($"tmp/qr{todaysnumber}.svg", qrCodeAsSvg);
if (ExternalProcess.GoPlz("convert", $"tmp/qr{todaysnumber}.svg tmp/qr{todaysnumber}.png"))
{
await message.Channel.SendFile($"tmp/qr{todaysnumber}.png", null);
File.Delete($"tmp/qr{todaysnumber}.svg");
File.Delete($"tmp/qr{todaysnumber}.png");
}
else
{
await message.Channel.SendMessage("convert failed :( aaaaaaadam!");
Console.Error.WriteLine($"convert failed :( qr{todaysnumber}");
}
}
public static async void Convert(Message message, string contentWithoutMention)
{
await message.Channel.SendMessage(Conversion.Converter.convert(contentWithoutMention));
@ -163,17 +44,17 @@ public static class Features
{
await message.Channel.SendMessage("I don't know any. Adam!");
}
var thisJoke = jokes[r.Next(jokes.Length)];
var thisJoke = jokes[Shared.r.Next(jokes.Length)];
if (thisJoke.Contains("?") && !thisJoke.EndsWith('?'))
{
#pragma warning disable 4014
#pragma warning disable 4014
Task.Run(async () =>
{
var firstIndexAfterQuestionMark = thisJoke.LastIndexOf('?') + 1;
var straightline = thisJoke.Substring(0, firstIndexAfterQuestionMark);
var punchline = thisJoke.Substring(firstIndexAfterQuestionMark, thisJoke.Length - firstIndexAfterQuestionMark);
Task.WaitAll(message.Channel.SendMessage(straightline));
Thread.Sleep(TimeSpan.FromSeconds(r.Next(5, 30)));
Thread.Sleep(TimeSpan.FromSeconds(Shared.r.Next(5, 30)));
await message.Channel.SendMessage(punchline);
// var myOwnMsg = await message.Channel.SendMessage(punchline);
// if (r.Next(8) == 0)
@ -181,7 +62,7 @@ public static class Features
// await myOwnMsg.React("\U0001F60E"); //smiling face with sunglasses
// }
});
#pragma warning restore 4014
#pragma warning restore 4014
}
else
{
@ -193,7 +74,7 @@ public static class Features
{
var sb = new StringBuilder();
var snarkSeg1 = new string[] { "ew", "gross", "that seems a bit hard for you" };
sb.AppendLine(snarkSeg1[r.Next(snarkSeg1.Length)]);
sb.AppendLine(snarkSeg1[Shared.r.Next(snarkSeg1.Length)]);
var snarkSeg2 = new string[]{@"here's an easier recipe for you:
Ingredients:
- Corn flakes cereal
@ -223,12 +104,12 @@ Instructions:
I hope you have fun making and eating your PB&J 🥪!",
"just order pizza instead"
};
sb.AppendLine(snarkSeg2[r.Next(snarkSeg2.Length)]);
sb.AppendLine(snarkSeg2[Shared.r.Next(snarkSeg2.Length)]);
await message.Channel.SendMessage(sb.ToString());
}
public static async void Skynet(Message message)
{
switch (r.Next(5))
switch (Shared.r.Next(5))
{
default:
await message.Channel.SendFile("assets/coding and algorithms.png", "i am actually niether a neural-net processor nor a learning computer. but I do use **coding** and **algorithms**.");
@ -317,6 +198,6 @@ I hope you have fun making and eating your PB&J 🥪!",
"so get used to it."
};
await message.Channel.SendMessage(piece1[r.Next(piece1.Count)] + piece2[r.Next(piece2.Count)] + piece3[r.Next(piece3.Count)] + piece4[r.Next(piece4.Count)]);
await message.Channel.SendMessage(piece1[Shared.r.Next(piece1.Count)] + piece2[Shared.r.Next(piece2.Count)] + piece3[Shared.r.Next(piece3.Count)] + piece4[Shared.r.Next(piece4.Count)]);
}
}

49
Behavior/QRify.cs Normal file
View File

@ -0,0 +1,49 @@
namespace vassago.Behavior;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using vassago.Models;
using QRCoder;
public class QRify : Behavior
{
public override string Name => "qr-ify";
public override string Trigger => "!qrplz";
public override string Description => "generate text QR codes";
public override async Task<bool> ActOn(PermissionSettings permissions, Message message)
{
var qrContent = message.Content.Substring($"{Trigger} ".Length + message.Content.IndexOf(Trigger));
Console.WriteLine($"qring: {qrContent}");
QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeData qrCodeData = qrGenerator.CreateQrCode(qrContent, QRCodeGenerator.ECCLevel.Q);
SvgQRCode qrCode = new SvgQRCode(qrCodeData);
string qrCodeAsSvg = qrCode.GetGraphic(20);
int todaysnumber = Shared.r.Next();
if (!Directory.Exists("tmp"))
{
Directory.CreateDirectory("tmp");
}
File.WriteAllText($"tmp/qr{todaysnumber}.svg", qrCodeAsSvg);
if (ExternalProcess.GoPlz("convert", $"tmp/qr{todaysnumber}.svg tmp/qr{todaysnumber}.png"))
{
await message.Channel.SendFile($"tmp/qr{todaysnumber}.png", null);
File.Delete($"tmp/qr{todaysnumber}.svg");
File.Delete($"tmp/qr{todaysnumber}.png");
}
else
{
await message.Channel.SendMessage("convert failed :( aaaaaaadam!");
Console.Error.WriteLine($"convert failed :( qr{todaysnumber}");
return false;
}
return true;
}
}

View File

@ -9,6 +9,7 @@ namespace vassago
{
public string ExchangePairsLocation {get;set;}
public IEnumerable<string> DiscordTokens { get; set; }
public IEnumerable<Tuple<string, string>> TwitchTokens{get;set;}
public string DBConnectionString{get;set;}
private Configuration(){}

View File

@ -25,11 +25,6 @@ public class DiscordInterface
public async Task Init(string token)
{
//var c = _db.Channels.FirstOrDefault(ci => ci.ExternalId == channel.Id);
//Todo: find protocol reference in DB.
//TODO: should protocol be shared across mutliple accounts on that protocol? should protocol be a per-vassago-account thing?
//TODO: should protocol be associated with a connection token? how would that be updated?
client = new DiscordSocketClient(new DiscordSocketConfig() { GatewayIntents = GatewayIntents.All });
client.Log += (msg) =>
@ -96,7 +91,7 @@ public class DiscordInterface
if ((suMessage.Author.Id != client.CurrentUser.Id))
{
if (await thingmanagementdoer.Instance.ActOn(m))
if (await Behaver.Instance.ActOn(m))
{
m.ActedOn = true;
}
@ -110,27 +105,7 @@ public class DiscordInterface
var defaultChannel = UpsertChannel(arg.Guild.DefaultChannel);
defaultChannel.ParentChannel = guild;
var u = UpsertUser(arg);
//TODO: seen in channels
// if (u.SeenInChannels == null) u.SeenInChannels = new List<Channel>();
// var sighting = u.SeenInChannels?.FirstOrDefault(c => c.ExternalId == arg.Guild.Id);
// if (sighting == null)
// {
// var seenIn = u.SeenInChannels as List<Channel>;
// seenIn.Add(guild);
// seenIn.Add(defaultChannel);
// u.SeenInChannels = seenIn;
// _db.SaveChanges();
// }
return thingmanagementdoer.Instance.OnJoin(u, defaultChannel);
// Console.WriteLine($"user joined: {arg.Nickname}. Guid: {arg.Guild.Id}. Channel: {arg.Guild.DefaultChannel}");
// var abbreviatedNickname = arg.Nickname;
// if (arg.Nickname.Length > 3)
// {
// abbreviatedNickname = arg.Nickname.Substring(0, arg.Nickname.Length / 3);
// }
// Console.WriteLine($"imma call him {abbreviatedNickname}");
// return arg.Guild.DefaultChannel.SendMessageAsync($"oh hey {abbreviatedNickname}- IPLAYTHESEALOFORICHALCOS <:ORICHALCOS:852749196633309194>");
return Behaver.Instance.OnJoin(u, defaultChannel);
}
private async Task ButtonHandler(SocketMessageComponent component)
{
@ -240,9 +215,6 @@ public class DiscordInterface
c.ExternalId = channel.Id;
c.IsDM = channel is IPrivateChannel;
c.Messages = c.Messages ?? new List<Message>();
//c.Messages = await channel.GetMessagesAsync(); //TODO: this, but only on startup or channel join
//c.OtherUsers = c.OtherUsers ?? new List<User>();
//c.OtherUsers = await channel.GetUsersAsync(); //TODO: this, but only on startup or channel join
c.Protocol = PROTOCOL;
if (channel is IGuildChannel)
{
@ -282,9 +254,6 @@ public class DiscordInterface
c.ExternalId = channel.Id;
c.IsDM = false;
c.Messages = c.Messages ?? new List<Message>();
//c.Messages = await channel.GetMessagesAsync(); //TODO: this, but only on startup or channel join
//c.OtherUsers = c.OtherUsers ?? new List<User>();
//c.OtherUsers = await channel.GetUsersAsync(); //TODO: this, but only on startup or channel join
c.Protocol = PROTOCOL;
c.ParentChannel = null;
c.SubChannels = c.SubChannels ?? new List<Channel>();
@ -317,4 +286,25 @@ public class DiscordInterface
return u;
}
internal async void BackfillChannelInfo(Channel channel)
{
//TODO: some sort of "when you get around to it" task queue
//c.Messages = await channel.GetMessagesAsync(); //TODO: this
//c.OtherUsers = c.OtherUsers ?? new List<User>();
//c.OtherUsers = await channel.GetUsersAsync();
var dChannel = client.GetChannel(channel.ExternalId.Value);
if(dChannel is IGuild)
{
var guild = channel as IGuild;
}
else if(dChannel is IGuildChannel)
{
var gc = dChannel as IGuildChannel;
}
else if (dChannel is IPrivateChannel)
{
var dm = dChannel as IPrivateChannel;
}
}
}

View File

@ -18,7 +18,7 @@ public class Channel
public List<Channel> SubChannels { get; set; }
public Channel ParentChannel { get; set; }
public string Protocol { get; set; }
public IEnumerable<Message> Messages { get; set; }
public List<Message> Messages { get; set; }
[NonSerialized]
public Func<string, string, Task> SendFile;

View File

@ -5,7 +5,7 @@ using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Reflection;
public class User //more like "user's account - no concept of the person outside of the protocol. (yet?)
public class User //TODO: distinguish the user and their account
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }