private async Task OnGuildLeave(SocketGuild guild) { await Task.Run(async() => { try { DatabaseContext context = new DatabaseContext(); if ((context.Auth.Any(o => o.Serverid == guild.Id) || ((context.OnJoin.Any(o => o.Serverid == guild.Id))))) { try { string token = context.Auth.AsQueryable().Where(a => a.Serverid == guild.Id).Single().Token; await BotTools.Sendmsg(guild.Id, $"status|OnHold"); await BotTools.Sendmsg(guild.Id, $"rec"); await BotTools.Sendmsg(guild.Id, $"unsub|serverListEvent"); await BotTools.Sendmsg(guild.Id, $"unsub|playerEvent"); Program.AliveTokens.Remove(token); } catch (Exception ex) { logger.Warn($"Exception occured: {ex.ToString()}"); } context.Remove(context.Auth.Single(a => a.Serverid == guild.Id)); context.Remove(context.Notify.Single(a => a.Serverid == guild.Id)); context.Remove(context.OnJoin.Single(a => a.Serverid == guild.Id)); context.SaveChanges(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }); }
private async Task GetReadyWS() { if (KKK.IsClientReady != true) { Console.WriteLine("Waiting for client to be ready..."); //Dont start events until discord api is ready } do { // nothing, just pauses the tasks until discord is ready } while (KKK.IsClientReady != true); Console.WriteLine("It's ready, lets start, shall we?"); DatabaseContext context = new DatabaseContext(); #if RELEASE var server = new WebSocketServer("wss://0.0.0.0:8181"); var config = BuildConfig(); server.Certificate = new X509Certificate2(config["certPath"], config["certPassword"]); #elif DEBUG var server = new WebSocketServer("ws://0.0.0.0:8181"); #endif server.Start(socket => { socket.OnOpen = () => { if (allSockets.Any(client => client.ConnectionInfo.ClientIpAddress == socket.ConnectionInfo.ClientIpAddress)) { var socket2 = allSockets.Find(client => client.ConnectionInfo.ClientIpAddress == socket.ConnectionInfo.ClientIpAddress); try { allSockets.Remove(socket2); } catch (Exception ex) { logger.Warn(ex.ToString(), "An error occured."); } //Little security, dont let same ip to connect twice allSockets.Add(socket); } else { try { allSockets.Remove(socket); } catch (Exception ex) { logger.Warn(ex.ToString(), "An error occured."); } allSockets.Add(socket); } }; socket.OnClose = () => { Console.WriteLine("Closed connection: " + socket.ConnectionInfo.ClientIpAddress); allSockets.Remove(socket); if (context.Auth.Any(o => o.IP == socket.ConnectionInfo.ClientIpAddress)) { string token = context.Auth.AsQueryable().Where(a => a.IP == socket.ConnectionInfo.ClientIpAddress).Single().Token; if (AliveTokens.Contains(token)) { AliveTokens.Remove(token); logger.Info($"{socket.ConnectionInfo.ClientIpAddress} Removed from alive tokens list"); } } }; socket.OnMessage = message => { Task.Run(async() => { try { #if DEBUG Console.WriteLine($"Message Received: {message}"); #endif string[] codes = message.Split('|'); switch (codes[0]) { case "login": string token = codes[1]; if (context.Auth.Any(o => o.Token == token)) { if (!AliveTokens.Contains(context.Auth.AsQueryable().Where(a => a.IP == socket.ConnectionInfo.ClientIpAddress).Single().Token)) { try { AliveTokens.Add(token); Console.WriteLine( $"{socket.ConnectionInfo.ClientIpAddress}:{token} Added to alive tokens list"); #if DEBUG Console.WriteLine("Here is Serverid: " + context.Auth.AsQueryable().Where(a => a.Token == token).Single().Serverid); #endif if (KKK.Client.GetGuild(context.Auth.AsQueryable().Where(a => a.Token == token).Single().Serverid) != null) { var guild = KKK.Client.GetGuild( context.Auth.AsQueryable().Where(a => a.Token == token).Single().Serverid); await socket.Send($"status|Linked|{guild.Name}"); } else { await socket.Send($"status|Linked|null"); } if (context.Notify.Any(o => o.Serverid == context.Auth.AsQueryable().Where(a => a.Token == token).Single().Serverid)) { await socket.Send($"subscribe|playerEvent"); } if (context.OnJoin.Any(o => (o.Serverid == context.Auth.AsQueryable().Where(a => a.Token == token).Single().Serverid) && o.sevent == 1)) { await socket.Send($"subscribe|serverListEvent"); } } catch (Exception ex) { logger.Warn(ex.ToString(), "An error occured."); } } } else if (!(context.Auth.Any(o => o.Token == token))) { if (!(context.OnHold.Any(o => o.IP == socket.ConnectionInfo.ClientIpAddress))) { using (var contextt = new DatabaseContext()) { OnHold newonhold = new OnHold(); newonhold.IP = socket.ConnectionInfo.ClientIpAddress; newonhold.Token = token; contextt.Add(newonhold); contextt.SaveChanges(); } } else if ((context.OnHold.Any(o => o.IP == socket.ConnectionInfo.ClientIpAddress))) { var onhold = context.OnHold.First(a => a.IP == socket.ConnectionInfo.ClientIpAddress); onhold.Token = token; context.SaveChanges(); } Console.WriteLine("Token: " + token + $" IP: {socket.ConnectionInfo.ClientIpAddress} Added to onhold list"); await socket.Send("status|OnHold"); } break; case "notify": if (AliveTokens.Contains(context.Auth.AsQueryable().Where(a => a.IP == socket.ConnectionInfo.ClientIpAddress).Single().Token)) { await Task.Run(async() => { try { string servername = codes[1]; string discordname = codes[2]; string channelid = codes[3]; string messageid = codes[4]; string eventt = codes[5]; string result = codes[6]; switch (eventt) { case "stop": switch (result) { //notify|{servername}|{discordname}|{channelid}|{messageid}|{eventt}|400|this is a test case "20": //ok await BotTools.NotificationControlAsync( ulong.Parse(messageid), ulong.Parse(channelid), $"Your `{servername}` stopped successfully, command was executed by `{discordname}`", int.Parse(result)); break; case "40": //its stopped already await BotTools.NotificationControlAsync( ulong.Parse(messageid), ulong.Parse(channelid), $"Your `{servername}` is stopped already, command was executed by `{discordname}`", int.Parse(result)); break; case "44": //server not found await BotTools.NotificationControlAsync( ulong.Parse(messageid), ulong.Parse(channelid), $"I couldnt find your `{servername}` server, please make sure you typed the right name, command was executed by `{discordname}`", int.Parse(result)); break; } break; case "start": switch (result) { //notify|{servername}|{discordname}|{channelid}|{messageid}|{eventt}|400|this is a test case "20": //ok await BotTools.NotificationControlAsync( ulong.Parse(messageid), ulong.Parse(channelid), $"Your `{servername}` server is starting.. , command was executed by `{discordname}`", int.Parse(result)); break; case "21": //ok await BotTools.NotificationControlAsync( ulong.Parse(messageid), ulong.Parse(channelid), $"Your `{servername}` started successfully, command was executed by `{discordname}`", int.Parse(result)); break; case "40": //its stopped already await BotTools.NotificationControlAsync( ulong.Parse(messageid), ulong.Parse(channelid), $"Your `{servername}` is running already, command was executed by `{discordname}`", int.Parse(result)); break; case "44": //server not found await BotTools.NotificationControlAsync( ulong.Parse(messageid), ulong.Parse(channelid), $"I couldnt find your `{servername}` server, please make sure you typed the right name, command was executed by `{discordname}`", int.Parse(result)); break; } break; } } catch (Exception ex) { logger.Warn($"Couldn't process request: {ex.Message}"); } }); } break; case "event": await Task.Run(async() => { string eventname = codes[1]; string servername = codes[2]; string playername = codes[3]; try { string token = context.Auth.AsQueryable().Where(a => a.IP == socket.ConnectionInfo.ClientIpAddress).Single().Token; if (AliveTokens.Contains(token)) { if (KKK.Client.GetGuild(context.Auth.AsQueryable().Where(a => a.Token == token).Single().Serverid) != null) { if (eventname.StartsWith("p") && context.Notify.AsQueryable().Any(x => x.Serverid == context.Auth.AsQueryable().Where(a => a.Token == token).Single().Serverid) && KKK.Client.GetGuild(context.Auth.AsQueryable().Where(a => a.Token == token).Single().Serverid) .GetChannel( context.Notify.AsQueryable().Where(a => a.Serverid == context.Auth.AsQueryable().Where(a => a.Token == token).Single().Serverid).Single().Channelid) != null) { switch (eventname) { case "pjoin": await BotTools.NotificationControlAsync(0, context.Notify.AsQueryable().Where(a => a.Serverid == context.Auth.AsQueryable().Where(a => a.Token == token).Single().Serverid).Single().Channelid, $"***{playername}*** Just joined ***{servername}***", 0, 1); break; case "pleave": await BotTools.NotificationControlAsync(0, context.Notify.AsQueryable().Where(a => a.Serverid == context.Auth.AsQueryable().Where(a => a.Token == token).Single().Serverid).Single().Channelid, $"***{playername}*** Just left ***{servername}***", 0, 1); break; } } else if (eventname.StartsWith("serverList") && context.OnJoin.Any(o => (o.Serverid == context.Auth.AsQueryable().Where(a => a.Token == token).Single().Serverid) && o.sevent == 1) && KKK.Client .GetGuild(context.Auth.AsQueryable().Where(a => a.Token == token).Single().Serverid) .GetChannel( context.OnJoin.AsQueryable().Where(a => a.Serverid == context.Auth.AsQueryable().Where(a => a.Token == token).Single().Serverid).Single().Channelid) != null) { await Task.Run(async() => { try { if (AliveTokens.Contains(token) && (context.OnJoin.Any(o => (o.Serverid == context.Auth.AsQueryable().Where(a => a.Token == token).Single().Serverid) && o.sevent == 1))) { ulong guild = context.Auth.AsQueryable().Where(a => a.Token == token).Single().Serverid; if (KKK.Client.GetGuild(guild) .GetChannel( context.OnJoin.AsQueryable().Where(a => a.Serverid == context.Auth.AsQueryable().Where(a => a.Token == token).Single().Serverid).Single().Channelid) != null) { if (context.OnJoin.AsQueryable().Where(a => a.Serverid == context.Auth.AsQueryable().Where(a => a.Token == token).Single().Serverid).Single().Messageid != 0) { IMessageChannel chan = (IMessageChannel)KKK.Client.GetChannel(context.OnJoin.AsQueryable().Where(a => a.Serverid == context.Auth.AsQueryable().Where(a => a.Token == token).Single().Serverid).Single().Channelid); IUserMessage msg = (IUserMessage)await chan.GetMessageAsync(context.OnJoin.AsQueryable().Where(a => a.Serverid == context.Auth.AsQueryable().Where(a => a.Token == token).Single().Serverid).Single().Messageid); if (msg != null) { await msg.ModifyAsync(msgProperty => { msgProperty.Embed = BuildServerListEmbed(message); }); } else { var msgg = await chan.SendMessageAsync(null, false, BotTools.Embed( "Dont remove this message, this message will be updated continuously", 20)); var server = context.OnJoin.First(a => a.Serverid == guild); server.Messageid = msgg.Id; server.sevent = 1; context.SaveChanges(); await msgg.ModifyAsync(msgProperty => { msgProperty.Embed = BuildServerListEmbed(message); }); } } } } } catch (Exception ex) { Console.WriteLine("Exception occured: " + ex.ToString()); } }); } } } } catch (Exception ex) { Console.WriteLine("Exception occured: " + ex.ToString()); } }); break; default: // ban ip in case gets to x requests To-DO Console.WriteLine($"Someone is trying to troll here, invalid packet: {message}"); break; } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }); //Console.WriteLine(message); //allSockets.ToList().ForEach(s => s.Send(message)); }; }); var input = Console.ReadLine(); while (input != "exit") { //foreach (var socket in allSockets.ToList()) //{ // await socket.Send(input); //} //input = Console.ReadLine(); } }
private async Task OnGuildJoin(SocketGuild guild) { await Task.Run(async() => { try { DatabaseContext context = new DatabaseContext(); if (!(context.Auth.Any(o => o.Serverid == guild.Id) && (!(context.OnJoin.Any(o => o.Serverid == guild.Id))))) { string warning = null; try { if (guild.Roles.Any(x => x.Name == "Fork-Mods")) { foreach (var Role in guild.Roles.Where(x => x.Name == "Fork-Mods")) { await Role.DeleteAsync(); } } } catch (Exception ex) { warning += $"`Fork-Mods` role detected, please move my role above the `Fork-Mods` role and authenticate using `$auth [token]` then run `$rec` to clean it." + Environment.NewLine; } try { if (guild.TextChannels.Any(x => x.Name == "Fork-Bot")) { foreach (var Chan in guild.Channels.Where(x => x.Name == "Fork-Bot")) { await Chan.DeleteAsync(); } } } catch (Exception ex) { warning += $"`Fork-Bot` channel detected, please move my role above the `Fork-Mods` role and authenticate using `$auth [token]` then run `$rec` to clean it." + Environment.NewLine; } if (warning == null) { ulong origin = (ulong)GuildPermission.Speak + (ulong)GuildPermission.SendTTSMessages + (ulong)GuildPermission.SendMessages + (ulong)GuildPermission.ViewChannel + (ulong)GuildPermission.EmbedLinks + (ulong)GuildPermission.Connect + (ulong)GuildPermission.AttachFiles + (ulong)GuildPermission.AddReactions; GuildPermissions perms = new GuildPermissions(origin); //Color Colorr = new Color(21, 22, 34); var roleee = await guild.CreateRoleAsync("Fork-Mods", perms, null, false, false, null); var vChan = await guild.CreateTextChannelAsync("Fork-Bot"); await vChan.AddPermissionOverwriteAsync(roleee, AdminPermissions()); await vChan.AddPermissionOverwriteAsync(guild.EveryoneRole, NoPermissions()); var ebd = new EmbedBuilder(); ebd.Color = Color.Green; ebd.WithCurrentTimestamp(); ebd.WithAuthor($"Fork Server Management", guild.CurrentUser.GetAvatarUrl()); ebd.WithDescription( "Hello there," + Environment.NewLine + "I'm Fork Bot if you don't know me, I can help you control your Fork Minecraft servers and display their status in Discord." + Environment.NewLine + "I made a private channel for you, please use `$auth [token]` to link this Discord server with your Fork app." + Environment.NewLine + "You can check for your token in Fork app settings."); //var ownerr = KKK.Client.GetGuild(guild.Id).OwnerId; await vChan.SendMessageAsync($"<@{guild.OwnerId}>", false, ebd.Build()); var msgg = await vChan.SendMessageAsync(null, false, BotTools.Embed("Don't remove this message, this message will be updated continuously and display the status of you Fork servers.", 20)); using (var contextt = new DatabaseContext()) { OnJoin newset = new OnJoin(); newset.Serverid = guild.Id; newset.Roleid = roleee.Id; newset.Channelid = vChan.Id; newset.Messageid = msgg.Id; contextt.Add(newset); contextt.SaveChanges(); } } else { var ebd = new EmbedBuilder(); ebd.Color = Color.Red; ebd.WithCurrentTimestamp(); ebd.WithAuthor($"Error", guild.CurrentUser.GetAvatarUrl()); ebd.WithDescription(warning); //var ownerr = KKK.Client.GetGuild(guild.Id).OwnerId; await guild.DefaultChannel.SendMessageAsync($"<@{guild.OwnerId}>", false, ebd.Build()); } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }); }