static bool OnGuildQuery(LoginClient client, CMSG msgID, BinReader data) { uint guildId = data.ReadUInt32(); BinWriter pkg = LoginClient.NewPacket(SMSG.GUILD_QUERY_RESPONSE); Chat.System(client, "Guild Query"); DBGuild guild = (DBGuild)DataServer.Database.FindObjectByKey(typeof(DBGuild), guildId); if (guild == null) { return(true); } else { pkg.Write(guild.ObjectId); pkg.Write(guild.Name); for (uint i = 0; i < 10; i++) { pkg.Write(guild.getRankName(i)); } pkg.Write((uint)guild.Icon); pkg.Write((uint)guild.IconColor); pkg.Write((uint)guild.Border); pkg.Write((uint)guild.BorderColor); pkg.Write((uint)guild.Color); } client.Send(pkg); return(true); } //OnGuildQuery
static bool OnGuildLeader(LoginClient client, CMSG msgID, BinReader data) { DBGuild guild = client.Character.Guild; if (guild == null || client.Character.GuildID == 0) { SendResult(client, 2, " ", (int)GUILDRESULT.NOT_IN_GUILD); return(true); } if (client.Character.GuildRank != 0) { SendResult(client, 1, " ", (int)GUILDRESULT.PERMISSIONS); ; return(true); } string name = data.ReadString(); DBCharacter tChar = (DBCharacter)DataServer.Database.FindObjectByKey(typeof(DBCharacter), name.ToLower()); if (tChar == null) { SendResult(client, 1, name, (int)GUILDRESULT.NOT_FOUND); return(true); } else if (client.Character.GuildID != tChar.GuildID) { SendResult(client, 1, name, (int)GUILDRESULT.NOT_IN_GUILD_S); return(true); } DBGuildMembers tMember = (DBGuildMembers)DataServer.Database.FindObjectByKey(typeof(DBGuildMembers), tChar.ObjectId); if (tMember == null) { SendResult(client, 1, name, (int)GUILDRESULT.INTERNAL); return(true); } tChar.GuildRank = 0; tMember.Rank = 0; guild.Leader = tChar.ObjectId; client.Character.GuildRank = 1; DBGuildMembers oldLeader = (DBGuildMembers)DataServer.Database.FindObjectByKey(typeof(DBGuildMembers), client.Character.ObjectId); if (oldLeader == null) { SendResult(client, 1, name, (int)GUILDRESULT.INTERNAL); return(true); } oldLeader.Rank = 1; SendToWorld(client, tChar); SendToWorld(client, client.Character); GuildMessage(guild, tChar.Name + " has been promoted to the rank of " + guild.getRankName(tChar.GuildRank) + " by " + client.Character.Name); SendRoster(client, guild); return(true); } //OnGuildLeader
static bool OnGuildDelRank(LoginClient client, CMSG msgID, BinReader data) { DBGuild tguild = client.Character.Guild; if (tguild == null || client.Character.GuildID == 0) { SendResult(client, 2, " ", (int)GUILDRESULT.NOT_IN_GUILD); return(true); } bool inuse = false; foreach (DBGuildMembers member in tguild.Members) { if (member.Rank == tguild.MaxRank) { inuse = true; } } if (inuse) { SendResult(client, 3, " ", (int)GUILDRESULT.NOT_IN_GUILD); return(true); } tguild.setRankName(tguild.MaxRank, "Unused"); tguild.MaxRank--; DataServer.Database.SaveObject(tguild); UpdateGuild(client); SendRoster(client, tguild); return(true); } //OnGuildDelRank
static bool OnGuildSetONote(LoginClient client, CMSG msgID, BinReader data) { DBGuild tguild = client.Character.Guild; if (tguild == null || client.Character.GuildID == 0) { SendResult(client, 2, " ", (int)GUILDRESULT.NOT_IN_GUILD); return(true); } DBCharacter tChar = (DBCharacter)DataServer.Database.FindObjectByKey(typeof(DBCharacter), data.ReadString()); if (tChar == null) { return(true); } DBGuildMembers tMember = (DBGuildMembers)DataServer.Database.FindObjectByKey(typeof(DBGuildMembers), tChar.ObjectId); if (tMember == null) { Chat.System(client, "No member found for " + tChar.Name); return(true); } tMember.OfficerNote = data.ReadString(); DataServer.Database.SaveObject(tMember); SendRoster(client, tguild); return(true); } //OnGuildRoster
static bool OnGuildCreate(LoginClient client, string input) { string[] split = input.Split(' '); if (split.Length < 2) { return(false); } string newName = split[1]; DataObject[] objt = DataServer.Database.SelectObjects(typeof(DBGuild), "Name = '" + newName + "'"); if (objt.Length != 0) { SendResult(client, 0, newName, (int)GUILDRESULT.NAME_EXISTS); return(true); } DBGuild newGuild = new DBGuild(); newGuild.Name = newName; newGuild.Leader = client.Character.ObjectId; newGuild.CreationDate = DateTime.Now; newGuild.MOTD = "Welcome to " + newName; DataServer.Database.AddNewObject(newGuild); DataServer.Database.SaveObject(newGuild); DataServer.Database.ReloadObject(newGuild); bool success = AddMember(client, newGuild, 0); SendResult(client, 0, newName, (int)GUILDRESULT.SUCCESS); return(true); } //OnGuildCreate
static bool OnGuildInvite(LoginClient client, CMSG msgID, BinReader data) { DBGuild guild = client.Character.Guild; if (guild == null || client.Character.GuildID == 0) { SendResult(client, 2, " ", (int)GUILDRESULT.NOT_IN_GUILD); return(true); } if ((guild.getRankFlags(client.Character.GuildRank) & (uint)GUILDFLAGS.INVITE) != (uint)GUILDFLAGS.INVITE) { SendResult(client, 1, " ", (int)GUILDRESULT.PERMISSIONS); ; return(true); } string name = data.ReadString(); DBCharacter character = (DBCharacter)DataServer.Database.FindObjectByKey(typeof(DBCharacter), name.ToLower()); if (character == null) { SendResult(client, 1, name, (int)GUILDRESULT.NOT_FOUND); } else { LoginClient targetClient = LoginServer.GetLoginClientByCharacterID(character.ObjectId); if (targetClient != null) { // targetClient.Character.LastGuildID=client.Character.GuildID; if (targetClient.Character.LastGuildInviterID != 0) { SendResult(client, 1, name, (int)GUILDRESULT.ALREADY_INVITED_TO_GUILD_S); return(true); } if (targetClient.Character.GuildID != 0) { SendResult(client, 1, targetClient.Character.Name, (int)GUILDRESULT.ALREADY_IN_GUILD_S); return(true); } targetClient.Character.LastGuildInviterID = client.Character.ObjectId; BinWriter gpkg = LoginClient.NewPacket(SMSG.GUILD_INVITE); gpkg.Write(client.Character.Name); gpkg.Write(guild.Name); targetClient.Send(gpkg); SendResult(client, 1, name, (int)GUILDRESULT.SUCCESS); } else { Chat.System(client, name + " is not currently online"); } } return(true); } //OnGuildInvite
static bool OnGuildDemote(LoginClient client, CMSG msgID, BinReader data) { DBGuild guild = client.Character.Guild; if (guild == null || client.Character.GuildID == 0) { SendResult(client, 2, " ", (int)GUILDRESULT.NOT_IN_GUILD); return(true); } if ((guild.getRankFlags(client.Character.GuildRank) & (uint)GUILDFLAGS.DEMOTE) != (uint)GUILDFLAGS.DEMOTE) { SendResult(client, 1, " ", (int)GUILDRESULT.PERMISSIONS); ; return(true); } string name = data.ReadString(); DBCharacter tChar = (DBCharacter)DataServer.Database.FindObjectByKey(typeof(DBCharacter), name.ToLower()); if (tChar == null) { SendResult(client, 1, name, (int)GUILDRESULT.NOT_FOUND); return(true); } else if (client.Character.GuildID != tChar.GuildID) { SendResult(client, 1, name, (int)GUILDRESULT.NOT_IN_GUILD_S); return(true); } // 2 1 if (tChar.GuildRank <= client.Character.GuildRank) { SendResult(client, 1, name, (int)GUILDRESULT.RANK_TO_HIGH); return(true); } else if (tChar.GuildRank >= guild.MaxRank) { SendResult(client, 1, name, (int)GUILDRESULT.RANK_TO_LOW); return(true); } DBGuildMembers tMember = (DBGuildMembers)DataServer.Database.FindObjectByKey(typeof(DBGuildMembers), tChar.ObjectId); if (tMember != null) { tChar.GuildRank++; } tMember.Rank++; SendToWorld(client, tChar); GuildMessage(guild, tChar.Name + "has been demoted to the rank of " + guild.getRankName(tChar.GuildRank) + " by " + client.Character.Name); SendRoster(client, guild); return(true); } //OnGuildDemote
static bool OnGuildRemove(LoginClient client, CMSG msgID, BinReader data) { DBGuild guild = client.Character.Guild; if (guild == null || client.Character.GuildID == 0) { SendResult(client, 2, " ", (int)GUILDRESULT.NOT_IN_GUILD); return(true); } if ((guild.getRankFlags(client.Character.GuildRank) & (uint)GUILDFLAGS.DEMOTE) != (uint)GUILDFLAGS.DEMOTE) { SendResult(client, 1, " ", (int)GUILDRESULT.PERMISSIONS); ; return(true); } string name = data.ReadString(); DBCharacter tChar = (DBCharacter)DataServer.Database.FindObjectByKey(typeof(DBCharacter), name.ToLower()); if (tChar == null) { SendResult(client, 1, name, (int)GUILDRESULT.NOT_FOUND); return(true); } else if (client.Character.GuildID != tChar.GuildID) { SendResult(client, 1, name, (int)GUILDRESULT.NOT_IN_GUILD_S); return(true); } // 2 1 if (tChar.GuildRank <= client.Character.GuildRank) { SendResult(client, 1, name, (int)GUILDRESULT.RANK_TO_HIGH); return(true); } DBGuildMembers member = (DBGuildMembers)DataServer.Database.FindObjectByKey(typeof(DBGuildMembers), tChar.ObjectId); if (member == null || member.GuildID != client.Character.GuildID) { SendResult(client, 1, name, (int)GUILDRESULT.NOT_IN_GUILD_S); return(true); } if (RemoveMember(member, client)) { Chat.System(client, "You have removed " + tChar.Name + " from the guild"); } else { SendResult(client, 1, name, (int)GUILDRESULT.INTERNAL); } return(true); } //OnGuildRemove
public static void PlayerLogin(LoginClient client, uint id) { if (client.Account == null) { client.Close("Tried to login with a character without an account."); return; } DataObject[] chars = DataServer.Database.SelectObjects(typeof(DBCharacter), "Character_ID = '" + id + "'"); if (chars.Length == 0) { client.Close("Failed to find character in database?"); return; } DBCharacter c = (DBCharacter)chars[0]; if (c.AccountID != client.Account.ObjectId) { client.Close("Tried to login another account's character."); return; } client.Character = c; if (client.Character.GuildID != 0) { DBGuild guild = (DBGuild)DataServer.Database.FindObjectByKey((typeof(DBGuild)), client.Character.GuildID); if (guild != null) { client.Character.Guild = guild; client.Character.GuildName = guild.Name; } else { client.Character.GuildID = 0; client.Character.GuildRank = 0; client.Character.GuildName = " "; } } string[] RemoteIP = client.RemoteEndPoint.ToString().Split(':'); client.Account.LastIP = RemoteIP[0]; if (c.WorldMapID == 0) { client.Close(c.Name + " is missing world map id."); return; } client.WorldConnection = (WorldConnection)m_worldMapServer[c.WorldMapID]; if (client.WorldConnection == null) { client.Close("Missing worldserver for world map id " + c.WorldMapID); return; } m_loginCharacters[id] = client; FriendIsOnline(client); client.OnEnterWorld(); // client.WorldConnection.OnEnterWorld(client.Character, client.Account.AccessLvl); }
static bool OnGuildRank(LoginClient client, CMSG msgID, BinReader data) { uint rank = data.ReadUInt32(); uint rankflags = data.ReadUInt32(); string rankname = data.ReadString(); DBGuild guild = client.Character.Guild; guild.setRankName(rank, rankname); guild.setRankFlags(rank, rankflags); DataServer.Database.SaveObject(guild); UpdateGuild(client); SendRoster(client, guild); return(true); } //OnGuildRank
public static Guild CreateGuild(eRealm realm, string guildName, GamePlayer creator = null) { if (DoesGuildExist(guildName)) { if (creator != null) { creator.Out.SendMessage(guildName + " already exists!", eChatType.CT_System, eChatLoc.CL_SystemWindow); } return(null); } try { DBGuild dbGuild = new DBGuild(); dbGuild.GuildName = guildName; dbGuild.GuildID = System.Guid.NewGuid().ToString(); dbGuild.Realm = (byte)realm; Guild newguild = new Guild(dbGuild); if (newguild.AddToDatabase() == false) { if (creator != null) { creator.Out.SendMessage("Database error, unable to add a new guild!", eChatType.CT_System, eChatLoc.CL_SystemWindow); } return(null); } AddGuild(newguild); CreateRanks(newguild); if (log.IsDebugEnabled) { log.Debug("Create guild; guild name=\"" + guildName + "\" Realm=" + GlobalConstants.RealmToName(newguild.Realm)); } return(newguild); } catch (Exception e) { if (log.IsErrorEnabled) { log.Error("CreateGuild", e); } return(null); } }
static bool OnGuildInfo(LoginClient client, CMSG msgID, BinReader data) { DBGuild tguild = client.Character.Guild; tguild.GuildInfo = data.ReadString(); DataServer.Database.SaveObject(tguild); BinWriter gpkg = LoginClient.NewPacket(SMSG.GUILD_INFO); gpkg.Write(tguild.ObjectId); gpkg.Write(tguild.GuildInfo); // gpkg.Write(rankname); client.Send(gpkg); return(true); } //OnGuildRoster
public static void GuildMessage(DBGuild guild, string msg) { foreach (DBGuildMembers member in guild.Members) { LoginClient targetClient = LoginServer.GetLoginClientByCharacterID(member.MemberID); if (targetClient == null || targetClient.Character == null) { continue; } else { Chat.GuildSay(0, targetClient, msg, CHATMESSAGETYPE.GUILD); } } }
public List <DBMessage> GetMessagesFromChannel(DBGuild dbGuild, IMessage m, string channelName) { List <DBMessage> messages = new List <DBMessage>(); foreach (var message in dbGuild.TextChannels.FirstOrDefault(x => x.Name == channelName).Messages) { messages.Add(message); } if (messages.Count == 0) { throw new Exception("No messages :/"); } return(messages); }
static bool OnGuildMOTD(LoginClient client, CMSG msgID, BinReader data) { DBGuild tguild = client.Character.Guild; if ((tguild.getRankFlags(client.Character.GuildRank) & (uint)GUILDFLAGS.SET_MOTD) != (uint)GUILDFLAGS.SET_MOTD) { SendResult(client, 1, " ", (int)GUILDRESULT.PERMISSIONS); ; return(true); } tguild.MOTD = data.ReadString(); DataServer.Database.SaveObject(tguild); SendRoster(client, tguild); GuildMessage(tguild, "MOTD: " + tguild.MOTD); return(true); } //OnGuildRoster
static bool OnTabClear(LoginClient client, string input) { DBGuild guild = client.Character.Guild; if (guild == null || client.Character.GuildRank != 0) { Chat.System(client, "You must be a guild leader to use this command"); } guild.Border = 0xFFFFFFFF; guild.BorderColor = 0xFFFFFFFF;; guild.Color = 0xFFFFFFFF;; guild.Icon = 0xFFFFFFFF;; guild.IconColor = 0xFFFFFFFF;; DataServer.Database.SaveObject(guild); return(true); } //OnTabClear
public List <DBMessage> GetAllMessages(DBGuild dbGuild, IMessage m) { List <DBMessage> allGuildMessages = new List <DBMessage>(); foreach (var channel in dbGuild.TextChannels) { allGuildMessages.AddRange(channel.Messages); } if (allGuildMessages.Count == 0) { throw new Exception("No messages :/"); } return(allGuildMessages); }
static bool OnGuildAddRank(LoginClient client, CMSG msgID, BinReader data) { DBGuild tguild = client.Character.Guild; if (tguild == null || client.Character.GuildID == 0) { SendResult(client, 2, " ", (int)GUILDRESULT.NOT_IN_GUILD); return(true); } tguild.MaxRank++; tguild.setRankName(tguild.MaxRank, data.ReadString()); DataServer.Database.SaveObject(tguild); UpdateGuild(client); SendRoster(client, tguild); return(true); } //OnGuildAddRank
static bool OnGuildAccept(LoginClient client, CMSG msgID, BinReader data) { LoginClient inviter = LoginServer.GetLoginClientByCharacterID(client.Character.LastGuildInviterID); client.Character.LastGuildInviterID = 0; if (inviter == null) { return(true); } DBGuild guild = (DBGuild)DataServer.Database.FindObjectByKey(typeof(DBGuild), inviter.Character.GuildID); AddMember(client, guild, guild.MaxRank); Chat.GuildSay(0, client, "You have joined " + guild.Name, CHATMESSAGETYPE.GUILD); //Chat.System(inviter, client.Character.Name+" joins "+guild.Name); GuildMessage(guild, client.Character.Name + " has been accepted to the guild by" + inviter.Character.Name); return(true); } //OnGuildAccept
public static async Task UserUpdated(SocketGuildUser beforeUser, SocketGuildUser afterUser) { if (beforeUser.Username != afterUser.Username || beforeUser.Nickname != afterUser.Nickname) { var guildDb = new DBGuild(afterUser.Guild.Id); if (guildDb.Users.Any(u => u.ID.Equals(afterUser.Id))) // if already exists { guildDb.Users.Find(u => u.ID.Equals(afterUser.Id)).AddUsername(beforeUser.Username); guildDb.Users.Find(u => u.ID.Equals(afterUser.Id)).AddNickname(beforeUser); guildDb.Users.Find(u => u.ID.Equals(afterUser.Id)).AddUsername(afterUser.Username); guildDb.Users.Find(u => u.ID.Equals(afterUser.Id)).AddNickname(afterUser); } else { guildDb.Users.Add(new DBUser(afterUser)); } guildDb.Save(); } }
public static void SendRoster(LoginClient client, DBGuild tGuild) { BinWriter pkg = LoginClient.NewPacket(SMSG.GUILD_ROSTER); pkg.Write((int)tGuild.Members.Length); pkg.Write((string)tGuild.MOTD); //Guild.MOTD); pkg.Write((uint)tGuild.MaxRank + 1); //# of ranks for (uint i = 0; i < tGuild.MaxRank + 1; i++) { pkg.Write((uint)tGuild.getRankFlags(i)); //Rank Flags for each rank } foreach (DBGuildMembers member in tGuild.Members) { DataServer.Database.FillObjectRelations(member); pkg.Write((ulong)member.MemberID); //((LoginClient)e.Current).Character.Race); bool online = false; if (LoginServer.GetLoginClientByCharacterID(member.MemberID) != null) { online = true; } pkg.Write((bool)online); //Online? 0-no/1-yes pkg.Write((string)member.Character.Name); //Name pkg.Write((int)member.Character.GuildRank); //Rank pkg.Write((byte)member.Character.Level); //Level pkg.Write((byte)member.Character.Class); //Class((LoginClient)e.Current).Character.Level); pkg.Write((uint)member.Character.Zone); //Zone if (online) { pkg.Write((byte)member.Character.GroupLook); // Group (0-No/1-Yes) Only if online } else { pkg.Write((uint)member.Character.GuildTimeStamp); // GuildTimeStamp } pkg.Write((string)(member.Note == null?" ":member.Note)); //Player Note pkg.Write((string)(member.Note == null?" ":member.OfficerNote)); //Officer's Note } client.Send(pkg); return; } //SendRoster
static bool OnGuildTabard(LoginClient client, CMSG msgID, BinReader data) { DBGuild tguild = client.Character.Guild; ulong vGUID = data.ReadUInt64(); tguild.Icon = data.ReadUInt32(); tguild.IconColor = data.ReadUInt32(); tguild.Border = data.ReadUInt32(); tguild.BorderColor = data.ReadUInt32(); tguild.Color = data.ReadUInt32(); DataServer.Database.SaveObject(tguild); SendToWorld(client, client.Character); DBItem newItem = new DBItem(); newItem.OwnerID = client.Character.ObjectId; newItem.OwnerSlot = 18; newItem.TemplateID = 343; DataServer.Database.AddNewObject(newItem); DataServer.Database.FillObjectRelations(newItem); client.WorldConnection.Send(newItem); ScriptPacket Item = new ScriptPacket(SCRMSG.BUYITEM); Item.Write(client.Character.ObjectId); Item.Write(newItem.ObjectId); Item.Write((int)100000); client.WorldConnection.Send(Item); BinWriter tpkg = LoginClient.NewPacket(SMSG.TABARDVENDOR_ACTIVATE); tpkg.Write(client.Character.Selected); client.Send(tpkg); string gmsg = "Congratulations on your purchase, You may now give them to your members using !givetabard <member>"; Chat.GuildSay(0, client, gmsg, CHATMESSAGETYPE.GUILD); return(true); } //OnGuildTabard
} //RemoveMember public static bool AddMember(LoginClient client, DBGuild newGuild, uint Rank) { client.Character.GuildID = newGuild.ObjectId; client.Character.GuildRank = Rank; client.Character.GuildName = newGuild.Name; client.Character.Guild = newGuild; DataServer.Database.SaveObject(client.Character); SendToWorld(client, client.Character); DBGuildMembers newMember = new DBGuildMembers(); newMember.GuildID = newGuild.ObjectId; newMember.MemberID = client.Character.ObjectId; newMember.Rank = (uint)Rank; DataServer.Database.AddNewObject(newMember); DataServer.Database.SaveObject(newMember); DataServer.Database.FillObjectRelations(newMember); DataServer.Database.FillObjectRelations(newGuild); return(true); } //AddMember
static bool OnGuildDisband(LoginClient client, CMSG msgID, BinReader data) { if (client.Character.GuildRank != 0) { SendResult(client, 2, " ", (int)GUILDRESULT.PERMISSIONS); return(true); } DBGuild tguild = client.Character.Guild; if (tguild == null || client.Character.GuildID == 0) { SendResult(client, 2, " ", (int)GUILDRESULT.NOT_IN_GUILD); return(true); } GuildMessage(tguild, "You guild has been disbanded by " + client.Character.Name); foreach (DBGuildMembers member in tguild.Members) { RemoveMember(member, client); } Chat.System(client, "You have disbanded " + tguild.Name); DataServer.Database.DeleteObject(tguild); return(true); } //OnGuildDisband
public static async Task UserJoined(SocketGuildUser user) { #region Database var guildDb = new DBGuild(user.Guild.Id); bool alreadyJoined = false; if (guildDb.Users.Any(u => u.ID.Equals(user.Id))) // if already exists { guildDb.Users.Find(u => u.ID.Equals(user.Id)).AddUsername(user.Username); alreadyJoined = true; } else { guildDb.Users.Add(new DBUser(user)); } guildDb.Save(); #endregion Databasae #region Logging var guildConfig = GenericBot.GuildConfigs[user.Guild.Id]; if (!(guildConfig.VerifiedRole == 0 || (string.IsNullOrEmpty(guildConfig.VerifiedMessage) || guildConfig.VerifiedMessage.Split().Length < 32 || !user.Guild.Roles.Any(r => r.Id == guildConfig.VerifiedRole)))) { string vMessage = $"Hey {user.Username}! To get verified on **{user.Guild.Name}** reply to this message with the hidden code in the message below\n\n" + GenericBot.GuildConfigs[user.Guild.Id].VerifiedMessage; string verificationMessage = VerificationEngine.InsertCodeInMessage(vMessage, VerificationEngine.GetVerificationCode(user.Id, user.Guild.Id)); try { await user.GetOrCreateDMChannelAsync().Result.SendMessageAsync(verificationMessage); } catch { await GenericBot.Logger.LogErrorMessage($"Could not send verification DM to {user} ({user.Id}) on {user.Guild} ({user.Guild.Id})"); } } if (guildConfig.ProbablyMutedUsers.Contains(user.Id)) { try { await user.AddRoleAsync(user.Guild.GetRole(guildConfig.MutedRoleId)); } catch { } } if (guildConfig.AutoRoleIds != null && guildConfig.AutoRoleIds.Any()) { foreach (var role in guildConfig.AutoRoleIds) { try { await user.AddRoleAsync(user.Guild.GetRole(role)); } catch { // Supress } } } if (guildConfig.UserLogChannelId == 0) { return; } EmbedBuilder log = new EmbedBuilder() .WithAuthor(new EmbedAuthorBuilder().WithName("User Joined") .WithIconUrl(user.GetAvatarUrl()).WithUrl(user.GetAvatarUrl())) .WithColor(114, 137, 218) .AddField(new EmbedFieldBuilder().WithName("Username").WithValue(user.ToString().Escape()).WithIsInline(true)) .AddField(new EmbedFieldBuilder().WithName("UserId").WithValue(user.Id).WithIsInline(true)) .AddField(new EmbedFieldBuilder().WithName("Mention").WithValue(user.Mention).WithIsInline(true)) .AddField(new EmbedFieldBuilder().WithName("User Number").WithValue(user.Guild.MemberCount + (!alreadyJoined ? " (New Member)" : "")).WithIsInline(true)) .AddField(new EmbedFieldBuilder().WithName("Database Number").WithValue(guildDb.Users.Count + (alreadyJoined ? " (Previous Member)" : "")).WithIsInline(true)) .WithFooter($"{DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT"); if ((DateTimeOffset.Now - user.CreatedAt).TotalDays < 7) { log.AddField(new EmbedFieldBuilder().WithName("New User") .WithValue($"Account made {(DateTimeOffset.Now - user.CreatedAt).Nice()} ago").WithIsInline(true)); } try { DBUser usr = guildDb.Users.First(u => u.ID.Equals(user.Id)); if (!usr.Warnings.Empty()) { string warns = ""; for (int i = 0; i < usr.Warnings.Count; i++) { warns += $"{i + 1}: {usr.Warnings.ElementAt(i)}\n"; } log.AddField(new EmbedFieldBuilder().WithName($"{usr.Warnings.Count} Warnings") .WithValue(warns)); } } catch { } await user.Guild.GetTextChannel(guildConfig.UserLogChannelId).SendMessageAsync("", embed: log.Build()); #endregion Logging #region Antispam if (guildConfig.AntispamLevel >= GuildConfig.AntiSpamLevel.Advanced) { var inviteLink = new Regex(@"(?:https?:\/\/)?(?:www\.)?(discord\.gg|discord\.io|discord\.me|discordapp\.com\/invite|paypal\.me|twitter\.com|youtube\.com|bit\.ly|twitch\.tv)\/(\S+)"); if (inviteLink.Matches(user.Username).Any()) { if (guildConfig.AntispamLevel == GuildConfig.AntiSpamLevel.Advanced) { await user.KickAsync("Username Contains Discord Spam Invite"); var builder = new EmbedBuilder() .WithTitle("User Kicked") .WithDescription("Discord Invite in Username (Antispam)") .WithColor(new Color(0xFFFF00)) .WithFooter(footer => { footer .WithText($"By {GenericBot.DiscordClient.CurrentUser} at {DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT"); }) .WithAuthor(author => { author .WithName(user.ToString()) .WithIconUrl(user.GetAvatarUrl()); }); var guilddb = new DBGuild(user.Guild.Id); var guildconfig = GenericBot.GuildConfigs[user.Guild.Id]; guilddb.GetUser(user.Id) .AddWarning( $"Kicked for `Username Contains Discord Spam Invite` (By `{GenericBot.DiscordClient.CurrentUser}` At `{DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT`)"); guilddb.Save(); if (guildconfig.UserLogChannelId != 0) { await(GenericBot.DiscordClient.GetChannel(guildconfig.UserLogChannelId) as SocketTextChannel) .SendMessageAsync("", embed: builder.Build()); } } else if (guildConfig.AntispamLevel >= GuildConfig.AntiSpamLevel.Aggressive) { await user.BanAsync(0, "Username Contains Discord Spam Invite"); var builder = new EmbedBuilder() .WithTitle("User Banned") .WithDescription("Discord Invite in Username (Antispam)") .WithColor(new Color(0xFFFF00)) .WithFooter(footer => { footer .WithText($"By {GenericBot.DiscordClient.CurrentUser} at {DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT"); }) .WithAuthor(author => { author .WithName(user.ToString()) .WithIconUrl(user.GetAvatarUrl()); }); var guilddb = new DBGuild(user.Guild.Id); var guildconfig = GenericBot.GuildConfigs[user.Guild.Id]; guilddb.GetUser(user.Id) .AddWarning( $"Banned for `Username Contains Discord Spam Invite` (By `{GenericBot.DiscordClient.CurrentUser}` At `{DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT`)"); guilddb.Save(); if (guildconfig.UserLogChannelId != 0) { await(GenericBot.DiscordClient.GetChannel(guildconfig.UserLogChannelId) as SocketTextChannel) .SendMessageAsync("", embed: builder.Build()); } } } } #endregion Antispam }
public List <Command> GetPointsCommands() { var pointCommands = new List <Command>(); Command points = new Command("points"); points.Description = "Show the number of points the user has"; points.ToExecute += async(client, msg, parameters) => { if (!GenericBot.GuildConfigs[msg.GetGuild().Id].PointsEnabled) { return; } var user = new DBGuild(msg.GetGuild().Id).GetUser(msg.Author.Id); await msg.ReplyAsync($"{msg.Author.Mention}, you have `{Math.Floor(user.PointsCount)}` {GenericBot.GuildConfigs[msg.GetGuild().Id].PointsName}s!"); }; pointCommands.Add(points); Command leaderboard = new Command(nameof(leaderboard)); leaderboard.ToExecute += async(client, msg, parameters) => { var db = new DBGuild(msg.GetGuild().Id); var topUsers = db.Users.OrderByDescending(u => u.PointsCount).Take(10); string result = $"Top 10 users in {msg.GetGuild().Name}\n"; int i = 1; var config = GenericBot.GuildConfigs[msg.GetGuild().Id]; foreach (var user in topUsers) { if (msg.GetGuild().Users.HasElement(u => u.Id == user.ID, out SocketGuildUser sgu)) { result += $"{i++}: {sgu.GetDisplayName().Escape()}: `{Math.Floor(user.PointsCount)}` {config.PointsName}s\n"; } else { result += $"{i++}: Unknown User (ID: `{user.ID}`): `{Math.Floor(user.PointsCount)}` {config.PointsName}s\n"; } } await msg.ReplyAsync(result); }; pointCommands.Add(leaderboard); Command award = new Command("award"); award.Description = "Give a user one of your points"; award.ToExecute += async(client, msg, parameters) => { var config = GenericBot.GuildConfigs[msg.GetGuild().Id]; if (!config.PointsEnabled) { return; } var dbGuild = new DBGuild(msg.GetGuild().Id); var user = dbGuild.GetUser(msg.Author.Id); if (user.PointsCount < 1) { await msg.ReplyAsync($"You don't have any {config.PointsName} to give!"); } else { if (msg.MentionedUsers.Any()) { if (msg.MentionedUsers.Count > user.PointsCount) { await msg.ReplyAsync($"You don't have that many {GenericBot.GuildConfigs[msg.GetGuild().Id].PointsName}s to give!"); } else { foreach (var u in msg.MentionedUsers) { if (u.Id == msg.Author.Id) { continue; } user.PointsCount--; dbGuild.GetUser(u.Id).PointsCount++; } dbGuild.Save(); await msg.ReplyAsync($"{msg.MentionedUsers.Select(us => us.Mention).ToList().SumAnd()} received a {GenericBot.GuildConfigs[msg.GetGuild().Id].PointsName} from {msg.Author.Mention}!"); } } else { await msg.ReplyAsync($"You have to select a user to give a {config.PointsName} to"); } } }; pointCommands.Add(award); Command setPoints = new Command("setpoints"); setPoints.RequiredPermission = Command.PermissionLevels.GlobalAdmin; setPoints.ToExecute += async(client, msg, parameters) => { var dbGuild = new DBGuild(msg.GetGuild().Id); var user = dbGuild.GetUser(ulong.Parse(parameters[0])); user.PointsCount = decimal.Parse(parameters[1]); dbGuild.Save(); await msg.ReplyAsync($"`{parameters[0]}` now has {(user.PointsCount)} points"); }; pointCommands.Add(setPoints); return(pointCommands); }
static bool OnMessageChat(LoginClient client, CMSG msgID, BinReader data) { CHATMESSAGETYPE type = (CHATMESSAGETYPE)data.ReadInt32(); /*int language =*/ data.ReadInt32(); string target = string.Empty; if (type == CHATMESSAGETYPE.WHISPER) { target = data.ReadString(0x100); } string msg = data.ReadString(0x100); if (msg.StartsWith("!") || msg.StartsWith("%")) { return(OnChatCommand(client, msg.Substring(1))); } switch (type) { case CHATMESSAGETYPE.PARTY: case CHATMESSAGETYPE.CHANNEL: case CHATMESSAGETYPE.CHANNEL_JOIN: case CHATMESSAGETYPE.CHANNEL_LEAVE: case CHATMESSAGETYPE.CHANNEL_LIST: case CHATMESSAGETYPE.CHANNEL_NOTICE: case CHATMESSAGETYPE.CHANNEL_NOTICE_USER: case CHATMESSAGETYPE.SAY: case CHATMESSAGETYPE.YELL: case CHATMESSAGETYPE.EMOTE: return(false); // let worldserver handle it case CHATMESSAGETYPE.WHISPER: { DataObject[] objs = DataServer.Database.SelectObjects(typeof(DBCharacter), "Name = '" + target + "'"); if (objs.Length == 0) { Chat.System(client, "No such player."); return(true); } LoginClient targetClient = LoginServer.GetLoginClientByCharacterID(objs[0].ObjectId); if (targetClient == null || targetClient.Character == null) { Chat.System(client, "That player is not online."); return(true); } Chat.Whisper(client, targetClient, msg); break; } case CHATMESSAGETYPE.GUILD: { DBGuild guild = client.Character.Guild; if (guild == null) { return(true); } if ((guild.getRankFlags(client.Character.GuildRank) & (uint)GUILDFLAGS.SAY) == (uint)GUILDFLAGS.SAY) { foreach (DBGuildMembers member in guild.Members) { if ((guild.getRankFlags(member.Rank) & (uint)GUILDFLAGS.LISTEN) == (uint)GUILDFLAGS.LISTEN) { LoginClient targetClient = LoginServer.GetLoginClientByCharacterID(member.MemberID); if (targetClient == null || targetClient.Character == null) { continue; } else { Chat.GuildSay(client.Character.ObjectId, targetClient, msg, CHATMESSAGETYPE.GUILD); } } } } else { Chat.GuildSay(0, client, "You do not have permission", CHATMESSAGETYPE.GUILD); } break; } case CHATMESSAGETYPE.OFFICER: { DBGuild guild = client.Character.Guild; if (guild == null) { return(true); } if ((guild.getRankFlags(client.Character.GuildRank) & (uint)GUILDFLAGS.OFFICER_SAY) == (uint)GUILDFLAGS.OFFICER_SAY) { foreach (DBGuildMembers member in guild.Members) { if ((guild.getRankFlags(member.Rank) & (uint)GUILDFLAGS.OFFICER_LISTEN) == (uint)GUILDFLAGS.OFFICER_LISTEN) { LoginClient targetClient = LoginServer.GetLoginClientByCharacterID(member.MemberID); if (targetClient == null || targetClient.Character == null) { continue; } else { Chat.GuildSay(client.Character.ObjectId, targetClient, msg, CHATMESSAGETYPE.OFFICER); } } } } else { Chat.GuildSay(0, client, "You do not have permission", CHATMESSAGETYPE.GUILD); } break; } default: Chat.System(client, "Received " + type + ": " + msg); break; } return(true); }
public List <Command> GetTestCommands() { List <Command> TestCommands = new List <Command>(); Command listEmotes = new Command("listemotes"); listEmotes.RequiredPermission = Command.PermissionLevels.Admin; listEmotes.Delete = true; listEmotes.ToExecute += async(client, msg, parameters) => { if (!msg.GetGuild().Emotes.Any()) { await msg.ReplyAsync($"`{msg.GetGuild().Name}` has no emotes"); return; } string emotes = $"`{msg.GetGuild().Name}` has `{msg.GetGuild().Emotes.Count}` emotes:"; int i = 0; foreach (var emote in msg.GetGuild().Emotes) { if (i % 3 == 0) { emotes += "\n"; } if (emote.Url.Contains("gif")) { emotes += $"<a:{emote.Name}:{emote.Id}> `:{emote.Name}:`"; } else { emotes += $"<:{emote.Name}:{emote.Id}> `:{emote.Name}:`"; } for (int c = emote.Name.Length + 2; c < 16; c++) { emotes += " "; } i++; } await msg.ReplyAsync(emotes); }; TestCommands.Add(listEmotes); Command updateDB = new Command("updateDB"); updateDB.Delete = false; updateDB.RequiredPermission = Command.PermissionLevels.GlobalAdmin; updateDB.ToExecute += async(client, msg, paramList) => { await msg.GetGuild().DownloadUsersAsync(); int newUsers = 0; int updatedUsers = 0; var db = new DBGuild(msg.GetGuild().Id); foreach (var user in msg.GetGuild().Users) { if (!db.Users.Any(u => u.ID.Equals(user.Id))) { db.Users.Add(new DBUser(user)); newUsers++; } else { db.GetUser(user.Id).AddUsername(user.Username); db.GetUser(user.Id).AddNickname(user); updatedUsers++; } } db.Save(); await msg.ReplyAsync($"`{newUsers}` users added to database, `{updatedUsers}` updated"); }; TestCommands.Add(updateDB); Command IdInfo = new Command("idInfo"); IdInfo.Aliases = new List <string> { "id" }; IdInfo.Description = "Get information from a given ID"; IdInfo.ToExecute += async(client, msg, parameters) => { if (parameters.Empty()) { await msg.ReplyAsync("No ID given"); return; } ulong id; if (ulong.TryParse(parameters[0], out id)) { ulong rawtime = id >> 22; long epochtime = (long)rawtime + 1420070400000; DateTimeOffset time = DateTimeOffset.FromUnixTimeMilliseconds(epochtime); await msg.ReplyAsync($"ID: `{id}`\nDateTime: `{time.ToString(@"yyyy-MM-dd HH:mm:ss.fff tt")} GMT`"); } else { await msg.ReplyAsync("That's not a valid ID"); } }; TestCommands.Add(IdInfo); Command DBStats = new Command("dbstats"); DBStats.RequiredPermission = Command.PermissionLevels.GlobalAdmin; DBStats.ToExecute += async(client, msg, parameters) => { Stopwatch stw = new Stopwatch(); stw.Start(); string info = ""; var guildDb = new DBGuild(msg.GetGuild().Id); info += $"Registered Users: `{guildDb.Users.Count}`\n"; int unc = 0, nnc = 0, wnc = 0, nuc = 0; foreach (var user in guildDb.Users) { if (user.Usernames != null && user.Usernames.Any()) { unc += user.Usernames.Count; } if (user.Nicknames != null && user.Nicknames.Any()) { nnc += user.Nicknames.Count; } if (user.Warnings != null && user.Warnings.Any()) { wnc += user.Warnings.Count; nuc++; } } info += $"Stored Usernames: `{unc}`\n"; info += $"Stored Nicknames: `{nnc}`\n"; info += $"Stored Warnings: `{wnc}`\n"; info += $"Users with Warnings: `{nuc}`\n"; info += $"Access time: `{stw.ElapsedMilliseconds}`ms\n"; await msg.ReplyAsync(info); }; TestCommands.Add(DBStats); Command addwarning = new Command("oldwarning"); addwarning.Description += "Add a warning to the database without meta info"; addwarning.Usage = "oldwarning <user> <warning>"; addwarning.RequiredPermission = Command.PermissionLevels.Admin; ulong uid; addwarning.ToExecute += async(client, msg, parameters) => { if (parameters.Empty()) { await msg.ReplyAsync("You must specify a user"); return; } if (ulong.TryParse(parameters[0].TrimStart('<', '@', '!').TrimEnd('>'), out uid)) { parameters.RemoveAt(0); string warning = parameters.reJoin(); var guildDb = new DBGuild(msg.GetGuild().Id); if (guildDb.Users.Any(u => u.ID.Equals(uid))) // if already exists { guildDb.Users.Find(u => u.ID.Equals(uid)).AddWarning(warning); } else { guildDb.Users.Add(new DBUser { ID = uid, Warnings = new List <string> { warning } }); } guildDb.Save(); await msg.ReplyAsync($"Added `{warning.Replace('`', '\'')}` to <@{uid}> (`{uid}`)"); } else { await msg.ReplyAsync("Could not find that user"); } }; TestCommands.Add(addwarning); Command archivePins = new Command("archivePins"); archivePins.RequiredPermission = Command.PermissionLevels.GlobalAdmin; archivePins.ToExecute += async(client, msg, parameters) => { var msgs = msg.Channel.GetPinnedMessagesAsync().Result.ToList(); if (msgs.Any()) { msgs.Reverse(); string header = "<html><head><style>body {background-color: #36393e; color: #fff; font-family: \"Trebuchet MS\", Helvetica, sans-serif; font-size: small }server {font-size: 150%}channel {font-size: 130%}username {font-size: 100%}message {font-size: 80%}reqinf {font-size: 60%; color: grey;}</style></head>"; string server = $"<body> <i><server>{msg.GetGuild().Name}</server> in <channel>#{msg.Channel.Name}</channel></i><hr>"; string messages = ""; foreach (var m in msgs) { string mess = m.Content; foreach (var u in m.MentionedUsers) { mess = mess.Replace($"<@!{u.Id}>", $"@{u.Username}"); mess = mess.Replace($"<@{u.Id}>", $"@{u.Username}"); mess = mess.Replace(u.Mention, $"@{u.Username}"); } foreach (var c in m.MentionedChannelIds) { mess = mess.Replace($"<#{c}>", $"#{(client.GetChannel(c) as IMessageChannel).Name}"); } foreach (var u in m.MentionedRoleIds) { mess = mess.Replace($"<@&u>", $"@{msg.GetGuild().GetRole(u).Name}"); } messages += $"<username>{m.Author}</username><br><message>{mess}</message><hr>"; } string footer = $"<br><br> <i><reqinf>Requested by <b>{msg.Author}</b></reqinf></i></body></html>"; File.WriteAllText($"files/{msg.Channel.Name}_pins.html", header + server + messages + footer, Encoding.UTF8); await msg.Channel.SendFileAsync($"files/{msg.Channel.Name}_pins.html"); File.Delete($"files/{msg.Channel.Name}_pins.html"); } else { await msg.ReplyAsync($"This channel has no pinned messages!"); } }; TestCommands.Add(archivePins); TestCommands.Add(DBStats); Command verify = new Command("verify"); verify.RequiredPermission = Command.PermissionLevels.User; verify.ToExecute += async(client, msg, parameter) => { List <SocketUser> users = new List <SocketUser>(); var guildConfig = GenericBot.GuildConfigs[msg.GetGuild().Id]; if (parameter.Empty()) { if ((msg.Author as SocketGuildUser).Roles.Any(r => r.Id == guildConfig.VerifiedRole)) { await msg.ReplyAsync("You're already verified"); return; } users.Add(msg.Author); } else { foreach (var user in msg.GetMentionedUsers()) { if ((user as SocketGuildUser).Roles.Any(r => r.Id == guildConfig.VerifiedRole)) { await msg.ReplyAsync($"{user.Username} is already verified"); } else { users.Add(user); } } } if (guildConfig.VerifiedRole == 0) { await msg.ReplyAsync($"Verification is disabled on this server"); return; } if ((string.IsNullOrEmpty(guildConfig.VerifiedMessage) || guildConfig.VerifiedMessage.Split().Length < 32 || !msg.GetGuild().Roles.Any(r => r.Id == guildConfig.VerifiedRole))) { await msg.ReplyAsync( $"It looks like verifiction is configured improperly (either the message is too short or the role does not exist.) Please contact your server administrator to resolve it."); return; } List <SocketUser> failed = new List <SocketUser>(); List <SocketUser> success = new List <SocketUser>(); foreach (var user in users) { string message = $"Hey {user.Username}! To get verified on **{msg.GetGuild().Name}** reply to this message with the hidden code in the message below\n\n" + GenericBot.GuildConfigs[msg.GetGuild().Id].VerifiedMessage; string verificationMessage = VerificationEngine.InsertCodeInMessage(message, VerificationEngine.GetVerificationCode(user.Id, msg.GetGuild().Id)); try { await user.GetOrCreateDMChannelAsync().Result.SendMessageAsync(verificationMessage); success.Add(user); } catch { failed.Add(user); } } string reply = ""; if (success.Any()) { reply += $"I've sent {success.Select(u => u.Username).ToList().SumAnd()} instructions!"; } if (failed.Any()) { reply += $" {failed.Select(u => u.Username).ToList().SumAnd()} could not be messaged."; } await msg.ReplyAsync(reply); }; TestCommands.Add(verify); Command cmdp = new Command("cmd"); cmdp.RequiredPermission = Command.PermissionLevels.GlobalAdmin; cmdp.ToExecute += async(client, msg, parameters) => { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Process cmd = new Process(); cmd.StartInfo.FileName = "cmd.exe"; cmd.StartInfo.RedirectStandardInput = true; cmd.StartInfo.RedirectStandardOutput = true; cmd.StartInfo.CreateNoWindow = true; cmd.StartInfo.UseShellExecute = false; cmd.Start(); cmd.StandardInput.WriteLine(parameters.reJoin()); cmd.StandardInput.Flush(); cmd.StandardInput.Close(); cmd.WaitForExit(); foreach (var str in cmd.StandardOutput.ReadToEnd().SplitSafe('\n')) { await msg.ReplyAsync($"```\n{str}\n```"); } } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { Process proc = new System.Diagnostics.Process(); proc.StartInfo.FileName = "/bin/bash"; proc.StartInfo.Arguments = "-c \"" + parameters.reJoin() + " > results\""; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.CreateNoWindow = true; proc.StartInfo.UseShellExecute = false; proc.Start(); proc.WaitForExit(); Console.WriteLine(proc.StandardOutput.ReadToEnd()); foreach (string str in File.ReadAllText("results").SplitSafe('\n')) { await msg.ReplyAsync($"```\n{str}\n```"); } } else { await msg.ReplyAsync("Unrecognized platform"); } }; TestCommands.Add(cmdp); Command decryptDb = new Command("decryptDb"); decryptDb.RequiredPermission = Command.PermissionLevels.GlobalAdmin; decryptDb.ToExecute += async(client, msg, parameters) => { File.WriteAllText($"files/guildDbs/{parameters[0]}_raw.json", AES.DecryptText(File.ReadAllText($"files/guildDbs/{parameters[0]}.json"), GenericBot.GlobalConfiguration.DatabasePassword)); var res = msg.Channel.SendFileAsync($"files/guildDbs/{parameters[0]}_raw.json", "Self-destructing in 15 seconds!").Result; await Task.Delay(TimeSpan.FromSeconds(15)); try { await res.DeleteAsync(); } catch { } }; TestCommands.Add(decryptDb); Command repairDb = new Command("repairDb"); repairDb.RequiredPermission = Command.PermissionLevels.GlobalAdmin; repairDb.ToExecute += async(client, msg, paramList) => { lock (msg.GetGuild().Id.ToString()) { var db = new DBGuild(msg.GetGuild().Id); foreach (var user in db.Users) { if (!user.Nicknames.Empty()) { user.Nicknames = user.Nicknames.Where(n => !string.IsNullOrEmpty(n)).ToList(); } if (!user.Usernames.Empty()) { user.Usernames = user.Usernames.Where(n => !string.IsNullOrEmpty(n)).ToList(); } } db.Save(); } await msg.ReplyAsync($"Done!"); }; TestCommands.Add(repairDb); return(TestCommands); }
public void Update() { if (log.IsInfoEnabled) { log.Info("Start Searching for records that need update..."); } // Change the Leader Relation if Missing var alliances = GameServer.Database.SelectObjects <DBAlliance>("LeaderGuildID = @LeaderGuildID OR LeaderGuildID IS NULL", new QueryParameter("@LeaderGuildID", string.Empty)); if (alliances.Any()) { var leadingGuilds = GameServer.Database.SelectObjects <DBGuild>( "AllianceID = @AllianceID AND GuildName = @GuildName", alliances.Select(al => new [] { new QueryParameter("@AllianceID", al.ObjectId), new QueryParameter("@GuildName", al.AllianceName) })); var alliancesWithLeader = leadingGuilds.Select((gd, i) => { var al = alliances[i]; DBGuild lead = null; try { lead = gd.SingleOrDefault(gld => al.AllianceName.Equals(gld.GuildName)); } catch (Exception e) { if (log.IsErrorEnabled) { log.ErrorFormat("Wrong records while trying to retrieve Guild Leader (AllianceID: {0}, AllianceName: {1})\n{2}", al.ObjectId, al.AllianceName, e); } } return(new { Alliance = al, Leader = lead }); }).ToArray(); if (log.IsInfoEnabled) { log.InfoFormat("Fixing Alliances without Leader : {0} records found.", alliancesWithLeader.Length); } foreach (var pair in alliancesWithLeader) { if (pair.Leader != null) { pair.Alliance.LeaderGuildID = pair.Leader.GuildID; } else if (log.IsWarnEnabled) { log.WarnFormat("Alliance (ID:{0}, Name:{1}) can't resolve its Leading Guild !", pair.Alliance.ObjectId, pair.Alliance.AllianceName); } } var saved = GameServer.Database.SaveObject(alliancesWithLeader.Select(pair => pair.Alliance)); if (saved && log.IsInfoEnabled) { log.InfoFormat("Finished saving Alliances without Leader successfully!"); } if (!saved && log.IsErrorEnabled) { log.ErrorFormat("Could not save all Alliances without Leader, check logs or records..."); } } if (log.IsInfoEnabled) { log.Info("End of Database Update..."); } }
public List <Command> GetConfigComamnds() { List <Command> ConfigCommands = new List <Command>(); Command config = new Command("config"); config.Usage = "config <option> <value>`\nOptions are: `adminroles`, `moderatorroles`, `userroles`, `twitter`, `user`, `mutedroleid"; config.Description = "Configure the bot's option"; config.RequiredPermission = Command.PermissionLevels.Admin; config.ToExecute += async(client, msg, paramList) => { if (paramList.Empty()) { await msg.Channel.SendMessageAsync($"Please enter a value to configure."); return; } #region AdminRoles if (paramList[0].ToLower().Equals("adminroles")) { if (config.GetPermissions(msg.Author, msg.GetGuild().Id) >= Command.PermissionLevels.GuildOwner) { if (paramList.Count == 1) { await msg.ReplyAsync($"Please enter a config option"); return; } if (paramList.Count == 2) { await msg.ReplyAsync($"Please enter a roleId"); return; } ulong id; if (ulong.TryParse(paramList[2], out id) && msg.GetGuild().Roles.Select(r => r.Id).Any(u => u.Equals(id))) { if (paramList[1].ToLower().Equals("add")) { if (!GenericBot.GuildConfigs[msg.GetGuild().Id].AdminRoleIds.Contains(id)) { GenericBot.GuildConfigs[msg.GetGuild().Id].AdminRoleIds.Add(id); await msg.ReplyAsync($"Added {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name} to Admin Roles"); } else { await msg.ReplyAsync($"Admin Roles already contains {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name}"); } } else if (paramList[1].ToLower().Equals("remove")) { if (GenericBot.GuildConfigs[msg.GetGuild().Id].AdminRoleIds.Contains(id)) { GenericBot.GuildConfigs[msg.GetGuild().Id].AdminRoleIds.Remove(id); await msg.ReplyAsync($"Removed {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name} from Admin Roles"); } else { await msg.ReplyAsync( $"Admin Roles doesn't contain {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name}"); } } else { await msg.ReplyAsync($"Unknown property `{paramList[1]}`."); } } else { await msg.ReplyAsync($"That is not a valid roleId"); } } else { await msg.ReplyAsync($"You don't have the permissions to do that"); } } #endregion AdminRoles #region ModRoles else if (paramList[0].ToLower().Equals("moderatorroles") || paramList[0].ToLower().Equals("modroles")) { if (config.GetPermissions(msg.Author, msg.GetGuild().Id) >= Command.PermissionLevels.Admin) { if (paramList.Count == 1) { await msg.ReplyAsync($"Please enter a config option"); return; } if (paramList.Count == 2) { await msg.ReplyAsync($"Please enter a roleId"); return; } ulong id; if (ulong.TryParse(paramList[2], out id) && msg.GetGuild().Roles.Select(r => r.Id).Any(u => u.Equals(id))) { if (paramList[1].ToLower().Equals("add")) { if (!GenericBot.GuildConfigs[msg.GetGuild().Id].ModRoleIds.Contains(id)) { GenericBot.GuildConfigs[msg.GetGuild().Id].ModRoleIds.Add(id); await msg.ReplyAsync($"Added {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name} to Moderator Roles"); } else { await msg.ReplyAsync($"Moderator Roles already contains {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name}"); } } else if (paramList[1].ToLower().Equals("remove")) { if (GenericBot.GuildConfigs[msg.GetGuild().Id].ModRoleIds.Contains(id)) { { GenericBot.GuildConfigs[msg.GetGuild().Id].ModRoleIds.Remove(id); await msg.ReplyAsync( $"Removed {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name} from Moderator Roles"); } } else { await msg.ReplyAsync( $"Moderator Roles doesn't contain {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name}"); } } else { await msg.ReplyAsync($"Unknown property `{paramList[1]}`."); } } else { await msg.ReplyAsync($"That is not a valid roleId"); } } else { await msg.ReplyAsync($"You don't have the permissions to do that"); } } #endregion ModRoles #region UserRoles else if (paramList[0].ToLower().Equals("userroles")) { if (config.GetPermissions(msg.Author, msg.GetGuild().Id) >= Command.PermissionLevels.Admin) { if (paramList.Count == 1) { await msg.ReplyAsync($"Please enter a config option"); return; } if (paramList.Count == 2) { await msg.ReplyAsync($"Please enter a roleId"); return; } ulong id; if (ulong.TryParse(paramList[2], out id) && msg.GetGuild().Roles.Select(r => r.Id).Any(u => u.Equals(id))) { if (paramList[1].ToLower().Equals("add")) { if (!GenericBot.GuildConfigs[msg.GetGuild().Id].UserRoleIds.Contains(id)) { GenericBot.GuildConfigs[msg.GetGuild().Id].UserRoleIds.Add(id); await msg.ReplyAsync($"Added {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name} to User Roles"); } else { await msg.ReplyAsync($"User Roles already contains {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name}"); } } else if (paramList[1].ToLower().Equals("remove")) { if (GenericBot.GuildConfigs[msg.GetGuild().Id].UserRoleIds.Contains(id)) { { GenericBot.GuildConfigs[msg.GetGuild().Id].UserRoleIds.Remove(id); await msg.ReplyAsync( $"Removed {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name} from User Roles"); } } else { await msg.ReplyAsync($"User Roles doesn't contain {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name}"); } } else { await msg.ReplyAsync($"Unknown property `{paramList[1]}`."); } } else { await msg.ReplyAsync($"That is not a valid roleId"); } } else { await msg.ReplyAsync($"You don't have the permissions to do that"); } } #endregion UserRoles #region Twitter else if (paramList[0].ToLower().Equals("twitter")) { if (paramList[1].ToLower() == "true") { GenericBot.GuildConfigs[msg.GetGuild().Id].AllowTwitter = true; await msg.ReplyAsync("Tweeting on this server has been enabled"); } else if (paramList[1].ToLower() == "false") { GenericBot.GuildConfigs[msg.GetGuild().Id].AllowTwitter = false; await msg.ReplyAsync("Tweeting on this server has been disabled"); } else { await msg.ReplyAsync("That's not a valid option"); } } #endregion Twitter #region Prefix else if (paramList[0].ToLower().Equals("prefix")) { try { paramList.RemoveAt(0); GenericBot.GuildConfigs[msg.GetGuild().Id].Prefix = paramList.reJoin(); if (msg.Content.EndsWith('"') && paramList[0].ToCharArray()[0].Equals('"')) { GenericBot.GuildConfigs[msg.GetGuild().Id].Prefix = new Regex("\"(.*?)\"").Match(msg.Content).Value.Trim('"'); } await msg.ReplyAsync($"The prefix has been set to `{GenericBot.GuildConfigs[msg.GetGuild().Id].Prefix}`"); } catch (Exception Ex) { GenericBot.GuildConfigs[msg.GetGuild().Id].Prefix = ""; await msg.ReplyAsync($"The prefix has been reset to the default of `{GenericBot.GlobalConfiguration.DefaultPrefix}`"); } } #endregion Prefix #region Logging else if (paramList[0].ToLower().Equals("logging")) { if (paramList[1].ToLower().Equals("channelid")) { if (paramList.Count() == 2) { await msg.ReplyAsync( $"Current user event channel: <#{GenericBot.GuildConfigs[msg.GetGuild().Id].UserLogChannelId}>"); } else { ulong cId; if (ulong.TryParse(paramList[2], out cId) && (msg.GetGuild().Channels.Any(c => c.Id == cId) || cId == 0)) { GenericBot.GuildConfigs[msg.GetGuild().Id].UserLogChannelId = cId; await msg.ReplyAsync( $"User event channel set to <#{GenericBot.GuildConfigs[msg.GetGuild().Id].UserLogChannelId}>"); } else { await msg.ReplyAsync("Invalid Channel Id"); } } } else if (paramList[1].ToLower().Equals("ignorechannel")) { if (paramList.Count == 2) { string m = "Ignored channels:"; foreach (var id in GenericBot.GuildConfigs[msg.GetGuild().Id].MessageLoggingIgnoreChannels) { m += $"\n<#{id}>"; } await msg.ReplyAsync(m); } else { if (ulong.TryParse(paramList[2], out ulong cId) && msg.GetGuild().TextChannels.Any(c => c.Id == cId)) { if (!GenericBot.GuildConfigs[msg.GetGuild().Id].MessageLoggingIgnoreChannels.Contains(cId)) { GenericBot.GuildConfigs[msg.GetGuild().Id].MessageLoggingIgnoreChannels.Add(cId); await msg.ReplyAsync($"No longer logging <#{cId}>"); } else { GenericBot.GuildConfigs[msg.GetGuild().Id].MessageLoggingIgnoreChannels.Remove(cId); await msg.ReplyAsync($"Resuming logging <#{cId}>"); } } else { await msg.ReplyAsync("Invalid Channel Id"); } } } } #endregion Logging #region MutedRoleId else if (paramList[0].ToLower().Equals("mutedroleid")) { paramList.RemoveAt(0); if (paramList.Count != 1) { await msg.ReplyAsync( "Incorrect number of arguments. Make sure the command is `voicerole [VoiceChannelId] [RoleId]`"); return; } else { ulong roleId; if (ulong.TryParse(paramList[0], out roleId) && (msg.GetGuild().Roles.Any(r => r.Id == roleId) || roleId == 0)) { GenericBot.GuildConfigs[msg.GetGuild().Id].MutedRoleId = roleId; GenericBot.GuildConfigs[msg.GetGuild().Id].Save(); await msg.ReplyAsync($"MutedRoleId is now `{roleId}`"); } else { await msg.ReplyAsync("Invalid Role Id"); } } } #endregion MutedRoleId #region Verification else if (paramList[0].ToLower().Equals("verification")) { if (paramList[1].ToLower().Equals("roleid")) { if (paramList.Count == 2) { var roleId = GenericBot.GuildConfigs[msg.GetGuild().Id].VerifiedRole; if (roleId == 0) { await msg.ReplyAsync("Verification is disabled on this server"); } else { await msg.ReplyAsync( $"Verification role is `{msg.GetGuild().Roles.First(g => g.Id == roleId).Name}`"); } } else if (ulong.TryParse(paramList[2], out ulong roleId) && (msg.GetGuild().Roles.Any(g => g.Id == roleId) || roleId == 0)) { GenericBot.GuildConfigs[msg.GetGuild().Id].VerifiedRole = roleId; if (roleId != 0) { await msg.ReplyAsync( $"Verification role set to `{msg.GetGuild().Roles.First(g => g.Id == roleId).Name}`"); } else { await msg.ReplyAsync("Verification role cleared. Verification is off for this server."); } } else { await msg.ReplyAsync("Invalid RoleId"); } } else if (paramList[1].ToLower().Equals("message")) { string pref = GenericBot.GlobalConfiguration.DefaultPrefix; if (!String.IsNullOrEmpty(GenericBot.GuildConfigs[msg.GetGuild().Id].Prefix)) { pref = GenericBot.GuildConfigs[msg.GetGuild().Id].Prefix; } string message = msg.Content; message = message.Remove(0, pref.Length).TrimStart(' ').Remove(0, "config".Length).TrimStart(' ').Remove(0, "verification".Length).TrimStart(' ').Remove(0, "message".Length).Trim(' '); if (!string.IsNullOrEmpty(message)) { GenericBot.GuildConfigs[msg.GetGuild().Id].VerifiedMessage = message; } await msg.ReplyAsync("Example verification message:"); string vm = $"Hey {msg.Author.Username}! To get verified on **{msg.GetGuild().Name}** reply to this message with the hidden code in the message below\n\n" + GenericBot.GuildConfigs[msg.GetGuild().Id].VerifiedMessage; string verificationMessage = VerificationEngine.InsertCodeInMessage(vm, VerificationEngine.GetVerificationCode(msg.Author.Id, msg.GetGuild().Id)); await msg.ReplyAsync(verificationMessage); } else { await msg.ReplyAsync("Invalid Option"); } } #endregion Verification #region Points else if (paramList[0].ToLower().Equals("points")) { if (paramList[1].ToLower().Equals("enabled")) { GenericBot.GuildConfigs[msg.GetGuild().Id].PointsEnabled = !GenericBot.GuildConfigs[msg.GetGuild().Id].PointsEnabled; if (GenericBot.GuildConfigs[msg.GetGuild().Id].PointsEnabled) { await msg.ReplyAsync($"Enabled points for this server"); } else { await msg.ReplyAsync($"Disabled points for this server"); } } else if (paramList[1].ToLower().Equals("noun")) { if (paramList.Count != 3) { await msg.ReplyAsync("Please use one word as the name for the points name"); } else { GenericBot.GuildConfigs[msg.GetGuild().Id].PointsName = paramList[2]; await msg.ReplyAsync($"Set the name for points to `{paramList[2]}`"); } } else if (paramList[1].ToLower().Equals("verb")) { if (paramList.Count != 3) { await msg.ReplyAsync("Please use one word as the name for the points verb"); return; } else { GenericBot.GuildConfigs[msg.GetGuild().Id].PointsVerb = paramList[2]; await msg.ReplyAsync($"Set the verb for using points to `{paramList[2]}`"); } } else { await msg.ReplyAsync("Unknown option"); } } #endregion Points #region GlobalBanOptOut else if (paramList[0].ToLower().Equals("globalbanoptout")) { if (paramList.Count > 1 && paramList[1].ToLower().Equals("true")) { GenericBot.GuildConfigs[msg.GetGuild().Id].GlobalBanOptOut = true; await msg.ReplyAsync($"You have opted out of the global bans"); } else if (paramList.Count > 1 && paramList[1].ToLower().Equals("false")) { GenericBot.GuildConfigs[msg.GetGuild().Id].GlobalBanOptOut = false; await msg.ReplyAsync($"You have opted into the global bans"); } else { GenericBot.GuildConfigs[msg.GetGuild().Id].GlobalBanOptOut = !GenericBot.GuildConfigs[msg.GetGuild().Id].GlobalBanOptOut; if (GenericBot.GuildConfigs[msg.GetGuild().Id].GlobalBanOptOut) { await msg.ReplyAsync($"You have opted out of the global bans"); } else { await msg.ReplyAsync($"You have opted into the global bans"); } } } #endregion GlobalBanOptOut #region AutoRole else if (paramList[0].ToLower().Equals("autoroles") || paramList[0].ToLower().Equals("autorole")) { if (paramList.Count == 2) { await msg.ReplyAsync($"Please enter a roleId"); return; } if (ulong.TryParse(paramList[2], out ulong id)) { if (paramList[1].ToLower().Equals("add")) { if (msg.GetGuild().Roles.Select(r => r.Id).Any(u => u.Equals(id))) { if (!GenericBot.GuildConfigs[msg.GetGuild().Id].AutoRoleIds.Contains(id)) { GenericBot.GuildConfigs[msg.GetGuild().Id].AutoRoleIds.Add(id); await msg.ReplyAsync($"Added {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name} to autoroles"); } else { await msg.ReplyAsync($"Autoroles already contains {msg.GetGuild().Roles.FirstOrDefault(r => r.Id == id).Name}"); } } else { await msg.ReplyAsync("Invalid RoleId (Not a role)"); } } else if (paramList[1].ToLower().Equals("remove")) { if (GenericBot.GuildConfigs[msg.GetGuild().Id].AutoRoleIds.Contains(id)) { { GenericBot.GuildConfigs[msg.GetGuild().Id].AutoRoleIds.Remove(id); await msg.ReplyAsync( $"Removed `{id}` from autoroles"); } } else { await msg.ReplyAsync( $"The autoroles don't contain `{id}`"); } } else { await msg.ReplyAsync($"Unknown property `{paramList[1]}`."); } } else { await msg.ReplyAsync($"That is not a valid roleId"); } } #endregion AutoRole else { await msg.ReplyAsync($"Unknown property `{paramList[0]}`."); } GenericBot.GuildConfigs[msg.GetGuild().Id].Save(); }; ConfigCommands.Add(config); Command levels = new Command(nameof(levels)); levels.RequiredPermission = Command.PermissionLevels.Admin; levels.Description = "Set the number of points to get a role"; levels.ToExecute += async(client, msg, parameters) => { var guildConfig = GenericBot.GuildConfigs[msg.GetGuild().Id]; if (parameters.Empty()) { if (guildConfig.Levels.Any(kvp => msg.GetGuild().GetRole(kvp.Value) != null)) { string res = ""; foreach (var level in guildConfig.Levels.OrderBy(kvp => kvp.Key).Where(kvp => msg.GetGuild().GetRole(kvp.Value) != null)) { var role = msg.GetGuild().GetRole(level.Value); res += $"Role `{role.Name.Escape()}` at `{level.Key}` Points\n"; } await msg.ReplyAsync(res); } else { await msg.ReplyAsync("There are no levels for this server!"); } } else { if (parameters[0].ToLower() == "add") { if (parameters.Count == 3) { if (decimal.TryParse(parameters[1], out decimal pointValue) && ulong.TryParse(parameters[2], out ulong roleId) && msg.GetGuild().Roles.Any(r => r.Id == roleId)) { var db = new DBGuild(msg.GetGuild().Id); guildConfig.Levels.Add(pointValue, roleId); int addedUsers = 0; foreach (var user in msg.GetGuild().Users) { if (db.GetUser(user.Id).PointsCount >= pointValue) { try { await user.AddRoleAsync(msg.GetGuild().GetRole(roleId)); addedUsers++; } catch { } } } await msg.ReplyAsync($"Users will get `{msg.GetGuild().GetRole(roleId).Name.Escape()}` at `{pointValue}` points. `{addedUsers}` had the more than the number of points and have had the role assigned"); } } else { await msg.ReplyAsync($"The command should be formatted as `levels add pointsValue roleId`"); } } else if (parameters[0].ToLower() == "remove") { if (parameters.Count == 2) { if (ulong.TryParse(parameters[1], out ulong roleId) && guildConfig.Levels.Any(kvp => kvp.Value.Equals(roleId))) { guildConfig.Levels.Remove(guildConfig.Levels.First(kvp => kvp.Value.Equals(roleId)).Key); await msg.ReplyAsync("Done!"); } else { await msg.ReplyAsync("That is not a valid RoleId!"); } } else { await msg.ReplyAsync($"The command should be formatted as `levels remove roleId`"); } } guildConfig.Save(); } }; ConfigCommands.Add(levels); return(ConfigCommands); }