Ejemplo n.º 1
0
        private void Vnc_VoiceDisconnected(DiscordGuild guild)
        {
            VoiceNextConnection vnc = null;

            if (this.ActiveConnections.ContainsKey(guild.Id))
            {
                this.ActiveConnections.TryRemove(guild.Id, out vnc);
            }

            var vsd = new VoiceDispatch
            {
                OpCode  = 4,
                Payload = new VoiceStateUpdatePayload
                {
                    GuildId   = guild.Id,
                    ChannelId = null
                }
            };
            var vsj = JsonConvert.SerializeObject(vsd, Formatting.None);

            (guild.Discord as DiscordClient)._webSocketClient.SendMessage(vsj);
        }
Ejemplo n.º 2
0
        private async Task Vnc_VoiceDisconnected(DiscordGuild guild)
        {
            VoiceNextConnection vnc = null;

            if (this.ActiveConnections.ContainsKey(guild.Id))
            {
                this.ActiveConnections.TryRemove(guild.Id, out vnc);
            }

            var vsd = new VoiceDispatch
            {
                OpCode  = 4,
                Payload = new VoiceStateUpdatePayload
                {
                    GuildId   = guild.Id,
                    ChannelId = null
                }
            };
            var vsj = JsonConvert.SerializeObject(vsd, Formatting.None);

            await(guild.Discord as DiscordClient).WsSendAsync(vsj).ConfigureAwait(false);
        }
Ejemplo n.º 3
0
        public static IEnumerable <IMention> ParseAllMentions(this string input, bool allowEveryone = false,
                                                              DiscordGuild guild = null)
        {
            var mentions = new List <IMention>();

            mentions.AddRange(USER_MENTION.Matches(input)
                              .Select(x => new UserMention(ulong.Parse(x.Groups[1].Value)) as IMention));

            // Only allow role mentions through where the role is actually listed as *mentionable*
            // (ie. any user can @ them, regardless of permissions)
            // Still let the allowEveryone flag override this though (privileged users can @ *any* role)
            // Original fix by Gwen
            mentions.AddRange(ROLE_MENTION.Matches(input)
                              .Select(x => ulong.Parse(x.Groups[1].Value))
                              .Where(x => allowEveryone || guild != null && guild.GetRole(x).IsMentionable)
                              .Select(x => new RoleMention(x) as IMention));
            if (EVERYONE_HERE_MENTION.IsMatch(input) && allowEveryone)
            {
                mentions.Add(new EveryoneMention());
            }
            return(mentions);
        }
Ejemplo n.º 4
0
        protected override async Task UpdateInternal(DiscordLink plugin, DLEventType trigger, object data)
        {
            if (!(data is WorkOrderAction craftingEvent))
            {
                return;
            }
            if (craftingEvent.Citizen == null)
            {
                return;                                // Happens when a crafting table contiues crafting after finishing an item
            }
            if (craftingEvent.MarkedUpName != "Create Work Order")
            {
                return;                                                    // Happens when a player feeds materials to a blocked work order
            }
            string itemName = craftingEvent.OrderCount > 1 ? craftingEvent.CraftedItem.DisplayNamePlural : craftingEvent.CraftedItem.DisplayName;
            string message  = $"**{craftingEvent.Citizen.Name}** started crafting {craftingEvent.OrderCount} `{itemName}` at {(craftingEvent.WorldObject as WorldObject).Name}.";

            foreach (ChannelLink craftingChannel in DLConfig.Data.CraftingChannels)
            {
                if (!craftingChannel.IsValid())
                {
                    continue;
                }
                DiscordGuild discordGuild = plugin.GuildByNameOrId(craftingChannel.DiscordGuild);
                if (discordGuild == null)
                {
                    continue;
                }
                DiscordChannel discordChannel = discordGuild.ChannelByNameOrId(craftingChannel.DiscordChannel);
                if (discordChannel == null)
                {
                    continue;
                }
                await DiscordUtil.SendAsync(discordChannel, message);

                ++_opsCount;
            }
        }
Ejemplo n.º 5
0
        private async Task OnMessage(DiscordClient client, DiscordGuild guild, DiscordUser author, DiscordChannel channel, DiscordMessage message)
        {
            if (guild.Id != this._Guild.Id)
            {
                return;
            }

            var member = await this._Guild.GetMemberAsync(author.Id);

            if (member == null)
            {
                return;
            }

            if (channel.Parent != this._ParentChannel)
            {
                return;
            }

            // if player is not bot
            if (member != client.CurrentUser)
            {
                var player = await GetOrCreatePlayer(member);

                if (player.Room is null)
                {
                    player.Reply("Please join a voice channel");
                }
                else if (_PlayerNameToDiscordChannel.TryGetValue(player.NormalizedName, out DiscordChannel playerChannel))
                {
                    if (channel is not null && channel == playerChannel)
                    {
                        var cmd = new BaseCommand <TGame, TPlayer, TRoom, TContainer, TThing>(player, message.Content);
                        Game.RaiseCommand(cmd);
                    }
                }
            }
        }
Ejemplo n.º 6
0
        public async Task Birth(CommandContext context)
        {
            if (interactivity == null)
            {
                nickname = Nickname(context.User.ToString());

                interactivity = context.Client.GetInteractivity();

                museifu = context.Guild;

                LoadAlerts(context);

                string schedule = await Schedule.GenerateSchedule();

                timer = await context.RespondAsync($"Aloha! Let me get the timer running!\n\n" +
                                                   $"{schedule}\n" +
                                                   $"Please feel free to help us keep track of **field bosses** and **Golden Bells** by letting me know where you spot them!\n\n" +
                                                   $"You are also welcome to share this timer with any friendly spirits who cross your path.\n\n" +
                                                   $"https://discord.gg/ndVAvQ3");

                lastComment = await context.RespondAsync($"Health, wealth, and stealth, dachi! :wink: I hope you're having a lovely grind!");
            }

            if (context != null)
            {
                await context.Message.DeleteAsync();
            }

            try
            {
                await Existence();
            }
            catch (Exception error)
            {
                await CommandRespond(context, $"An strange error occurred! {error}");
                await Rebirth();
            }
        }
Ejemplo n.º 7
0
        public List <TransactionItem> GetTopTransactions(DiscordGuild guild)
        {
            var data = MultiBotDb.Transactions
                       .Join(
                MultiBotDb.Mcmember,
                trans => trans.UserId,
                mem => mem.UserId,
                (trans, mem) => new
            {
                memberName = mem.Username,
                orgId      = mem.OrgId.GetValueOrDefault(),
                amount     = trans.Amount,
                merits     = trans.Merits
            }
                ).Where(x => x.orgId == new OrgController().GetOrgId(guild) && x.amount != 0).OrderByDescending(x => x.amount).ToList();

            var transactions = new List <TransactionItem>();

            var length = data.Count;

            if (length < 3)
            {
                for (int i = 0; i < length; i++)
                {
                    transactions.Add(new TransactionItem(data[i].memberName, data[i].orgId, data[i].amount.GetValueOrDefault(), data[i].merits.GetValueOrDefault()));
                }
            }
            else
            {
                for (int i = 0; i <= 2; i++)
                {
                    transactions.Add(new TransactionItem(data[i].memberName, data[i].orgId, data[i].amount.GetValueOrDefault(), data[i].merits.GetValueOrDefault()));
                }
            }


            return(transactions);
        }
Ejemplo n.º 8
0
        public async Task <bool> RemoveModuleLimitAsync(DiscordGuild guild, IMessageChannel channel, string module)
        {
            using (var db = new ModixContext())
            {
                var limit = await db.ChannelLimits
                            .Where(c =>
                                   c.ModuleName.ToUpper() == module.ToUpper() &&
                                   c.Guild.Id == guild.Id &&
                                   c.ChannelId == channel.Id.ToLong())
                            .FirstOrDefaultAsync();

                if (limit != null)
                {
                    db.ChannelLimits.Remove(limit);

                    await db.SaveChangesAsync();

                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 9
0
        public static async Task LogFleetCreationAsync(DiscordGuild guild, DiscordMember member, DiscordChannel fleetCategory)
        {
            var embed = new DiscordEmbedBuilder
            {
                Title       = $"{fleetCategory.Name} создан",
                Description = $"`{fleetCategory.Id}`",
                Color       = DiscordColor.SpringGreen
            };

            var channels = "";

            foreach (var channel in fleetCategory.Children.OrderBy(x => x.Position))
            {
                channels += $"**{channel.Name}** \t\t `{channel.Id}` \n";
            }
            embed.AddField("Каналы", channels);


            embed.WithAuthor($"{member.Username}#{member.Discriminator}", iconUrl: member.AvatarUrl);
            embed.WithTimestamp(DateTime.Now);

            await guild.GetChannel(Bot.BotSettings.FleetLogChannel).SendMessageAsync(embed: embed.Build());
        }
Ejemplo n.º 10
0
            public async Task SetColor(DiscordMember user, DiscordGuild server, DiscordChannel channel, DiscordColor color)
            {
                IReadOnlyDictionary <ulong, DiscordRole> roles = server.Roles;
                DiscordRole existingRole = null;
                string      UserId       = user.Id.ToString();

                if (roles.Any(xr => xr.Value.Name == UserId))
                {
                    existingRole = roles.First(xr => xr.Value.Name == UserId).Value;
                    await existingRole.ModifyAsync(color : color, reason : "Coloring role edit");
                }
                else
                {
                    DiscordRole CreatedRole = await server.CreateRoleAsync(user.Id.ToString(), Permissions.None, color, null, null, "Coloring role creation");

                    await user.GrantRoleAsync(CreatedRole, "Coloring role assignment");
                }

                await channel.SendMessageAsync("Color set successfully.");

                Console.WriteLine("User {0}'s color was set to {1}", user.Username, color.R + ", " + color.G + ", " + color.B);
                return;
            }
Ejemplo n.º 11
0
        private async Task Discord_ChannelDeleted(ChannelDeleteEventArgs e)
        {
            var logs = (await e.Guild.GetAuditLogsAsync(5, null, AuditLogActionType.ChannelDelete).ConfigureAwait(false)).Cast <DiscordAuditLogChannelEntry>();

            foreach (var entry in logs)
            {
                Debug.Log("TargetId: " + entry.Target.Id, Discord);
            }

            //Check through the guild entries and make sure that theres no deleted recorded adresses
            foreach (guildData dataEntries in data)
            {
                ulong        guildID = dataEntries.guildId;
                DiscordGuild guild   = await Discord.GetGuildAsync(guildID);

                DiscordChannel channel = await Discord.GetChannelAsync(dataEntries.disabledChannelID);

                if (channel == null || dataEntries.disabledChannelID == 0)
                {
                    dataEntries.disabledChannelID = 0;
                }
            }
        }
Ejemplo n.º 12
0
        public async Task SayAsync(CommandContext ctx,
                                   [Description("Id of the guild where to post")] ulong guildId,
                                   [Description("Id of the text channel where to post")] ulong channelId,
                                   [RemainingText, Description("Message to post")] string message)
        {
            DiscordGuild guild = await ctx.Client.GetGuildAsync(guildId);

            if (guild == null)
            {
                await ctx.ErrorAsync("Guild not found");

                return;
            }
            DiscordChannel channel = guild.GetChannel(channelId);

            if (channel == null)
            {
                await ctx.ErrorAsync("Channel not found");

                return;
            }
            await channel.SendMessageAsync(message);
        }
Ejemplo n.º 13
0
        public static async Task CheckBacklogAsync(DiscordClient client, DiscordGuild guild)
        {
            try
            {
                var after = DateTime.UtcNow - Config.ModerationTimeThreshold;
                foreach (var channel in guild.Channels.Where(ch => !ch.IsCategory))
                {
                    var messages = await channel.GetMessagesAsync(500).ConfigureAwait(false);

                    var messagesToCheck = from msg in messages
                                          where msg.CreationTimestamp > after
                                          select msg;
                    foreach (var message in messagesToCheck)
                    {
                        await CheckMessageForInvitesAsync(client, message).ConfigureAwait(false);
                    }
                }
            }
            catch (Exception e)
            {
                Config.Log.Error(e);
            }
        }
Ejemplo n.º 14
0
        //TODO need a better way to store/specify permissions, and preferably one where no permissions is left out (because of my OCD)
        List <DiscordOverwriteBuilder> GeneratePermissionOverwrites(DiscordGuild guild, DiscordMember creator, ChannelPublicity publicity, params DiscordMember[] permittedMembers)
        {
            //TODO implement the ranking method that allows moderators to specify what roles have access to naming capabilities, publicity options, and bitrate options
            List <DiscordOverwriteBuilder> channelPermissionsBuilderList = new List <DiscordOverwriteBuilder>
            {
                new DiscordOverwriteBuilder().For(guild.EveryoneRole).Deny(Permissions.AccessChannels | Permissions.UseVoice),                                                                                                                                                                                                                                         //Prevent everyone from viewing any channel
                new DiscordOverwriteBuilder().For(registeredGuildData[guild].MemberRole).Allow(publicity == ChannelPublicity.Hidden ? Permissions.None : Permissions.AccessChannels).Deny(publicity == ChannelPublicity.Private ? Permissions.UseVoice : Permissions.None).Deny(publicity == ChannelPublicity.Hidden ? Permissions.AccessChannels : Permissions.None), //Allow members to see private channels
                new DiscordOverwriteBuilder().For(registeredGuildData[guild].MutedRole).Allow(publicity == ChannelPublicity.Hidden ? Permissions.None : Permissions.AccessChannels).Deny(Permissions.UseVoice | Permissions.Speak | Permissions.UseVoiceDetection | Permissions.Stream)                                                                                //Dissallow muted members from accessing or viewing
            };

            //TODO this might be redundant...need to test if the muted role overwrite will disallow the muted role from joining even if this allows them...though i think i know the behavior that the role system will produce
            //TODO may need to accomodate other blacklist roles
            foreach (var member in permittedMembers)
            {
                if (member.Roles.Contains(registeredGuildData[guild].MutedRole))
                {
                    continue;                                                                              //TODO we want to inform the creator this member was not whitelisted in the vc because they have the muted role
                }
                channelPermissionsBuilderList.Add(new DiscordOverwriteBuilder().For(member).Allow(Permissions.AccessChannels | Permissions.UseVoice | Permissions.Speak | Permissions.UseVoiceDetection | Permissions.Stream));
            }

            return(channelPermissionsBuilderList);
        }
Ejemplo n.º 15
0
        private async Task RequestLogin(DiscordMessage message)
        {
            if (!message.Channel.IsPrivate)
            {
                await message.RespondAsync(embed : PresetEmbeds.ErrorEmbed("This command must be run in a DM.", message).Build());
            }
            else
            {
                DiscordGuild streamGuild = messageEvent.Guild.GetChannel(StreamChannel).Guild;
                if (await streamGuild.GetMemberAsync(message.Author.Id) == null)
                {
                    await message.RespondAsync(embed : PresetEmbeds.ErrorEmbed($"We can't find you in our guild. are you part of {streamGuild.Name}?", message).Build());

                    return;
                }

                string signedId    = Hmac.SignMessage(message.Author.Id.ToString(), TokenKey);
                string encryptedId = StringCipher.Encrypt(signedId, TokenPassword);

                await message.RespondAsync(embed : PresetEmbeds.SuccessEmbed($"[Click here to login.]({ApiUrl}BotLogin?token={encryptedId})\n\n" +
                                                                             $"This link expires in 30 seconds.", message).Build());
            }
        }
Ejemplo n.º 16
0
        public async Task OutputBeeMovie(CommandContext context)
        {
            StringBuilder contentBuilder = new();

            DiscordGuild movieGuild = await context.Client.GetGuildAsync(this.options.Value.MovieEmojiGuildId);

            Dictionary <string, DiscordEmoji> movieEmojis = movieGuild.Emojis.Values.ToList().ToDictionary(emoji => emoji.Name);

            for (int row = 0; row < 5; row++)
            {
                for (int column = 0; column < 8; column++)
                {
                    contentBuilder.Append(movieEmojis[$"beemovie{column}x{row}"].ToString());
                }
                contentBuilder.AppendLine();
            }

            using FileStream fs = new(this.options.Value.MovieFilePath, FileMode.Open);
            DiscordMessageBuilder messageBuilder = new DiscordMessageBuilder().WithContent(contentBuilder.ToString());

            messageBuilder.WithFile("movie", fs);
            await context.RespondAsync(messageBuilder);
        }
Ejemplo n.º 17
0
    private async Task Client_Ready(ReadyEventArgs e)
    {
        if (!MainThreadQueue.Instance.IsMain())
        {
            MainThreadQueue.Instance.Queue(async() => await Client_Ready(e));
            return;
        }
        Debug.Log($"{Log.Timestamp()} Discord-ClientReady: Client is connected.");
        PushNotification.Instance.Push($"Connected as: {e.Client.CurrentUser.Username}", "Success");

        if (Client.Guilds.Count > 0)
        {
            Debug.Log($"Guild already exists. {Client.Guilds.First()}");
            return;
        }

        Guild = await Client.CreateGuildAsync(_guildName);

        var invite = await Guild.Channels.First().CreateInviteAsync();

        PushNotification.Instance.Push($"Invite: {invite}", "Success");
        OnInviteCreated?.Invoke(invite.ToString());
    }
Ejemplo n.º 18
0
        public CrabgileMeeting(DiscordMember hostMember)
        {
            this.hostMember = hostMember;
            guild           = hostMember.Guild;
            channels        = new ConcurrentBag <DiscordChannel>();

            if (!GuildMeetings.ContainsKey(guild.Id))
            {
                GuildMeetings.TryAdd(guild.Id, new ConcurrentDictionary <ulong, CrabgileMeeting>());
            }
            registrySuccess = GuildMeetings[guild.Id].TryAdd(hostMember.Id, this);

            if (registrySuccess)
            {
                Task.Run(async() => {
                    meetingCategory = await guild.CreateChannelCategoryAsync($"::{hostMember.Id}::");
                    AddChannelToMeeting(meetingCategory);
                    meetingTextChannel = await guild.CreateChannelAsync("meeting-chat", DSharpPlus.ChannelType.Text, meetingCategory, "A minuted text channel for the timebox meeting.");
                    //AddChannelToMeeting(meetingTextChannel);
                    //Don't add the channel to the bag, as it shouldn't get destroyed.
                });
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Using the cache, this will attempt to verify that the current bot can
        /// join the selected voice channel. If the cache does not have the required details,
        /// this will NOT throw an exception (the handshake timeout will handle invalid permission anyway).
        /// </summary>
        /// <exception cref="DiscordPermissionException"></exception>
        /// <exception cref="InvalidOperationException"></exception>
        void AssertUserCanJoin(Snowflake guildId, Snowflake voiceChannelId)
        {
            DiscordGuildMember       member       = cache.GetGuildMember(guildId, Shard.UserId.Value);
            DiscordGuild             guild        = cache.GetGuild(guildId);
            DiscordGuildVoiceChannel voiceChannel = cache.GetGuildVoiceChannel(voiceChannelId);

            if (member != null && guild != null && voiceChannel != null)
            {
                // Check if the user has permission to connect.
                DiscordPermissionHelper.AssertPermission(DiscordPermission.Connect, member, guild, voiceChannel);

                // Check if the voice channel has room
                bool channelHasRoom = false;
                if (voiceChannel.UserLimit == 0)
                {
                    channelHasRoom = true;
                }
                else if (DiscordPermissionHelper.HasPermission(DiscordPermission.Administrator, member, guild, voiceChannel))
                {
                    channelHasRoom = true;
                }
                else
                {
                    IReadOnlyList <Snowflake> usersInChannel = Shard.Voice.GetUsersInVoiceChannel(voiceChannelId);
                    if (usersInChannel.Count < voiceChannel.UserLimit)
                    {
                        channelHasRoom = true;
                    }
                }

                if (!channelHasRoom)
                {
                    throw new InvalidOperationException("The voice channel is full, and the current bot " +
                                                        "does not have the administrator permission.");
                }
            }
        }
Ejemplo n.º 20
0
        private async Task <bool> CheckIfHasPermissionAsync(DiscordUser discordUser, DiscordGuild discordGuild,
                                                            Guild dbGuild)
        {
            var hasPermission = false;
            var invoker       = await _botService.GetMemberAsync(dbGuild.GuildId, discordUser.Id);

            if (invoker.IsOwner)
            {
                hasPermission = true;
            }

            if (!hasPermission)
            {
                var managerIds = dbGuild.Managers.Select(m => m.UserId).ToList();
                if (managerIds.Contains(invoker.Id.ToString()))
                {
                    hasPermission = true;
                }
            }

            if (!hasPermission)
            {
                var moderatorRoleIds = dbGuild.AutoModPlugin.ModeratorRoles
                                       .Select(r => r.RoleId)
                                       .ToList();
                foreach (var roleId in invoker.Roles.Select(r => r.Id).ToList())
                {
                    if (moderatorRoleIds.Contains(roleId.ToString()))
                    {
                        hasPermission = true;
                        break;
                    }
                }
            }

            return(hasPermission);
        }
Ejemplo n.º 21
0
        private async Task SkipSong(DiscordGuild guild, DiscordChannel channel,
                                    LavalinkGuildConnection lvc, bool fromVoteSkip = false)
        {
            string title = ShimakazeBot.playlists[guild].songRequests[0].track.Title;

            ShimakazeBot.playlists[guild].songRequests.RemoveAt(0);
            bool wasLooping = false;

            if (ShimakazeBot.playlists[guild].loopCount > 0)
            {
                wasLooping = true;
                ShimakazeBot.playlists[guild].loopCount = 0;
            }

            if (ShimakazeBot.playlists[guild].songRequests.Count > 0)
            {
                await lvc.PlayAsync(ShimakazeBot.playlists[guild].songRequests.First().track);

                await CTX.SendSanitizedMessageAsync(channel,
                                                    $"Skipped *{title}*{(wasLooping ? " and stopped loop" : "")}." +
                                                    (fromVoteSkip ?
                                                     $"\nSkip requested by **{ShimakazeBot.playlists[guild].voteSkip.requester.DisplayName}**" :
                                                     ""));
            }
            else
            {
                await lvc.StopAsync();

                await CTX.SendSanitizedMessageAsync(channel, $"Playlist ended with skip. (Skipped *{title}*" +
                                                    $"{(wasLooping ? " and stopped loop" : "")})" +
                                                    (fromVoteSkip ?
                                                     $"\nSkip requested by **{ShimakazeBot.playlists[guild].voteSkip.requester.DisplayName}**" :
                                                     ""));
            }

            ShimakazeBot.playlists[guild].voteSkip = null;
        }
Ejemplo n.º 22
0
        private static async Task UpdateDisplayName(DiscordGuild guild, DiscordMember guildMember)
        {
            try
            {
                if (guildMember.IsWhitelisted())
                {
                    return;
                }

                if (guild.Permissions?.HasFlag(Permissions.ChangeNickname) is false)
                {
                    return;
                }

                await using var db = new BotDb();
                var forcedNickname = await db.ForcedNicknames.AsNoTracking().FirstOrDefaultAsync(x => x.UserId == guildMember.Id && x.GuildId == guildMember.Guild.Id).ConfigureAwait(false);

                if (forcedNickname is null)
                {
                    return;
                }

                if (guildMember.DisplayName == forcedNickname.Nickname)
                {
                    return;
                }

                Config.Log.Debug($"Expected nickname {forcedNickname.Nickname}, but was {guildMember.Nickname}. Renaming...");
                await guildMember.ModifyAsync(mem => mem.Nickname = forcedNickname.Nickname).ConfigureAwait(false);

                Config.Log.Info($"Enforced nickname {forcedNickname.Nickname} for user {guildMember.Id} ({guildMember.Username}#{guildMember.Discriminator})");
            }
            catch (Exception e)
            {
                Config.Log.Error(e);
            }
        }
Ejemplo n.º 23
0
        public static async Task <bool> CheckBansAsync()
        {
            DiscordChannel logChannel = await Program.discord.GetChannelAsync(Program.cfgjson.LogChannel);

            Dictionary <string, MemberPunishment> banList = Program.db.HashGetAll("bans").ToDictionary(
                x => x.Name.ToString(),
                x => JsonConvert.DeserializeObject <MemberPunishment>(x.Value)
                );

            if (banList == null | banList.Keys.Count == 0)
            {
                return(false);
            }
            else
            {
                // The success value will be changed later if any of the unmutes are successful.
                bool success = false;
                foreach (KeyValuePair <string, MemberPunishment> entry in banList)
                {
                    MemberPunishment banEntry    = entry.Value;
                    DiscordGuild     targetGuild = await Program.discord.GetGuildAsync(banEntry.ServerId);

                    if (DateTime.Now > banEntry.ExpireTime)
                    {
                        targetGuild = await Program.discord.GetGuildAsync(banEntry.ServerId);
                        await UnbanFromServerAsync(targetGuild, banEntry.MemberId);

                        success = true;
                    }
                }
#if DEBUG
                Console.WriteLine($"Checked bans at {DateTime.Now} with result: {success}");
#endif
                return(success);
            }
        }
        private async Task RunPooperAsync(DiscordGuild gld, DiscordMember mbr)
        {
            var gid = (long)gld.Id;

            if (!await this.CheckWhitelistAsync(gid))
            {
                return;
            }

            var cmbr = gld.CurrentMember;

            if (cmbr == null)
            {
                this.Discord.Logger.LogError(LogEvent, "Current member in '{0}' ({1}) is null - could not process pooping!", gld.Name, gld.Id);
                return;
            }

            if (!this.CanPoop(mbr, cmbr))
            {
                return;
            }

            await DoPoopAsync(mbr);
        }
Ejemplo n.º 25
0
        private DiscordRole ResolveRole(DiscordGuild guild, string input)
        {
            if (input == null)
            {
                return(null);
            }

            var roles = GetTimeSortedRoles(guild);

            if (ulong.TryParse(input, out ulong num))
            {
                if (num <= (ulong)roles.Count && num != 0)
                {
                    return(roles[(int)(num - 1)]);
                }
                var tmp = roles.Find(r => r.Id == num);
                if (tmp != null)
                {
                    return(tmp);
                }
            }

            int         min    = int.MaxValue;
            DiscordRole result = null;

            foreach (var role in roles)
            {
                int tmp = Utils.Levenshtein(role.Name, input);
                if (tmp < min)
                {
                    min    = tmp;
                    result = role;
                }
            }
            return(result);
        }
Ejemplo n.º 26
0
 public async Task MusicAsync(CommandContext ctx,
                              [Description("Guild for which to toggle the setting.")] DiscordGuild guild,
                              [Description("Whether the music module should be available.")] bool whitelist,
                              [RemainingText, Description("Reason why the guild has music enabled.")] string reason = null)
 {
     /*var gid = (long)guild.Id;
      * var enable = this.Database.MusicWhitelist.SingleOrDefault(x => x.GuildId == gid);
      * if (whitelist && enable == null)
      * {
      *  enable = new DatabaseMusicWhitelistedGuild
      *  {
      *      GuildId = gid,
      *      Reason = reason
      *  };
      *  this.Database.MusicWhitelist.Add(enable);
      * }
      * else if (!whitelist && enable != null)
      * {
      *  this.Database.MusicWhitelist.Remove(enable);
      * }
      *
      * await this.Database.SaveChangesAsync().ConfigureAwait(false);
      * await ctx.RespondAsync($"{DiscordEmoji.FromName(ctx.Client, ":msokhand:")} {Formatter.Bold(Formatter.Sanitize(guild.Name))} is {(whitelist ? "now whitelisted for music playback" : "not whitelisted for music playback anymore")}.").ConfigureAwait(false);*/
 }
Ejemplo n.º 27
0
        /// <summary>
        /// Strictly gets a user from their user ID. Unlike <see cref="GetMemberFromDataAsync(DiscordGuild, string)"/>, this code will return null if a name or discriminator is passed in.
        /// </summary>
        /// <param name="data">The query to get a XanBotMember from. This can either be a ulong as a string or a user ping (&lt;@ulong&gt;)</param>
        /// <returns></returns>
        public static async Task <XanBotMember> GetMemberFromDataIDStrictAsync(DiscordGuild server, string data)
        {
            string newdata = data;

            if (data.StartsWith("<@") && data.EndsWith(">"))
            {
                newdata = data.Substring(2, data.Length - 3);
            }
            if (ulong.TryParse(newdata, out ulong uuid))
            {
                DiscordUser user = await XanBotCoreSystem.Client.GetUserAsync(uuid);

                // Catch case: Someone's username is a bunch of numbers OR they link a user ID that isn't in the server.
                if (user != null)
                {
                    XanBotMember member = XanBotMember.GetMemberFromUser(server, user);
                    if (member != null)
                    {
                        return(member);
                    }
                }
            }
            return(null);
        }
Ejemplo n.º 28
0
        public DiscordChannel GetChannelByName(string channelName, DiscordGuild server)
        {
            _log.Debug("Getting channel by name {channelName} on server {serverName}.", channelName, server.Name);

            DiscordChannel res;

            try
            {
                res = server.Channels.Values.FirstOrDefault(c => c.Name == channelName);
            }
            catch (InvalidOperationException e)
            {
                throw new AmbiguousIdentifierException($"Could not uniquely identify channel with name {channelName} in server {server.Name}.", e);
            }

            if (res != null)
            {
                return(res);
            }
            else
            {
                throw new UnmatchedIdentifierException($"Could not find any channel with name {channelName} in server {server.Name}.");
            }
        }
Ejemplo n.º 29
0
        public async Task ServerInfo(CommandContext ctx)
        {
            DiscordGuild  guild = ctx.Guild;
            SilkDbContext db    = _dbFactory.CreateDbContext();

            var staffMembers = db.Guilds.Include(g => g.Users)
                               .First(g => g.Id == guild.Id)
                               .Users
                               .Where(u => u.Flags.HasFlag(UserFlag.Staff));

            int staffCount = staffMembers.Count();

            DiscordEmbedBuilder embed = new DiscordEmbedBuilder()
                                        .WithTitle($"Guild info for {guild.Name}:")
                                        .WithColor(DiscordColor.Gold)
                                        .WithFooter($"Silk! | Requested by: {ctx.User.Id}", ctx.Client.CurrentUser.AvatarUrl);

            embed.WithThumbnail(guild.IconUrl);

            if (guild.PremiumSubscriptionCount.Value > 0)
            {
                embed.AddField("Boosts:", $"{guild.PremiumSubscriptionCount.Value} boosts (level {guild.PremiumTier})");
            }

            if (guild.Features.Count > 0)
            {
                embed.AddField("Enabled guild features: ", string.Join(", ", guild.Features));
            }

            embed.AddField("Verification Level:", guild.VerificationLevel.ToString().ToUpper());
            embed.AddField("Member Count:", guild.MemberCount.ToString());
            embed.AddField("Owner:", guild.Owner.Mention);
            embed.AddField("Approximate staff member count:", staffCount.ToString());

            await ctx.RespondAsync(embed : embed);
        }
Ejemplo n.º 30
0
        public static async Task LogAutoActionAsync(this DiscordClient clnt, DiscordGuild gld, DatabaseContext db,
                                                    string additionalinfo = "")
        {
            var cfg = db.GuildConfig.SingleOrDefault(xc => (ulong)xc.GuildId == gld.Id);
            var s   = cfg.GetSettings();

            if (s.ActionLog.Enable)
            {
                var w = await clnt.GetWebhookWithTokenAsync(s.ActionLog.WebhookId, s.ActionLog.WebhookToken);

                var b = new DiscordEmbedBuilder();

                b.WithTitle($"New Automated action executed")
                .WithDescription($"Executed action: {additionalinfo}")
                .WithFooter($"Guild: {gld.Name}", string.IsNullOrEmpty(gld.IconHash) ? "" : gld.IconUrl);

                var e = new List <DiscordEmbed>
                {
                    b.Build()
                };

                await w.ExecuteAsync(null, null, null, false, e, null);
            }
        }