public static string GetCommand(this Permissionv2 perm, SocketGuild guild = null) { var com = ""; switch (perm.PrimaryTarget) { case PrimaryPermissionType.User: com += "u"; break; case PrimaryPermissionType.Channel: com += "c"; break; case PrimaryPermissionType.Role: com += "r"; break; case PrimaryPermissionType.Server: com += "s"; break; } switch (perm.SecondaryTarget) { case SecondaryPermissionType.Module: com += "m"; break; case SecondaryPermissionType.Command: com += "c"; break; case SecondaryPermissionType.AllModules: com = "a" + com + "m"; break; } com += " " + (perm.SecondaryTargetName != "*" ? perm.SecondaryTargetName + " " : "") + (perm.State ? "enable" : "disable") + " "; switch (perm.PrimaryTarget) { case PrimaryPermissionType.User: com += guild?.GetUser(perm.PrimaryTargetId).ToString() ?? $"<@{perm.PrimaryTargetId}>"; break; case PrimaryPermissionType.Channel: com += $"<#{perm.PrimaryTargetId}>"; break; case PrimaryPermissionType.Role: com += guild?.GetRole(perm.PrimaryTargetId)?.ToString() ?? $"<@&{perm.PrimaryTargetId}>"; break; case PrimaryPermissionType.Server: break; } return(NadekoBot.ModulePrefixes[typeof(Permissions).Name] + com); }
/// <summary> /// Retrieves role socket entities from the IDs in the <see cref="Role"/> enum. /// </summary> /// <exception cref="InvalidOperationException">Thrown when a role can't be found.</exception> private async Task GetRoles() { SocketGuild guild = _client.Guilds.FirstOrDefault(); PlayTesterRole = GetRole(Role.Playtester); ModRole = GetRole(Role.Moderators); RconRole = GetRole(Role.RconAccess); MuteRole = GetRole(Role.Muted); ActiveRole = GetRole(Role.ActiveMember); PatreonsRole = GetRole(Role.Patreons); CommunityTesterRole = GetRole(Role.CommunityTester); var roleMeRoles = new HashSet <SocketRole>(); foreach (string role in Config["roleMeWhiteListCSV"].Split(',')) { roleMeRoles.Add(await ParseRole(role)); } RoleMeWhiteList = roleMeRoles.ToImmutableHashSet(); SocketRole GetRole(Role role) { SocketRole r = guild?.GetRole((ulong)role); if (r == null) { throw new InvalidOperationException($"The role '{role}' could not be found."); } return(r); } async Task <SocketRole> ParseRole(string name) { SocketRole role = await RoleTypeReader <SocketRole> .GetBestResultAsync(guild, name); if (role == null) { throw new InvalidOperationException($"'{name}' could not be parsed as a role."); } return(role); } }
/// <summary> /// Retrieves role socket entities from the IDs in the <see cref="Role"/> enum. /// </summary> /// <exception cref="InvalidOperationException">Thrown when a role can't be found.</exception> private void GetRoles() { SocketGuild guild = _client.Guilds.FirstOrDefault(); Th3DmodRole = GetRole(Role.th3dmod); Th3DsupeRole = GetRole(Role.th3dsuper); SocketRole GetRole(Role role) { SocketRole r = guild?.GetRole((ulong)role); if (r == null) { throw new InvalidOperationException($"The role '{role}' could not be found."); } return(r); } }
private async Task RoleRestore(SocketGuild guild) { _logger.LogInformation("RoleRestore"); var members = (await guild.GetUsersAsync().ToListAsync()).SelectMany(e => e).ToDictionary(k => k.Id); var roles = EmojiRolePairs .Select(s => new { Key = guild.Emotes.First(e => e.Id == s.EmojiId) !, Value = guild.GetRole(s.RoleId) })
public static async Task UpdateGuild(SettingManager settingManager, SocketGuild guild, SocketGuildUser selfUser) { if (bool.TryParse(await settingManager.GetSettingValue("GUILDCONFIG_DOMINANCE", guild), out var result) && result) { if (ulong.TryParse(await settingManager.GetSettingValue("GUILDCONFIG_DOMINANCE_ROLE", guild), out var roleId)) { var dominanceRole = guild.GetRole(roleId); ITextChannel annChannel = null; var annChannelId = await settingManager.GetSettingValue("GUILDCONFIG_ANN_CHANNEL", guild); if (annChannelId != null) { annChannel = guild.GetChannel(ulong.Parse(annChannelId)) as ITextChannel; } if (selfUser.Roles.Any(x => x.Position > dominanceRole.Position)) { foreach (var user in dominanceRole.Members.ToList()) { await user.RemoveRoleAsync(dominanceRole); } using (var ctx = new DataContext()) { var externalEmojis = guild.CurrentUser.GuildPermissions.UseExternalEmojis; var latestDominance = ctx.FRDominances.OrderByDescending(x => x.Timestamp).First(); if ((Flight)latestDominance.First != Flight.Beastclans) { if (ulong.TryParse(await settingManager.GetSettingValue($"GUILDCONFIG_DOMINANCE_ROLE_{latestDominance.First}", guild), out var firstPlaceFlight)) { var firstPlaceRole = guild.GetRole(firstPlaceFlight); foreach (var user in firstPlaceRole.Members.ToList()) { if ((await settingManager.GetSettingValue($"GUILDCONFIG_DOMINANCE_USER_{user.Id}", guild)) == "true") { await user.AddRoleAsync(dominanceRole); } } if (annChannel != null) { var embed = new EmbedBuilder() .WithTitle($"Congratulations to the {(externalEmojis ? (DiscordHelpers.DiscordEmojis[(DiscordEmoji)latestDominance.First] + " ") : "")}**{(Flight)latestDominance.First}** flight for claiming 1st place!") .WithFields( new EmbedFieldBuilder().WithIsInline(true).WithName("Info").WithValue($"Those who opted in for the {dominanceRole.Mention} role now have it, enjoy your discounts!\r\n\nSecond place: {(externalEmojis ? (DiscordHelpers.DiscordEmojis[(DiscordEmoji)latestDominance.Second] + " ") : "")}{(Flight)latestDominance.Second}\r\nThird place: {(externalEmojis ? (DiscordHelpers.DiscordEmojis[(DiscordEmoji)latestDominance.Third] + " ") : "")}{(Flight)latestDominance.Third}"), new EmbedFieldBuilder().WithIsInline(true).WithName("Benefits").WithValue($"{(externalEmojis ? (DiscordHelpers.DiscordEmojis[DiscordEmoji.Dominance] + " ") : "")}15% off marketplace treasure items\r\n{(externalEmojis ? (DiscordHelpers.DiscordEmojis[DiscordEmoji.Lair] + " ") : "")}5% off lair expansions\r\n{(externalEmojis ? (DiscordHelpers.DiscordEmojis[DiscordEmoji.Treasure] + " ") : "")}+1500 treasure a day\r\n{(externalEmojis ? (DiscordHelpers.DiscordEmojis[DiscordEmoji.Food] + " ") : "")}+3 gathering turns a day") ); await annChannel.SendMessageAsync(embed : embed.Build()); } } } else { if (annChannel != null) { var embed = new EmbedBuilder() .WithTitle($"{(externalEmojis ? (DiscordHelpers.DiscordEmojis[DiscordEmoji.Beastclans] + " ") : "")}Beastclans won 1st place this week, somehow, so nobody gets the dominance role : (") .WithFields( new EmbedFieldBuilder().WithIsInline(true).WithName("Info").WithValue($"How did {(externalEmojis ? (DiscordHelpers.DiscordEmojis[DiscordEmoji.Earth] + " ") : "")}Earth not get 1st place? Strange..\r\n\nSecond place: {(externalEmojis ? (DiscordHelpers.DiscordEmojis[(DiscordEmoji)latestDominance.Second] + " ") : "")}{(Flight)latestDominance.Second}\r\nThird place: {(externalEmojis ? (DiscordHelpers.DiscordEmojis[(DiscordEmoji)latestDominance.Third] + " ") : "")}{(Flight)latestDominance.Third}"), new EmbedFieldBuilder().WithIsInline(true).WithName("Benefits (for 2nd place)").WithValue($"{(externalEmojis ? (DiscordHelpers.DiscordEmojis[DiscordEmoji.Dominance] + " ") : "")}7% off marketplace treasure items\r\n{(externalEmojis ? (DiscordHelpers.DiscordEmojis[DiscordEmoji.Lair] + " ") : "")}1% off lair expansions\r\n{(externalEmojis ? (DiscordHelpers.DiscordEmojis[DiscordEmoji.Treasure] + " ") : "")}+750 treasure a day\r\n{(externalEmojis ? (DiscordHelpers.DiscordEmojis[DiscordEmoji.Food] + " ") : "")}+2 gathering turns a day") ); await annChannel.SendMessageAsync(embed : embed.Build()); } } } } else { if (annChannel != null) { await annChannel.SendMessageAsync("Dominance has updated, but I does not have permission to grant dominance role on this server"); } } } } }
public async Task <string> RemoveUnverifyAsync(SocketGuild guild, SocketGuildUser user, SocketUser fromUser, bool isAuto = false) { try { BotState.CurrentReturningUnverifyFor.Add(user); var userEntity = await GrillBotRepository.UsersRepository.GetUserAsync(guild.Id, user.Id, UsersIncludes.Unverify); if (userEntity?.Unverify == null) { return(MessageGenerator.CreateRemoveAccessUnverifyNotFound(user)); } var unverifyConfig = (await GrillBotRepository.ConfigRepository.FindConfigAsync(guild.Id, "unverify", null, false))?.GetData <UnverifyConfig>(); var mutedRole = unverifyConfig == null ? null : guild.GetRole(unverifyConfig.MutedRoleID); var rolesToReturn = userEntity.Unverify.DeserializedRoles.Where(o => !user.Roles.Any(x => x.Id == o)) .Select(o => guild.GetRole(o)).Where(role => role != null).ToList(); var channelsToReturn = userEntity.Unverify.DeserializedChannels .Select(o => new ChannelOverwrite(guild.GetChannel(o.ChannelIdSnowflake), o.GetPermissions())) .Where(o => o.Channel != null).ToList(); if (isAuto) { await UnverifyLogger.LogAutoRemoveAsync(rolesToReturn, channelsToReturn, user, guild); } else { await UnverifyLogger.LogRemoveAsync(rolesToReturn, channelsToReturn, guild, user, fromUser); } foreach (var channel in channelsToReturn) { if (channel.Channel is SocketGuildChannel socketGuildChannel) { try { await socketGuildChannel.AddPermissionOverwriteAsync(user, channel.Perms); } catch (HttpException ex) { var message = new LogMessage(LogSeverity.Error, nameof(UnverifyService), $"An error occured when unverify returning access to channel {channel.Channel.Name} for user {user.GetFullName()}", ex); await Logger.OnLogAsync(message); } } } await user.AddRolesAsync(rolesToReturn); if (mutedRole != null) { await user.RemoveRoleAsync(mutedRole); } userEntity.Unverify = null; await GrillBotRepository.CommitAsync(); Queue.TryRemove <UnverifyBackgroundTask>(o => o.GuildId == guild.Id && o.UserId == user.Id); if (!isAuto) { var message = MessageGenerator.CreateRemoveAccessManuallyPMMessage(guild); await user.SendPrivateMessageAsync(message); } return(MessageGenerator.CreateRemoveAccessManuallyToChannel(user)); } catch (Exception ex) { if (!isAuto) { throw; } var message = new LogMessage(LogSeverity.Error, nameof(UnverifyService), "An error occured when unverify returning access.", ex); await Logger.OnLogAsync(message); return(MessageGenerator.CreateRemoveAccessManuallyFailed(user, ex)); } finally { BotState.CurrentReturningUnverifyFor.RemoveAll(o => o.Id == user.Id); } }
static async Task UpdateAsync(AccountInfo account, SocketGuildUser user) { try { UserInfo userInfo = await ApiAccess.ApiClient.UserClient.GetUserInfoAsync(account.altaIdentifier); MembershipStatusResponse result = await ApiAccess.ApiClient.UserClient.GetMembershipStatus(account.altaIdentifier); if (userInfo == null) { Console.WriteLine("Couldn't find userinfo for " + account.username); return; } if (result == null) { Console.WriteLine("Couldn't find membership status for " + account.username); return; } account.supporterExpiry = result.ExpiryTime ?? DateTime.MinValue; account.isSupporter = result.IsMember; account.username = userInfo.Username; if (account.isSupporter) { database.expiryAccounts.Add(account); } if (user == null) { user = guild.GetUser(account.discordIdentifier); } if (user == null) { Console.WriteLine("Couldn't find Discord user for " + account.username + " " + account.discordIdentifier); return; } if (supporterRole == null) { supporterRole = guild.GetRole(547202953505800233); supporterChannel = guild.GetTextChannel(547204432144891907); generalChannel = guild.GetChannel(334933825383563266) as SocketTextChannel; } if (account.isSupporter) { if (user.Roles == null || !user.Roles.Contains(supporterRole)) { try { await user.AddRoleAsync(supporterRole); } catch (Exception) { Console.WriteLine("Error adding role"); Console.WriteLine(user); Console.WriteLine(supporterRole); } await supporterChannel.SendMessageAsync($"{user.Mention} joined. Thanks for the support!"); await generalChannel.SendMessageAsync($"{user.Mention} became a supporter! Thanks for the support!\nIf you'd like to find out more about supporting, visit https://townshiptale.com/supporter"); } } else { await user.RemoveRoleAsync(supporterRole); } isChanged = true; } catch (Exception e) { Console.WriteLine("Error updating " + account.username); Console.WriteLine(e.Message); } }
/// <summary> /// Goes through the process of initializing and populating all data collections with the passed in data. /// </summary> /// <param name="bs"></param> public static void SetupServerData(BotSettings bs) { DiscordSocketClient client = Program.Client; Server = client.GetGuild(bs.KamtroID); #region Other Servers if (bs.KamexicoID == 0) { Kamexico = null; } else { Kamexico = client.GetGuild(bs.KamexicoID); } if (bs.RetropolisID == 0) { Retropolis = null; } else { Retropolis = client.GetGuild(bs.RetropolisID); } #endregion #region Channels AdminChannel = Server.GetTextChannel(bs.AdminChannelID); LogChannel = Server.GetTextChannel(bs.LogChannelID); BotChannel = Server.GetTextChannel(bs.BotChannelID); #endregion #region AllRoles // Add all server roles to the AllRoles collection. - Arcy AllRoles = Server.Roles.ToList(); #endregion #region ModifiableRoles, SilencedRoles, TrustedRoles & ModeratorRoles ModifiableRoles = new List <SocketRole>(); ModeratorRoles = new List <SocketRole>(); TrustedRoles = new List <SocketRole>(); SilencedRoles = new List <SocketRole>(); // Loop through each role id and add the SocketRole to the collection it is in. - Arcy foreach (SocketRole role in Server.Roles) { // Moderator Roles foreach (ulong roleId in bs.ModeratorRoles) { // When finding a match, add to the collection. - Arcy if (role.Id == roleId) { ModeratorRoles.Add(role); break; } } // Trusted roles (Member, Veteran) foreach (ulong roleId in bs.TrustedRoles) { if (role.Id == roleId) { TrustedRoles.Add(role); } } // Silenced roles foreach (ulong roleId in bs.SilencedRoles) { if (role.Id == roleId) { SilencedRoles.Add(role); } } } // Order matters for modifiable roles - Arcy // Modifiable Roles foreach (ulong roleId in bs.ModifiableRoles) { foreach (SocketRole role in Server.Roles) { // When finding a match, add to the collection. - Arcy if (role.Id == roleId) { ModifiableRoles.Add(role); break; } } } #endregion #region Individual Roles KamtroBotRole = Server.GetRole(bs.KamtroBotRoleId); NSFWRole = Server.GetRole(bs.NSFWRole); Kamexican = Server.GetRole(bs.KamexicanID); Retropolitan = Server.GetRole(bs.RetropolitanID); Lurker = Server.GetRole(bs.LurkerID); #endregion #region Admin Users AdminUsers = new List <SocketGuildUser>(); // Read in all recorded ids foreach (ulong userId in bs.AdminUsers) { SocketGuildUser user = Server.GetUser(userId); // Check if user is in server if (user != null) { // Add to collection if in server AdminUsers.Add(user); } } #endregion #region Relay Users RelayUsers = new List <SocketGuildUser>(); // Read in all recorded ids foreach (ulong userId in bs.RelayUsers) { SocketGuildUser user = Server.GetUser(userId); RelayUsers.Add(user); } #endregion #region Individual Users PrimaryContactUser = Server.GetUser(bs.PrimaryContactUserId); #endregion }
public override async Task ServerUpdate(SocketGuild server) { var triviaServerData = server.GetMemory().GetData <TriviaSystem, TriviaServerData>(); if (!triviaServerData.IsReady) { return; //TODO: Let the admins know that this is misconfigured. } var now = DateTime.Now; if ((now - triviaServerData.lastTriviaPost).TotalSeconds <= triviaServerData.postIntervalInSeconds) { return; } triviaServerData.lastTriviaPost = now; triviaServerData.currentChannel = triviaServerData.triviaChannels[MopBot.Random.Next(triviaServerData.triviaChannels.Count)]; var channel = server.GetTextChannel(triviaServerData.currentChannel); if (channel == null) { return; //TODO: Same as above } TriviaQuestion[] validQuestions; //Find questions we didn't pick yet, handle running out of them. while (true) { lock (triviaServerData.questions) { validQuestions = triviaServerData.questions.Where(q => !q.wasPosted).ToArray(); } if (validQuestions.Length == 0) { if (triviaServerData.autoClearCache && triviaServerData.questions.Count > 0) { ClearCache(triviaServerData); continue; } else { await channel.SendMessageAsync($"{server.Owner.Mention} We're out of trivia questions!\r\n\r\nAdd new questions, or..\r\n• Use `!trivia clearcache` to clear list of used questions;\r\n• Use `!trivia autoclearcache true` to automate this process, if you're fully okay with same questions being repeat;"); return; } } break; } //Set new question triviaServerData.currentQuestion = validQuestions[MopBot.Random.Next(validQuestions.Length)]; triviaServerData.currentQuestion.wasPosted = true; currentQuestionRegex = null; //This will cause a new one to be made, when needed. string mention = null; SocketRole role = null; bool disallowRoleMention = false; var currentUser = server.CurrentUser; if (triviaServerData.triviaRole > 0) { role = server.GetRole(triviaServerData.triviaRole); if (role != null) { if (!role.IsMentionable && currentUser.HasDiscordPermission(gp => gp.ManageRoles)) { await role.ModifyAsync(rp => rp.Mentionable = true); disallowRoleMention = true; } mention = role.Mention; } else { triviaServerData.triviaRole = 0; } } var embedBuilder = MopBot.GetEmbedBuilder(server) .WithAuthor("The next question is...") //.WithTitle("The next question is...") .WithDescription($"**{triviaServerData.currentQuestion.question}**") .WithFooter("Type your answer right in this channel!"); if (triviaServerData.thumbnailUrls?.Length > 0 == true) { try { embedBuilder.WithThumbnailUrl(triviaServerData.thumbnailUrls[MopBot.Random.Next(triviaServerData.thumbnailUrls.Length)]); } catch { } } await channel.SendMessageAsync(mention, embed : embedBuilder.Build()); if (disallowRoleMention) { await role.ModifyAsync(rp => rp.Mentionable = false); } if (triviaServerData.lockTriviaChannel && currentUser.HasChannelPermission(channel, DiscordPermission.ManageChannel)) { //Unlock the channel, since there's a question now. await channel.ModifyPermissions(server.EveryoneRole, op => op.SendMessages == PermValue.Deny?op.Modify(sendMessages : PermValue.Inherit) : op); } }
/// <summary> /// Main method where actual guild processing occurs. /// </summary> private async Task <PGDiagnostic> ProcessGuildAsync(SocketGuild guild) { var diag = new PGDiagnostic(); // Load guild information - stop if there is none (bot never previously used in guild) var gc = await GuildConfiguration.LoadAsync(guild.Id, true).ConfigureAwait(false); if (gc == null) { return(diag); } // Check if role settings are correct before continuing with further processing SocketRole role = null; if (gc.RoleId.HasValue) { role = guild.GetRole(gc.RoleId.Value); } diag.RoleCheck = CheckCorrectRoleSettings(guild, role); if (diag.RoleCheck != null) { return(diag); } // Determine who's currently having a birthday if (!guild.HasAllMembers) { await guild.DownloadUsersAsync().ConfigureAwait(false); await Task.Delay(500); } var users = await GuildUserConfiguration.LoadAllAsync(guild.Id).ConfigureAwait(false); var tz = gc.TimeZone; var birthdays = GetGuildCurrentBirthdays(users, tz); // Note: Don't quit here if zero people are having birthdays. Roles may still need to be removed by BirthdayApply. diag.CurrentBirthdays = birthdays.Count.ToString(); IEnumerable <SocketGuildUser> announcementList; // Update roles as appropriate try { var updateResult = await UpdateGuildBirthdayRoles(guild, role, birthdays).ConfigureAwait(false); announcementList = updateResult.Item1; diag.RoleApplyResult = updateResult.Item2; // statistics } catch (Discord.Net.HttpException ex) { diag.RoleApply = ex.Message; return(diag); } diag.RoleApply = null; // Birthday announcement var announce = gc.AnnounceMessages; var announceping = gc.AnnouncePing; SocketTextChannel channel = null; if (gc.AnnounceChannelId.HasValue) { channel = guild.GetTextChannel(gc.AnnounceChannelId.Value); } if (announcementList.Count() != 0) { var announceResult = await AnnounceBirthdaysAsync(announce, announceping, channel, announcementList).ConfigureAwait(false); diag.Announcement = announceResult; } else { diag.Announcement = "No new role additions. Announcement not needed."; } return(diag); }
public async Task ExecuteAsync(SocketUserMessage msg, string[] parameters) { EmbedBuilder eb = new EmbedBuilder(); EmbedFooterBuilder efb = new EmbedFooterBuilder(); string leaderRole = Config.leaderRole; var uRole = Convert.ToUInt64(leaderRole); string targetId = msg.MentionedUsers.Count == 1 ? msg.MentionedUsers.First().Id.ToString() : parameters[0]; SocketGuild server = ((SocketGuildChannel)msg.Channel).Guild; SocketGuildUser target = server.Users.FirstOrDefault(x => x.Id.ToString() == targetId); var lRole = server.GetRole(uRole); SocketGuildUser gUser = (SocketGuildUser)msg.Author; if (msg.Channel.Id != Convert.ToUInt64(File.ReadAllText(Program.channelLocation))) { string tcID = File.ReadAllText(Program.channelLocation); eb.AddField("Locked!", $"**This bot can only be used in <#{tcID}>**"); eb.Color = Color.Red; var embedLocked = eb.Build(); await msg.Channel.SendMessageAsync("", embed : embedLocked); return; } if (parameters.Length != 1) { eb.AddField("**Wrong command usage**", $"**{Syntax}**"); eb.Color = Color.Red; var embedWU = eb.Build(); var wrongUsage = await msg.Channel.SendMessageAsync("", embed : embedWU); await Task.Delay(5000); await wrongUsage.DeleteAsync(); return; } //Parse Role ID string r1 = parameters[0].Replace("<", ""); string r2 = r1.Replace("&", ""); string r3 = r2.Replace("@", ""); string RoleID = r3.Replace(">", ""); //replace this with a foreach statement var roleOut = Convert.ToUInt64(RoleID); var RoleL = server.GetRole(roleOut); var members = RoleL.Members.ToList(); foreach (var member in members) { eb.AddField($"Member", $"{member.Mention}"); } eb.Color = RoleL.Color; eb.Title = "Members"; eb.WithTimestamp(DateTime.Now); efb.Text = $"{RoleL.Members.Count()}/{Config.teamLimit} Members"; efb.IconUrl = msg.Author.GetAvatarUrl(); eb.WithFooter(efb); var embed = eb.Build(); await msg.Channel.SendMessageAsync(embed : embed); }
public async Task ExecuteAsync(SocketUserMessage msg, string[] parameters) { EmbedBuilder eb = new EmbedBuilder(); EmbedFooterBuilder efb = new EmbedFooterBuilder(); string leaderRole = Config.leaderRole; var uRole = Convert.ToUInt64(leaderRole); string targetId = msg.MentionedUsers.Count == 1 ? msg.MentionedUsers.First().Id.ToString() : parameters[0]; SocketGuild server = ((SocketGuildChannel)msg.Channel).Guild; SocketGuildUser target = server.Users.FirstOrDefault(x => x.Id.ToString() == targetId); var lRole = server.GetRole(uRole); SocketGuildUser gUser = (SocketGuildUser)msg.Author; if (msg.Channel.Id != Convert.ToUInt64(Config.channelLockId)) { string tcID = Config.channelLockId; eb.AddField("Locked!", $"**This bot can only be used in <#{tcID}>**"); eb.Color = Color.Red; var embedLocked = eb.Build(); await msg.Channel.SendMessageAsync("", embed : embedLocked); return; } if (!gUser.Roles.Contains(lRole)) { eb.AddField("No permission!", $"You need the {lRole.Mention} role to execute this command!"); eb.Color = Color.Red; efb.IconUrl = gUser.GetAvatarUrl(); eb.WithTimestamp(DateTime.Now); eb.WithFooter(efb); var embedR = eb.Build(); await msg.Channel.SendMessageAsync("", embed : embedR); return; } if (parameters.Length != 2) { eb.AddField("**Wrong command usage**", $"**{Syntax}**"); eb.Color = Color.Red; var embedWU = eb.Build(); var wrongUsage = await msg.Channel.SendMessageAsync("", embed : embedWU); await Task.Delay(5000); await wrongUsage.DeleteAsync(); return; } //Parse Role ID string r1 = parameters[1].Replace("<", ""); string r2 = r1.Replace("&", ""); string r3 = r2.Replace("@", ""); string RoleID = r3.Replace(">", ""); //replace this with a foreach statement var roleOut = Convert.ToUInt64(RoleID); var RoleL = server.GetRole(roleOut); SocketGuildUser author = (SocketGuildUser)msg.Author; if (RoleL.Id == lRole.Id) { await msg.Channel.SendMessageAsync("**You can't kick anyone from the Leader role!**"); return; } if (!author.Roles.Contains(RoleL)) { eb.AddField("Error!", $"{author.Mention} you can't invite an user to a role you don't have! If this is a mistake please contact a moderator!"); eb.Color = Color.Red; efb.IconUrl = author.GetAvatarUrl(); eb.WithTimestamp(DateTime.Now); eb.WithFooter(efb); var embedA = eb.Build(); await msg.Channel.SendMessageAsync("", embed : embedA); return; } if (!target.Roles.Contains(RoleL)) { eb.AddField("Error!", $"{author.Mention}: **You can't kick someone from a role they don't have!**"); eb.Color = Color.Red; efb.IconUrl = author.GetAvatarUrl(); eb.WithTimestamp(DateTime.Now); eb.WithFooter(efb); var embedT = eb.Build(); await msg.Channel.SendMessageAsync("", embed : embedT); return; } await target.RemoveRoleAsync(RoleL); eb.Title = "Kick"; eb.AddField("Success!", $"{target.Mention} has been removed from {RoleL.Mention}"); eb.Color = RoleL.Color; eb.ThumbnailUrl = target.GetAvatarUrl(); eb.WithTimestamp(DateTime.Now); efb.IconUrl = author.GetAvatarUrl(); var embed = eb.Build(); await msg.Channel.SendMessageAsync("", embed : embed); }
public async Task ExecuteAsync(SocketUserMessage msg, string[] parameters) { EmbedBuilder eb = new EmbedBuilder(); EmbedFooterBuilder efb = new EmbedFooterBuilder(); string leaderRole = Config.leaderRole; var uRole = Convert.ToUInt64(leaderRole); string targetId = msg.MentionedUsers.Count == 1 ? msg.MentionedUsers.First().Id.ToString() : parameters[0]; SocketGuild server = ((SocketGuildChannel)msg.Channel).Guild; SocketGuildUser target = server.Users.FirstOrDefault(x => x.Id.ToString() == targetId); var lRole = server.GetRole(uRole); SocketGuildUser gUser = (SocketGuildUser)msg.Author; if (msg.Channel.Id != Convert.ToUInt64(File.ReadAllText(Program.channelLocation))) { string tcID = File.ReadAllText(Program.channelLocation); eb.AddField("Locked!", $"**This bot can only be used in <#{tcID}>**"); eb.Color = Color.Red; var embedLocked = eb.Build(); await msg.Channel.SendMessageAsync("", embed : embedLocked); return; } if (!gUser.Roles.Contains(lRole)) { eb.AddField("No permission!", $"You need the {lRole.Mention} role to execute this command!"); eb.Color = Color.Red; efb.IconUrl = gUser.GetAvatarUrl(); eb.WithTimestamp(DateTime.Now); eb.WithFooter(efb); var embedR = eb.Build(); await msg.Channel.SendMessageAsync("", embed : embedR); return; } if (parameters.Length != 2) { eb.AddField("**Wrong command usage**", $"**{Syntax}**"); eb.Color = Color.Red; var embedWU = eb.Build(); var wrongUsage = await msg.Channel.SendMessageAsync("", embed : embedWU); await Task.Delay(5000); await wrongUsage.DeleteAsync(); return; } //Parse Role ID string r1 = parameters[1].Replace("<", ""); string r2 = r1.Replace("&", ""); string r3 = r2.Replace("@", ""); string RoleID = r3.Replace(">", ""); //replace this with a foreach statement var roleOut = Convert.ToUInt64(RoleID); var RoleL = server.GetRole(roleOut); SocketGuildUser author = (SocketGuildUser)msg.Author; if (RoleL.Id == lRole.Id) { await msg.Channel.SendMessageAsync("**You can't add anyone to the Leader role!**"); return; } if (!author.Roles.Contains(RoleL)) { eb.AddField("Error!", $"{author.Mention} you can't invite an user to a role you don't have! If this is a mistake please contact a moderator!"); eb.Color = Color.Red; efb.IconUrl = author.GetAvatarUrl(); eb.WithTimestamp(DateTime.Now); eb.WithFooter(efb); var embedA = eb.Build(); await msg.Channel.SendMessageAsync("", embed : embedA); return; } if (target.Roles.Contains(RoleL)) { eb.AddField("Error!", $"{target.Mention} already has the {RoleL.Mention} role!"); eb.Color = Color.Red; efb.IconUrl = author.GetAvatarUrl(); eb.WithTimestamp(DateTime.Now); eb.WithFooter(efb); var embedT = eb.Build(); await msg.Channel.SendMessageAsync("", embed : embedT); return; } int teamLimit = Convert.ToInt32(File.ReadAllText(Program.teamLimitLocation)); if (RoleL.Members.Count() >= teamLimit) { eb.Title = "Limit reached."; eb.AddField("Limit reached!", $"**This role has already reached it's limit of {teamLimit} members!**"); eb.Color = Color.Red; efb.IconUrl = msg.Author.GetAvatarUrl(); eb.WithTimestamp(DateTime.Now); eb.WithFooter(efb); var embedLimit = eb.Build(); await msg.Channel.SendMessageAsync("", embed : embedLimit); return; } await target.AddRoleAsync(RoleL); eb.Title = "Invite"; eb.AddField("User", $"{target.Mention}"); eb.AddField("Role", $"{RoleL.Mention}"); eb.AddField("Invited by", $"{msg.Author.Mention}"); eb.AddField("Team Members", $"{RoleL.Members.Count()}"); eb.Color = RoleL.Color; eb.ImageUrl = target.GetAvatarUrl(); efb.IconUrl = msg.Author.GetAvatarUrl(); efb.Text = $"Invited by {msg.Author.Mention}"; var embed = eb.Build(); await msg.Channel.SendMessageAsync($"", embed : embed); }
public async Task ExecuteAsync(SocketUserMessage msg, string[] parameters) { EmbedBuilder eb = new EmbedBuilder(); EmbedFooterBuilder efb = new EmbedFooterBuilder(); string role = Config.leaderRole; var uRole = Convert.ToUInt64(role); string targetId = msg.MentionedUsers.Count == 1 ? msg.MentionedUsers.First().Id.ToString() : parameters[0]; SocketGuild server = ((SocketGuildChannel)msg.Channel).Guild; SocketGuildUser target = server.Users.FirstOrDefault(x => x.Id.ToString() == targetId); var lRole = server.GetRole(uRole); if (target.Roles.Contains(lRole)) { eb.AddField("Error!", $"**{target.Mention} already has this role.**"); eb.Color = Color.Red; efb.IconUrl = target.GetAvatarUrl(); eb.WithTimestamp(DateTime.Now); eb.WithFooter(efb); var embedI = eb.Build(); await msg.Channel.SendMessageAsync("", embed : embedI); return; } if (msg.Channel.Id != Convert.ToUInt64(File.ReadAllText(Program.channelLocation))) { string tcID = File.ReadAllText(Program.channelLocation); eb.AddField("Locked!", $"**This bot can only be used in <#{tcID}>**"); eb.Color = Color.Red; var embedLocked = eb.Build(); await msg.Channel.SendMessageAsync("", embed : embedLocked); return; } if (parameters.Length != 1) { eb.AddField("**Wrong command usage**", $"**{Syntax}**"); eb.Color = Color.Red; var embedWU = eb.Build(); var wrongUsage = await msg.Channel.SendMessageAsync("", embed : embedWU); await Task.Delay(5000); await wrongUsage.DeleteAsync(); return; } if (target.IsBot) { await msg.Channel.SendMessageAsync("**Disclaimer:** This user is a bot, but to experimental reasons we won't do anything about that. :D"); } await target.AddRoleAsync(lRole); eb.AddField("Success!", $"**{target.Mention} was added to the {lRole.Mention} role!**"); eb.Color = Color.Green; efb.IconUrl = target.GetAvatarUrl(); eb.WithTimestamp(DateTime.Now); eb.WithFooter(efb); var embed = eb.Build(); await msg.Channel.SendMessageAsync("", embed : embed); }
public async Task ExecuteAsync(SocketUserMessage msg, string[] parameters) { //set embed variables EmbedBuilder eb = new EmbedBuilder(); EmbedFooterBuilder efb = new EmbedFooterBuilder(); //parse user input string s1 = parameters[0].Replace("<", ""); string s2 = s1.Replace(">", ""); string s3 = s2.Replace("!", ""); string s4 = s3.Replace("@", ""); string final = s4.Replace("&", ""); //declare server variables string targetId = msg.MentionedUsers.Count == 1 ? msg.MentionedUsers.First().Id.ToString() : parameters[0]; SocketGuild server = ((SocketGuildChannel)msg.Channel).Guild; SocketGuildUser target = server.Users.FirstOrDefault(x => x.Id.ToString() == targetId); SocketRole role; //try converting string to ulong try { role = server.GetRole(Convert.ToUInt64(final)); } //give user heads up if something is wrong catch { await msg.Channel.SendMessageAsync($"**Something went wrong.. Is this a valid role? => {parameters[0]}**"); return; } //get file contents from Config string FileInput = Config.leaderRole; //check if the leader role is already set to the same role if (final == FileInput) { eb.AddField("Warning!", $"**The leader role is already set to {role.Mention}**"); eb.Color = Color.Red; efb.IconUrl = msg.Author.GetAvatarUrl(); eb.WithTimestamp(DateTime.Now); eb.WithFooter(efb); var embed = eb.Build(); await msg.Channel.SendMessageAsync("", embed : embed); return; } //check if command was executed in the locked channel if (msg.Channel.Id != Convert.ToUInt64(File.ReadAllText(Program.channelLocation))) { string tcID = File.ReadAllText(Program.channelLocation); eb.AddField("Locked!", $"**This bot can only be used in <#{tcID}>**"); eb.Color = Color.Red; var embedLocked = eb.Build(); await msg.Channel.SendMessageAsync("", embed : embedLocked); return; } //check that paramaters is of correct length if (parameters.Length != 1) { eb.AddField("**Wrong command usage**", $"**{Syntax}**"); eb.Color = Color.Red; var embedWU = eb.Build(); var wrongUsage = await msg.Channel.SendMessageAsync("", embed : embedWU); await Task.Delay(5000); await wrongUsage.DeleteAsync(); return; } //write id to file File.WriteAllText(Program.leaderLocation, string.Empty); File.WriteAllText(Program.leaderLocation, final); await msg.Channel.SendMessageAsync($"**{role.Mention} has been set as the leader role!**"); }
public async Task XpRoleRewardRetroactive() { var embed = new EmbedBuilder().WithTitle(GetText("retroactive_role_reward")); var msg = await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); var rewards = _service.GetRoleRewards(Context.Guild.Id).ToList(); if (rewards.Count == 0) { await msg.ModifyAsync(x => x.Embed = embed.WithErrorColor() .AddField("⚠", GetText("retroactive_role_reward_norolerewards")) .Build()).ConfigureAwait(false); return; } var rewardsOutput = _service.GetRoleRewards(Context.Guild.Id) .Select(x => x.RoleId) .Distinct() .Select(x => new { Key = x, Value = Context.Guild.GetRole(x)?.ToString() }) .Where(x => x.Value != null) .ToDictionary(x => x.Key, x => x.Value); await msg.ModifyAsync(x => { x.Embed = embed.AddField(GetText("retroactive_role_reward_rolespending"), string.Join("\n", rewardsOutput.Values)) .Build(); }).ConfigureAwait(false); SocketGuild gContext = ((SocketGuild)Context.Guild); foreach (var reward in rewards) { var users = _service.XpRoleRewardRetroactive(Context.Guild.Id, reward.RoleId); if ((users?.Count() ?? 0) > 0) { foreach (var userId in users) { var usr = gContext.GetUser(userId); if (usr != null) { await usr.AddRoleAsync(gContext.GetRole(reward.RoleId)); } } } rewardsOutput.Remove(reward.RoleId); await msg.ModifyAsync(x => { embed.Fields.Clear(); x.Embed = embed.AddField(GetText("retroactive_role_reward_rolespending"), rewardsOutput.Count > 0 ? string.Join("\n", rewardsOutput.Values) : "✅") .Build(); }).ConfigureAwait(false); } await msg.ModifyAsync(x => { embed.Fields.Clear(); x.Embed = embed.WithOkColor() .AddField("✅", GetText("retroactive_role_reward_done")) .Build(); }).ConfigureAwait(false); /* * { * await msg.DeleteAsync(); * embed.Fields.Clear(); * embed = embed.WithOkColor() * .AddField("✅", GetText("retroactive_role_reward_done")); * await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); * } */ }
private async Task RoleRestore(SocketGuild guild) { _logger.LogInformation("RoleRestore"); IReadOnlyDictionary <GuildEmote, SocketRole> roles = EmojiRolePairs .Select(s => new { Key = guild.Emotes.First(e => e.Id == s.EmojiId) !, Value = guild.GetRole(s.RoleId) })
public static string GetCommand(this Permission perm, string prefix, SocketGuild guild = null) { var com = ""; switch (perm.PrimaryTarget) { case PrimaryPermissionType.User: com += "u"; break; case PrimaryPermissionType.Channel: com += "c"; break; case PrimaryPermissionType.Role: com += "r"; break; case PrimaryPermissionType.Server: com += "s"; break; } switch (perm.SecondaryTarget) { case SecondaryPermissionType.Module: com += "m"; break; case SecondaryPermissionType.Command: com += "c"; break; case SecondaryPermissionType.AllModules: com = "a" + com + "m"; break; } var secName = perm.SecondaryTarget == SecondaryPermissionType.Command ? prefix + perm.SecondaryTargetName : perm.SecondaryTargetName; com += $" {(perm.SecondaryTargetName != "*" ? $"{secName} " : "")}{(perm.State ? "enable" : "disable")} "; switch (perm.PrimaryTarget) { case PrimaryPermissionType.User: com += guild?.GetUser(perm.PrimaryTargetId)?.ToString() ?? $"<@{perm.PrimaryTargetId}>"; break; case PrimaryPermissionType.Channel: com += $"<#{perm.PrimaryTargetId}>"; break; case PrimaryPermissionType.Role: com += guild?.GetRole(perm.PrimaryTargetId)?.ToString() ?? $"<@&{perm.PrimaryTargetId}>"; break; case PrimaryPermissionType.Server: break; } return(prefix + com); }
public static async Task ReactionAdded(Cacheable <IUserMessage, ulong> message, ISocketMessageChannel channel, SocketReaction emoji) { SocketGuild guild = DiscordBot.client.GetGuild(DiscordBot.mainGuildId); SocketGuildUser user = guild.GetUser(emoji.UserId); SocketGuildUser messageAuthor = guild.GetUser((await channel.GetMessageAsync(message.Id)).Author.Id); RestUserMessage replyMessage; if (channel.Id == DiscordBot.welcomeChannelID && emoji.Emote.Name == "👍") { if (messageAuthor.Roles.Count == 1) { if (user.Roles.Contains(guild.GetRole(DiscordBot.staffRoleId))) { await messageAuthor.AddRoleAsync(guild.GetRole(DiscordBot.memberRoleId)); } else { replyMessage = await channel.SendMessageAsync("Error 0x1: Permission Denied, you're not a staff member."); await Task.Delay(3000); await replyMessage.DeleteAsync(); } } else { replyMessage = await channel.SendMessageAsync("Error 0x2: This user already has a role."); await Task.Delay(3000); await replyMessage.DeleteAsync(); } } else if (channel.Id == DiscordBot.roleChannelID && message.Id == DiscordBot.roleMessageID && emoji.UserId != DiscordBot.client.CurrentUser.Id) { switch (emoji.Emote.Name) { case "🔔": await user.AddRoleAsync(guild.GetRole(DiscordBot.notificationRoleID)); break; case "🕵": await user.AddRoleAsync(guild.GetRole(DiscordBot.cyberSecurityRoleId)); break; case "💻": await user.AddRoleAsync(guild.GetRole(DiscordBot.programmingRoleID)); break; default: await(await channel.GetMessageAsync(message.Id) as RestUserMessage).RemoveReactionAsync(emoji.Emote, user); break; } } else { return; } }