From 5bbb8c95d1b2a3ce59230c2e3ded32fca8127196 Mon Sep 17 00:00:00 2001 From: "Adam R. Grey" Date: Sat, 15 Jan 2022 20:32:23 -0500 Subject: [PATCH] JOKES --- Features.cs | 44 +++++++++++-- Program.cs | 157 +++++++++++++++++++++++++++++++++++++-------- externalProcess.cs | 3 +- jokes.txt | 42 ++++++++++++ twitchery.cs | 112 -------------------------------- 5 files changed, 212 insertions(+), 146 deletions(-) create mode 100644 jokes.txt delete mode 100644 twitchery.cs diff --git a/Features.cs b/Features.cs index a9656d8..386abd0 100644 --- a/Features.cs +++ b/Features.cs @@ -1,6 +1,8 @@ using System; using System.IO; using System.Net; +using System.Threading; +using System.Threading.Tasks; using Discord; using Discord.WebSocket; using Newtonsoft.Json; @@ -10,6 +12,7 @@ namespace silverworker_discord { public static class Features { + public static Random r = new Random(); public static async void detiktokify(Uri link, SocketUserMessage message) { var ytdl = new YoutubeDLSharp.YoutubeDL(); @@ -52,7 +55,7 @@ namespace silverworker_discord { var request = WebRequest.Create(att.Url); HttpWebResponse response = request.GetResponse() as HttpWebResponse; - if(!Directory.Exists("tmp")) + if (!Directory.Exists("tmp")) { Directory.CreateDirectory("tmp"); } @@ -61,11 +64,11 @@ namespace silverworker_discord { input.CopyTo(output); } - if(ExternalProcess.GoPlz("convert", $"tmp/{att.Filename} tmp/{att.Filename}.jpg")) + if (ExternalProcess.GoPlz("convert", $"tmp/{att.Filename} tmp/{att.Filename}.jpg")) { await message.Channel.SendFileAsync($"tmp/{att.Filename}.jpg", "converted from jpeg-but-apple to jpeg"); File.Delete($"tmp/{att.Filename}"); - File.Delete($"tmp/{att.Filename}.jpg"); + File.Delete($"tmp/{att.Filename}.jpg"); } else { @@ -87,16 +90,16 @@ namespace silverworker_discord SvgQRCode qrCode = new SvgQRCode(qrCodeData); string qrCodeAsSvg = qrCode.GetGraphic(20); int todaysnumber = Shared.r.Next(); - if(!Directory.Exists("tmp")) + 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")) + if (ExternalProcess.GoPlz("convert", $"tmp/qr{todaysnumber}.svg tmp/qr{todaysnumber}.png")) { await message.Channel.SendFileAsync($"tmp/qr{todaysnumber}.png"); File.Delete($"tmp/qr{todaysnumber}.svg"); - File.Delete($"tmp/qr{todaysnumber}.png"); + File.Delete($"tmp/qr{todaysnumber}.png"); } else { @@ -104,5 +107,34 @@ namespace silverworker_discord Console.Error.WriteLine($"convert failed :( qr{todaysnumber}"); } } + public static async void Joke(SocketUserMessage message) + { + var jokes = File.ReadAllLines("jokes.txt"); + var thisJoke = jokes[r.Next(jokes.Length)]; + if (thisJoke.Contains("?") && !thisJoke.EndsWith('?')) + { +#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.SendMessageAsync(straightline)); + Thread.Sleep(TimeSpan.FromSeconds(r.Next(5, 30))); + var myOwnMsg = await message.Channel.SendMessageAsync(punchline); + if (r.Next(8) == 0) + { + await myOwnMsg.AddReactionAsync(new Emoji("\U0001F60E")); //smiling face with sunglasses + } + }); +#pragma warning restore 4014 + } + else + { + await message.Channel.SendMessageAsync(thisJoke); + } + + + } } } \ No newline at end of file diff --git a/Program.cs b/Program.cs index 9b9c0b5..7e5f480 100644 --- a/Program.cs +++ b/Program.cs @@ -16,6 +16,7 @@ namespace silverworker_discord class Program { private DiscordSocketClient _client; + private Random r = new Random(); IConfigurationRoot config = new ConfigurationBuilder() .AddJsonFile("appsettings.json", true, true) @@ -48,6 +49,7 @@ namespace silverworker_discord await Task.Delay(-1); } +#pragma warning disable 4014 //the "you're not awaiting this" warning. yeah I know, that's the beauty of an async method lol #pragma warning disable 1998 //the "it's async but you're not awaiting anything". private async Task MessageReceived(SocketMessage messageParam) #pragma warning restore 1998 @@ -56,51 +58,152 @@ namespace silverworker_discord if (message == null) return; if (message.Author.Id == _client.CurrentUser.Id) return; - Console.WriteLine($"{message.Channel}, {message.Content} (message id: {message.Id})"); + Console.WriteLine($"#{message.Channel}[{DateTime.Now}][{message.Author.Username} [id={message.Author.Id}]][msg id: {message.Id}] {message.Content}"); - if (message.Author.IsWebhook) + if (message.Author.IsWebhook || message.Author.IsBot) { } else { - //any channel, from a user - if (message.Content.StartsWith("!qrplz ")) + var contentWithoutMention = message.Content; + var mentionedMe = false; + if (message.MentionedUsers?.FirstOrDefault(muid => muid.Id == _client.CurrentUser.Id) != null) { - Features.qrify(message.Content.Substring("!qrplz ".Length), message); + var mentionOfMe = "<@!" + _client.CurrentUser.Id + ">"; + contentWithoutMention = message.Content.Replace(mentionOfMe + " ", null); + contentWithoutMention = contentWithoutMention.Replace(mentionOfMe, null); + mentionedMe = true; } - else + 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) { - 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) { - foreach (var link in links) + if (link.Host == "vm.tiktok.com") { - if (link.Host == "vm.tiktok.com") - { - Features.detiktokify(link, message); - } + Features.detiktokify(link, message); } } + } - if (message.Attachments?.Count > 0) + if (message.Attachments?.Count > 0) + { + Console.WriteLine($"{message.Attachments.Count} attachments"); + var appleReactions = false; + foreach (var att in message.Attachments) { - Console.WriteLine($"{message.Attachments.Count} attachments"); - var appleReactions = false; - foreach (var att in message.Attachments) + if (att.Filename?.EndsWith(".heic") == true) { - if (att.Filename?.EndsWith(".heic") == true) - { - Features.deheic(message, att); - appleReactions = true; - } + Features.deheic(message, att); + appleReactions = true; } - if (appleReactions) + } + if (appleReactions) + { + message.AddReactionAsync(new Emoji("\U0001F34F")); + } + } + + var msgText = message.Content?.ToLower(); + if (!string.IsNullOrWhiteSpace(msgText)) + { + + if (Regex.IsMatch(msgText, "\\bcloud( |-)?native\\b", RegexOptions.IgnoreCase) || + Regex.IsMatch(msgText, "\\benterprise( |-)?(level|solution)\\b", RegexOptions.IgnoreCase)) + { + switch (r.Next(2)) { -#pragma warning disable 4014 //the "you're not awaiting this" warning. yeah I know, that's the beauty of an async method lol - message.AddReactionAsync(new Emoji("\U0001F34F")); + case 0: + await message.AddReactionAsync(new Emoji("\uD83E\uDD2E")); //vomit emoji + break; + case 1: + await message.AddReactionAsync(new Emoji("\uD83C\uDDE7")); //B emoji + await message.AddReactionAsync(new Emoji("\uD83C\uDDE6")); //A + await message.AddReactionAsync(new Emoji("\uD83C\uDDF3")); //N + break; + } + } + if (Regex.IsMatch(msgText, "^(s?he|(yo)?u|y'?all) thinks? i'?m (playin|jokin|kiddin)g?$", RegexOptions.IgnoreCase)) + { + var outgoingMessage = await message.Channel.SendMessageAsync("I believed you for a second, but then you assured me you's a \uD83C\uDDE7 \uD83C\uDDEE \uD83C\uDDF9 \uD83C\uDDE8 \uD83C\uDDED"); + } + if (Regex.IsMatch(msgText, "\\bwish me luck\\b", RegexOptions.IgnoreCase)) + { + if (r.Next(20) == 0) + { + await message.AddReactionAsync(new Emoji("\U0001f340"));//4-leaf clover + } + else + { + await message.AddReactionAsync(new Emoji("☘️")); + } + + } + if (msgText.Contains("!qrplz ")) + { + Features.qrify(msgText.Substring("!qrplz ".Length + msgText.IndexOf("!qrplz ")), message); + } + if (msgText.Contains("!countdown ")) + { + //Features.countdown(msgText.Substring("!countdown ".Length + msgText.IndexOf("!countdown ")), message); //converting human readable times is hard :/ + } + if (Regex.IsMatch(msgText, "!joke\\b")) + { + Features.Joke(message); + } + if (msgText.Contains("cognitive dissonance") == true) + { + message.ReplyAsync("that's not what cognitive dissonance means."); + } + if (Regex.IsMatch(msgText, "\\bthank (yo)?u\\b", RegexOptions.IgnoreCase) && + (mentionedMe || Regex.IsMatch(msgText, "\\b(sh?tik)?bot\\b", RegexOptions.IgnoreCase))) + { + switch (r.Next(4)) + { + case 0: + message.Channel.SendMessageAsync("you're welcome, citizen!"); + break; + case 1: + message.AddReactionAsync(new Emoji("☺")); + break; + case 2: + message.AddReactionAsync(new Emoji("\U0001F607")); //smiling face with halo + break; + case 3: + switch (r.Next(9)) + { + case 0: + message.AddReactionAsync(new Emoji("❤")); //normal heart, usually rendered red + break; + case 1: + message.AddReactionAsync(new Emoji("\U0001F9E1")); //orange heart + break; + case 2: + message.AddReactionAsync(new Emoji("\U0001F49B")); //yellow heart + break; + case 3: + message.AddReactionAsync(new Emoji("\U0001F49A")); //green heart + break; + case 4: + message.AddReactionAsync(new Emoji("\U0001F499")); //blue heart + break; + case 5: + message.AddReactionAsync(new Emoji("\U0001F49C")); //purple heart + break; + case 6: + message.AddReactionAsync(new Emoji("\U0001F90E")); //brown heart + break; + case 7: + message.AddReactionAsync(new Emoji("\U0001F5A4")); //black heart + break; + case 8: + message.AddReactionAsync(new Emoji("\U0001F90D")); //white heart + break; + } + break; + } #pragma warning restore 4014 - } } } } diff --git a/externalProcess.cs b/externalProcess.cs index e366534..cec629f 100644 --- a/externalProcess.cs +++ b/externalProcess.cs @@ -5,6 +5,7 @@ using System.Diagnostics; using System.IO; using System.Text; using System.Text.RegularExpressions; +using Newtonsoft.Json; namespace silverworker_discord { @@ -59,7 +60,7 @@ namespace silverworker_discord errorFilename = $"{dumpDir}/error{i}.err"; } File.WriteAllText(outputFilename, outputData.ToString()); - File.WriteAllText(errorFilename, errorFilename.ToString()); + File.WriteAllText(errorFilename, JsonConvert.SerializeObject(e, Formatting.Indented)); return false; } return true; diff --git a/jokes.txt b/jokes.txt new file mode 100644 index 0000000..624a687 --- /dev/null +++ b/jokes.txt @@ -0,0 +1,42 @@ +I got a joke for you: wealth trickles down. +Why did the celebrity egg start losing her friends? They called her a shell-out. +What's the difference between a hippo and a zippo? One is really heavy and the other is a little lighter. +The best time on a watch is 6:30, hands down. (ask your parents, young ones) +What killed the painter? He had too many strokes +Artists know how to draw the line, so you can’t really peer pressure them. +Why did the hand cross the road? To get to the secondhand store. +Why do seagulls fly over the ocean? Because if they flew over the bay, we'd call them bagels. +Why don't oysters donate to charity? Because they're shellfish +I only know 25 letters of the alphabet. I don't know y. +What did the fish say when it ran into a wall? Dam. +What do you call a factory that makes okay products? A satisfactory. +What do you call a fly without wings? A walk. +Don't trust those trees. They seem kind of shady. +I don't trust stairs. They're up to something. +What did the teacher do with the students report on cheese? Grated it. +What do you call a man with no legs and arms in a pool? Bob. +I was going to tell a joke about hammers but ...I don't think I'll nail it +why did the can recycler quit his job? because it was so depressing. +They told me to stop impersonating a flamingo. I had to put my foot down. +I failed math so many times at school, I can’t even count. +When I was a child, I threw a boomerang, but it didn't come back. I live in constant fear. +When life gives you melons, you might be dyslexic. +Don’t you hate it when someone answers their own questions? I do. +It takes a lot of balls to golf the way I do. +The problem with kleptomaniacs is that they always take things literally. +I can’t believe I got fired from the calendar factory. All I did was take a day off. +Most people are shocked when they find out how bad I am as an electrician. +I was addicted to the hokey pokey, but then I turned myself around. +A termite walks into the bar and asks, "Is the bartender here?" +Just burned 2,000 calories. That’s the last time I leave brownies in the oven while I nap. +A recent study has found that women who carry a little extra weight live longer than the men who mention it. +I got a new pair of gloves today, but they’re both ‘lefts,’ which on the one hand is great, but on the other, it’s just not right. +I can tell when people are being judgmental just by looking at them. +Are people born with photographic memories, or does it take time to develop? (ask your parents, young ones) +I buy all my guns from a guy called T-Rex. He’s a small arms dealer. +A book fell on my head the other day. I only have my shelf to blame though. +If you don’t pay your exorcist, do you get repossessed? +A ghost walked into a bar and ordered a shot of vodka. The bartender said, ‘Sorry, we don’t serve spirits here.’ +A blind man walked into a bar. and a table. and a chair. +How do you make holy water? You boil the hell out of it. +My teachers told me I’d never amount to much because I procrastinate so much. I told them, “Just you wait!” \ No newline at end of file diff --git a/twitchery.cs b/twitchery.cs deleted file mode 100644 index 7ab7f4b..0000000 --- a/twitchery.cs +++ /dev/null @@ -1,112 +0,0 @@ -using System; -using System.Linq; -using System.Net; -using System.Text; -using System.Threading.Tasks; -using Newtonsoft.Json; - -namespace silverworker_discord -{ - //replace me with a proper twitch interface - public class twitchery - { - public static async Task twitcherize(string type, string subData) - { - string purchaser, action; - switch (type) - { - case "reward-request": - await CustomReward(subData); - break; - case "subscription": - purchaser = subData.Split("•")[0].Trim(); - action = subData.Split("•")[1].Trim(); - var subObj = JsonConvert.SerializeObject(new{ - purchaserUsername = purchaser, - actionData = action - }, Formatting.None); - if (action == "Subscribed with Prime") - { - await post("http://192.168.1.151:3001/shortcuts/primeFreshSub", subObj); - } - else if (action.StartsWith("Resubscribed with Prime.")) - { - await post("http://192.168.1.151:3001/shortcuts/primeResub", subObj); - } - else if (action.StartsWith("Gifted ")) - { - await post("http://192.168.1.151:3001/shortcuts/giftSub", subObj); - } - else if (action.StartsWith("Subscribed for")) - { - await post("http://192.168.1.151:3001/shortcuts/rawSub", subObj); - } - else if (action.StartsWith("Resubscribed for")) - { - await post("http://192.168.1.151:3001/shortcuts/rawResub", subObj); - } - break; - case "follow": - await post("http://192.168.1.151:3001/shortcuts/follow", subData.Split("•")[0].Trim()); - break; - case "monetary": - await post("http://192.168.1.151:3001/shortcuts/cheer", JsonConvert.SerializeObject(new{ - purchaserUsername = subData.Split("•")[0].Trim(), - actionData = subData.Split("•")[1].Trim() - }, Formatting.None)); - break; - case "raiding": - string partySizeStr = subData.Split("•")[1].Trim().Split(' ').Last(); - int partySize = -1; - int.TryParse(partySizeStr, out partySize); - await post("http://192.168.1.151:3001/shortcuts/raid", JsonConvert.SerializeObject(new{ - raidLeader = subData.Split("•")[0].Trim(), - partySize = partySize - }, Formatting.None)); - break; - default: - await UnhandledRedemption(type, subData); - break; - } - } - private static async Task CustomReward(string redemptionData) - { - var components = redemptionData.Split("•"); - Console.WriteLine($"{components.Length} components:"); - var rewardName = components[0].Trim(); - var redeemer = components[1].Trim(); - var textData = ""; - if (components[1].Contains(":")) - { - redeemer = components[1].Substring(0, components[1].IndexOf(":")).Trim(); - textData = components[1].Substring(components[1].IndexOf(":")).Trim(); - } - Console.WriteLine($"user: {redeemer} redeems {rewardName}, text data? {textData}"); - - var redemptionSerialized = JsonConvert.SerializeObject(new - { - redeemer = redeemer, - rewardName = rewardName, - textData = textData - }, Formatting.None); - await post("http://192.168.1.151:3001/shortcuts/redeemReward", redemptionSerialized); - } - private static async Task UnhandledRedemption(params string[] data) - { - await post("http://192.168.1.151:3001/shortcuts/unhandledRedemption", JsonConvert.SerializeObject(data, Formatting.None)); - } - private static async Task post(string endpoint, string body) - { - byte[] sendable = Encoding.ASCII.GetBytes(body); - var wr = WebRequest.Create(endpoint); - wr.Method = "POST"; - wr.ContentType = "application/json"; - wr.ContentLength = sendable.Length; - using (var postStream = wr.GetRequestStream()) - { - postStream.Write(sendable); - } - await wr.GetResponseAsync(); - } - } -} \ No newline at end of file