Пример #1
0
        public async Task Warn(CommandContext ctx,
                               [Description("Server user to warn.")] DiscordMember member,
                               [Description("Warning message.")][RemainingText]
                               string reason = null)
        {
            var output = new DiscordEmbedBuilder()
                         .WithTitle("Warning received!")
                         .WithDescription(Formatter.Bold(ctx.Guild.Name) + " has issued you a server warning!")
                         .AddField("Sender:", ctx.Member.Username + "#" + ctx.Member.Discriminator, true)
                         .AddField("Server Owner:", ctx.Guild.Owner.Username + "#" + ctx.Guild.Owner.Discriminator, true)
                         .WithThumbnail(ctx.Guild.IconUrl)
                         .WithTimestamp(DateTime.Now)
                         .WithColor(DiscordColor.Red);

            if (!string.IsNullOrWhiteSpace(reason))
            {
                output.AddField("Warning message:", reason);
            }

            var dm = await member.CreateDmChannelAsync().ConfigureAwait(false);

            if (dm is null)
            {
                await BotServices.SendResponseAsync(ctx, "Unable to direct message this user", ResponseType.Warning)
                .ConfigureAwait(false);

                return;
            }

            await dm.SendMessageAsync(output.Build()).ConfigureAwait(false);

            await ctx.RespondAsync("Successfully sent a warning to " + Formatter.Bold(member.Username))
            .ConfigureAwait(false);
        }
Пример #2
0
            public async Task Unsudo(CommandContext ctx, [Description("Discord user on the moderator list to strip the sudoer rights from")] DiscordMember sudoer)
            {
                if (ctx.Client.CurrentApplication.Owners.Any(u => u.Id == sudoer.Id))
                {
                    var dm = await sudoer.CreateDmChannelAsync().ConfigureAwait(false);

                    await dm.SendMessageAsync($@"Just letting you know that {ctx.Message.Author.Mention} just tried to strip you off of your sudo permissions ¯\\_(ツ)_/¯").ConfigureAwait(false);

                    await ctx.ReactWithAsync(Config.Reactions.Denied, $"{ctx.Message.Author.Mention} why would you even try this?! Alerting {sudoer.Mention}", true).ConfigureAwait(false);
                }
                else if (ModProvider.IsMod(sudoer.Id))
                {
                    if (await ModProvider.UnmakeSudoerAsync(sudoer.Id).ConfigureAwait(false))
                    {
                        await ctx.ReactWithAsync(Config.Reactions.Success, $"{sudoer.Mention} is no longer a sudoer").ConfigureAwait(false);
                    }
                    else
                    {
                        await ctx.ReactWithAsync(Config.Reactions.Failure, $"{sudoer.Mention} is not a sudoer").ConfigureAwait(false);
                    }
                }
                else
                {
                    await ctx.ReactWithAsync(Config.Reactions.Failure, $"{sudoer.Mention} is not even a moderator!").ConfigureAwait(false);
                }
            }
Пример #3
0
        public async Task Tempban(CommandContext ctx,

                                  [Description("UserID to tempban")]
                                  DiscordMember user,

                                  [Description("Duration")]
                                  Int16 Time,

                                  [Description("Timer ID")]
                                  Char TimeID,

                                  [Description("Reason")]
                                  [RemainingText]
                                  String Reason = "No reason given.")
        {
            var modlog    = ctx.Guild.GetChannel(693567857107402762);
            var dmchannel = await user.CreateDmChannelAsync();

            var invite = await ctx.Channel.CreateInviteAsync(max_uses : 1, max_age : -1);

            _ = ctx.Guild.BanMemberAsync(user, reason: Reason);
            _ = dmchannel.SendMessageAsync($"Oh no, you have been temporarily banned for \"{Reason}\"! Your ban will expire in {Time}{TimeID}");

            DiscordEmbedBuilder embedBuilder = new DiscordEmbedBuilder
            {
                Color       = DiscordColor.DarkRed,
                Description = $"<:insanitybotSuccess:737297353316499566> {user.Username} has been banned successfully.",
                Footer      = new DiscordEmbedBuilder.EmbedFooter
                {
                    Text = "InsanityBot - Exa 2020"
                }
            };
            await ctx.RespondAsync(embed : embedBuilder.Build());

            embedBuilder.Title       = "TEMPBAN";
            embedBuilder.Description = null;
            embedBuilder.AddField("User", user.Username, true);
            embedBuilder.AddField("Moderator", ctx.Member.DisplayName, true);
            embedBuilder.AddField("Duration", $"{Time}{TimeID}", true);
            embedBuilder.AddField("Reason", Reason, true);

            await modlog.SendMessageAsync(embed : embedBuilder.Build());

            User modlogUser = Serializer.Deserialize(user.Id);

            modlogUser.AddModlogEntry(ModlogType.ban, Reason);
            Serializer.Serialize(modlogUser, user.Id);

            await Task.Delay(TimeConverter.GetTimeSpan(Time, TimeID));

            _ = ctx.Guild.UnbanMemberAsync(user, reason: "[InsanityBot]: Tempban expired.");
            _ = dmchannel.SendMessageAsync($"Your tempban on Insanity has expired. Use this rejoin link if you want to be a part of the community again: {invite}");

            embedBuilder.Title = "UNBAN";
            embedBuilder.Color = DiscordColor.SpringGreen;
            embedBuilder.ClearFields();
            embedBuilder.AddField("User", user.Username, true);

            await modlog.SendMessageAsync(embed : embedBuilder.Build());
        }
Пример #4
0
        public async Task Warn(CommandContext ctx, DiscordMember member, [RemainingText] string reason = null)
        {
            await ctx.TriggerTypingAsync();

            var output = new DiscordEmbedBuilder()
                         .WithTitle("Warning received!")
                         .WithDescription($"Guild **{ctx.Guild.Name}** issued you a warning!")
                         .WithTimestamp(DateTime.Now)
                         .WithColor(DiscordColor.Red);

            if (!string.IsNullOrWhiteSpace(reason))
            {
                output.AddField("Warning message:", reason);
            }
            output.AddField("Sender:", $"{ctx.Member.Username}#{ctx.Member.Discriminator}");
            var dm = await member.CreateDmChannelAsync().ConfigureAwait(false);

            if (dm == null)
            {
                await ctx.RespondAsync("Unable to direct message this user");
            }
            else
            {
                await dm.SendMessageAsync(embed : output.Build()).ConfigureAwait(false);

                await ctx.RespondAsync($"Successfully sent a warning to {Formatter.Bold(member.Username)}.").ConfigureAwait(false);
            }
        }
Пример #5
0
        public async Task Chit(CommandContext ctx, DiscordMember member)
        {
            bool chitsAllowed = await guilds.GetGuildChitsAllowed(ctx.Guild.Id);

            if (!chitsAllowed)
            {
                await ctx.RespondAsync("Chits have been disabled, you cannot set them");

                return;
            }

            try
            {
                await ctx.Member.CreateDmChannelAsync();
            }
            catch (Exception)
            {
                await ctx.RespondAsync($"{ctx.Member.Mention}, it seems you have DMs disabled, please turn on DMs to send a chit");

                return;
            }

            try
            {
                await member.CreateDmChannelAsync();
            }
            catch (Exception)
            {
                var dmChannel = await ctx.Member.CreateDmChannelAsync();

                await dmChannel.SendMessageAsync($"It seems {member.Username} has their DMs turned off, cant send a chit to them");

                return;
            }
        }
Пример #6
0
        public async Task BanUserAsync(CommandContext ctx, DiscordMember user, [RemainingText] string reason)
        {
            // !ban @Garcia is bad at everything <---- There for epicness
            var caseId = await produceID(20);

            if (!CheckInteraction.CanModerate(ctx.Member, (DiscordMember)user))
            {
                await ctx.Message.DeleteAsync();

                return;
            }
            if (user == ctx.Member)
            {
                await ctx.Channel.SendMessageAsync("You cannot ban yourself.");

                return;
            }
            try
            {
                var x = await user.CreateDmChannelAsync();

                await x.SendBanDMAsync("You were banned", $"You were banned from **{ ctx.Guild.Name}**\n** Reason**: { reason}\nID: `{ caseId}`\nTo appeal, fill out the form ");
            }
            catch (Exception)
            {
                Console.WriteLine("Unable to DM user.");
            }
            var e = new DiscordEmbedBuilder()
                    .WithDescription($"{user.Mention} was **banned** from the server with ID: `{caseId}`")
                    .WithColor(DiscordColor.Green);
            var message = await ctx.Channel.SendMessageAsync(embed : e.Build());

            await ctx.Guild.BanMemberAsync(user, 7, reason);
        }
Пример #7
0
        public async Task WarnAsync(CommandContext ctx,
                                    [Description("Member.")] DiscordMember member,
                                    [RemainingText, Description("Warning message.")] string msg = null)
        {
            var emb = new DiscordEmbedBuilder()
            {
                Title       = "Warning received!",
                Description = $"Guild {Formatter.Bold(ctx.Guild.Name)} issued a warning to you through me.",
                Color       = DiscordColor.Red,
                Timestamp   = DateTime.Now
            };

            if (!string.IsNullOrWhiteSpace(msg))
            {
                emb.AddField("Warning message", msg);
            }

            try {
                DiscordDmChannel dm = await member.CreateDmChannelAsync();

                await dm.SendMessageAsync(embed : emb.Build());
            } catch {
                throw new CommandFailedException("I can't talk to that user...");
            }

            await this.InformAsync(ctx, $"Successfully warned member {Formatter.Bold(member.DisplayName)} with message: {Formatter.BlockCode(msg)}", important : false);
        }
Пример #8
0
        public static Task <DiscordDmChannel> CreateDmChannelAsync(this DiscordClient client, ulong uid)
        {
            DiscordMember member = client.Guilds.Values
                                   .SelectMany(e => e.Members)
                                   .FirstOrDefault(e => e.Id == uid);

            return(member?.CreateDmChannelAsync() ?? Task.FromResult <DiscordDmChannel>(null));
        }
        public async Task <HashSet <string> > NotifyAsync(IReadOnlyCollection <string> userIds, TvShow tvShow, int seasonNumber, CancellationToken token)
        {
            var userNotified = new HashSet <string>();

            if (_discordClient.Guilds.Any())
            {
                foreach (var userId in userIds)
                {
                    if (token.IsCancellationRequested)
                    {
                        return(userNotified);
                    }

                    try
                    {
                        DiscordMember user = null;

                        foreach (var guild in _discordClient.Guilds.Values)
                        {
                            try
                            {
                                user = await guild.GetMemberAsync(ulong.Parse(userId));

                                break;
                            }
                            catch { }
                        }

                        if (user != null)
                        {
                            var channel = await user.CreateDmChannelAsync();

                            if (_discordSettingsProvider.Provide().TvShowDownloadClient == DownloadClient.Overseerr)
                            {
                                await channel.SendMessageAsync(Language.Current.DiscordNotificationTvDMSeason.ReplaceTokens(tvShow, seasonNumber), DiscordTvShowUserInterface.GenerateTvShowDetailsAsync(tvShow));
                            }
                            else
                            {
                                await channel.SendMessageAsync(Language.Current.DiscordNotificationTvDMFirstEpisode.ReplaceTokens(tvShow, seasonNumber), DiscordTvShowUserInterface.GenerateTvShowDetailsAsync(tvShow));
                            }
                        }
                        else
                        {
                            _logger.LogWarning($"Removing tv show notification for user with ID {userId} as it could not be found in any of the guilds.");
                        }

                        userNotified.Add(userId);
                    }
                    catch (System.Exception ex)
                    {
                        _logger.LogError(ex, "An error occurred while sending a tv show notification to a specific user: " + ex.Message);
                    }
                }
            }

            return(userNotified);
        }
Пример #10
0
        /// <summary>
        /// Creates a direct message channel between the bot and the user
        /// </summary>
        /// <param name="userId">User needs to be in the same guild as <see cref="DClientSettings.GuildId"/></param>
        public static async Task <DiscordDmChannel> GetDmChanelAsync(ulong userId)
        {
            DiscordMember member = await GetMemberAsync(userId).ConfigureAwait(false);

            if (member == null)
            {
                return(null);
            }

            return(await member.CreateDmChannelAsync().ConfigureAwait(false));
        }
        public async Task <HashSet <string> > NotifyAsync(IReadOnlyCollection <string> userIds, Movie movie, CancellationToken token)
        {
            var userNotified = new HashSet <string>();

            if (_discordClient.Guilds.Any())
            {
                foreach (var userId in userIds)
                {
                    if (token.IsCancellationRequested)
                    {
                        return(userNotified);
                    }

                    try
                    {
                        DiscordMember user = null;

                        foreach (var guild in _discordClient.Guilds.Values)
                        {
                            try
                            {
                                user = await guild.GetMemberAsync(ulong.Parse(userId));

                                break;
                            }
                            catch { }
                        }

                        if (user != null)
                        {
                            var channel = await user.CreateDmChannelAsync();

                            await channel.SendMessageAsync(Language.Current.DiscordNotificationMovieDM.ReplaceTokens(movie), await DiscordMovieUserInterface.GenerateMovieDetailsAsync(movie));
                        }
                        else
                        {
                            _logger.LogWarning($"Removing movie notification for user with ID {userId} as it could not be found in any of the guilds.");
                        }

                        userNotified.Add(userId);
                    }
                    catch (System.Exception ex)
                    {
                        _logger.LogError(ex, "An error occurred while sending a private message movie notification to a specific user: " + ex.Message);
                    }
                }
            }

            return(userNotified);
        }
Пример #12
0
        public static async Task ProcWelComeMessage(DiscordMember pMember, DiscordChannel pChannel)
        {
            DiscordEmbedBuilder pEmbedBuilder_WellCome = new DiscordEmbedBuilder();

            pEmbedBuilder_WellCome.WithColor(DiscordColor.Cyan).
            WithTitle(_pRoomManager.strWelcomeTitle).
            WithDescription(_pRoomManager.strWelcomeText_ForNewMan);

            await pChannel.SendMessageAsync($"{pMember.Mention} {_pRoomManager.strWelcomeText_ForEveryone}");

            await pChannel.SendMessageAsync(null, false, pEmbedBuilder_WellCome);

            await(pMember.CreateDmChannelAsync().GetAwaiter().GetResult().SendMessageAsync(null, false, CreateWelcomeDM(pMember)));
        }
Пример #13
0
        public async Task JoinVillageCommand(CommandContext ctx)
        {
            //Vérification de base character + guild
            if (!dep.Entities.Characters.IsPresent(ctx.User.Id) ||
                !dep.Entities.Guilds.IsPresent(ctx.Guild.Id))
            {
                return;
            }

            Character character   = dep.Entities.Characters.GetCharacterByDiscordId(ctx.User.Id);
            Case      currentCase = dep.Entities.Map.GetCase(character.Location);

            //1 check existence village + appartenance village
            if (character.VillageName != null || currentCase.VillageId == ulong.MinValue)
            {
                DiscordEmbedBuilder embed = dep.Embed.CreateBasicEmbed(ctx.User, dep.Dialog.GetString("errorCantJoinVillage"));
                await ctx.RespondAsync(embed : embed);

                return;
            }

            //2 sinon ajout liste attente village
            // + prévenir roi ?
            Village village = dep.Entities.Villages.GetVillageById(currentCase.VillageId);

            if (!village.WaitingList.Contains(character.Id))
            {
                village.WaitingList.Add(character.Id);
            }

            DiscordMember king = await ctx.Guild.GetMemberAsync(village.KingId);

            if (king != null)
            {
                DiscordDmChannel dm = await king.CreateDmChannelAsync();

                DiscordEmbedBuilder embed = dep.Embed.CreateBasicEmbed(king, dep.Dialog.GetString("joinVillageMPKing"));
                await dm.SendMessageAsync(embed : embed);

                DiscordEmbedBuilder embedConfirm = dep.Embed.CreateBasicEmbed(king, dep.Dialog.GetString("joinvillageConfirmWaiting"));
                await ctx.RespondAsync(embed : embedConfirm);
            }
            else
            {
                DiscordEmbedBuilder embed = dep.Embed.CreateBasicEmbed(ctx.User, dep.Dialog.GetString("error"));
                await ctx.RespondAsync(embed : embed);
            }
        }
Пример #14
0
 private static async Task UpdateOwnerDm()
 {
     if (_ownerDm == null)
     {
         DiscordMember ownerMember = Client.Guilds.Values.SelectMany(g => g.Members).FirstOrDefault(m => m.Id == Client.CurrentApplication.Owner.Id);
         if (ownerMember != null)
         {
             _appLogArea.WriteLine($"Owner member found! {ownerMember}");
             _ownerDm = await ownerMember.CreateDmChannelAsync();
         }
         else
         {
             _appLogArea.WriteLine("Unable to find owner member, Exception information will be unavailable.");
         }
     }
 }
Пример #15
0
        private static async Task DmUser(DiscordClient client, DiscordMember member, string suggestedName)
        {
            try
            {
                var rulesChannel = await client.GetChannelAsync(Config.BotRulesChannelId).ConfigureAwait(false);

                var msg = $"Hello, your current _display name_ is breaking {rulesChannel.Mention} #7, please change it accordingly.\n" +
                          $"I'd suggest using `{suggestedName}`, but I'm not perfect and can't clean all the junk in some cases, so change it at your discretion.\n" +
                          "You can change your _display name_ by clicking on the server name at the top left and selecting **Change Nickname**.";
                var dm = await member.CreateDmChannelAsync().ConfigureAwait(false);

                await dm.SendMessageAsync(msg).ConfigureAwait(false);
            }
            catch (Exception e)
            {
                Config.Log.Warn(e);
            }
        }
Пример #16
0
            public async Task Remove(CommandContext ctx, [Description("Discord user to remove from the bot mod list")] DiscordMember user)
            {
                if (ctx.Client.CurrentApplication.Owners.Any(u => u.Id == user.Id))
                {
                    var dm = await user.CreateDmChannelAsync().ConfigureAwait(false);

                    await dm.SendMessageAsync($@"Just letting you know that {ctx.Message.Author.Mention} just tried to strip you off of your mod role ¯\\_(ツ)_/¯").ConfigureAwait(false);

                    await ctx.ReactWithAsync(Config.Reactions.Denied, $"{ctx.Message.Author.Mention} why would you even try this?! Alerting {user.Mention}", true).ConfigureAwait(false);
                }
                else if (await ModProvider.RemoveAsync(user.Id).ConfigureAwait(false))
                {
                    await ctx.ReactWithAsync(Config.Reactions.Success, $"{user.Mention} removed as moderator!").ConfigureAwait(false);
                }
                else
                {
                    await ctx.ReactWithAsync(Config.Reactions.Failure, $"{user.Mention} is not a moderator").ConfigureAwait(false);
                }
            }
Пример #17
0
        private async Task test(CommandContext ctx, DiscordMember u, string str)
        {
            var pollEmbed = new DiscordEmbedBuilder
            {
                Title       = "Quick test",
                Description = str
            };
            var interactivity = ctx.Client.GetInteractivity();
            var channel       = await u.CreateDmChannelAsync().ConfigureAwait(false);

            var message = await channel.SendMessageAsync(embed : pollEmbed).ConfigureAwait(false);

            await message.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":white_check_mark:"));

            await message.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":x:"));

            var result = await interactivity.CollectReactionsAsync(message, TimeSpan.FromMinutes(1)).ConfigureAwait(false);

            var userChannel = await ctx.Member.CreateDmChannelAsync().ConfigureAwait(false);

            foreach (var r in result)
            {
                bool flag = false;
                foreach (var us in r.Users)
                {
                    if (!us.IsBot)
                    {
                        if (r.Emoji == DiscordEmoji.FromName(ctx.Client, ":white_check_mark:") || r.Emoji == DiscordEmoji.FromName(ctx.Client, ":x:"))
                        {
                            var username = ctx.Guild.GetMemberAsync(us.Id).Result.DisplayName;
                            await userChannel.SendMessageAsync($"{username} unswered {r.Emoji}\n").ConfigureAwait(false);

                            flag = true;
                            break;
                        }
                    }
                }
                if (flag)
                {
                    break;
                }
            }
        }
Пример #18
0
        public async Task Kick(CommandContext ctx,

                               [Description("User to kick")]
                               DiscordMember user,

                               [Description("Reason")]
                               [RemainingText]
                               String Reason = "[no reason given]")
        {
            var modlog    = ctx.Guild.GetChannel(693567857107402762);
            var dmchannel = await user.CreateDmChannelAsync();

            var invite = await ctx.Channel.CreateInviteAsync(max_uses : 1);

            User modlogUser = Serializer.Deserialize(user.Id);

            modlogUser.AddModlogEntry(ModlogType.kick, Reason);
            Serializer.Serialize(modlogUser, user.Id);

            _ = ctx.Guild.RemoveMemberAsync(user);
            _ = dmchannel.SendMessageAsync($"Oh no, you have been kicked for {Reason}! Use this fancy invite link to rejoin: {invite}");

            DiscordEmbedBuilder embedBuilder = new DiscordEmbedBuilder
            {
                Description = $"<:insanitybotSuccess:737297353316499566> {user.Username} has been kicked successfully.",
                Color       = DiscordColor.Red,
                Footer      = new DiscordEmbedBuilder.EmbedFooter
                {
                    Text = "InsanityBot - Exa 2020"
                }
            };
            await ctx.RespondAsync(embed : embedBuilder.Build());

            embedBuilder.Title       = "KICK";
            embedBuilder.Description = null;
            embedBuilder.AddField("User", user.Username, true);
            embedBuilder.AddField("Moderator", ctx.Member.DisplayName, true);
            embedBuilder.AddField("Reason", Reason, true);

            await modlog.SendMessageAsync(embed : embedBuilder.Build());
        }
Пример #19
0
        private static async Task DmAndRenameUserAsync(DiscordClient client, DiscordMember member, string suggestedName)
        {
            try
            {
                var renameTask = member.ModifyAsync(m => m.Nickname = suggestedName);
                Config.Log.Info($"Renamed {member.Username}#{member.Discriminator} ({member.Id}) to {suggestedName}");
                var rulesChannel = await client.GetChannelAsync(Config.BotRulesChannelId).ConfigureAwait(false);

                var msg = $"Hello, your current _display name_ is breaking {rulesChannel.Mention} #7, so you have been renamed to `{suggestedName}.\n" +
                          "I'm not perfect and can't clean all the junk in names in some cases, so change your nickname at your discretion.\n" +
                          "You can change your _display name_ by clicking on the server name at the top left and selecting **Change Nickname**.";
                var dm = await member.CreateDmChannelAsync().ConfigureAwait(false);

                await dm.SendMessageAsync(msg).ConfigureAwait(false);

                await renameTask.ConfigureAwait(false);
            }
            catch (Exception e)
            {
                Config.Log.Warn(e);
            }
        }
Пример #20
0
        public async Task Ban(CommandContext ctx,

                              [Description("User to ban")]
                              DiscordMember user,

                              [Description("Reason")]
                              [RemainingText]
                              String Reason = "[no reason given]")
        {
            var modlog    = ctx.Guild.GetChannel(693567857107402762);
            var dmchannel = await user.CreateDmChannelAsync();

            _ = ctx.Guild.BanMemberAsync(user, reason: Reason);
            _ = dmchannel.SendMessageAsync($"Oh no, you have been banned for \"{Reason}\"!");

            User modlogUser = Serializer.Deserialize(user.Id);

            modlogUser.AddModlogEntry(ModlogType.ban, Reason);
            Serializer.Serialize(modlogUser, user.Id);

            DiscordEmbedBuilder embedBuilder = new DiscordEmbedBuilder
            {
                Description = $"<:insanitybotSuccess:737297353316499566> {user.Username} has been banned successfully.",
                Color       = DiscordColor.Red,
                Footer      = new DiscordEmbedBuilder.EmbedFooter
                {
                    Text = "InsanityBot - Exa 2020"
                }
            };
            await ctx.RespondAsync(embed : embedBuilder.Build());

            embedBuilder.Title       = "BAN";
            embedBuilder.Description = null;
            embedBuilder.AddField("User", user.Username, true);
            embedBuilder.AddField("Moderator", ctx.Member.DisplayName, true);
            embedBuilder.AddField("Reason", Reason, true);

            await modlog.SendMessageAsync(embed : embedBuilder.Build());
        }
Пример #21
0
        private async Task SendDM(DiscordMember member, string message, bool kicked)
        {
            DiscordDmChannel dmChannel = await member.CreateDmChannelAsync();

            DiscordChannel sbaChannel = await this.dClient.GetChannelAsync(SBGChannels.SecretBaseAlpha);

            try
            {
                await dmChannel.SendMessageAsync(message);
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception e)
#pragma warning restore CA1031 // Do not catch general exception types
            {
                // Send the message in SBA as a public message to warn the user before we kick them.
                if (!kicked)
                {
                    await sbaChannel.SendMessageAsync($"{member.Mention}, we tried to send you a message but failed. {message}");
                }

                Log.Error(e, $"Unable to send an inactivity DM to {member.Username} : {member.Id}");
                this.bloonLog.Error($"Unable to send an inactivity DM to {member.Username} : {member.Id}");
            }
        }
Пример #22
0
        private async Task SendWelcomeMessage(DiscordMember member, DiscordEmbed embed)
        {
            var channel = await member.CreateDmChannelAsync();

            await channel.SendMessageAsync(embed : embed);
        }
Пример #23
0
        public async Task WarnUserAsync(CommandContext ctx, DiscordMember user, [RemainingText] string reason)
        {
            if (!CheckInteraction.CanModerate(ctx.Member, user))
            {
                await ctx.Message.DeleteAsync();

                return;
            }
            var caseId = await produceID(20);

            await user.CreateDmChannelAsync();

            var l = new DiscordEmbedBuilder()
                    .WithTitle("You were warned.")
                    .WithColor(DiscordColor.Gold)
                    .WithDescription($"You were warned in **{ctx.Guild.Name}**\n\nYou were warned for reason: {reason}\nID `{caseId}`.\n**Moderator** | Hidden");

            try
            {
                await user.CreateDmChannelAsync();

                await user.SendMessageAsync(embed : l.Build());
            }
            catch (Exception)
            {
                Console.WriteLine("Unable to Dm user.");
            }
            var k = new DiscordEmbedBuilder()
                    .WithDescription($"{user.Mention} was **warned** with ID: `{caseId}`.\n**{user.Mention}**, check your DM's for information.")
                    .WithColor(DiscordColor.Green);
            await ctx.Channel.SendMessageAsync(embed : k.Build());

            // If the user has no warns, we make a new user.
            if (data.serverdata.warnedusers is null)
            {
                data.serverdata.warnedusers = new warneduser[1] {
                    new warneduser {
                        userId = user.Id, reasons = new string[] { reason }, caseId = new string[] { caseId }
                    }
                };
            }
            // If the user exists in the file, then we execute the command in the if statement.
            else
            {
                // Set the done variable, which defines if the user has been put into the file.
                bool done = false;
                // For each warned usr, we set their old reasons.
                foreach (warneduser u in data.serverdata.warnedusers)
                {
                    // If the warned user is equal to the warned user's ID
                    if (u.userId == user.Id)
                    {
                        // Set the old reasons
                        string[] oldReasons = u.reasons;
                        u.reasons = new string[oldReasons.Length + 1];
                        // Set the reasons to be old reasons
                        for (int i = 0; i < oldReasons.Length; i++)
                        {
                            u.reasons[i] = oldReasons[i];
                        }
                        // Do the same thing, but with case id's
                        string[] oldcaseid = u.caseId;
                        u.caseId = new string[oldcaseid.Length + 1];
                        for (int i = 0; i < oldcaseid.Length; i++)
                        {
                            u.caseId[i] = oldcaseid[i];
                        }
                        u.caseId[oldcaseid.Length]   = caseId;
                        u.reasons[oldReasons.Length] = reason;
                        // After adding them, we call this done.
                        done = true;
                        break;
                    }
                }
                // If done is false
                if (!done)
                {
                    // We get the previously warned users.
                    warneduser[] prevUsers = data.serverdata.warnedusers;
                    data.serverdata.warnedusers = new warneduser[prevUsers.Length + 1];
                    for (int i = 0; i < prevUsers.Length; i++)
                    {
                        data.serverdata.warnedusers[i] = prevUsers[i];
                    }
                    data.serverdata.warnedusers[prevUsers.Length] = new warneduser {
                        userId = user.Id, reasons = new string[] { reason }, caseId = new string[] { caseId }
                    };
                }
            }
            warneduser user2 = null;

            // Make sure that the previously warned user is not the same user
            foreach (warneduser user3 in data.serverdata.warnedusers)
            {
                if (user3.userId == user.Id)
                {
                    user2 = user3;
                }
            }
        }
Пример #24
0
        public async Task BanUserTempAsync(CommandContext ctx, DiscordMember user, string duration, [RemainingText] string reason)
        {
            if (!CheckInteraction.CanModerate(ctx.Member, user))
            {
                await ctx.Message.DeleteAsync();

                return;
            }
            var caseId = await produceID(20);

            char minute   = 'm';
            char day      = 'd';
            char hour     = 'h';
            char second   = 's';
            char week     = 'w';
            var  BanTimer = new string(duration.Where(char.IsDigit).ToArray());

            if (minute.ToString().Any(duration.Contains) && day.ToString().Any(duration.Contains) && hour.ToString().Any(duration.Contains) && second.ToString().Any(duration.Contains))
            {
                await ctx.Channel.SendMessageAsync("You cannot pass multiple time formats.");

                return;
            }
            if (BanTimer.Length == 0)
            {
                return;
            }
            var Timer = Convert.ToInt32(BanTimer);

            if (minute.ToString().Any(duration.ToLower().Contains))
            {
                Bot.Bans.Add(new Ban {
                    Guild = ctx.Guild, User = user, End = DateTime.Now + TimeSpan.FromMinutes(Timer)
                });
            }
            else if (day.ToString().Any(duration.ToLower().Contains))
            {
                Bot.Bans.Add(new Ban {
                    Guild = ctx.Guild, User = user, End = DateTime.Now + TimeSpan.FromDays(Timer)
                });
            }
            else if (second.ToString().Any(duration.ToLower().Contains))
            {
                Bot.Bans.Add(new Ban {
                    Guild = ctx.Guild, User = user, End = DateTime.Now + TimeSpan.FromSeconds(Timer)
                });
            }
            else if (hour.ToString().Any(duration.ToLower().Contains))
            {
                Bot.Bans.Add(new Ban {
                    Guild = ctx.Guild, User = user, End = DateTime.Now + TimeSpan.FromHours(Timer)
                });
            }
            else if (week.ToString().Any(duration.ToLower().Contains))
            {
                Bot.Bans.Add(new Ban {
                    Guild = ctx.Guild, User = user, End = DateTime.Now + TimeSpan.FromDays(Timer * 7)
                });
            }
            else
            {
                Console.WriteLine("");
            }
            var e = new DiscordEmbedBuilder()
                    .WithDescription($"{user.Mention} was **banned*8 from the server with ID: `{caseId}`")
                    .WithColor(DiscordColor.Green);
            var message = await ctx.Channel.SendMessageAsync(embed : e.Build());

            try
            {
                var x = await user.CreateDmChannelAsync();

                await x.SendBanDMAsync("You were banned", $"You were banned from **{ctx.Guild.Name}**\n**Reason**: {reason}\nID: `{caseId}`\nTo appeal, fill out the form ");
            }
            catch (Exception)
            {
                Console.WriteLine("Unable to DM user.");
            }
            await ctx.Guild.BanMemberAsync(user, 7, reason);
        }
Пример #25
0
        private async void StartStopSpamming(object sender, RoutedEventArgs e)
        {
            Button senderBtn = (Button)sender;

            if (spamTimer == null)
            {
                try
                {
                    if (IsDirect.IsChecked ?? false)
                    {
                        DiscordGuild server;
                        ulong        serverId = Convert.ToUInt64(GuildId.Text);
                        if (MainWindow.userClient.Guilds.TryGetValue(serverId, out server))
                        {
                            ulong channelIdVal = Convert.ToUInt64(ChannelId.Text);
                            try
                            {
                                DiscordMember dmUser = await server.GetMemberAsync(channelIdVal);

                                DiscordDmChannel dm = await dmUser.CreateDmChannelAsync();

                                if (dm != null)
                                {
                                    targChannel = dm;
                                }
                                else
                                {
                                    MessageBox.Show("Ошибка: неверный ID пользователя.");
                                }
                            }
                            catch (Exception)
                            {
                                MessageBox.Show("Ошибка: неверный ID пользователя.");
                            }
                        }
                    }
                    else
                    {
                        DiscordGuild server;
                        ulong        serverId = Convert.ToUInt64(GuildId.Text);
                        if (MainWindow.userClient.Guilds.TryGetValue(serverId, out server))
                        {
                            ulong channelIdVal = Convert.ToUInt64(ChannelId.Text);
                            try
                            {
                                DiscordChannel channel = server.GetChannel(channelIdVal);
                                if (channel != null)
                                {
                                    targChannel = channel;
                                }
                                else
                                {
                                    MessageBox.Show("Ошибка: неверный ID канала.");
                                }
                            }
                            catch (Exception)
                            {
                                MessageBox.Show("Ошибка: неверный ID канала.");
                            }
                        }
                        else
                        {
                            MessageBox.Show("Ошибка: неверный ID сервера.");
                        }
                    }
                }
                catch (Exception) { return; }

                int interval = 0;

                if (!int.TryParse(SpamPeriod.Text, out interval))
                {
                    return;
                }

                msg       = SpamContent.Text;
                spamTimer = new Timer()
                {
                    Interval = interval
                };
                spamTimer.Elapsed += sendMsg;
                spamTimer.Start();
                senderBtn.Content = "Стоп";
            }
            else
            {
                spamTimer.Stop();
                spamTimer         = null;
                senderBtn.Content = "Старт";
            }
        }
Пример #26
0
        public async Task TempMuteMember(CommandContext ctx, DiscordMember user, string duration, [RemainingText] string reason)
        {
            if (user == ctx.Member)
            {
                return;
            }
            if (!CheckInteraction.CanModerate(ctx.Member, user))
            {
                await ctx.Message.DeleteAsync();

                return;
            }
            var role         = ctx.Guild.GetRole(826243826946408498);
            var textChannels = await ctx.Guild.GetChannelsAsync();

            foreach (var channel in textChannels.Where(x => x.Type == ChannelType.Text))
            {
                if (!channel.PermissionOverwrites.Any(x => x.CheckPermission(Permissions.SendMessages) == PermissionLevel.Denied))
                {
                    await channel.AddOverwriteAsync(role, deny : Permissions.SendMessages);
                }
            }
            var voiceChannels = await ctx.Guild.GetChannelsAsync();

            foreach (var channel in voiceChannels.Where(x => x.Type == ChannelType.Voice))
            {
                if (!channel.PermissionOverwrites.Any(x => x.CheckPermission(Permissions.SendMessages) == PermissionLevel.Denied))
                {
                    await channel.AddOverwriteAsync(role, deny : Permissions.Speak);
                }
            }
            var caseId = await produceID(20);

            char minute    = 'm';
            char day       = 'd';
            char hour      = 'h';
            char second    = 's';
            char week      = 'w';
            var  MuteTimer = new string(duration.Where(char.IsDigit).ToArray());

            if (minute.ToString().Any(duration.Contains) && day.ToString().Any(duration.Contains) && hour.ToString().Any(duration.Contains) && second.ToString().Any(duration.Contains))
            {
                await ctx.Channel.SendMessageAsync("You cannot pass multiple time formats.");

                return;
            }
            if (MuteTimer.Length == 0)
            {
                return;
            }
            var Timer = Convert.ToInt32(MuteTimer);

            if (minute.ToString().Any(duration.ToLower().Contains))
            {
                Bot.Mutes.Add(new Mute {
                    Guild = ctx.Guild, User = user, End = DateTime.Now + TimeSpan.FromMinutes(Timer), Role = role
                });
            }
            else if (day.ToString().Any(duration.ToLower().Contains))
            {
                Bot.Mutes.Add(new Mute {
                    Guild = ctx.Guild, User = user, End = DateTime.Now + TimeSpan.FromDays(Timer), Role = role
                });
            }
            else if (second.ToString().Any(duration.ToLower().Contains))
            {
                Bot.Mutes.Add(new Mute {
                    Guild = ctx.Guild, User = user, End = DateTime.Now + TimeSpan.FromSeconds(Timer), Role = role
                });
            }
            else if (hour.ToString().Any(duration.ToLower().Contains))
            {
                Bot.Mutes.Add(new Mute {
                    Guild = ctx.Guild, User = user, End = DateTime.Now + TimeSpan.FromHours(Timer), Role = role
                });
            }
            else if (week.ToString().Any(duration.ToLower().Contains))
            {
                Bot.Mutes.Add(new Mute {
                    Guild = ctx.Guild, User = user, End = DateTime.Now + TimeSpan.FromDays(Timer * 7), Role = role
                });
            }
            else
            {
                Console.WriteLine("");
            }
            await user.GrantRoleAsync(role);

            var e = new DiscordEmbedBuilder()
                    .WithDescription($"{user.Username} was muted with ID: `{caseId}`\n**{user.Username}**, check your DM's for information.")
                    .WithColor(DiscordColor.Green);
            var message = ctx.Channel.SendMessageAsync(embed: e.Build()).Result;
            await Task.Delay(5000);

            await message.DeleteAsync();

            var userEmbed = new DiscordEmbedBuilder()
                            .WithTitle("You were muted")
                            .WithColor(DiscordColor.Red)
                            .WithDescription($"You were muted in {ctx.Guild.Name}\n\nYou were muted for reason: {reason}.\nCaseID: `{caseId}`\n\nMute Timer: {duration}");

            try
            {
                await user.CreateDmChannelAsync();

                await user.SendMessageAsync(embed : userEmbed.Build());
            }
            catch (Exception)
            {
                Console.WriteLine("Unable to DM user.");
            }
        }
Пример #27
0
        private async void SendEmbed(object sender, RoutedEventArgs e)
        {
            if (MainWindow.userClient != null)
            {
                DiscordEmbedBuilder embedBuilder = new DiscordEmbedBuilder();

                embedBuilder.Title = EmbGenTitle.Text;

                embedBuilder.Description = EmbGenDescription.Text;

                Color col = EmbGenColor.SelectedColor ?? Colors.Black;
                embedBuilder.Color = new DiscordColor(col.R, col.G, col.B);

                embedBuilder.ImageUrl = EmbGenImgURL.Text;

                embedBuilder.ThumbnailUrl = EmbGenAvatarURL.Text;

                embedBuilder.Url = EmbGenTitleURL.Text;

                foreach (StackPanel panel in EmbGenParams.Items)
                {
                    TextBox  nameBox   = (TextBox)panel.Children[0];
                    TextBox  valueBox  = (TextBox)panel.Children[1];
                    CheckBox inlineBox = (CheckBox)panel.Children[2];

                    embedBuilder.AddField(nameBox.Text, valueBox.Text, inlineBox.IsChecked ?? false);
                }

                if (IsDirect.IsChecked ?? false)
                {
                    DiscordGuild server;
                    ulong        serverId = Convert.ToUInt64(GuildId.Text);
                    if (MainWindow.userClient.Guilds.TryGetValue(serverId, out server))
                    {
                        ulong channelIdVal = Convert.ToUInt64(ChannelId.Text);
                        try
                        {
                            DiscordMember dmUser = await server.GetMemberAsync(channelIdVal);

                            DiscordDmChannel dm = await dmUser.CreateDmChannelAsync();

                            if (dm != null)
                            {
                                MessageBoxResult result = MessageBox.Show($"Вы хотите отправить сообщение {dmUser.Username}. Продолжить?", "Ожидание подтверждения", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No);
                                if (result == MessageBoxResult.No)
                                {
                                    MessageBox.Show("Отправка отменена.");
                                    return;
                                }
                                await dm.SendMessageAsync(embed : embedBuilder.Build());
                            }
                            else
                            {
                                MessageBox.Show("Ошибка: неверный ID пользователя.");
                            }
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("Ошибка: неверный ID пользователя.");
                        }
                    }
                    else
                    {
                        MessageBox.Show("Ошибка: неверный ID сервера.");
                    }
                }
                else
                {
                    DiscordGuild server;
                    ulong        serverId = Convert.ToUInt64(GuildId.Text);
                    if (MainWindow.userClient.Guilds.TryGetValue(serverId, out server))
                    {
                        ulong channelIdVal = Convert.ToUInt64(ChannelId.Text);
                        try
                        {
                            DiscordChannel channel = server.GetChannel(channelIdVal);
                            if (channel != null)
                            {
                                MessageBoxResult result = MessageBox.Show($"Вы хотите отправить сообщение в канал {channel.Name} на сервере {server.Name}. Продолжить?", "Ожидание подтверждения", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No);
                                if (result == MessageBoxResult.No)
                                {
                                    MessageBox.Show("Отправка отменена.");
                                    return;
                                }
                                await channel.SendMessageAsync(embed : embedBuilder.Build());
                            }
                            else
                            {
                                MessageBox.Show("Ошибка: неверный ID канала.");
                            }
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("Ошибка: неверный ID канала.");
                        }
                    }
                    else
                    {
                        MessageBox.Show("Ошибка: неверный ID сервера.");
                    }
                }
            }
            else
            {
                MessageBox.Show("Ошибка: клиент не подключен.");
            }
        }
Пример #28
0
        private async Task ExecuteKickCommand(CommandContext ctx,
                                              DiscordMember member,
                                              String Reason,
                                              Boolean Silent,
                                              Boolean DmMember,
                                              Boolean Invite)
        {
            if (!ctx.Member.HasPermission("insanitybot.moderation.kick"))
            {
                await ctx.Channel.SendMessageAsync(InsanityBot.LanguageConfig["insanitybot.error.lacking_permission"]);

                return;
            }

            //actually do something with the usedefault value
            String KickReason = Reason switch
            {
                "usedefault" => GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.no_reason_given"],
                                                   ctx, member),
                _ => GetFormattedString(Reason, ctx, member)
            };

            DiscordEmbedBuilder embedBuilder = null;

            DiscordEmbedBuilder moderationEmbedBuilder = new()
            {
                Title  = "KICK",
                Color  = DiscordColor.Red,
                Footer = new DiscordEmbedBuilder.EmbedFooter
                {
                    Text = "InsanityBot 2020-2021"
                }
            };

            moderationEmbedBuilder.AddField("Moderator", ctx.Member.Mention, true)
            .AddField("Member", member.Mention, true)
            .AddField("Reason", KickReason, true);

            try
            {
                _            = member.TryAddModlogEntry(ModlogEntryType.kick, KickReason);
                embedBuilder = new DiscordEmbedBuilder
                {
                    Description = GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.kick.success"],
                                                     ctx, member),
                    Color  = DiscordColor.Red,
                    Footer = new DiscordEmbedBuilder.EmbedFooter
                    {
                        Text = "InsanityBot 2020-2021"
                    }
                };

                if (Invite || DmMember)
                {
                    DiscordDmChannel channel = await member.CreateDmChannelAsync();

                    if (DmMember)
                    {
                        await channel.SendMessageAsync(GetReason(GetFormattedString(
                                                                     InsanityBot.LanguageConfig["insanitybot.moderation.kick.reason"],
                                                                     ctx, member), KickReason));
                    }

                    if (Invite)
                    {
                        await channel.SendMessageAsync((await ctx.Channel.CreateInviteAsync()).ToString());
                    }
                }

                _ = member.RemoveAsync(KickReason);
                _ = InsanityBot.ModlogQueue.QueueMessage(ModlogMessageType.Moderation, new DiscordMessageBuilder
                {
                    Embed = moderationEmbedBuilder
                });
            }
            catch (Exception e)
            {
                embedBuilder = new DiscordEmbedBuilder
                {
                    Description = GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.kick.failure"],
                                                     ctx, member),
                    Color  = DiscordColor.Red,
                    Footer = new DiscordEmbedBuilder.EmbedFooter
                    {
                        Text = "InsanityBot 2020-2021"
                    }
                };
                InsanityBot.Client.Logger.LogError($"{e}: {e.Message}");
            }
            finally
            {
                if (!Silent)
                {
                    await ctx.Channel.SendMessageAsync(embed : embedBuilder.Build());
                }
            }
        }
    }
Пример #29
0
 public Player(DiscordMember user)
 {
     this.user = user;
     dmChannel = user.CreateDmChannelAsync().Result;
 }
Пример #30
0
        public async Task DeleteMessageByLinkAndNotify(CommandContext commandContext,
                                                       [Description("Deleteing message")] DiscordMessage msg,
                                                       [Description("Deleting reason"), RemainingText] string reason)
        {
            if (msg is null)
            {
                await commandContext.RespondAsync("Deleting message is not specified");

                return;
            }

            if (string.IsNullOrEmpty(reason))
            {
                reason = "not stated";
            }

            DiscordEmbedBuilder builder = new DiscordEmbedBuilder()
                                          .WithFooter($"Mod: {commandContext.Message.Author.Username} {msg.Timestamp}", iconUrl: commandContext.Message.Author.AvatarUrl)
                                          .WithDescription(msg.Content);


            if (!(msg.Author is null))
            {
                builder.WithAuthor(name: $"From {msg.Channel.Name} by {msg.Author.Username}",
                                   iconUrl: msg.Author.AvatarUrl);
            }

            DiscordMember user = await wavGuild.GetMemberAsync(msg.Author.Id);

            if (!user.IsBot)
            {
                DiscordDmChannel targetChannel = await user.CreateDmChannelAsync();

                await targetChannel.SendMessageAsync(content : $"Удалено по причине по причине: {reason}", embed : builder.Build());

                if (msg.Embeds?.Count != 0)
                {
                    foreach (var embed in msg.Embeds)
                    {
                        await targetChannel.SendMessageAsync(embed : embed);
                    }
                }

                if (msg.Attachments?.Count != 0)
                {
                    foreach (var att in msg.Attachments)
                    {
                        await targetChannel.SendMessageAsync(att.Url);
                    }
                }
            }

            await LogChannel.SendMessageAsync(
                embed : new DiscordEmbedBuilder().WithAuthor(name : commandContext.Message.Author.Username, iconUrl : commandContext.Message.Author.AvatarUrl)
                .AddField("**Action**:", "delete message", true)
                .AddField("**Violator**:", msg.Author.Mention, true)
                .AddField("**From**:", msg.Channel.Name, true)
                .AddField("**Reason**:", reason, true)
                .WithFooter()
                .Build());

            await LogChannel.SendMessageAsync(content : $"Deleted message: \n{new string('=', 20)}\n{msg.Content}");

            if (msg.Embeds?.Count != 0)
            {
                foreach (var embed in msg.Embeds)
                {
                    await LogChannel.SendMessageAsync(embed: embed);
                }
            }

            if (msg.Attachments?.Count != 0)
            {
                foreach (var att in msg.Attachments)
                {
                    await LogChannel.SendMessageAsync(att.Url);
                }
            }

            await msg.Channel.DeleteMessageAsync(msg, reason);
        }