public async Task Save() { //var json = JsonConvert.SerializeObject(this); //File.WriteAllText("config.json", json); await JsonStorage.SerializeObjectToFile(this, "config.json"); }
private async Task RunAsync() { socketClient = new DiscordSocketClient(new DiscordSocketConfig { LogLevel = LogSeverity.Verbose, AlwaysDownloadUsers = true, MessageCacheSize = 100 }); socketClient.Log += Log; restClient = new DiscordRestClient(new DiscordRestConfig { LogLevel = LogSeverity.Verbose }); restClient.Log += Log; if (File.Exists("./update")) { var temp = File.ReadAllText("./update"); ulong.TryParse(temp, out updateChannel); File.Delete("./update"); Console.WriteLine($"Found an update file! It contained [{temp}] and we got [{updateChannel}] from it!"); } config = await Config.Load(); dbhelper = new DatabaseHelper(); logger = new Logger(); var map = new ServiceCollection().AddSingleton(socketClient).AddSingleton(config).AddSingleton(logger).AddSingleton(dbhelper).BuildServiceProvider(); await socketClient.LoginAsync(TokenType.Bot, config.Token); await socketClient.StartAsync(); await restClient.LoginAsync(TokenType.Bot, config.Token); if (File.Exists("./deadlock")) { Console.WriteLine("We're recovering from a deadlock."); File.Delete("./deadlock"); foreach (var u in config.OwnerIds) { (await restClient.GetUserAsync(u))? .SendMessageAsync($"I recovered from a deadlock.\n`{DateTime.Now.ToShortDateString()}` `{DateTime.Now.ToLongTimeString()}`"); } } socketClient.GuildAvailable += Client_GuildAvailable; socketClient.Disconnected += SocketClient_Disconnected; await dbhelper.Install(map); await logger.Install(map); SpoilerWords = JsonStorage.DeserializeObjectFromFile <List <string> >("filter.json"); RoleColors = JsonStorage.DeserializeObjectFromFile <Dictionary <string, ulong> >("colors.json"); handler = new CommandHandler(); await handler.Install(map); try { socketClient.MessageReceived += Client_MessageReceived; socketClient.ReactionAdded += Client_ReactionAdded; socketClient.ReactionRemoved += Client_ReactionRemoved; } catch (Exception ex) { Console.WriteLine($"{ex.Source}\n{ex.Message}\n{ex.StackTrace}"); } //var avatar = new Image(File.OpenRead(".\\TaranzaSOUL.png")); //await client.CurrentUser.ModifyAsync(x => x.Avatar = avatar); await Task.Delay(-1); }
private async Task Client_MessageReceived(SocketMessage msg) { //if (msg.Source == MessageSource.System) //{ // var systemMsg = msg as SocketSystemMessage; // if (systemMsg.Type != MessageType.ChannelPinnedMessage) // return; //} //if (msg.Content.ToLower().Contains("r/place")) //{ // var user = msg.Author as IGuildUser; // if (user.JoinedAt > DateTimeOffset.Now.AddDays(-1) && !placeUsers.Contains(user.Id)) // { // placeUsers.Add(user.Id); // await msg.Channel.SendMessageAsync(messageReference: new MessageReference(msg.Id), // text: "Hello r/place user! While we acknowledge the enthusiasm for Reddit's April Fool's event, we're not affiliated with any of the Kirbys on the canvas. " + // "If you're looking to use any of the space on or around the various Kirbys, we won't stop you, but we also don't have any say over those areas. " + // "If you're looking for permission or wanting people for something else you're organizing, we suggest you look in the megathreads on r/place."); // return; // } //} if ((msg.Channel.Id == 195126987558354944 || msg.Channel.Id == 599165344019644426) && (msg.Content.ToLower().StartsWith("https://tenor.com/") || msg.Content.ToLower().StartsWith("https://giphy.com/"))) { await msg.DeleteAsync(); var sentMessage = await msg.Channel.SendMessageAsync($"{msg.Author.Mention} please don't post reaction gifs in the art channels!"); await Task.Delay(5000); await sentMessage.DeleteAsync(); } if (msg.Author.Id == 102528327251656704 && msg.Content.ToLower() == "<@267405866162978816> update colors") { RoleColors = JsonStorage.DeserializeObjectFromFile <Dictionary <string, ulong> >("colors.json"); await msg.Channel.SendMessageAsync("Done!"); return; } if (msg.Author.Id == 267405866162978816) { return; } if ((msg.Channel as IGuildChannel) == null) { return; } if ((msg.Author as IGuildUser).RoleIds.Contains(config.StaffId) && (msg.Content.ToLower() == "<@!267405866162978816> get filter" || msg.Content.ToLower() == "<@267405866162978816> get filter")) { await msg.Channel.SendMemoryFile("filter.json", JsonConvert.SerializeObject(SpoilerWords, Formatting.Indented)); } if ((msg.Author as IGuildUser).RoleIds.Contains(config.StaffId) && (msg.Content.ToLower() == "<@!267405866162978816> update filter" || msg.Content.ToLower() == "<@267405866162978816> update filter")) { string file = ""; string downloadedWords = ""; if (msg.Attachments.Count() > 0) { if (msg.Attachments.FirstOrDefault().Filename.ToLower().EndsWith(".json")) { file = msg.Attachments.FirstOrDefault().Url; } else { await msg.Channel.SendMessageAsync("That isn't a .json file!"); return; } } else { await msg.Channel.SendMessageAsync("I don't see any attachments!"); return; } await Task.Run(async() => { Console.WriteLine($"setting download url to: {file}"); try { using (WebClient client = new WebClient()) { Console.WriteLine("Downloading..."); downloadedWords = client.DownloadString(new Uri(file)); Console.WriteLine("Downloaded"); } } catch (Exception ex) { await msg.Channel.SendMessageAsync($"There was an error downloading that file:\n{ex.Message}"); string exMessage; if (ex != null) { while (ex is AggregateException && ex.InnerException != null) { ex = ex.InnerException; } exMessage = $"{ex.Message}"; if (exMessage != "Reconnect failed: HTTP/1.1 503 Service Unavailable") { exMessage += $"\n{ex.StackTrace}"; } } else { exMessage = null; } Console.WriteLine(exMessage); return; } }); var tempWords = new List <string>(); try { tempWords = JsonConvert.DeserializeObject <List <string> >(downloadedWords); } catch (Exception ex) { await msg.Channel.SendMessageAsync($"There was an error loading that file:\n{ex.Message}"); string exMessage; if (ex != null) { while (ex is AggregateException && ex.InnerException != null) { ex = ex.InnerException; } exMessage = $"{ex.Message}"; if (exMessage != "Reconnect failed: HTTP/1.1 503 Service Unavailable") { exMessage += $"\n{ex.StackTrace}"; } } else { exMessage = null; } Console.WriteLine(exMessage); return; } try { JsonStorage.SerializeObjectToFile(tempWords, "filter.json"); } catch (Exception ex) { await msg.Channel.SendMessageAsync($"There was an error replacing the filter:\n{ex.Message}"); string exMessage; if (ex != null) { while (ex is AggregateException && ex.InnerException != null) { ex = ex.InnerException; } exMessage = $"{ex.Message}"; if (exMessage != "Reconnect failed: HTTP/1.1 503 Service Unavailable") { exMessage += $"\n{ex.StackTrace}"; } } else { exMessage = null; } Console.WriteLine(exMessage); return; } Console.WriteLine("Filter replaced"); SpoilerWords = JsonStorage.DeserializeObjectFromFile <List <string> >("filter.json"); SpoilerWords = SpoilerWords.Select(x => x.ToLower()).ToList(); await msg.Channel.SendMessageAsync("Done!"); return; } if (msg.Channel.Id == 952748828858155038 || msg.Channel.Id == 361589776433938432 || msg.Channel.Id == 425752341833187328 || msg.Channel.Id == 952748828858155038 || msg.Channel.Id == 186342269274554368 || msg.Channel.Id == 529898152547844116 || msg.Channel.Id == 952748828858155038 || msg.Channel.Id == 447789034131947530 || msg.Channel.Id == 429821654068101120 || msg.Channel.Id == 508903543856562176 || msg.Channel.Id == 346371452620111872 || msg.Channel.Id == 955554476264161300 || msg.Channel.Id == 268945818470449162 || msg.Channel.Id == 957411530972999731 || msg.Channel.Id == 635234053016256524 || msg.Channel.Id == 361589776433938432 || msg.Channel.Id == 937410715659149373 || msg.Channel.Id == 429821654068101120 || msg.Channel.Id == 186342269274554368 || msg.Channel.Id == 772590802618679377 || msg.Channel.Id == 637466803227983893 || msg.Channel.Id == 425752341833187328 || msg.Channel.Id == 776811442795053097 || msg.Channel.Id == 575390652444180481 || msg.Channel.Id == 447789034131947530 || msg.Channel.Id == 423578054775013377) { return; } var tmp = msg.Content.ToLower(); foreach (var s in SpoilerWords) { //if (msg.Channel.Id == 268945818470449162 && s == "flamberge") // continue; if (tmp.Contains(s)) { bool match = true; if (tmp.Length > tmp.IndexOf(s) + s.Length) { if (char.IsLetter(tmp[tmp.IndexOf(s) + s.Length])) { match = false; continue; } } if (tmp.IndexOf(s) > 0) { if (char.IsLetter(tmp[tmp.IndexOf(s) - 1])) { match = false; continue; } } //if (!s.Contains(" ")) //{ // bool match = false; // foreach (var word in tmp.Split(' ')) // { // if (word == s) // { // match = true; // break; // } // } // if (!match) continue; //} if (match) { await Task.Delay(100); await msg.DeleteAsync(); string send = $"{msg.Author.Mention} that's a potential Forgotten Land spoiler! That belongs in <#268945818470449162>!\nCheck in <#431953417024307210> if you need access."; await msg.Channel.SendMessageAsync(send); break; } } } }
private async Task Client_MessageReceived(SocketMessage msg) { if (msg.Author.Id == 102528327251656704 && msg.Content.ToLower() == "<@267405866162978816> update colors") { RoleColors = JsonStorage.DeserializeObjectFromFile <Dictionary <string, ulong> >("colors.json"); await msg.Channel.SendMessageAsync("Done!"); return; } //if (msg.Author.Id == 267405866162978816) return; ////if ((msg.Channel as IGuildChannel) == null) //// return; //if ((((IGuildUser)msg.Author).RoleIds.Contains((ulong)132721372848848896) || // (((IGuildUser)msg.Author).RoleIds.Contains((ulong)190657363798261769))) // && msg.Content.ToLower() == "<@267405866162978816> get filter") //{ // await msg.Channel.SendFileAsync("@./filter.json", "Here you go."); //} //if ((((IGuildUser)msg.Author).RoleIds.Contains((ulong)132721372848848896) || // (((IGuildUser)msg.Author).RoleIds.Contains((ulong)190657363798261769))) // && msg.Content.ToLower() == "<@267405866162978816> update filter") //{ // string file = ""; // if (msg.Attachments.Count() > 0) // { // if (msg.Attachments.FirstOrDefault().Filename.ToLower().EndsWith(".json")) // file = msg.Attachments.FirstOrDefault().Url; // else // { // await msg.Channel.SendMessageAsync("That isn't a .json file!"); // return; // } // } // else // { // await msg.Channel.SendMessageAsync("I don't see any attachments!"); // return; // } // using (WebClient client = new WebClient()) // { // await client.DownloadFileTaskAsync(new Uri(file), $"@./temp/{file}"); // } // var tempWords = new List<string>(); // try // { // tempWords = JsonStorage.DeserializeObjectFromFile<List<string>>($"@./temp/{file}"); // } // catch (Exception ex) // { // await msg.Channel.SendMessageAsync($"There was an error loading that file:\n{ex.Message}"); // return; // } // File.Delete("@./filter.json"); // File.Move($"@./temp/{file}", "@./filter.json"); // SpoilerWords = JsonStorage.DeserializeObjectFromFile<List<string>>("filter.json"); // await msg.Channel.SendMessageAsync("Done!"); // return; //} //if (msg.Channel.Id == 417458111553470474 || msg.Channel.Id == 423578054775013377 || // msg.Channel.Id == 361589776433938432 || msg.Channel.Id == 425752341833187328 || // msg.Channel.Id == 429821654068101120 || msg.Channel.Id == 186342269274554368 || // msg.Channel.Id == 190674947381657600) // return; //if (((IGuildChannel)msg.Channel).GuildId != 132720341058453504) // return; //var tmp = msg.Content.ToLower(); //if (msg.Content.ToLower().Split(' ').Any(x => SpoilerWords.Contains(x))) //{ //} //foreach (var s in SpoilerWords) //{ // if (msg.Channel.Id == 268945818470449162 && s == "flamberge") // continue; // if (tmp.Contains(s)) // { // if (!s.Contains(" ")) // { // bool match = false; // foreach (var word in tmp.Split(' ')) // { // if (word == s) // { // match = true; // break; // } // } // if (!match) continue; // } // await Task.Delay(100); // await msg.DeleteAsync(); // string send = $"{msg.Author.Mention} that's a late game spoiler! That belongs in <#417458111553470474>!"; // await msg.Channel.SendMessageAsync(send); // } //} }
private async Task RunAsync() { socketClient = new DiscordSocketClient(new DiscordSocketConfig { LogLevel = LogSeverity.Verbose, AlwaysDownloadUsers = true, MessageCacheSize = 100, GatewayIntents = GatewayIntents.DirectMessages | GatewayIntents.GuildMessages | GatewayIntents.GuildMembers | GatewayIntents.Guilds | GatewayIntents.GuildMessageReactions }); socketClient.Log += Log; restClient = new DiscordRestClient(new DiscordRestConfig { LogLevel = LogSeverity.Verbose }); restClient.Log += Log; if (File.Exists("./update")) { var temp = File.ReadAllText("./update"); ulong.TryParse(temp, out updateChannel); File.Delete("./update"); Console.WriteLine($"Found an update file! It contained [{temp}] and we got [{updateChannel}] from it!"); } config = await Config.Load(); dbhelper = new DatabaseHelper(); logger = new Logger(); var map = new ServiceCollection().AddSingleton(socketClient).AddSingleton(config).AddSingleton(logger).AddSingleton(dbhelper).AddSingleton(restClient).BuildServiceProvider(); await socketClient.LoginAsync(TokenType.Bot, config.Token); await socketClient.StartAsync(); await restClient.LoginAsync(TokenType.Bot, config.Token); if (File.Exists("./deadlock")) { Console.WriteLine("We're recovering from a deadlock."); File.Delete("./deadlock"); foreach (var u in config.OwnerIds) { (await restClient.GetUserAsync(u))? .SendMessageAsync($"I recovered from a deadlock.\n`{DateTime.Now.ToShortDateString()}` `{DateTime.Now.ToLongTimeString()}`"); } } socketClient.GuildAvailable += Client_GuildAvailable; socketClient.Disconnected += SocketClient_Disconnected; await dbhelper.Install(map); await logger.Install(map); SpoilerWords = JsonStorage.DeserializeObjectFromFile <List <string> >("filter.json"); RoleColors = JsonStorage.DeserializeObjectFromFile <Dictionary <string, ulong> >("colors.json"); handler = new CommandHandler(); await handler.Install(map); try { socketClient.MessageReceived += Client_MessageReceived; socketClient.ReactionAdded += Client_ReactionAdded; socketClient.ReactionRemoved += Client_ReactionRemoved; socketClient.GuildMemberUpdated += SocketClient_GuildMemberUpdated; } catch (Exception ex) { Console.WriteLine($"{ex.Source}\n{ex.Message}\n{ex.StackTrace}"); } // perpetual queue to add/remove color roles Task.Run(async() => { while (true) { await Task.Delay(3000); try { if (lastRole < DateTimeOffset.Now.AddSeconds(-15)) { continue; } List <RoleAddition> temp = new List <RoleAddition>(); RoleAddition tempAction = null; while (RoleAdditions.TryDequeue(out tempAction)) { if (config.BlacklistedUsers.ContainsKey(tempAction.userId) && config.BlacklistedUsers[tempAction.userId] > DateTimeOffset.Now) { continue; } else { temp.Add(tempAction); } } if (temp.Count() != temp.Select(x => x.userId).Distinct().Count()) { // SOMEONE clicked on more than one role at a time! Dictionary <ulong, int> counter = new Dictionary <ulong, int>(); foreach (var u in temp.Select(x => x.userId)) { if (!counter.ContainsKey(u)) { counter[u] = 0; } counter[u]++; } foreach (var u in counter) { if (u.Value > 4) { try { await socketClient.GetUser(u.Key).SendMessageAsync("Hey, slow down! You don't need every color on that list! No more colors for an hour!"); } catch (Exception ex) { // User has their DMs disabled } await RemoveAllColors(u.Key); //config.BlacklistedUsers.Add(u.Key, DateTimeOffset.Now.AddHours(1)); Console.WriteLine($"Blacklisted [{u.Key}] from colors."); while (temp.Select(x => x.userId).Contains(u.Key)) { temp.Remove(temp.FirstOrDefault(x => x.userId == u.Key)); } } } } foreach (var ra in temp) { if (ra.remove) { await RemoveAllColors(ra.userId); } else { var user = socketClient.GetGuild(config.HomeGuildId).GetUser(ra.userId) as SocketGuildUser; user.AddRoleAsync(user.Guild.GetRole(ra.roleId)); } } } catch (Exception ex) { await Task.Delay(1000); // idk something errored } } }); //var avatar = new Image(File.OpenRead(".\\TaranzaSOUL.png")); //await client.CurrentUser.ModifyAsync(x => x.Avatar = avatar); await Task.Delay(-1); }