public async Task NewBanroyale([Remainder] string roleName = "") { var banroyale = await BanroyaleDb.GetBanroyale(Context.Channel.Id); if (banroyale != null) { await Context.Channel.SendMessageAsync($":x: There is already a running Ban Royale in this channel. Type `{Program.GetPrefix(Context)}cbrl` to cancel it."); return; } SocketRole role = null; if (roleName != "") { role = await this.SelectRole(roleName); if (role == null) { return; } } var roleId = await BanroyaleDb.GetRoleId(Context.Guild.Id); if (roleId != 0) { try { roleId = Context.Guild.GetRole(roleId).Id; } catch { roleId = 0; } } if (roleId == 0) { var newRole = await Context.Guild.CreateRoleAsync("Namiko-Banroyale", null, Color.Red, false, false, null); roleId = newRole.Id; await ReplyAsync($"Creating a role - {newRole.Mention}. It will be used to track the Ban Royale participants automatically by assigning/removing the role to/from them.\n" + $"You can change the name and the color of the role. But make sure it is lower in the role list than my bot role, Senpai."); } banroyale = new Banroyale { Active = true, BanLengthHours = 0, ChannelId = Context.Channel.Id, MaxParticipants = 0, MinParticipants = 0, RewardPool = 0, GuildId = Context.Guild.Id, RoleReqId = role == null ? 0 : role.Id, Kick = false, WinnerAmount = 1, ParticipantRoleId = roleId, MinFrequency = 10, MaxFrequency = 20 }; string prefix = Program.GetPrefix(Context); await BanroyaleDb.AddBanroyale(banroyale); await Context.Channel.SendMessageAsync("Setting up a new game of Ban Royale! It's on." + $"\n\n**More settings:**" + $"\n`{prefix}sbrlrp` - set reward pool" + $"\n`{prefix}sbrlw` - set amount of winners" + $"\n`{prefix}sbrlminp` - minimum participants" + $"\n`{prefix}sbrlmaxp` - maximum participants" + $"\n`{prefix}sbrlban` - set loser ban duration" + $"\n`{prefix}sbrlkick` - set loser kick" + $"\n`{prefix}sbrlminf` - set min message frequency in seconds" + $"\n`{prefix}sbrlmaxf` - set max message frequency in seconds" + $"\n\n*Type `{prefix}jbrl` to join the game.*" + $"\n*Type `{prefix}startbrl` to start the game after some players join.*" + $"\n*Type `{prefix}brl` to view current settings.*", embed : BanroyaleUtil.BanroyaleDetailsEmbed(banroyale, Context.Guild.GetRole(banroyale.ParticipantRoleId), Context.Guild.GetRole(banroyale.RoleReqId)).Build()); }
public async Task Pronouns([Remainder] string args) { await Context.Message.DeleteAsync(); if (args == null || args == "") { return; } int[] pronounList = args.Split(' ').Select(int.Parse).ToArray(); SocketGuildUser user = Context.User as SocketGuildUser; SocketRole any = Context.Guild.GetRole((ulong)Program.RoleIds.PrAny) as SocketRole; SocketRole he = Context.Guild.GetRole((ulong)Program.RoleIds.PrHe) as SocketRole; SocketRole they = Context.Guild.GetRole((ulong)Program.RoleIds.PrThey) as SocketRole; SocketRole she = Context.Guild.GetRole((ulong)Program.RoleIds.PrShe) as SocketRole; SocketRole xe = Context.Guild.GetRole((ulong)Program.RoleIds.PrXe) as SocketRole; if (user.Roles.Contains <SocketRole>(any)) { await user.RemoveRoleAsync(any); } if (user.Roles.Contains <SocketRole>(he)) { await user.RemoveRoleAsync(he); } if (user.Roles.Contains <SocketRole>(they)) { await user.RemoveRoleAsync(they); } if (user.Roles.Contains <SocketRole>(she)) { await user.RemoveRoleAsync(she); } if (user.Roles.Contains <SocketRole>(xe)) { await user.RemoveRoleAsync(xe); } foreach (int pronoun in pronounList) { switch (pronoun) { case 0: await user.AddRoleAsync(they); break; case 1: await user.AddRoleAsync(he); break; case 2: await user.AddRoleAsync(she); break; case 3: await user.AddRoleAsync(xe); break; case 4: await user.AddRoleAsync(any); break; } } }
internal void roleDeleted(SocketRole role) { RoleDeleted.Invoke(this, role); }
private async Task RoleDeleted(SocketRole role) { }
private async Task RoleDeleted(SocketRole role) { _serverActivityLogger.Client_RoleDeleted(role); }
public async Task Client_RoleDeleted(SocketRole arg) { RoleDeleted(arg); await Task.CompletedTask; }
private async Task OnReactionAdded(Cacheable <IUserMessage, ulong> cache, ISocketMessageChannel channel, SocketReaction reaction) { IGuildChannel guildChannel = channel as IGuildChannel; SocketGuild guild = guildChannel.Guild as SocketGuild; //GlobalUtils.client.Guilds.FirstOrDefault(); SocketUser user = GlobalUtils.client.GetUser(reaction.UserId); SocketGuildUser guser = guild.GetUser(user.Id); if (user.IsBot) { return; // Task.CompletedTask; } // add vote Console.WriteLine($"Emoji added: {reaction.Emote.Name}"); if (pendingGames.ContainsKey(reaction.MessageId) && reaction.Emote.Name == "\u2705") { pendingGames[reaction.MessageId].votes++; if (pendingGames[reaction.MessageId].votes >= voteThreshold || user.Id == 346219993437831182) { Console.WriteLine("Adding game: " + pendingGames[reaction.MessageId].game); // add the game now! RestRole gRole = await guild.CreateRoleAsync(pendingGames[reaction.MessageId].game); Console.WriteLine("Game Role: " + gRole.Name); RestTextChannel txtChan = await guild.CreateTextChannelAsync(pendingGames[reaction.MessageId].game, x => { x.CategoryId = gamesText.Id; }); Console.WriteLine("Text Channel: " + txtChan.Name); await txtChan.AddPermissionOverwriteAsync(gRole, permissions); RestVoiceChannel voiceChan = await guild.CreateVoiceChannelAsync(pendingGames[reaction.MessageId].game, x => { x.CategoryId = gamesVoice.Id; }); Console.WriteLine("Voice Channel: " + voiceChan.Name); await voiceChan.AddPermissionOverwriteAsync(gRole, permissions); games.Add(new GameInfo(pendingGames[reaction.MessageId].game, txtChan.Id, voiceChan.Id)); // remove poll message, add new game announcement and remove pending game ISocketMessageChannel chan = gameChannel as ISocketMessageChannel; await chan.DeleteMessageAsync(reaction.MessageId); EmbedBuilder embed = new EmbedBuilder(); embed.WithTitle("New Game Added"); embed.WithDescription($"`{pendingGames[reaction.MessageId].game}`\n"); embed.WithColor(GlobalUtils.color); await chan.SendMessageAsync("", false, embed.Build()); pendingGames.Remove(reaction.MessageId); UpdateOrAddRoleMessage(); } } Console.WriteLine($"Emoji added: {reaction.MessageId} == {roleMessageId} : {reaction.MessageId == roleMessageId}"); Console.WriteLine("Add Game Role: " + guser.Nickname); if (reaction.MessageId == roleMessageId) { // they reacted to the correct role message Console.WriteLine("Add Game Role: " + guser.Nickname); for (int i = 0; i < games.Count && i < GlobalUtils.menu_emoji.Count <string>(); i++) { if (GlobalUtils.menu_emoji[i] == reaction.Emote.Name) { Console.WriteLine("Emoji Found"); var result = from a in guild.Roles where a.Name == games[i].game select a; SocketRole role = result.FirstOrDefault(); Console.WriteLine("Role: " + role.Name); await guser.AddRoleAsync(role); } } } Console.WriteLine("what?!"); Save(); }
public async Task MarkSelfassignable([Summary("The code to add the role as")] string code, [Summary("The role itself")] SocketRole role = null) { bool success = await GranularPermissionsStorage.SetSelfassignable(this.Context.Guild.Id, code, role); if (success) { await this.Context.Message.AddReactionAsync(new Emoji("👌")); } else { await this.Context.Message.AddReactionAsync(new Emoji("👎")); } }
public static async Task <bool> SetSelfassignable(ulong guildID, string code, SocketRole role) { try { DocumentReference guildDocument = Db.Document(Convert.ToString(guildID)).Collection("lite").Document("data"); DocumentSnapshot guildSnapshot = await guildDocument.GetSnapshotAsync(); guildSnapshot.TryGetValue("selfAssignable", out Dictionary <string, object> selfAssignables); if (selfAssignables == null) { selfAssignables = new Dictionary <string, object>(); } if (selfAssignables.ContainsKey(code) && role == null) { selfAssignables[code] = null; } else { selfAssignables[code] = role.Id; } Dictionary <string, Dictionary <string, object> > update = new Dictionary <string, Dictionary <string, object> > { ["selfAssignable"] = selfAssignables }; WriteResult wrire = await guildDocument.SetAsync(update, SetOptions.MergeAll); return(true); } catch { return(false); } }
private bool _isReceiveStart = false; // WORKAROUND public SockBase(Socket s, SocketRole r, bool isHost) { _socket = s; this.Role = r; this.IsHost = isHost; }
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed #pragma warning disable CS1998 // This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. public async Task MessageReceived(SocketMessage message, DiscordShardedClient client) { try { if (message.Author.IsBot) { return; } var context = new ShardedCommandContextCustom(client, message as SocketUserMessage); var account = UserAccounts.GetAccount(context.User, context.Guild.Id); var guild = ServerAccounts.GetServerAccount(context.Guild); var rolesToGiveList = guild.Roles.ToList(); var roleToGive = "2gagwerweghsxbd"; var userCheck = "ju"; if (account.MyPrefix != null) { userCheck = context.Message.Content.Substring(0, account.MyPrefix.Length); } var serverCheck = context.Message.Content.Substring(0, guild.Prefix.Length); if (serverCheck == guild.Prefix) { roleToGive = context.Message.Content.Substring(guild.Prefix.Length, message.Content.Length - guild.Prefix.Length); } if (userCheck == account.MyPrefix) { roleToGive = context.Message.Content.Substring(account.MyPrefix.Length, message.Content.Length - account.MyPrefix.Length); } if (userCheck != account.MyPrefix && serverCheck != guild.Prefix) { return; } if (rolesToGiveList.Any(x => string.Equals(x.Key, roleToGive, StringComparison.CurrentCultureIgnoreCase))) { SocketRole roleToAdd = null; foreach (var t in rolesToGiveList) { if (string.Equals(t.Key, roleToGive, StringComparison.CurrentCultureIgnoreCase)) { roleToAdd = context.Guild.Roles.SingleOrDefault(x => x.Name.ToString().ToLower() == t.Value.ToLower()); } } if (!(context.User is SocketGuildUser guildUser) || roleToAdd == null) { return; } var roleList = guildUser.Roles.ToArray(); if (roleList.Any(t => string.Equals(t.Name, roleToAdd.Name, StringComparison.CurrentCultureIgnoreCase))) { await guildUser.RemoveRoleAsync(roleToAdd); await CommandHandeling.ReplyAsync(context, $"-{roleToAdd.Name}"); return; } await guildUser.AddRoleAsync(roleToAdd); await CommandHandeling.ReplyAsync(context, $"+{roleToAdd.Name}"); } } catch { // ignored } }
private async Task Client_RoleCreated(SocketRole arg) { await RepeatingTimer.UpdateAuditLog(); }
public async void RefreshRoles(object sender, System.Timers.ElapsedEventArgs events) { if (!BotReady()) { _ = Logger.Log("Shards not connected.", LogSeverity.Warning, "RefreshRoles"); return; } DatabaseUtil db = new DatabaseUtil(Program.mysqlAuth); List <ulong> roleUsers = new List <ulong>(); try { MySqlDataReader data_response = db.Execute("SELECT `" + DB_column + "` FROM `" + DB_table + "`"); if (data_response.HasRows) { while (data_response.Read()) { ulong id = 0; ulong.TryParse(data_response.GetString(DB_column), out id); if (id == 0) { _ = Logger.Log("Invalid row in database: " + DB_column + " => " + data_response.GetString(DB_column) + ". Could not be parsed to 'ulong' number. Please fix your database!", LogSeverity.Verbose, "RefreshRoles"); continue; } roleUsers.Add(id); } } else { _ = Logger.Log("No rows returned from Database.", LogSeverity.Warning, "RefreshRoles"); } } catch (MySqlException exception) { _ = Logger.Log(new LogMessage(LogSeverity.Error, "RefreshRoles", "MySQL Error Happened", exception)); } foreach (SocketGuild guild in client.Guilds) { //Get all roles in that server List <SocketRole> guildRoles = new List <SocketRole>(); foreach (ulong roleid in roles) { SocketRole role = guild.GetRole(roleid); if (role != null) { guildRoles.Add(role); //Now we check if there's anyone with the role that shouldn't have it IEnumerable <SocketGuildUser> users = role.Members.Where(gUser => !roleUsers.Any(id => gUser.Id == id)); foreach (SocketGuildUser u in users) { _ = Logger.Log("I will remove " + u.Username + " because he has the role " + role.Name + ", but shouldn't have. "); try { await u.RemoveRoleAsync(role); } catch (HttpException e) { if (e.HttpCode != System.Net.HttpStatusCode.NotFound && e.HttpCode != System.Net.HttpStatusCode.Forbidden) { //Unknown Error _ = Logger.Log(new LogMessage(LogSeverity.Warning, "RefreshRoles()", "An HTTPException occoured: ", e)); } else { //No Permission or not Found _ = Logger.Log(new LogMessage(LogSeverity.Warning, "RefreshRoles()", "Could not remove role from user.. Probably missing permission..", e)); } } continue; } } } foreach (ulong id in roleUsers) { SocketGuildUser user = guild.GetUser(id); if (user == null) { //User not in server continue; } //Get roles foreach (SocketRole role in guildRoles) { if (user.Roles.Any(r => r.Id == role.Id)) { //User has the role already, so we should not try to add it again. continue; } _ = Logger.Log("Giving " + role.Name + " to " + user.Username + "#" + user.Discriminator + " in " + guild.Name, LogSeverity.Info, "RefreshRoles"); try { await user.AddRoleAsync(role); } catch (HttpException e) { if (e.HttpCode != System.Net.HttpStatusCode.NotFound && e.HttpCode != System.Net.HttpStatusCode.Forbidden) { //Unknown Error _ = Logger.Log(new LogMessage(LogSeverity.Warning, "RefreshRoles()", "An HTTPException occoured: ", e)); } else { //No Permission or not Found _ = Logger.Log(new LogMessage(LogSeverity.Warning, "RefreshRoles()", "Could not add role to user.. Probably missing permission..", e)); } continue; } } } } db.Disconnect(); }
public async Task Register(string code, SocketRole roleName) { await Register(code, roleName.Name); }
private Task OnRoleUpdatedAsync(SocketRole oldRole, SocketRole newRole) { MessageDispatcher.Publish(new RoleUpdatedNotification(oldRole, newRole)); return(Task.CompletedTask); }
public async Task SetRoleCommand(SocketRole role) { Context.server.GetMemory().GetData <TriviaSystem, TriviaServerData>().triviaRole = role?.Id ?? 0; }
private static async Task AssignRoles(DiscordSocketClient client, IList <IList <Object> > values) { Stopwatch time = Stopwatch.StartNew(); if (values != null && values.Count > 0) { foreach (SocketGuild g in client.Guilds) // Updates for every guild the bot is registered in. Take note that this will quickly hit a discord limit. This is fine, it will resume after a few seconds. { Dictionary <SocketGuildUser, IList <object> > redoUsers = new Dictionary <SocketGuildUser, IList <object> >(); Console.WriteLine("\n\nUpdating roles in " + g.Name + "."); await g.DownloadUsersAsync(); // Gets all users SocketGuildUser[] allUsers = g.Users.ToArray(); // Converts list of users to array foreach (SocketGuildUser u in allUsers) { bool change = false; // Checking roles for user foreach (IList <object> row in values) { if (!SheetsFunctionality.FindUsername(u, row)) { continue; } //await SheetsFunctionality.StoreUserID(u); if (Config.GoogleData.NicknameOnly) { Console.WriteLine("Updating Nickname for " + u.Username + "#" + u.Discriminator); change = await SheetsFunctionality.FindAndSetNickname(u, row); break; } Console.WriteLine("Updating Roles for " + u.Username + "#" + u.Discriminator); List <string> allUserRoles = new List <string>(); // All of the rolls that need to be assigned to the user // Gets all roles that need to be assigned to the user in addition to removing those that interfere with roleGroups.json allUserRoles = await SheetsFunctionality.GetRoles(row, u); if (Config.Bot.AutoRole != "") { allUserRoles.Add(Config.Bot.AutoRole); } List <SocketRole> formattedRoles = new List <SocketRole>(); bool redo = false; // Google Sheets data to SocketRole foreach (string s in allUserRoles) { SocketRole role = g.Roles.FirstOrDefault(x => x.Name == s); if (role == default(SocketRole)) { role = await SheetsFunctionality.CreateRole(g, s); redo = true; change = true; } // Don't add the role if the user already has it. if (u.Roles.Contains(role)) { continue; } change = true; formattedRoles.Add(role); // Adds role to list of queued roles } // Add user to list of roles to redo if (redo) { redoUsers.Add(u, row); } // Add Roles To User await SheetsFunctionality.AddRolesToUser(u, formattedRoles.ToArray()); // Find and set nickname await SheetsFunctionality.FindAndSetNickname(u, row); } // Secondary Role Assigner for roles that were just created await AssignNewRoles(g, redoUsers); if (change) { await DiscordSpecificHandler.VerifyUser(g, u); } } } } time.Stop(); Console.WriteLine(time.ElapsedMilliseconds + "ms\n"); }
public Task <ActionResult> ModRoleAsync([Remainder] SocketRole role) { Context.GuildData.Configuration.Moderation.ModRole = role.Id; Db.UpdateData(Context.GuildData); return(Ok($"Set **{role.Name}** as the Moderator role for this guild.")); }
public async Task AddRole(SocketGuildUser user, SocketRole role) { await user.AddRoleAsync(role); await ReplyAsync($"Successfully added role **{role.Name}** to **{user.Username}**."); }
public async Task AddToRegimentAsync( [Summary("The user to add to your regiment")] SocketGuildUser user) { if (Context.Channel.Name != lists.BotChannel) { return; } var requestingUser = Context.User; #region Representative Officer permissions var role = Context.Guild.Roles.FirstOrDefault(r => r.Name == lists.RegimentalAdminRole); if (role == null) { await ReplyAsync($"This command is temporarily disabled until Agentsvr knows what he's doing."); return; } bool hasPermission = false; foreach (var userRole in ((SocketGuildUser)requestingUser).Roles) { if (userRole.Id == role.Id) { hasPermission = true; } } if (!hasPermission) { await ReplyAsync($"Only Representative Officers can use this command."); return; } #endregion #region Load New Regiment SocketRole regimentRole = null; Regiment regiment = null; foreach (var userRole in ((SocketGuildUser)requestingUser).Roles) { foreach (var r in lists.Regiments) { if (userRole.Name == r.LongName) { regimentRole = userRole; regiment = r; } } } if (regimentRole == null) { await ReplyAsync($"How can you be in a Representative Officer and not be in a recognized Regiment?"); return; } #endregion #region Check if the user is already in a regiment foreach (var userRole in user.Roles) { foreach (var r in lists.Regiments) { if (userRole.Name == r.LongName) { await ReplyAsync($"The user you're trying to add to your regiment is already in another regiment. Talk with the representative officer of {userRole.Name}"); return; } } } #endregion var userMention = string.IsNullOrWhiteSpace(user.Nickname) ? user.Mention : user.Nickname; if (regiment.Faction != Faction.Unaligned) { var factionRole = Context.Guild.Roles.FirstOrDefault(r => r.Name == regiment.Faction.ToString()); await user.AddRoleAsync(factionRole); await ReplyAsync($"Added {userMention} to {factionRole.Name}"); } await user.AddRoleAsync(regimentRole); await ReplyAsync($"Added {userMention} to {regimentRole.Name}"); return; }
private async Task RoleCreated(SocketRole role) { }
public async Task RemoveRoleAsync( SocketGuildUser user) { if (Context.Channel.Name != lists.BotChannel) { return; } var requestingUser = Context.User; if (((SocketGuildUser)requestingUser) == user) { await RemoveRoleAsync(); return; } #region Representative Officer permissions var role = Context.Guild.Roles.FirstOrDefault(r => r.Name == lists.RegimentalAdminRole); if (role == null) { await ReplyAsync($"This command is temporarily disabled until Agentsvr knows what he's doing."); return; } bool hasPermission = false; foreach (var userRole in ((SocketGuildUser)requestingUser).Roles) { if (userRole.Id == role.Id) { hasPermission = true; } } if (!hasPermission) { await ReplyAsync($"Only Representative Officers can use this command."); return; } #endregion #region Load New Regiment SocketRole regimentRole = null; Regiment regiment = null; foreach (var userRole in ((SocketGuildUser)requestingUser).Roles) { foreach (var r in lists.Regiments) { if (userRole.Name == r.LongName) { regimentRole = userRole; regiment = r; } } } if (regimentRole == null) { await ReplyAsync($"How can you be in a Representative Officer and not be in a recognized Regiment?"); return; } #endregion bool wasInRegiment = false; foreach (var userRole in user.Roles) { if (userRole == regimentRole) { await(user as SocketGuildUser).RemoveRoleAsync(regimentRole); await ReplyAsync($"Remove the regiment {regimentRole.Name} from {user.Mention}."); wasInRegiment = true; } else if (userRole.Name == regiment.Faction.ToString()) { await(user as SocketGuildUser).RemoveRoleAsync(userRole); await ReplyAsync($"Remove the faction {regiment.Faction.ToString()} from {user.Mention}."); } } if (wasInRegiment) { return; } await ReplyAsync($"{user.Nickname} was not in your regiment {regimentRole.Name} anyway... you're welcome, I guess."); return; }
private async Task RoleUpdated(SocketRole roleBefore, SocketRole roleAfter) { }
public async Task ChangeNickname( [Summary("User whose tags you want to change")] SocketGuildUser user, [Remainder][Summary("New tags for that user")] string tag) { if (Context.Channel.Name != lists.BotChannel) { return; } var tagLimitation = 32; if (tag.Length > 32) { tag = tag.Substring(0, tagLimitation); await ReplyAsync($"Tag is longer than {tagLimitation} characters, and will be truncated to:{tag}"); } if (user == ((SocketGuildUser)Context.User)) { await ReplyAsync($"You're too fancy to use 'Change Nickname' are you?"); return; } var role = Context.Guild.Roles.FirstOrDefault(r => r.Name == lists.RegimentalAdminRole); if (role == null) { await ReplyAsync($"This command is temporarily disabled until Agentsvr knows what he's doing."); return; } var requestingUser = Context.User; if (!((SocketGuildUser)requestingUser).HasRole(role)) { await ReplyAsync($"Only {lists.RegimentalAdminRole}s can use this command."); return; } SocketRole regimentRole = null; foreach (var userRole in ((SocketGuildUser)requestingUser).Roles) { foreach (var regiment in lists.Regiments) { if (userRole.Name == regiment.LongName) { regimentRole = userRole; } } } if (regimentRole == null) { await ReplyAsync($"How can you be in a {lists.RegimentalAdminRole} and not be in a recognized Regiment?"); return; } var userBelongsToRegiment = false; foreach (var userRole in user.Roles) { if (userRole == regimentRole) { userBelongsToRegiment = true; } } if (!userBelongsToRegiment) { await ReplyAsync($"You can't change a tag for someone that is not in your Regiment."); return; } var oldName = user.Nickname; await user.ModifyAsync(x => { x.Nickname = tag; }); await ReplyAsync($"{oldName} tags changed to:{tag}"); }
private async Task RoleUpdated(SocketRole roleBefore, SocketRole roleAfter) { //_serverActivityLogger.Client_RoleUpdated(roleBefore, roleAfter); }
public async Task Command([Remainder] string arg) { Server server = await DatabaseQueries.GetOrCreateServerAsync(Context.Guild.Id); SocketRole role = null; int level = 0; if (arg.ToLower() == "clear") { await DatabaseQueries.DeleteAllForServerAsync <ServerRoleReward>(server.ServerId); await SendBasicSuccessEmbedAsync($"Successfully cleared this server's role-reward configuration(s)."); return; } if (arg.AsInteger(false) == 0 && arg.AsUlong(false) == 0) { role = Context.Guild.Roles.First(x => x.Name.ToLower() == arg.ToLower()); } if (arg.AsUlong(false) != 0 && arg.AsInteger(false) > 100000) { role = Context.Guild.Roles.First(x => x.Id == arg.AsUlong()); } if (arg.AsInteger(false) != 0 && arg.AsInteger(false) <= 100000) { level = arg.AsInteger(); } if (role == null && level == 0 && server.RoleRewards.Any(x => x.RoleId != arg.AsUlong())) { await SendBasicErrorEmbedAsync("You did not reply with a proper level or role name/ID."); return; } if (role != null && level == 0 || server.RoleRewards.Any(x => x.RoleId == arg.AsUlong())) { ServerRoleReward toRemove = role == null ? server.RoleRewards.ToList().First(x => x.RoleId == arg.AsUlong()) : server.RoleRewards.First(x => x.RoleId == role.Id); if (toRemove == null) { throw new KaguyaSupportException("The specified role could not be found in this server's " + "role rewards list."); } await DatabaseQueries.DeleteAsync(toRemove); await SendBasicSuccessEmbedAsync($"{Context.User.Mention} Successfully removed role " + $"{(role == null ? $"`{toRemove.RoleId}`" : role.Mention)} at `level " + $"{toRemove.Level}` from this server's role rewards."); return; } if (role == null && level != 0) { List <ServerRoleReward> toRemove = server.RoleRewards.Where(x => x.Level == level).ToList(); if (toRemove.Count != 0) { await DatabaseQueries.DeleteAsync(toRemove); await SendBasicSuccessEmbedAsync($"{Context.User.Mention} Successfully deleted " + $"all roles for the server that were given " + $"at `level {level:N0}`."); return; } throw new KaguyaSupportException($"There are no role rewards for this server at `level {level:N0}`"); } throw new KaguyaSupportException("There was nothing to remove."); }
internal void roleUpdated(SocketRole oldRole, SocketRole newRole) { RoleUpdated.Invoke(this, Tuple.Create(oldRole, newRole)); }
private Task OnRoleCreatedAsync(SocketRole role) { MessageDispatcher.Publish(new RoleCreatedNotification(role)); return(Task.CompletedTask); }
public async Task InfoRoleAsync([Remainder] string message) { if (!(await Access("roleinfo"))) { return; } SLog logger = new SLog("RoleInfo 1", Context); try { bool FoundARole = false; ulong roleId = 0; foreach (var rol in Context.Guild.Roles) { if (rol.Name == message) { roleId = rol.Id; FoundARole = true; } } if (!FoundARole) { await ReplyAndDeleteAsync("Роль не найдена", timeout : TimeSpan.FromSeconds(5)); return; } SocketRole Role = Context.Guild.GetRole(roleId); EmbedBuilder builder = new EmbedBuilder(); string strock = ""; int i = 1; foreach (var userr in Role.Members) { strock += $"{i++}: {userr.Username}#{userr.Discriminator}({userr.Nickname})\r\n"; } if (strock == "") { strock = "Пользователей нет"; } builder.WithTitle($"Информация о роле для {Context.User.Username}") .WithAuthor(Role.Name) .AddField("Кол-во пользователей с ролью", i - 1, true) .AddField("Цвет роли", $"{Role.Color}", true) .AddField("Администратор?", Role.Permissions.Administrator, true) .AddField("Дата создания", $"{Role.CreatedAt.Day}.{Role.CreatedAt.Month}.{Role.CreatedAt.Year} {Role.CreatedAt.Hour + Role.CreatedAt.Offset.Hours}:{Role.CreatedAt.Minute}:{Role.CreatedAt.Second}.{Role.CreatedAt.Millisecond}", true) .AddField("Пользователи", strock) .WithFooter(Context.Guild.Name, Context.Guild.IconUrl) .WithColor(ConstVariables.UserColor); await Context.Channel.SendMessageAsync("", embed : builder.Build()); } catch (Exception e) { await ReplyAsync("Ошибка во время выполнения! Обратитесь к админестратору!"); logger._exception = e; } logger.PrintLog(); }
private static Task OnRoleCreated(SocketRole arg) { Core.Log.Write(Core.Log.Type.SERVER, "Role " + arg.GetPath() + " has been created."); return(Task.CompletedTask); }