コード例 #1
0
        private static async Task<IRole> GetMuteRole(IGuild guild)
        {
            const string defaultMuteRoleName = "nadeko-mute";

            var muteRoleName = GuildMuteRoles.GetOrAdd(guild.Id, defaultMuteRoleName);

            var muteRole = guild.Roles.FirstOrDefault(r => r.Name == muteRoleName);
            if (muteRole == null)
            {

                //if it doesn't exist, create it 
                try { muteRole = await guild.CreateRoleAsync(muteRoleName, GuildPermissions.None).ConfigureAwait(false); }
                catch
                {
                    //if creations fails,  maybe the name is not correct, find default one, if doesn't work, create default one
                    muteRole = guild.Roles.FirstOrDefault(r => r.Name == muteRoleName) ??
                        await guild.CreateRoleAsync(defaultMuteRoleName, GuildPermissions.None).ConfigureAwait(false);
                }

                foreach (var toOverwrite in guild.GetTextChannels())
                {
                    try
                    {
                        await toOverwrite.AddPermissionOverwriteAsync(muteRole, new OverwritePermissions(sendMessages: PermValue.Deny, attachFiles: PermValue.Deny))
                                .ConfigureAwait(false);
                    }
                    catch { }
                    await Task.Delay(200).ConfigureAwait(false);
                }
            }
            return muteRole;
        }
コード例 #2
0
 public Poll(IUserMessage umsg, string question, IEnumerable<string> enumerable, bool isPublic = false)
 {
     this.originalMessage = umsg;
     this.guild = ((ITextChannel)umsg.Channel).Guild;
     this.question = question;
     this.answers = enumerable as string[] ?? enumerable.ToArray();
     this.isPublic = isPublic;
 }
コード例 #3
0
ファイル: TriviaGame.cs プロジェクト: Chewsterchew/NadekoBot
 public TriviaGame(IGuild guild, ITextChannel channel, bool showHints, int winReq = 10)
 {
     _log = LogManager.GetCurrentClassLogger();
     ShowHints = showHints;
     this.guild = guild;
     this.channel = channel;
     WinRequirement = winReq;
     Task.Run(async () => { try { await StartGame().ConfigureAwait(false); } catch { } });
 }
コード例 #4
0
ファイル: Timeout.cs プロジェクト: stepperman/HB-Discord-Bot
        public static async Task StopTimeoutAsync(List<TimedoutUser> users, TimedoutUser info, IGuildUser user, IGuild guild)
        {
            users.Remove(info);
            Console.WriteLine($"{user.Username}'s time out has been removed!");
            
            var role = guild.Roles.FirstOrDefault(x => x.Name == "qttimedout");
            var userroles = user.RoleIds.ToList();
            userroles.Remove(role.Id);
            try
            {
                await user.ModifyAsync(x => x.RoleIds = userroles.ToArray());
            }
            catch (Exception) { }

            info.timer.Dispose();
            return;
        }
コード例 #5
0
        //Voice Regions
        public static async Task <IReadOnlyCollection <RestVoiceRegion> > GetVoiceRegionsAsync(IGuild guild, BaseDiscordClient client,
                                                                                               RequestOptions options)
        {
            var models = await client.ApiClient.GetGuildVoiceRegionsAsync(guild.Id, options).ConfigureAwait(false);

            return(models.Select(x => RestVoiceRegion.Create(client, x)).ToImmutableArray());
        }
コード例 #6
0
ファイル: LogCommand.cs プロジェクト: Chewsterchew/NadekoBot
            private static ITextChannel TryGetLogChannel(IGuild guild, LogSetting logSetting, LogChannelType logChannelType = LogChannelType.Text)
            {
                ulong id = 0;
                switch (logChannelType)
                {
                    case LogChannelType.Text:
                        id = logSetting.ChannelId;
                        break;
                    case LogChannelType.Voice:
                        id = logSetting.VoicePresenceChannelId;
                        break;
                    case LogChannelType.UserPresence:
                        id = logSetting.UserPresenceChannelId;
                        break;
                }
                var channel = guild.GetTextChannel(id);

                if (channel == null)
                    using (var uow = DbHandler.UnitOfWork())
                    {
                        var newLogSetting = uow.GuildConfigs.For(guild.Id).LogSetting;
                        switch (logChannelType)
                        {
                            case LogChannelType.Text:
                                logSetting.IsLogging = false;
                                break;
                            case LogChannelType.Voice:
                                logSetting.LogVoicePresence = false;
                                break;
                            case LogChannelType.UserPresence:
                                logSetting.LogUserPresence = false;
                                break;
                        }
                        GuildLogSettings.AddOrUpdate(guild.Id, newLogSetting, (gid, old) => newLogSetting);
                        uow.Complete();
                        return null;
                    }
                else
                    return channel;
            }
コード例 #7
0
 public static async Task DeleteAsync(IGuild guild, BaseDiscordClient client,
                                      RequestOptions options)
 {
     await client.ApiClient.DeleteGuildAsync(guild.Id, options).ConfigureAwait(false);
 }
コード例 #8
0
        //General
        /// <exception cref="ArgumentNullException"><paramref name="func"/> is <c>null</c>.</exception>
        public static async Task <Model> ModifyAsync(IGuild guild, BaseDiscordClient client,
                                                     Action <GuildProperties> func, RequestOptions options)
        {
            if (func == null)
            {
                throw new ArgumentNullException(nameof(func));
            }

            var args = new GuildProperties();

            func(args);

            var apiArgs = new API.Rest.ModifyGuildParams
            {
                AfkChannelId                = args.AfkChannelId,
                AfkTimeout                  = args.AfkTimeout,
                SystemChannelId             = args.SystemChannelId,
                DefaultMessageNotifications = args.DefaultMessageNotifications,
                Icon              = args.Icon.IsSpecified ? args.Icon.Value?.ToModel() : Optional.Create <ImageModel?>(),
                Name              = args.Name,
                Splash            = args.Splash.IsSpecified ? args.Splash.Value?.ToModel() : Optional.Create <ImageModel?>(),
                VerificationLevel = args.VerificationLevel
            };

            if (args.AfkChannel.IsSpecified)
            {
                apiArgs.AfkChannelId = args.AfkChannel.Value.Id;
            }
            else if (args.AfkChannelId.IsSpecified)
            {
                apiArgs.AfkChannelId = args.AfkChannelId.Value;
            }

            if (args.SystemChannel.IsSpecified)
            {
                apiArgs.SystemChannelId = args.SystemChannel.Value.Id;
            }
            else if (args.SystemChannelId.IsSpecified)
            {
                apiArgs.SystemChannelId = args.SystemChannelId.Value;
            }

            if (args.Owner.IsSpecified)
            {
                apiArgs.OwnerId = args.Owner.Value.Id;
            }
            else if (args.OwnerId.IsSpecified)
            {
                apiArgs.OwnerId = args.OwnerId.Value;
            }

            if (args.Region.IsSpecified)
            {
                apiArgs.RegionId = args.Region.Value.Id;
            }
            else if (args.RegionId.IsSpecified)
            {
                apiArgs.RegionId = args.RegionId.Value;
            }

            if (!apiArgs.Splash.IsSpecified && guild.SplashId != null)
            {
                apiArgs.Splash = new ImageModel(guild.SplashId);
            }
            if (!apiArgs.Icon.IsSpecified && guild.IconId != null)
            {
                apiArgs.Icon = new ImageModel(guild.IconId);
            }

            return(await client.ApiClient.ModifyGuildAsync(guild.Id, apiArgs, options).ConfigureAwait(false));
        }
コード例 #9
0
ファイル: GuildInviteStatus.cs プロジェクト: wtfcolt/game
 /// <summary>
 /// Initializes the values of this object.
 /// </summary>
 /// <param name="guild">The guild.</param>
 /// <param name="inviteTime">The invite time.</param>
 internal void Initialize(IGuild guild, TickCount inviteTime)
 {
     _guild = guild;
     _inviteTime = inviteTime;
 }
コード例 #10
0
ファイル: EphemeralUser.cs プロジェクト: Perksey/MODiX
 public EphemeralUser WithGuildContext(IGuild guild)
 {
     if (guild is { })
コード例 #11
0
ファイル: FilterService.cs プロジェクト: samuelwhx/NadekoBot
 public async Task <bool> TryBlockEarly(IGuild guild, IUserMessage msg)
 => !(msg.Author is IGuildUser gu)     //it's never filtered outside of guilds, and never block administrators
コード例 #12
0
 public static bool HasCooldown(Command cmd, IGuild guild, IUser user)
 {
     if (guild == null)
         return false;
     var cmdcds = CmdCdsCommands.commandCooldowns.GetOrAdd(guild.Id, new ConcurrentHashSet<CommandCooldown>());
     CommandCooldown cdRule;
     if ((cdRule = cmdcds.FirstOrDefault(cc => cc.CommandName == cmd.Text.ToLowerInvariant())) != null)
     {
         var activeCdsForGuild = activeCooldowns.GetOrAdd(guild.Id, new ConcurrentHashSet<ActiveCooldown>());
         if (activeCdsForGuild.FirstOrDefault(ac => ac.UserId == user.Id && ac.Command == cmd.Text.ToLowerInvariant()) != null)
         {
             return true;
         }
         else
         {
             activeCdsForGuild.Add(new ActiveCooldown()
             {
                 UserId = user.Id,
                 Command = cmd.Text.ToLowerInvariant(),
             });
             var t = Task.Run(async () =>
             {
                 try
                 {
                     await Task.Delay(cdRule.Seconds * 1000);
                     activeCdsForGuild.RemoveWhere(ac => ac.Command == cmd.Text.ToLowerInvariant() && ac.UserId == user.Id);
                 }
                 catch { }
             });
         }
     }
     return false;
 }
コード例 #13
0
 public Task ServerBlacklist(AddRemove action, IGuild guild)
 => Blacklist(action, guild.Id, BlacklistType.Server);
コード例 #14
0
 public Task ResumeAudioAsync(IGuild guild)
 {
     throw new NotImplementedException();
 }
コード例 #15
0
 public ReplacementBuilder WithDefault(IUser user, IMessageChannel channel, IGuild guild, DiscordSocketClient client)
 => WithUser(user)
 .WithChannel(channel)
 .WithServer(client, guild)
 .WithClient(client);
 public UserTypeParserInput(IGuild guild, string username)
 {
     Guild    = guild;
     Username = username;
 }
コード例 #17
0
 public string GetPrefix(IGuild guild) => GetPrefix(guild?.Id);
コード例 #18
0
 public override async Task UploadDatabaseBackupAsync(IMessageChannel channel, IGuild guild)
 {
     await UploadDatabaseBackupAsync(channel, DatabaseFilePath);
 }
コード例 #19
0
        public static async Task <string> GetBestScores()
        {
            var scores = await Program.p.db.GetAllScores();

            string globalRankingStr = "";
            Dictionary <string, int> globalRanking = new Dictionary <string, int>();

            foreach (var s in scores)
            {
                int sScore = 0;
                foreach (var elem in s.Value)
                {
                    int best = scores.Where(x => x.Value.ContainsKey(elem.Key)).Max(x => int.Parse(x.Value[elem.Key].Split('|')[0]));
                    sScore += int.Parse(elem.Value.Split('|')[0]) * 100 / best;
                }
                if (sScore > 0)
                {
                    globalRanking.Add(s.Key, sScore);
                }
            }
            int i = 0;

            while (i < 5 && globalRanking.Count > 0)
            {
                var    elem  = globalRanking.First(x => x.Value.Equals(globalRanking.Values.Max()));
                IGuild guild = Program.p.client.GetGuild(ulong.Parse(elem.Key));
                if (guild != null && guild.Name != null)
                {
                    if (globalRankingStr != "")
                    {
                        globalRankingStr += "|";
                    }
                    globalRankingStr += Program.p.GetName(guild.Name) + "|" + (elem.Value / Constants.allRankedGames.Length);
                    i++;
                }
                globalRanking.Remove(elem.Key);
            }
            StringBuilder finalStr = new StringBuilder();

            // Output format: Game1Place1Server | Game1Place1Score | Game1Place2Server..... Game1Place3Score $ Game2Place1Server | Game2Place1Score
            foreach (var game in Constants.allRankedGames)
            {
                APreload preload  = (APreload)Activator.CreateInstance(game.Item1);
                string   gameName = preload.GetGameName();

                // Prepare array containing all games serverId/score
                List <Tuple <string, string> > allScores = new List <Tuple <string, string> >();
                foreach (var elem in scores)
                {
                    if (elem.Value.ContainsKey(gameName))
                    {
                        allScores.Add(new Tuple <string, string>(elem.Key, elem.Value[gameName].Split('|')[0]));
                    }
                }
                List <Tuple <string, int> > best = new List <Tuple <string, int> >();
                string        bestServer;
                int           bestScore;
                List <string> alreadySaid = new List <string>();
                while (best.Count < 5 && allScores.Count > alreadySaid.Count)
                {
                    bestServer = null;
                    bestScore  = -1;
                    foreach (var elem in allScores)
                    {
                        int score = int.Parse(elem.Item2);
                        if (!alreadySaid.Contains(elem.Item1) && (bestServer == null || score > bestScore))
                        {
                            bestServer = elem.Item1;
                            bestScore  = score;
                        }
                    }
                    alreadySaid.Add(bestServer);
                    IGuild guild = Program.p.client.GetGuild(ulong.Parse(bestServer));
                    if (guild != null)
                    {
                        var name = Program.p.client.GetGuild(ulong.Parse(bestServer)).Name;
                        if (name != null)
                        {
                            best.Add(new Tuple <string, int>(Program.p.GetName(name), bestScore));
                        }
                    }
                }
                finalStr.Append(string.Join("|", best.Select(x => x.Item1 + "|" + x.Item2)) + "$");
            }
            return(globalRankingStr + "$" + finalStr);
        }
コード例 #20
0
 private string GetText(IGuild server, ITextChannel channel, IGuildUser user, IUserMessage message) =>
     $"**{server.Name} | {channel.Name}** `{user.Username}`: " + message.Content;
コード例 #21
0
 public static async Task ReorderChannelsAsync(IGuild guild, BaseDiscordClient client,
                                               IEnumerable <ReorderChannelProperties> args, RequestOptions options)
 {
     var apiArgs = args.Select(x => new API.Rest.ModifyGuildChannelsParams(x.Id, x.Position));
     await client.ApiClient.ModifyGuildChannelsAsync(guild.Id, apiArgs, options).ConfigureAwait(false);
 }
コード例 #22
0
        private static async Task <string> GetLeaderboardStringAsync(IEnumerable <IGrouping <ulong, KeyValuePair <ulong, MessageData> > > userMessageGroups, IGuild guild, uint page, uint pageCount)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("✨⭐🌟 🏆 Star Leaderboard 🏆 🌟⭐✨\n\n");

            uint index     = 1 + ((page - 1) * ENTRIES_PER_PAGE);
            uint lastIndex = index;
            long lastCount = Int64.MaxValue;

            foreach (IGrouping <ulong, KeyValuePair <ulong, MessageData> > userMsgGroup in userMessageGroups)
            {
                long sum = userMsgGroup.Sum(mKv => mKv.Value.GetStarCount());

                if (sum < lastCount)
                {
                    lastIndex = index;
                    lastCount = sum;
                }

                AddUserLeaderboardRow(
                    await guild.GetUserAsync(userMsgGroup.Key),
                    sum,
                    sb,
                    lastIndex == 1 ? "**🥇" :
                    lastIndex == 2 ? "🥈" :
                    lastIndex == 3 ? "🥉" :
                    lastIndex.ToString() + "th",
                    lastIndex == 1 ? "**" : String.Empty
                    );

                if (lastIndex <= 3)
                {
                    sb.Append('\n');
                }

                index++;
            }

            sb.Append("*Page ");
            sb.Append(page);
            sb.Append(" of ");
            sb.Append(pageCount);
            sb.Append("*");
            return(sb.ToString());
        }
コード例 #23
0
ファイル: HelpService.cs プロジェクト: Trigger17/Ene-Bot
        private string GetText(string text, IGuild guild, params object[] replacements) =>

        _strings.GetText(text, guild?.Id, "Help".ToLowerInvariant(), replacements);
コード例 #24
0
ファイル: PermissionsService.cs プロジェクト: tepup/LinBot
        public async Task <bool> TryBlockLate(DiscordSocketClient client, IUserMessage msg, IGuild guild, IMessageChannel channel, IUser user, string moduleName, string commandName)
        {
            await Task.Yield();

            if (guild == null)
            {
                return(false);
            }
            else
            {
                var resetCommand = commandName == "resetperms";

                PermissionCache pc = GetCache(guild.Id);
                if (!resetCommand && !pc.Permissions.CheckPermissions(msg, commandName, moduleName, out int index))
                {
                    if (pc.Verbose)
                    {
                        try { await channel.SendErrorAsync(_strings.GetText("trigger", guild.Id, "Permissions".ToLowerInvariant(), index + 1, Format.Bold(pc.Permissions[index].GetCommand(_cmd.GetPrefix(guild), (SocketGuild)guild)))).ConfigureAwait(false); } catch { }
                    }
                    return(true);
                }


                if (moduleName == "Permissions")
                {
                    var roles = (user as SocketGuildUser)?.Roles ?? ((IGuildUser)user).RoleIds.Select(x => guild.GetRole(x)).Where(x => x != null);
                    if (!roles.Any(r => r.Name.Trim().ToLowerInvariant() == pc.PermRole.Trim().ToLowerInvariant()) && user.Id != ((IGuildUser)user).Guild.OwnerId)
                    {
                        var returnMsg = $"You need the **{pc.PermRole}** role in order to use permission commands.";
                        if (pc.Verbose)
                        {
                            try { await channel.SendErrorAsync(returnMsg).ConfigureAwait(false); } catch { }
                        }
                        return(true);
                    }
                }
            }

            return(false);
        }
コード例 #25
0
 internal RestGuildIntegration(BaseDiscordClient discord, IGuild guild, ulong id)
     : base(discord, id)
 {
     Guild = guild;
 }
コード例 #26
0
ファイル: PermissionCheck.cs プロジェクト: KianFitz/STDTBot
        private bool CommandAllowedByRole(CommandInfo command, STDTContext db, IGuildUser user, IGuild guild)
        {
            var perm = db.CommandRolePermissions.Find(command.Name);

            if (perm is null)
            {
                return(true);
            }

            var guildRoles  = guild.Roles;
            var userMinRole = guild.GetRole((ulong)perm.MinimumRole);

            foreach (var role in guildRoles)
            {
                if (role.Position >= userMinRole.Position)
                {
                    return(true);
                }
            }

            return(false);
        }
コード例 #27
0
        public async Task <PunishmentAction?> Warn(IGuild guild, ulong userId, string modName, string reason)
        {
            if (string.IsNullOrWhiteSpace(reason))
            {
                reason = "-";
            }

            var guildId = guild.Id;

            var warn = new Warning()
            {
                UserId    = userId,
                GuildId   = guildId,
                Forgiven  = false,
                Reason    = reason,
                Moderator = modName,
            };

            int warnings = 1;
            List <WarningPunishment> ps;

            using (var uow = _db.UnitOfWork)
            {
                ps = uow.GuildConfigs.For(guildId, set => set.Include(x => x.WarnPunishments))
                     .WarnPunishments;

                warnings += uow.Warnings
                            .For(guildId, userId)
                            .Where(w => !w.Forgiven && w.UserId == userId)
                            .Count();

                uow.Warnings.Add(warn);

                uow.Complete();
            }

            var p = ps.FirstOrDefault(x => x.Count == warnings);

            if (p != null)
            {
                var user = await guild.GetUserAsync(userId);

                if (user == null)
                {
                    return(null);
                }
                switch (p.Punishment)
                {
                case PunishmentAction.Mute:
                    if (p.Time == 0)
                    {
                        await _mute.MuteUser(user).ConfigureAwait(false);
                    }
                    else
                    {
                        await _mute.TimedMute(user, TimeSpan.FromMinutes(p.Time)).ConfigureAwait(false);
                    }
                    break;

                case PunishmentAction.Kick:
                    await user.KickAsync("Warned too many times.").ConfigureAwait(false);

                    break;

                case PunishmentAction.Ban:
                    await guild.AddBanAsync(user, reason : "Warned too many times.").ConfigureAwait(false);

                    break;

                case PunishmentAction.Softban:
                    await guild.AddBanAsync(user, 7, reason : "Warned too many times").ConfigureAwait(false);

                    try
                    {
                        await guild.RemoveBanAsync(user).ConfigureAwait(false);
                    }
                    catch
                    {
                        await guild.RemoveBanAsync(user).ConfigureAwait(false);
                    }
                    break;

                case PunishmentAction.RemoveRoles:
                    await user.RemoveRolesAsync(user.GetRoles().Where(x => x.Id != guild.EveryoneRole.Id));

                    break;

                default:
                    break;
                }
                return(p.Punishment);
            }

            return(null);
        }
コード例 #28
0
        public static async Task <IReadOnlyCollection <RoleModel> > ReorderRolesAsync(IGuild guild, BaseDiscordClient client,
                                                                                      IEnumerable <ReorderRoleProperties> args, RequestOptions options)
        {
            var apiArgs = args.Select(x => new API.Rest.ModifyGuildRolesParams(x.Id, x.Position));

            return(await client.ApiClient.ModifyGuildRolesAsync(guild.Id, apiArgs, options).ConfigureAwait(false));
        }
コード例 #29
0
ファイル: Votekick.cs プロジェクト: Fjoksch/Cirilla
        private async void Kick(IGuildUser user, IUserMessage message, IGuild guild)
        {
            try {
                if (await guild.GetUserAsync(user.Id) == null)
                {
                    //already kicked by ReactionAdded event or server left
                    return;
                }

                List <IUser> yesUser = new List <IUser>(await message.GetReactionUsersAsync(Information.VotekickYes));
                List <IUser> noUser  = new List <IUser>(await message.GetReactionUsersAsync(Information.VotekickNo));

                string nl = Environment.NewLine;

                // -1 for own reaction
                int yes = yesUser.Count - 1;
                int no  = noUser.Count - 1;
                //only users in a voice channel can votekick
                int online = new List <IGuildUser>(((await guild.GetUsersAsync()).Where(u => (u.Status == UserStatus.Online && u.VoiceChannel != null)))).Count;

                //more than half of server users voted yes
                if (yes > online / 2 && no < yes)
                {
                    //check if admin voted no -> dismiss vote
                    foreach (IUser iuser in noUser)
                    {
                        if (CheckIfAdmin(iuser as IGuildUser))
                        {
                            await message.Channel.SendMessageAsync($"An admin voted _no_, _{Helper.GetName(user)}_ cannot be kicked!");

                            return;
                        }
                    }

                    IInviteMetadata invite = await((IGuildChannel)message.Channel).CreateInviteAsync(maxUses: 1);
                    try {
                        IDMChannel dm = await user.CreateDMChannelAsync();

                        await dm.SendMessageAsync($"You've been kicked from the _{guild.Name}_ guild by votekick!" + nl +
                                                  $"As I'm very generous today, here's an invite link to the _{guild.Name}_ guild:" + nl + invite.Url);
                    } catch {
                        //user is not allowing DMs?
                        await message.Channel.SendMessageAsync($"{Helper.GetName(user)} is not allowing private messages, " +
                                                               "someone gotta send him an invite link again.." + nl + invite.Url);
                    }
                    await user.KickAsync();

                    await message.Channel.SendMessageAsync($"You bullies kicked the poor {Helper.GetName(user)}..");

                    try {
                        Cirilla.Client.ReactionAdded -= ReactionAdded;
                    } catch {
                        //event removed
                    }
                }
                else
                {
                    await message.Channel.SendMessageAsync($"Time's up. Less than half of the online users ({yes}) " +
                                                           $"voted to kick {Helper.GetName(user)}. Votekick dismissed.");
                }
            } catch {
                await message.Channel.SendMessageAsync($"Could not kick {Helper.GetName(user)}.. :confused:");
            }
        }
コード例 #30
0
        public static async Task <RestBan> GetBanAsync(IGuild guild, BaseDiscordClient client, ulong userId, RequestOptions options)
        {
            var model = await client.ApiClient.GetGuildBanAsync(guild.Id, userId, options).ConfigureAwait(false);

            return(RestBan.Create(client, model));
        }
コード例 #31
0
 public static IPagedEnumerable <IAuditLog> EnumerateAuditLogs(this IGuild guild,
                                                               int limit, Snowflake?actorId = null, Snowflake?startFromId = null,
                                                               IRestRequestOptions options  = null)
 {
     return(guild.EnumerateAuditLogs <IAuditLog>(limit, actorId, startFromId, options));
 }
コード例 #32
0
 public static async Task RemoveBanAsync(IGuild guild, BaseDiscordClient client,
                                         ulong userId, RequestOptions options)
 {
     await client.ApiClient.RemoveGuildBanAsync(guild.Id, userId, options).ConfigureAwait(false);
 }
コード例 #33
0
 public static Task <IReadOnlyList <IAuditLog> > FetchAuditLogsAsync(this IGuild guild,
                                                                     int limit = Discord.Limits.Rest.FetchAuditLogsPageSize, Snowflake?actorId = null, Snowflake?startFromId = null,
                                                                     IRestRequestOptions options = null, CancellationToken cancellationToken   = default)
 {
     return(guild.FetchAuditLogsAsync <IAuditLog>(limit, actorId, startFromId, options, cancellationToken));
 }
コード例 #34
0
ファイル: LogCommand.cs プロジェクト: Chewsterchew/NadekoBot
            private Task _client_UserBanned(IUser usr, IGuild guild)
            {
                LogSetting logSetting;
                if (!GuildLogSettings.TryGetValue(guild.Id, out logSetting)
                    || !logSetting.IsLogging
                    || !logSetting.UserBanned)
                    return Task.CompletedTask;

                ITextChannel logChannel;
                if ((logChannel = TryGetLogChannel(guild, logSetting)) == null)
                    return Task.CompletedTask;

                var task = Task.Run(async () =>
                {
                    try { await logChannel.SendMessageAsync($"‼️🕕`{prettyCurrentTime}`👤__**{usr.Username}#{usr.Discriminator}**__🚫 **| USER BANNED |** 🆔 `{usr.Id}`").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); }
                });

                return Task.CompletedTask;
            }
コード例 #35
0
        public static Task <IReadOnlyList <IGuildVoiceRegion> > FetchVoiceRegionsAsync(this IGuild guild,
                                                                                       IRestRequestOptions options = null, CancellationToken cancellationToken = default)
        {
            var client = guild.GetRestClient();

            return(client.FetchGuildVoiceRegionsAsync(guild.Id, options, cancellationToken));
        }
コード例 #36
0
        public static Task <IReadOnlyList <TAuditLog> > FetchAuditLogsAsync <TAuditLog>(this IGuild guild,
                                                                                        int limit = Discord.Limits.Rest.FetchAuditLogsPageSize, Snowflake?actorId = null, Snowflake?startFromId = null,
                                                                                        IRestRequestOptions options = null, CancellationToken cancellationToken   = default)
            where TAuditLog : class, IAuditLog
        {
            var client = guild.GetRestClient();

            return(client.FetchAuditLogsAsync <TAuditLog>(guild.Id, limit, actorId, startFromId, options, cancellationToken));
        }
コード例 #37
0
        /*
         * Application Commands
         */
        public static Task <IReadOnlyList <IApplicationCommand> > FetchApplicationCommandsAsync(this IGuild guild,
                                                                                                Snowflake applicationId,
                                                                                                IRestRequestOptions options = null, CancellationToken cancellationToken = default)
        {
            var client = guild.GetRestClient();

            return(client.FetchGuildApplicationCommandsAsync(applicationId, guild.Id, options, cancellationToken));
        }
コード例 #38
0
ファイル: Timeout.cs プロジェクト: stepperman/HB-Discord-Bot
 public TimeoutInfo(List<TimedoutUser> users, TimedoutUser info,
     IGuildUser user, IGuild guild)
 {
     this.users = users;
     this.info = info;
     this.user = user;
     this.guild = guild;
 }
コード例 #39
0
 /// <summary>
 ///     Gets if guild setup system messages are enabled.
 /// </summary>
 /// <param name="guild"> The guild to check. </param>
 /// <returns> A <c>bool</c> indicating if the guild setup messages are enabled in the system channel. </returns>
 public static bool GetGuildSetupTipMessagesEnabled(this IGuild guild)
 => !guild.SystemChannelFlags.HasFlag(SystemChannelMessageDeny.GuildSetupTip);
コード例 #40
0
        public async Task Donators(IUserMessage umsg)
        {
            var channel = (ITextChannel)umsg.Channel;
            IEnumerable<Donator> donatorsOrdered;

            using (var uow = DbHandler.UnitOfWork())
            {
                donatorsOrdered = uow.Donators.GetDonatorsOrdered();
            }

            string str = $"**Thanks to the people listed below for making this project happen!**\n";
            await channel.SendMessageAsync(str + string.Join("⭐", donatorsOrdered.Select(d => d.Name))).ConfigureAwait(false);
            
            nadekoSupportServer = nadekoSupportServer ?? NadekoBot.Client.GetGuild(117523346618318850);

            if (nadekoSupportServer == null)
                return;

            var patreonRole = nadekoSupportServer.GetRole(236667642088259585);
            if (patreonRole == null)
                return;

            var usrs = nadekoSupportServer.GetUsers().Where(u => u.Roles.Contains(patreonRole));
            await channel.SendMessageAsync("\n`Patreon supporters:`\n" + string.Join("⭐", usrs.Select(d => d.Username))).ConfigureAwait(false);
        }
コード例 #41
0
 /// <summary>
 ///     Gets if guild welcome messages have a reply with sticker button.
 /// </summary>
 /// <param name="guild"> The guild to check. </param>
 /// <returns> A <c>bool</c> indicating if the guild welcome messages have a reply with sticker button. </returns>
 public static bool GetGuildWelcomeMessageReplyEnabled(this IGuild guild)
 => !guild.SystemChannelFlags.HasFlag(SystemChannelMessageDeny.WelcomeMessageReply);
コード例 #42
0
ファイル: UserGuildInformation.cs プロジェクト: wtfcolt/game
        /// <summary>
        /// Appends a message to a <see cref="BitStream"/> for synchronizing the client's guild information for when
        /// the guild changes or the user is receiving their first update on the guild state and all values have to be sent.
        /// The message is then read and handled by the receiver using <see cref="UserGuildInformation.Read"/>.
        /// </summary>
        /// <param name="pw">The <see cref="BitStream"/> to append the message to.</param>
        /// <param name="guild">The guild to send the state values for.</param>
        public static void WriteGuildInfo(BitStream pw, IGuild guild)
        {
            pw.WriteEnum(GuildInfoMessages.SetGuild);

            if (guild == null)
            {
                pw.Write(false);
                return;
            }

            var members = guild.GetMembers().ToArray();
            var onlineMembers = guild.OnlineMembers.ToArray();

            pw.Write(true);
            pw.Write(guild.Name);
            pw.Write(guild.Tag);

            pw.Write((ushort)members.Length);
            for (var i = 0; i < members.Length; i++)
            {
                pw.Write(null, members[i]);
            }

            pw.Write((ushort)onlineMembers.Length);
            for (var i = 0; i < onlineMembers.Length; i++)
            {
                pw.Write(onlineMembers[i].Name);
            }
        }
コード例 #43
0
 public Task ServerBlacklist(IUserMessage imsg, AddRemove action, IGuild guild)
     => Blacklist(imsg, action, guild.Id, BlacklistType.Server);
コード例 #44
0
ファイル: GuildInviteStatus.cs プロジェクト: wtfcolt/game
 /// <summary>
 /// Resets the values of this object.
 /// </summary>
 internal void Reset()
 {
     _guild = null;
     _inviteTime = TickCount.MinValue;
 }
コード例 #45
0
        public static string GetCommand(this Permission perm, IGuild 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:
                    if (guild == null)
                        com += $"<@{perm.PrimaryTargetId}>";
                    else
                        com += guild.GetUser(perm.PrimaryTargetId).ToString() ?? $"<@{perm.PrimaryTargetId}>";
                    break;
                case PrimaryPermissionType.Channel:
                    com += $"<#{perm.PrimaryTargetId}>";
                    break;
                case PrimaryPermissionType.Role:
                    if(guild == null)
                        com += $"<@&{perm.PrimaryTargetId}>";
                    else
                        com += guild.GetRole(perm.PrimaryTargetId).ToString() ?? $"<@{perm.PrimaryTargetId}>";
                    break;
                case PrimaryPermissionType.Server:
                    break;
            }

            return NadekoBot.ModulePrefixes[typeof(Permissions).Name] + com;
        }