Ejemplo n.º 1
0
        private async Task ParseWarnCommand(CommandContext ctx, DiscordMember target, String arguments)
        {
            String cmdArguments = arguments;

            try
            {
                if (!arguments.Contains("-r") && !arguments.Contains("--reason"))
                {
                    cmdArguments += " --reason usedefault";
                }

                await Parser.Default.ParseArguments <WarnOptions>(cmdArguments.Split(' '))
                .WithParsedAsync(async o =>
                {
                    await ExecuteWarn(ctx, target, String.Join(' ', o.Reason), o.Silent, o.DmMember);
                });
            }
            catch (Exception e)
            {
                DiscordEmbedBuilder failed = new()
                {
                    Description = GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.warn.failure"],
                                                     ctx, target),
                    Color  = DiscordColor.Red,
                    Footer = new DiscordEmbedBuilder.EmbedFooter
                    {
                        Text = "InsanityBot 2020-2021"
                    }
                };
                InsanityBot.Client.Logger.LogError($"{e}: {e.Message}");

                await ctx.Channel.SendMessageAsync(embed : failed.Build());
            }
        }
Ejemplo n.º 2
0
        public async Task AddCommand(CommandContext ctx, DiscordMember member, [Description("When to remind someone (d/h/m/s) Ex. 7d for 7 Days")] string When, [Description("What to remind someone to"), RemainingText] string What = "No reminder message specified")
        {
            double   Time     = JokinsCommon.Methods.TimeConverter(When);
            DateTime dateTime = DateTime.Now.AddMilliseconds(Time);

            DiscordEmbedBuilder Reminder = new DiscordEmbedBuilder {
                Title       = $"Reminder | {member.Username}",
                Description = $"**Ok, I will remind him the following on {dateTime:dd.MM.yyyy HH:mm}:**\n{What}",
                Color       = Program.EmbedColor,
                Footer      = new DiscordEmbedBuilder.EmbedFooter {
                    Text = "Made by JokinAce 😎"
                },
                Timestamp = DateTimeOffset.Now
            };
            await ctx.RespondAsync(Reminder);

            await Program.SQLC.AddReminder((long)member.Id, (long)ctx.Channel.Id, dateTime.ToBinary(), What);

            _ = Task.Run(async() => {
                await Task.Delay((int)Time);

                await ctx.Channel.SendMessageAsync($":alarm_clock:, {member.Mention} someone wanted me to remind you the following:\n\n{What}");
                await Program.SQLC.DeleteRemindersWithDate(dateTime.ToBinary());
            });
        }
    }
Ejemplo n.º 3
0
        private Task GuildMemberAdded(GuildMemberAddEventArgs e)
        {
            var joinedLeftEventId = _redis.StringGet($"{e.Guild.Id}:Logs:JoinedLeftEvent");

            var guild  = e.Guild;
            var member = e.Member;

            if (!string.IsNullOrWhiteSpace(joinedLeftEventId))
            {
                var logChannel  = guild.GetChannel((ulong)joinedLeftEventId);
                var avatarUrl   = member.AvatarUrl;
                var title       = ":inbox_tray: Member joined";
                var description = new StringBuilder().AppendLine($"Username: `{member.GetUsertag()}`").AppendLine($"User identity: `{member.Id}`").AppendLine($"Registered: {member.CreatedAtLongDateTimeString().Result}").ToString();

                var footer = new DiscordEmbedBuilder.EmbedFooter
                {
                    Text = $"Member Id: {member.Id}"
                };

                logChannel.SendEmbedMessageAsync(title, description, DiscordColor.SpringGreen, thumbnailUrl: avatarUrl, footer: footer, timestamp: DateTimeOffset.UtcNow);
            }

            _logger.Information($"'{e.Member.GetUsertag()}' ({e.Member.Id}) has joined the guild '{e.Guild.Name}' ({e.Guild.Id}).");

            return(Task.CompletedTask);
        }
Ejemplo n.º 4
0
        public async Task TempmuteCommand(CommandContext ctx, [Description("The Member to mute (ID, Mention, Username)")] DiscordMember member, [RemainingText, Description("Length (d/h/m/s) Ex. 7d for 7 Days")] string time)
        {
            var PS = await Program.PlayerSystem.GetPlayer(member.Id);

            PS.Muted = true;
            await PS.Save(member.Id);

            double Time = Misc.TimeConverter(time);

            DiscordEmbedBuilder TempMute = new DiscordEmbedBuilder {
                Title       = $"TempMute | {member.Username}",
                Description = $"**{member.Mention} has been muted for {time}\nUnmuted on {DateTime.Now.AddMilliseconds(Time):dd.MM.yyyy HH:mm}**",
                Color       = Program.EmbedColor,
                Footer      = new DiscordEmbedBuilder.EmbedFooter {
                    Text = "Made by JokinAce 😎"
                },
                Timestamp = DateTimeOffset.Now
            };
            await ctx.RespondAsync(embed : TempMute);

            _ = Task.Run(async() => {
                try {
                    DiscordRole MutedRole = ctx.Guild.GetRole(Program.MutedRole);
                    await member.GrantRoleAsync(MutedRole);
                    await Task.Delay((int)Time);
                    var PS   = await Program.PlayerSystem.GetPlayer(member.Id);
                    PS.Muted = false;
                    await PS.Save(member.Id);
                    await member.RevokeRoleAsync(MutedRole);
                } catch (Exception) {
                    ctx.Client.Logger.LogInformation($"Failed the Tempmute process for {member.Mention}");
                }
            });
        }
    }
Ejemplo n.º 5
0
        public async Task UnlockCommand(CommandContext ctx, String args)
        {
            try
            {
                String cmdArguments = args;

                if (!args.Contains("-r") && !args.Contains("--reason"))
                {
                    cmdArguments += " --reason usedefault";
                }

                await Parser.Default.ParseArguments <LockOptions>(cmdArguments.Split(' '))
                .WithParsedAsync(async o =>
                {
                    await UnlockCommand(ctx, InsanityBot.HomeGuild.GetChannel(o.ChannelId), String.Join(' ', o.Reason), o.Silent);
                });
            }
            catch (Exception e)
            {
                DiscordEmbedBuilder failed = new()
                {
                    Description = GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.unlock.failure"],
                                                     ctx),
                    Color  = DiscordColor.Red,
                    Footer = new DiscordEmbedBuilder.EmbedFooter
                    {
                        Text = "InsanityBot 2020-2021"
                    }
                };
                InsanityBot.Client.Logger.LogError($"{e}: {e.Message}");

                await ctx.Channel.SendMessageAsync(embed : failed.Build());
            }
        }
Ejemplo n.º 6
0
        public static async Task SendLeaveMessageAsync(GuildMemberlogs g, string?msg, string username, string avatarUrl)
        {
            if (DiscordBot.Bot?.Rest is null)
            {
                return;
            }

            if (g.LeaveMessage?.IsEmbed ?? false)
            {
                DiscordEmbedBuilder embed = new DiscordEmbedBuilder()
                {
                    Color       = new DiscordColor(CommandModule.Colors[ColorType.Memberlog][1]),
                    Description = msg is null ? "" : msg,
                    Footer      = new DiscordEmbedBuilder.EmbedFooter()
                    {
                        IconUrl = avatarUrl,
                        Text    = "User Left"
                    },
                    Timestamp = DateTime.Now
                };

                try
                {
                    await DiscordBot.Bot.Rest.CreateMessageAsync(g.MemberlogChannel ?? 0UL, embed);
                }
                catch { /* Ignore errors from the REST client sening in the backgroung. */ }                 // ignore
            }
            else if (g.LeaveMessage?.IsImage ?? false)
            {
                using var stream = await SvgHandler.GetWelcomeImage(false, username, avatarUrl);

                if (!(stream is null))
                {
                    try
                    {
                        await DiscordBot.Bot.Rest.CreateMessageAsync(g.MemberlogChannel ?? 0UL,
                                                                     new DiscordMessageBuilder().WithFile("farewell-message.png", stream));
                    }
                    catch { /* Ignore errors from the REST client sening in the backgroung. */ }                     // ignore
                }
            }
            else if (!(g.LeaveMessage?.Message is null))
            {
                try
                {
                    await DiscordBot.Bot.Rest.CreateMessageAsync(g.MemberlogChannel ?? 0UL, msg);
                }
                catch { /* Ignore errors from the REST client sening in the backgroung. */ } // ignore
            }
        }
Ejemplo n.º 7
0
        public static async Task SendJoinMessageAsync(GuildMemberlogs g, string?msg, string username, string avatarUrl)
        {
            if (DiscordBot.Bot?.Rest is null)
            {
                return;
            }

            if (g.JoinMessage?.IsEmbed ?? false)
            {
                DiscordEmbedBuilder embed = new DiscordEmbedBuilder()
                {
                    Color       = new DiscordColor(CommandModule.Colors[ColorType.Memberlog][0]),
                    Description = msg is null ? "" : msg,
                    Footer      = new DiscordEmbedBuilder.EmbedFooter()
                    {
                        IconUrl = avatarUrl,
                        Text    = "User Joined"
                    },
                    Timestamp = DateTime.Now
                };

                try
                {
                    await DiscordBot.Bot.Rest.CreateMessageAsync(g.MemberlogChannel ?? 0UL, embed);
                }
                catch { /* Backgroun task, ignore rest exceptions. */ }                 // ignore
            }
            else if (g.JoinMessage?.IsImage ?? false)
            {
                using var stream = await SvgHandler.GetWelcomeImage(true, username, avatarUrl);

                if (!(stream is null))
                {
                    try
                    {
                        await DiscordBot.Bot.Rest.CreateMessageAsync(g.MemberlogChannel ?? 0UL,
                                                                     new DiscordMessageBuilder().WithFile("welcome-message.png", stream));
                    }
                    catch { /* Backgroun task, ignore rest exceptions. */ } // ignore
                }
            }
            else if (!(msg is null))
            {
                try
                {
                    await DiscordBot.Bot.Rest.CreateMessageAsync(g.MemberlogChannel ?? 0UL, msg);
                }
                catch { /* Backgroun task, ignore rest exceptions. */ }                 // ignore
            }
        }
Ejemplo n.º 8
0
        public static async Task SendBotMessage(String message, DiscordChannel channel, DiscordUser user = null)
        {
            if (Config.BlaclistedServers.Contains(channel.Parent.Name))
            {
                return;
            }                                                                       //Check if server is blacklisted
            if (message == "")
            {
                return;
            }                              //Check if message = Empty(Rule to not send message)
            string[] Sentances = message.Split('$');
            int      i         = 0;

            for (i = 0; i < Sentances.Length; i++)
            {
                String Sentance = Sentances[i];
                //Construct Sentance
                String Msg = Sentance;
                DiscordEmbedBuilder.EmbedAuthor DEFA = null;
                DiscordEmbedBuilder.EmbedFooter DEF  = null;
                if (user != null)
                {
                    DEF = new DiscordEmbedBuilder.EmbedFooter {
                        IconUrl = user.AvatarUrl,
                        Text    = "Executed by: " + user.Username + "#" + user.Discriminator
                    };
                    DEFA = new DiscordEmbedBuilder.EmbedAuthor {
                        IconUrl = Program.discord.CurrentUser.AvatarUrl,
                        Name    = Program.discord.CurrentUser.Username + "#" + Program.discord.CurrentUser.Discriminator
                    };
                }

                DiscordEmbed demd = new DiscordEmbedBuilder {
                    Color       = DiscordColor.Orange,
                    Description = Msg,
                    //ImageUrl = "http://onno204vps.nl.eu.org/Site1/AddOns/Pictures/Image.png",
                    Url    = Config.ReplyLink,
                    Footer = DEF,
                    Author = DEFA
                };

                Utils.Log(Msg, LogType.SendedMessages);
                if (Config.NoChatOutput)
                {
                    return;
                }
                await Program.discord.SendMessageAsync(channel, "", embed : demd).ConfigureAwait(false);
            }
        }
Ejemplo n.º 9
0
        public async Task Status(CommandContext ctx)
        {
            DiscordEmoji rabbitEmoji  = DiscordEmoji.FromName(ctx.Client, ":rabbit2:");
            DiscordEmoji rabbit2Emoji = DiscordEmoji.FromName(ctx.Client, ":rabbit:");
            DiscordEmoji toolsEmoji   = DiscordEmoji.FromName(ctx.Client, ":tools:");
            DiscordEmoji tadaEmoji    = DiscordEmoji.FromName(ctx.Client, ":tada:");
            DiscordEmoji sadEmoji     = DiscordEmoji.FromName(ctx.Client, ":cry:");

            var embedThumbnail = new DiscordEmbedBuilder.EmbedThumbnail
            {
                Url = Links.STATUS_THUMBNAIL_BUN
            };
            var embedFooter = new DiscordEmbedBuilder.EmbedFooter
            {
                Text = "Brought to you with <3 by Kubi, Genghis & pals"
            };

            var embed = new DiscordEmbedBuilder
            {
                Title     = $"{rabbitEmoji} LeafBot Status {toolsEmoji}",
                ImageUrl  = Links.STATUS_BUN,
                Thumbnail = embedThumbnail,
                Footer    = embedFooter,
                Color     = DiscordColor.SpringGreen,
            };

            var     uptime   = (DateTime.Now - Stats.StartTime);
            decimal upDays   = uptime.Days;
            decimal bunYears = Math.Round((upDays / 365) * 7.5M, 6);

            embed.AddField("Version", Program.VERSION, true);
            embed.AddField("DSharp Version", ctx.Client.VersionString, true);
            embed.AddField("Ping", ctx.Client.Ping.ToString(), true);
            embed.AddField("Bunnies served", Stats.BunniesServed.ToString(), true);
            embed.AddField("Commands run", Stats.ExecutedCommands.ToString(), true);
            embed.AddField("Roles picked", Stats.RolesPicked.ToString(), true);
            embed.AddField("Command errors", Stats.CommandErrors == 0 ? $"{tadaEmoji} {Stats.CommandErrors.ToString()} {tadaEmoji}" : Stats.CommandErrors.ToString() + $" {sadEmoji}", true);
            embed.AddField("Guilds", ctx.Client.Guilds.Count.ToString(), true);
            embed.AddField("Uptime", $"{uptime.Days} days {uptime.Hours} hours {uptime.Minutes} minutes {uptime.Seconds} seconds");
            embed.AddField("Age", $"{bunYears} bunny years {rabbit2Emoji}");
            embed.AddField("Connected to", ctx.Guild.Name.ToString(), true);
            embed.AddField("Running on", Stats.PCName, true);

            // Update bunnies served stat (there is a pic of a bunny in the status in bed silly)
            Stats.BunniesServed++;

            await ctx.Channel.SendMessageAsync(embed : embed);
        }
Ejemplo n.º 10
0
        private async Task ParseMuteCommand(CommandContext ctx,
                                            DiscordMember member,
                                            String arguments)
        {
            String cmdArguments = arguments;

            try
            {
                if (!arguments.Contains("-r") && !arguments.Contains("--reason"))
                {
                    cmdArguments += " --reason usedefault";
                }

                await Parser.Default.ParseArguments <MuteOptions>(cmdArguments.Split(' '))
                .WithParsedAsync(async o =>
                {
                    if (o.Time == "default")
                    {
                        await ExecuteMuteCommand(ctx, member, String.Join(' ', o.Reason), o.Silent, o.DmMember);
                    }
                    else
                    {
                        await ExecuteTempmuteCommand(ctx, member,
                                                     o.Time.ParseTimeSpan(TemporaryPunishmentType.Mute),
                                                     String.Join(' ', o.Reason), o.Silent, o.DmMember);
                    }
                });
            }
            catch (Exception e)
            {
                DiscordEmbedBuilder failed = new()
                {
                    Description = GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.mute.failure"],
                                                     ctx, member),
                    Color  = DiscordColor.Red,
                    Footer = new DiscordEmbedBuilder.EmbedFooter
                    {
                        Text = "InsanityBot 2020-2021"
                    }
                };
                InsanityBot.Client.Logger.LogError($"{e}: {e.Message}");

                await ctx.Channel.SendMessageAsync(embed : failed.Build());
            }
        }
Ejemplo n.º 11
0
        public async Task Urban(CommandContext ctx, [Description("The term to search")][RemainingText]
                                string text)
        {
            if (ctx.Channel.Get(ConfigManager.Enabled)
                .And(ctx.Channel.GetMethodEnabled()))
            {
                await ctx.TriggerTypingAsync();

                if (ctx.Channel.GetEvaluatedNsfw())
                {
                    using WebClient c = new WebClient();
                    JObject result = (JObject)JObject.Parse(c.DownloadString(
                                                                $"https://api.urbandictionary.com/v0/define?term={Uri.EscapeUriString(text)}"))["list"][0];
                    string definition = result.Value <string>("definition") ?? "";
                    definition = string.IsNullOrWhiteSpace(definition) ? "Not found" : definition;
                    string example = result.Value <string>("example") ?? "";
                    example = string.IsNullOrWhiteSpace(example) ? "Not found" : example;
                    string word = result.Value <string>("word") ?? "";
                    word = string.IsNullOrWhiteSpace(word) ? "Not found" : word;
                    string author = result.Value <string>("author") ?? "";
                    author = string.IsNullOrWhiteSpace(author) ? "Not found" : author;
                    string url =
                        $"https://www.urbandictionary.com/author.php?author={Uri.EscapeUriString(result.Value<string>("author"))}";
                    Console.WriteLine(author);
                    Console.WriteLine(url);
                    DiscordEmbed embed = new DiscordEmbedBuilder
                    {
                        Title  = word,
                        Author = new DiscordEmbedBuilder.EmbedAuthor
                        {
                            Name = author,
                            //Url = url
                        },
                        Url    = result.Value <string>("permalink"),
                        Footer = new DiscordEmbedBuilder.EmbedFooter
                        {
                            Text = $"{result.Value<string>("thumbs_up")}+ {result.Value<string>("thumbs_down")}-"
                        },
                        Timestamp = DateTime.TryParse(result.Value <string>("written_on"), out DateTime t)
                                ? t.Date
                                : new DateTime(2000, 1, 1)
                    }
Ejemplo n.º 12
0
        /// <summary>
        /// Restores the messages.
        /// </summary>
        internal static void RestoreMessages()
        {
            try
            {
                foreach (var Line in File.ReadAllLines("Backups/Messages.txt"))
                {
                    var Message = Line.Split(',');

                    var Channel = DiscordBot.Discord.GetChannelAsync(ulong.Parse(Message[2])).Result;

                    var Author = new DiscordEmbedBuilder.EmbedAuthor
                    {
                        Name = Message[0],
                        IconUrl = Message[1]
                    };

                    var Time = DateTimeOffset.Parse(Message[4]);

                    var Footer = new DiscordEmbedBuilder.EmbedFooter
                    {
                        Text = Time.Date.ToLongDateString()
                    };

                    var Embed = new DiscordEmbedBuilder
                    {
                        Author = Author,
                        Description = Environment.NewLine + Message[3] + Environment.NewLine,
                        Color = DiscordColor.CornflowerBlue,
                        Footer = Footer
                    };

                    Channel.SendMessageAsync(embed: Embed);
                }
            }
            catch (Exception Exception)
            {
                Console.WriteLine();
                Console.WriteLine($"{Exception.GetType()} : {Exception.Message}");
                Console.WriteLine();
            }
        }
        public async Task RemindmeCommand(CommandContext ctx, [Description("When to remind you (d/h/m/s) Ex. 7d for 7 Days")] string When, [Description("What to remind you to"), RemainingText] string What = "No reminder message specified")
        {
            double Time = Misc.TimeConverter(When);

            DiscordEmbedBuilder Reminder = new DiscordEmbedBuilder {
                Title       = $"Reminder | {ctx.Member.Username}",
                Description = $"**Ok, I will remind you the following on {DateTime.Now.AddMilliseconds(Time):dd.MM.yyyy HH:mm}:**\n{What}",
                Color       = Program.EmbedColor,
                Footer      = new DiscordEmbedBuilder.EmbedFooter {
                    Text = "Made by JokinAce 😎"
                },
                Timestamp = DateTimeOffset.Now
            };
            await ctx.RespondAsync(embed : Reminder);

            _ = Task.Run(async() => {
                await Task.Delay((int)Time);
                await ctx.RespondAsync($":alarm_clock:, {ctx.Member.Mention} you wanted me to remind you the following:\n\n{What}");
            });
        }
    }
Ejemplo n.º 14
0
        public async Task Status(CommandContext ctx)
        {
            await ctx.TriggerTypingAsync();

            Assembly        assembly        = Assembly.GetExecutingAssembly();
            FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(assembly.Location);
            string          version         = fileVersionInfo.ProductVersion;
            var             uptimeDelta     = System.DateTime.Now - Program.StartTime;
            var             embedFooter     = new DiscordEmbedBuilder.EmbedFooter();

            embedFooter.Text = "dNewsBot by geckon01";

            await ctx.RespondAsync(embed : new DiscordEmbedBuilder
            {
                Title       = "Stats",
                Description = string.Format(Resource.ResourceManager.GetString("statistics-text", ctx.Channel.GetCultureInfo()),
                                            Program.Discord.Ping, Program.Discord.Guilds.Count, Program.Discord.CurrentUser.Username, $"{uptimeDelta.Days} days {uptimeDelta.Hours}h {uptimeDelta.Minutes:n0}m {uptimeDelta.Seconds:n0}s", (Process.GetCurrentProcess().WorkingSet64 / 1024) / 1024, version),
                Footer = embedFooter,
                Color  = DiscordColor.Blurple
            });
        }
Ejemplo n.º 15
0
        public async Task Roles(CommandContext context)
        {
            var guild        = context.Guild;
            var roles        = guild.Roles.Values;
            var thumbnailUrl = guild.IconUrl;

            var guildAuthor = new DiscordEmbedBuilder.EmbedAuthor
            {
                Name    = guild.Name,
                IconUrl = guild.IconUrl
            };

            var footer = new DiscordEmbedBuilder.EmbedFooter
            {
                Text = $"Requested by {context.User.GetUsertag()} | {context.User.Id}"
            };

            var rolesList = roles.Where(x => x.Name != "@everyone").OrderByDescending(r => r.Position).Aggregate("", (current, x) => current + $"<@&{x.Id}>\n");

            await context.EmbeddedMessage(description : rolesList, author : guildAuthor, footer : footer, thumbnailUrl : thumbnailUrl, timestamp : DateTimeOffset.UtcNow);
        }
Ejemplo n.º 16
0
        public ResponseBuilder(CommandContext ctx, string responseName) : base()
        {
            if (responseName.Length > 1)
            {
                var c = responseName[0];
                responseName = c.ToString().ToUpperInvariant() + responseName.Substring(1);
            }

            Footer = new DiscordEmbedBuilder.EmbedFooter()
            {
                Text    = "Response to " + ctx.User.Username,
                IconUrl = AvatarAPI + ctx.User.Id
            };
            Author = new DiscordEmbedBuilder.EmbedAuthor()
            {
                Name    = responseName,
                Url     = "http://hyperlight.chickatrice.net/",
                IconUrl = "https://i.imgur.com/KLNIH31.png"
            };
            Color     = new DiscordColor(12794879);
            Timestamp = DateTimeOffset.Now;
        }
Ejemplo n.º 17
0
        private Task GuildMemberRemoved(GuildMemberRemoveEventArgs e)
        {
            var joinedLeftEventId = _redis.StringGet($"{e.Guild.Id}:Logs:JoinedLeftEvent");

            var guild  = e.Guild;
            var member = e.Member;

            if (!string.IsNullOrWhiteSpace(joinedLeftEventId))
            {
                var          logChannel  = guild.GetChannel((ulong)joinedLeftEventId);
                var          avatarUrl   = member.AvatarUrl;
                const string title       = ":outbox_tray: Member left";
                var          description = new StringBuilder().AppendLine($"Username: `{member.GetUsertag()}`").AppendLine($"User identity: `{member.Id}`").ToString();

                var roles = member.Roles.Any() ? member.Roles.Where(x => x.Name != "@everyone").OrderByDescending(r => r.Position).Aggregate("", (current, x) => current + $"{x.Mention} ") : "None";

                var fields = new List <EmbedField>
                {
                    new EmbedField
                    {
                        Inline = false,
                        Name   = "Roles",
                        Value  = roles
                    }
                };

                var footer = new DiscordEmbedBuilder.EmbedFooter
                {
                    Text = $"Member Id: {member.Id}"
                };

                logChannel.SendEmbedMessageAsync(title, description, DiscordColor.IndianRed, fields: fields, thumbnailUrl: avatarUrl, footer: footer, timestamp: DateTimeOffset.UtcNow);
            }

            _logger.Information($"'{e.Member.GetUsertag()}' ({e.Member.Id}) has left the guild '{e.Guild.Name}' ({e.Guild.Id}).");

            return(Task.CompletedTask);
        }
Ejemplo n.º 18
0
        public static DiscordEmbedBuilder GenerateEmbed(string title, string footerText, string description, DiscordColor color, string footerUrl = "", string headerUrl = "")
        {
            var footer = new DiscordEmbedBuilder.EmbedFooter();

            footer.Text = footerText;
            var embed = new DiscordEmbedBuilder
            {
                Title       = title,
                Footer      = footer,
                Description = description,
                Color       = color
            };

            if (footerUrl != "")
            {
                embed.Footer.IconUrl = footerUrl;
            }
            if (headerUrl != "")
            {
                embed.ImageUrl = headerUrl;
            }
            return(embed);
        }
Ejemplo n.º 19
0
        private async Task ParseUnbanCommand(CommandContext ctx,
                                             UInt64 memberId,
                                             String arguments)
        {
            String cmdArguments = arguments;

            try
            {
                if (!arguments.Contains("-r") && !arguments.Contains("--reason"))
                {
                    cmdArguments += " --reason void"; //we dont need the reason but its required by the protocol
                }

                await Parser.Default.ParseArguments <UnbanOptions>(cmdArguments.Split(' '))
                .WithParsedAsync(async o =>
                {
                    await ExecuteUnbanCommand(ctx, memberId, o.Silent, o.DmMember);
                });
            }
            catch (Exception e)
            {
                DiscordEmbedBuilder failed = new()
                {
                    Description = GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.unban.failure"],
                                                     ctx, memberId),
                    Color  = DiscordColor.Red,
                    Footer = new DiscordEmbedBuilder.EmbedFooter
                    {
                        Text = "InsanityBot 2020-2021"
                    }
                };
                InsanityBot.Client.Logger.LogError(new EventId(1144, "Unban"), $"{e}: {e.Message}");

                await ctx.Channel.SendMessageAsync(embed : failed.Build());
            }
        }
Ejemplo n.º 20
0
        private async Task ExecutePurgeCommand(CommandContext ctx,
                                               Int32 messageCount,
                                               Boolean silent,
                                               String reason)
        {
            if (!ctx.Member.HasPermission("insanitybot.moderation.purge"))
            {
                await ctx.Channel.SendMessageAsync(InsanityBot.LanguageConfig["insanitybot.error.lacking_permission"]);

                return;
            }

            //if silent delete command
            if (silent)
            {
                await ctx.Message.DeleteAsync();
            }

            String ModlogEmbedReason = reason switch
            {
                "usedefault" => InsanityBot.LanguageConfig["insanitybot.moderation.purge.default_reason"],
                _ => reason
            };

            DiscordEmbedBuilder tmpEmbedBuilder = null, moderationEmbedBuilder = new()
            {
                Title  = "Purge",
                Color  = DiscordColor.Yellow,
                Footer = new DiscordEmbedBuilder.EmbedFooter
                {
                    Text = "InsanityBot 2020-2021"
                }
            };

            moderationEmbedBuilder.AddField("Moderator", ctx.Member.Mention, true)
            .AddField("Messages", messageCount.ToString(), true)
            .AddField("Reason", ModlogEmbedReason, true);

            try
            {
                Byte batches  = (Byte)(messageCount / 100),
                     leftover = (Byte)((messageCount % 100) + 1);

                IReadOnlyList <DiscordMessage> messageHolder = null;

                for (Byte b = 0; b < batches; b++)
                {
                    messageHolder = await ctx.Channel.GetMessagesAsync(100);

                    _ = ctx.Channel.DeleteMessagesAsync(messageHolder);
                }

                messageHolder = await ctx.Channel.GetMessagesAsync(leftover);

                _ = ctx.Channel.DeleteMessagesAsync(messageHolder);

                tmpEmbedBuilder = new DiscordEmbedBuilder
                {
                    Description = InsanityBot.LanguageConfig["insanitybot.moderation.purge.success"],
                    Color       = DiscordColor.Red,
                    Footer      = new DiscordEmbedBuilder.EmbedFooter
                    {
                        Text = "InsanityBot 2020-2021"
                    }
                };

                _ = InsanityBot.ModlogQueue.QueueMessage(ModlogMessageType.Moderation, new DiscordMessageBuilder
                {
                    Embed = moderationEmbedBuilder
                });
            }
            catch (Exception e)
            {
                tmpEmbedBuilder = new DiscordEmbedBuilder
                {
                    Description = InsanityBot.LanguageConfig["insanitybot.moderation.purge.failure"],
                    Color       = DiscordColor.Red,
                    Footer      = new DiscordEmbedBuilder.EmbedFooter
                    {
                        Text = "InsanityBot 2020-2021"
                    }
                };
                InsanityBot.Client.Logger.LogError($"{e}: {e.Message}");
            }
            finally
            {
                if (!silent)
                {
                    DiscordMessage msg = await ctx.Channel.SendMessageAsync(embed : tmpEmbedBuilder.Build());

                    Thread.Sleep(5000);
                    await msg.DeleteAsync();
                }
            }
        }
    }
Ejemplo n.º 21
0
        public async Task WarnModlogCommand(CommandContext ctx, DiscordMember user)
        {
            if (!ctx.Member.HasPermission("insanitybot.moderation.modlog"))
            {
                await ctx.Channel.SendMessageAsync(InsanityBot.LanguageConfig["insanitybot.error.lacking_permission"]);

                return;
            }

            try
            {
                _ = user.TryFetchModlog(out UserModlog modlog);

                DiscordEmbedBuilder modlogEmbed = new()
                {
                    Title = GetFormattedString(InsanityBot.LanguageConfig["insanitybot.commands.modlog.embed_title"],
                                               ctx, user),
                    Footer = new DiscordEmbedBuilder.EmbedFooter
                    {
                        Text = "InsanityBot 2020-2021"
                    }
                };

                if (modlog.ModlogEntryCount == 0)
                {
                    modlogEmbed.Color       = DiscordColor.SpringGreen;
                    modlogEmbed.Description = GetFormattedString(InsanityBot.LanguageConfig["insanitybot.commands.modlog.empty_modlog"],
                                                                 ctx, user);
                    _ = ctx.Channel.SendMessageAsync(embed: modlogEmbed.Build());
                }
                else
                {
                    if (!ToBoolean(InsanityBot.Config["insanitybot.commands.modlog.allow_scrolling"]))
                    {
                        modlogEmbed.Color       = DiscordColor.Red;
                        modlogEmbed.Description = user.CreateModlogDescription(ModlogEntryType.warn, false);

                        await ctx.Channel.SendMessageAsync(embed : modlogEmbed.Build());
                    }
                    else
                    {
                        modlogEmbed.Color = DiscordColor.Red;
                        String embedDescription = user.CreateModlogDescription(ModlogEntryType.warn);

                        IEnumerable <DSharpPlus.Interactivity.Page> pages = InsanityBot.Interactivity.GeneratePagesInEmbed(embedDescription, SplitType.Line, modlogEmbed);

                        await ctx.Channel.SendPaginatedMessageAsync(ctx.Member, pages);
                    }
                }
            }
            catch (Exception e)
            {
                InsanityBot.Client.Logger.LogError(new EventId(1170, "Modlog"), $"Could not retrieve modlogs: {e}: {e.Message}");

                DiscordEmbedBuilder failedModlog = new()
                {
                    Color       = DiscordColor.Red,
                    Description = GetFormattedString(InsanityBot.LanguageConfig["insanitybot.commands.modlog.failed"], ctx, user),
                    Footer      = new DiscordEmbedBuilder.EmbedFooter
                    {
                        Text = "InsanityBot 2020-2021"
                    }
                };
                await ctx.Channel.SendMessageAsync(embed : failedModlog.Build());
            }
        }
    }
Ejemplo n.º 22
0
        private async Task ExecuteMuteCommand(CommandContext ctx,
                                              DiscordMember member,
                                              String Reason,
                                              Boolean Silent,
                                              Boolean DmMember)
        {
            if (!ctx.Member.HasPermission("insanitybot.moderation.mute"))
            {
                await ctx.Channel.SendMessageAsync(InsanityBot.LanguageConfig["insanitybot.error.lacking_permission"]);

                return;
            }

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

            DiscordEmbedBuilder embedBuilder = null;

            DiscordEmbedBuilder moderationEmbedBuilder = new()
            {
                Title  = "MUTE",
                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", MuteReason, true);

            try
            {
                _            = member.TryAddModlogEntry(ModlogEntryType.mute, MuteReason);
                embedBuilder = new DiscordEmbedBuilder
                {
                    Description = GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.mute.success"],
                                                     ctx, member),
                    Color  = DiscordColor.Red,
                    Footer = new DiscordEmbedBuilder.EmbedFooter
                    {
                        Text = "InsanityBot 2020-2021"
                    }
                };
                _ = member.GrantRoleAsync(InsanityBot.HomeGuild.GetRole(
                                              ToUInt64(InsanityBot.Config["insanitybot.identifiers.moderation.mute_role_id"])),
                                          MuteReason);
                _ = InsanityBot.ModlogQueue.QueueMessage(ModlogMessageType.Moderation, new DiscordMessageBuilder
                {
                    Embed = moderationEmbedBuilder
                });
            }
            catch (Exception e)
            {
                embedBuilder = new DiscordEmbedBuilder
                {
                    Description = GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.mute.failure"],
                                                     ctx, member),
                    Color  = DiscordColor.Red,
                    Footer = new DiscordEmbedBuilder.EmbedFooter
                    {
                        Text = "InsanityBot 2020-2021"
                    }
                };
                InsanityBot.Client.Logger.LogError($"{e}: {e.Message}");
            }
            finally
            {
                await ctx.Channel.SendMessageAsync(embed : embedBuilder.Build());
            }
        }
    }
Ejemplo n.º 23
0
        /* ctx can be null if automated is true since ctx is only used for two purposes
         * its used to respond to the command execution, which does not happen when silent mode is enabled
         * (silent is enforced by auto mode)
         * and its used to verify permissions, but that check is never called when auto mode is enabled */
        private async Task ExecuteUnbanCommand(CommandContext ctx,
                                               UInt64 memberId,
                                               Boolean silent,
                                               Boolean automated = false,
                                               params Object[] additionals)
        {
            if (!automated && !ctx.Member.HasPermission("insanitybot.moderation.unban"))
            {
                await ctx.Channel.SendMessageAsync(InsanityBot.LanguageConfig["insanitybot.error.lacking_permission"]);

                return;
            }

            if (ctx == null && silent == false)
            {
                InsanityBot.Client.Logger.LogError(new EventId(1144, "Unban"),
                                                   "Invalid command arguments - internal error. Please report this on https://github.com/InsanityNetwork/InsanityBot/issues" +
                                                   "\nInsanityBot/Commands/Moderation/Unban.cs: argument \"silent\" cannot be false without given command context");
                return;
            }
            if (automated && !silent)
            {
                InsanityBot.Client.Logger.LogError(new EventId(1144, "Unban"),
                                                   "Invalid command arguments - internal error. Please report this on https://github.com/InsanityNetwork/InsanityBot/issues" +
                                                   "\nInsanityBot/Commands/Moderation/Unban.cs: argument \"silent\" cannot be false for an automated unban");
                return;
            }

            DiscordEmbedBuilder nonSilent = null;
            DiscordEmbedBuilder moderationEmbedBuilder = new()
            {
                Title  = "UNBAN",
                Color  = DiscordColor.SpringGreen,
                Footer = new DiscordEmbedBuilder.EmbedFooter
                {
                    Text = "InsanityBot 2020-2021"
                }
            };

            if (automated)
            {
                moderationEmbedBuilder.AddField("Moderator", "InsanityBot", true);
            }
            else
            {
                moderationEmbedBuilder.AddField("Moderator", ctx.Member.Mention, true);
            }

            moderationEmbedBuilder.AddField("Member", memberId.ToString(), true);

            try
            {
                if (silent)
                {
                    await InsanityBot.HomeGuild.UnbanMemberAsync(memberId);

                    if (additionals != null)
                    {
                        for (Byte b = 0; b < additionals.Length; b++)
                        {
                            if (additionals[b] is String str && str == "timer_guid")
                            {
                                moderationEmbedBuilder.AddField("Timer Guid", ((Guid)additionals[b + 1]).ToString(), true);
                            }
                        }
                    }
                }
                else
                {
                    nonSilent = new DiscordEmbedBuilder
                    {
                        Description = GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.unban.success"],
                                                         ctx, memberId),
                        Color  = DiscordColor.Green,
                        Footer = new DiscordEmbedBuilder.EmbedFooter
                        {
                            Text = "InsanityBot 2020-2021"
                        }
                    };


                    await InsanityBot.HomeGuild.UnbanMemberAsync(memberId);

                    if (additionals.Length >= 2)
                    {
                        for (Byte b = 0; b <= additionals.Length; b++)
                        {
                            if (additionals[b] is String str && str == "timer_guid")
                            {
                                moderationEmbedBuilder.AddField("Timer Guid", ((Guid)additionals[b + 1]).ToString(), true);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (!silent)
                {
                    nonSilent = new DiscordEmbedBuilder
                    {
                        Description = GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.unban.failure"],
                                                         ctx, memberId),
                        Color  = DiscordColor.Red,
                        Footer = new DiscordEmbedBuilder.EmbedFooter
                        {
                            Text = "InsanityBot 2020-2021"
                        }
                    };
                }

                InsanityBot.Client.Logger.LogError(new EventId(1144, "Unban"), $"{e}: {e.Message}");
            }
            finally
            {
                if (!silent)
                {
                    if (nonSilent != null)
                    {
                        _ = ctx.Channel.SendMessageAsync(embed: nonSilent.Build());
                    }
                    else
                    {
                        InsanityBot.Client.Logger.LogError(new EventId(1145, "Unban"), $"DiscordEmbedBuilder nonSilent was null");
                    }
                }

                _ = InsanityBot.ModlogQueue.QueueMessage(ModlogMessageType.Moderation, new DiscordMessageBuilder
                {
                    Embed = moderationEmbedBuilder
                });
            }
        }
    }
Ejemplo n.º 24
0
        //check et affichage par channel des lives
        private static async Task WebRequestAsync(Status id, DiscordClient client)
        {
            Random rnd            = new Random();
            string WEBSERVICE_URL = "https://api.twitch.tv/kraken/streams/" + id.Id;

            // string WEBSERVICE_URL = "https://api.twitch.tv/kraken/users?login=moman";
            try
            {
                var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
                if (webRequest != null)
                {
                    webRequest.Method      = "GET";
                    webRequest.Timeout     = 12000;
                    webRequest.ContentType = "application/json";
                    webRequest.Headers.Add("Client-ID", Token);
                    webRequest.Headers.Add("Accept", "application/vnd.twitchtv.v5+json");

                    using System.IO.Stream s        = webRequest.GetResponse().GetResponseStream();
                    using System.IO.StreamReader sr = new System.IO.StreamReader(s);
                    var jsonResponse = sr.ReadToEnd();
                    //Console.WriteLine(string.Format("Response: {0}", jsonResponse));
                    if (jsonResponse.Contains("display_name"))
                    {
                        var twitch = JsonConvert.DeserializeObject <Streamer>(jsonResponse);
                        //return string.Format("Response: {0}", jsonResponse);
                        if (!id.IsLive)
                        {
                            Console.WriteLine(string.Format($"Live {id.Name} up!"));
                            // wrap it into an embed
                            var embed = new DiscordEmbedBuilder
                            {
                                Title        = twitch.Stream.Channel.Display_name,
                                Description  = twitch.Stream.Channel.Status,
                                Url          = twitch.Stream.Channel.Url,
                                ImageUrl     = twitch.Stream.Preview.Medium + rnd.Next(999999),
                                ThumbnailUrl = twitch.Stream.Channel.Logo
                            };
                            DiscordEmbedBuilder.EmbedFooter foot = new DiscordEmbedBuilder.EmbedFooter
                            {
                                Text    = $"Joue à: " + twitch.Stream.Channel.Game,
                                IconUrl = "https://puush.poneyy.fr/TDaq.png"
                            };
                            embed.Footer = foot;
                            DiscordChannel info;
                            foreach (ulong channel in id.Channels)
                            {
                                info = await client.GetChannelAsync(channel);

                                await info.SendMessageAsync(embed : embed);
                            }

                            /* DiscordChannel info = await client.GetChannelAsync(channel);
                             * await info.SendMessageAsync(embed: embed);*/
                            var conf = LoadConfig();
                            conf.Status.First(d => d.Id == id.Id).IsLive = true;
                            await SaveConfig(conf);

                            client.DebugLogger.LogMessage(LogLevel.Info, "PoneyyBot", $"{id} en live", DateTime.Now);
                        }
                        else
                        {
                            client.DebugLogger.LogMessage(LogLevel.Info, "PoneyyBot", $"{id} en live", DateTime.Now);
                        }
                    }
                    else if (id.IsLive)
                    {
                        // wrap it into an embed
                        var embed = new DiscordEmbedBuilder
                        {
                            Title       = id.Name,
                            Description = "Fin du live:wave: :wave:",
                            Url         = "https://zerator.com/programmation"
                        };
                        DiscordEmbedBuilder.EmbedFooter foot = new DiscordEmbedBuilder.EmbedFooter
                        {
                            Text    = "Consultez la programmation pour plus d'informations!",
                            IconUrl = "https://puush.poneyy.fr/TDaq.png"
                        };
                        embed.Footer = foot;
                        DiscordChannel info;

                        /*info = await client.GetChannelAsync(id.Channels[0]);
                         * await info.SendMessageAsync(embed: embed);*/
                        foreach (ulong channel in id.Channels)
                        {
                            info = await client.GetChannelAsync(channel);

                            await info.SendMessageAsync(embed : embed);
                        }

                        var conf = LoadConfig();
                        conf.Status.First(d => d.Id == id.Id).IsLive = false;
                        await SaveConfig(conf);

                        client.DebugLogger.LogMessage(LogLevel.Info, "PoneyyBot", $"{id} plus en live", DateTime.Now);
                    }
                    //else Console.WriteLine($"{id} pas en live");
                    else
                    {
                        client.DebugLogger.LogMessage(LogLevel.Info, "PoneyyBot", $"{id} pas en live", DateTime.Now);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Ejemplo n.º 25
0
        private async Task ExecuteTempbanCommand(CommandContext ctx,
                                                 DiscordMember member,
                                                 TimeSpan time,
                                                 String Reason,
                                                 Boolean Silent,
                                                 Boolean DmMember)
        {
            if (!ctx.Member.HasPermission("insanitybot.moderation.tempban"))
            {
                await ctx.Channel.SendMessageAsync(InsanityBot.LanguageConfig["insanitybot.error.lacking_permission"]);

                return;
            }

            String BanReason = Reason switch
            {
                "usedefault" => GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.no_reason_given"],
                                                   ctx, member),
                _ => GetFormattedString(Reason, ctx, member)
            };

            DiscordEmbedBuilder embedBuilder = null;

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

            moderationEmbedBuilder.AddField("Moderator", ctx.Member.Mention, true)
            .AddField("Member", member.Mention, true)
            .AddField("Duration", time.ToString(), true)
            .AddField("Reason", BanReason, true);

            try
            {
                BanStartingEvent();

                Timer callbackTimer = new(DateTime.Now.Add(time), $"tempban_{member.Id}");
                moderationEmbedBuilder.AddField("Timer GUID", callbackTimer.Guid.ToString(), true);
                TimeHandler.AddTimer(callbackTimer);

                _            = member.TryAddModlogEntry(ModlogEntryType.ban, BanReason);
                embedBuilder = new DiscordEmbedBuilder
                {
                    Description = GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.ban.success"],
                                                     ctx, member),
                    Color  = DiscordColor.Red,
                    Footer = new DiscordEmbedBuilder.EmbedFooter
                    {
                        Text = "InsanityBot 2020-2021"
                    }
                };
                _ = InsanityBot.HomeGuild.BanMemberAsync(member, 0, BanReason);
                _ = InsanityBot.ModlogQueue.QueueMessage(ModlogMessageType.Moderation, new DiscordMessageBuilder
                {
                    Embed = moderationEmbedBuilder
                });
            }
            catch
            {
                embedBuilder = new DiscordEmbedBuilder
                {
                    Description = GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.ban.failure"], ctx, member),
                    Color       = DiscordColor.Red,
                    Footer      = new DiscordEmbedBuilder.EmbedFooter
                    {
                        Text = "InsanityBot 2020-2021"
                    }
                };
            }
            finally
            {
                if (embedBuilder == null)
                {
                    InsanityBot.Client.Logger.LogError(new EventId(1151, "Tempban"),
                                                       "Could not execute tempban command, an unknown exception occured.");
                }
                else
                {
                    await ctx.Channel.SendMessageAsync(embed : embedBuilder.Build());
                }
            }
        }
Ejemplo n.º 26
0
        private Task MessageDeleted(MessageDeleteEventArgs e)
        {
            var guildPrefix    = _redis.StringGet($"{e.Guild.Id}:CommandPrefix");
            var messageEventId = _redis.StringGet($"{e.Guild.Id}:Logs:MessageEvent");
            var logChannel     = e.Guild.GetChannel((ulong)messageEventId);
            var title          = ":wastebasket: Message deleted";

            if (string.IsNullOrWhiteSpace(e.Message.Content))
            {
                if (!string.IsNullOrWhiteSpace(messageEventId))
                {
                    if (e.Channel != logChannel)
                    {
                        var description = $"Message ({e.Message.Id}) deleted in {e.Channel.Mention}.";

                        var fields = new List <EmbedField>
                        {
                            new EmbedField
                            {
                                Inline = false,
                                Name   = "Content",
                                Value  = "The value is not available due to the message was send while the bot were offline or it's no longer in the cache."
                            }
                        };

                        var footer = new DiscordEmbedBuilder.EmbedFooter
                        {
                            Text = $"Message Id: {e.Message.Id}"
                        };

                        logChannel.SendEmbedMessageAsync(title, description, DiscordColor.IndianRed, fields: fields, footer: footer, timestamp: DateTimeOffset.UtcNow);
                    }
                }

                _logger.Information($"The message ({e.Message.Id}) was deleted in '{e.Channel.Name}' ({e.Channel.Id}) on '{e.Guild.Name}' ({e.Guild.Id}).");
            }
            else
            {
                var avatarUrl   = e.Message.Author.AvatarUrl;
                var description = $"Message sent by {e.Message.Author.Mention} deleted in {e.Channel.Mention}.";

                if (e.Message.Author.IsBot)
                {
                    return(Task.CompletedTask);
                }

                var deletedMessage = e.Message.Content;

                if (e.Channel.IsPrivate)
                {
                    _logger.Information($"The message ({e.Message.Id}) from '{e.Message.Author.GetUsertag()}' ({e.Message.Author.Id}) was updated in the direct message.");

                    return(Task.CompletedTask);
                }

                if (!deletedMessage.StartsWith(guildPrefix))
                {
                    if (!string.IsNullOrWhiteSpace(messageEventId))
                    {
                        if (e.Channel != logChannel)
                        {
                            var attachmentCount = e.Message.Attachments.Count;

                            var singleImage = string.Empty;

                            var fields = new List <EmbedField>
                            {
                                new EmbedField
                                {
                                    Inline = false,
                                    Name   = "Content",
                                    Value  = deletedMessage
                                }
                            };

                            var footer = new DiscordEmbedBuilder.EmbedFooter
                            {
                                Text = $"Author: {e.Message.Author.Id} | Message Id: {e.Message.Id}"
                            };

                            if (!attachmentCount.Equals(0))
                            {
                                var attachments = new Dictionary <string, Stream>();
                            }
                            else
                            {
                                logChannel.SendEmbedMessageAsync(title, description, DiscordColor.IndianRed, fields: fields, thumbnailUrl: avatarUrl, image: singleImage, footer: footer, timestamp: DateTimeOffset.UtcNow);
                            }
                        }
                    }
                }

                _logger.Information($"The message ({e.Message.Id}) from '{e.Message.Author.GetUsertag()}' ({e.Message.Author.Id}) was deleted in '{e.Channel.Name}' ({e.Channel.Id}) on '{e.Guild.Name}' ({e.Guild.Id}).");
            }

            return(Task.CompletedTask);
        }
Ejemplo n.º 27
0
        private Task MessageUpdated(MessageUpdateEventArgs e)
        {
            var          messageEventId = _redis.StringGet($"{e.Guild.Id}:Logs:MessageEvent");
            var          logChannel     = e.Guild.GetChannel((ulong)messageEventId);
            const string title          = ":memo: Message updated";

            if (e.MessageBefore == null)
            {
                if (!string.IsNullOrWhiteSpace(messageEventId))
                {
                    if (e.Channel != logChannel)
                    {
                        var description = new StringBuilder().AppendLine($"Message ({e.Message.Id}) updated in {e.Channel.Mention}.").AppendLine($"[Jump to message]({e.Message.JumpLink})").ToString();

                        var fields = new List <EmbedField>
                        {
                            new EmbedField
                            {
                                Inline = false,
                                Name   = "Before",
                                Value  = "The values are not available due to the message was send while the bot were offline or it's no longer in the cache."
                            }
                        };

                        var footer = new DiscordEmbedBuilder.EmbedFooter
                        {
                            Text = $"Author: {e.Message.Author.Id} | Message Id: {e.Message.Id}"
                        };

                        logChannel.SendEmbedMessageAsync(title, description, DiscordColor.Orange, fields: fields, footer: footer, timestamp: DateTimeOffset.UtcNow);
                    }
                }

                _logger.Information($"The message ({e.Message.Id}) was updated in '{e.Channel.Name}' ({e.Channel.Id}) on '{e.Guild.Name}' ({e.Guild.Id}).");
            }
            else
            {
                if (e.Message.Author.IsBot)
                {
                    return(Task.CompletedTask);
                }
                var avatarUrl   = e.Message.Author.AvatarUrl;
                var description = new StringBuilder().AppendLine($"Message sent by {e.Message.Author.Mention} updated in {e.Channel.Mention}.").AppendLine($"[Jump to message]({e.Message.JumpLink})").ToString();

                var contentBefore = e.MessageBefore.Content;
                var contentNow    = e.Message.Content;

                if (contentBefore.Equals(contentNow))
                {
                    return(Task.CompletedTask);
                }

                if (e.Channel.IsPrivate)
                {
                    _logger.Information($"The message ({e.Message.Id}) from '{e.Message.Author.GetUsertag()}' ({e.Message.Author.Id}) was updated in the direct message.");

                    return(Task.CompletedTask);
                }

                if (!string.IsNullOrWhiteSpace(messageEventId))
                {
                    if (e.Channel != logChannel)
                    {
                        var fields = new List <EmbedField>
                        {
                            new EmbedField
                            {
                                Inline = false,
                                Name   = "Before",
                                Value  = contentBefore
                            },
                            new EmbedField
                            {
                                Inline = false,
                                Name   = "After",
                                Value  = contentNow
                            }
                        };

                        var footer = new DiscordEmbedBuilder.EmbedFooter
                        {
                            Text = $"Message Id: {e.Message.Id}"
                        };

                        logChannel.SendEmbedMessageAsync(title, description, DiscordColor.Orange, fields: fields, thumbnailUrl: avatarUrl, footer: footer, timestamp: DateTimeOffset.UtcNow);
                    }
                }

                _logger.Information($"The message ({e.Message.Id}) from '{e.Message.Author.GetUsertag()}' ({e.Message.Author.Id}) was updated in '{e.Channel.Name}' ({e.Channel.Id}) on '{e.Guild.Name}' ({e.Guild.Id}).");
            }

            return(Task.CompletedTask);
        }
Ejemplo n.º 28
0
        public async Task SubRSS(CommandContext ctx)
        {
            await ctx.RespondAsync("Started");

            var channels = await _service.GetGuildRssUrlsAsync(ctx.Guild);

            foreach (var channel in channels)
            {
                try
                {
                    await channel.SendMessageAsync($"Subscribed to {channel.Topic} at {DateTimeOffset.Now}");
                }
                catch
                {
                    Console.Error.WriteLine("Exception messsage");
                }
            }

            async void Callback(object?s)
            {
                foreach (var channel in channels)
                {
                    try
                    {
                        Uri uri_parsed = new(channel.Topic);
                        var path       = $"log_rss/{ctx.Guild.Id}_log_{uri_parsed.Host}.txt";
                        IEnumerable <SyndicationItem>?feed;
                        if (File.Exists(path))
                        {
                            var date = await File.ReadAllTextAsync(path);

                            feed = await _service.GetRssByUriLogAsync(uri_parsed.ToString(), DateTimeOffset.Parse(date),
                                                                      path);
                        }
                        else
                        {
                            feed = await _service.GetRssByUriLogAsync(uri_parsed.ToString(),
                                                                      DateTimeOffset.Now.Subtract(TimeSpan.FromDays(3)), path);
                        }

                        if (feed is null)
                        {
                            continue;
                        }

                        var homepage = $"https://{uri_parsed.Host}";

                        string favicon = await _service.FetchFaviconAsync(homepage) switch
                        {
                            { } fav when Uri.IsWellFormedUriString(fav, UriKind.Absolute) => fav,
                            _ => ctx.Client.CurrentUser.GetAvatarUrl(ImageFormat.Auto),
                        };
                        var author = new DiscordEmbedBuilder.EmbedAuthor()
                        {
                            IconUrl = favicon,
                            Url     = homepage,
                            Name    = uri_parsed.Host.Substring(0, Math.Min(uri_parsed.Host.Length, 200))
                        };
                        foreach (var item in feed)
                        {
                            DiscordEmbedBuilder embed = new()
                            {
                                Title       = item.Title?.Text.Substring(0, Math.Min(item.Title.Text.Length, 200)),
                                Url         = item.Links?.FirstOrDefault()?.Uri.ToString() ?? homepage,
                                Description = new ReverseMarkdown.Converter().Convert(
                                    item.Summary?.Text.Substring(0, Math.Min(item.Summary.Text.Length, 1000)) ??
                                    String.Empty),
                                Footer = new DiscordEmbedBuilder.EmbedFooter()
                                {
                                    Text = "RSS by Tomori"
                                },
                                Timestamp = DateTimeOffset.Now,
                                Author    = author,
                                Color     = Optional.FromValue <DiscordColor>(_random_color.Next(16777216)),
                            };
                            await channel.SendMessageAsync(embed : embed.Build());
                        }
                    }
                    catch (Exception e)
                    {
                        DiscordEmbedBuilder embed = new();
                        var built = embed.WithColor(new DiscordColor(255, 0, 0))
                                    .WithAuthor(channel.Name, "https://image.prntscr.com/image/1tlt8aj7RY_ywP-OPPivyg.png")
                                    .WithFooter("RSS by Tomori")
                                    .WithTitle(e.Message)
                                    .WithDescription(e.StackTrace)
                                    .Build();
                        await ctx.RespondAsync(built);
                    }
                }
            }

            _timers.Add(new Timer(Callback, null, TimeSpan.Zero, TimeSpan.FromMinutes(15)));
        }
Ejemplo n.º 29
0
        private async Task UnlockCommand(CommandContext ctx, DiscordChannel channel, String reason = "usedefault", Boolean silent = false)
        {
            if (!ctx.Member.HasPermission("insanitybot.moderation.unlock"))
            {
                await ctx.Channel.SendMessageAsync(InsanityBot.LanguageConfig["insanitybot.error.lacking_permission"]);

                return;
            }

            String UnlockReason = reason switch
            {
                "usedefault" => GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.no_reason_given"], ctx),
                _ => GetFormattedString(reason, ctx)
            };

            DiscordEmbedBuilder embedBuilder           = null;
            DiscordEmbedBuilder moderationEmbedBuilder = new()
            {
                Title  = "UNLOCK",
                Color  = DiscordColor.Blue,
                Footer = new DiscordEmbedBuilder.EmbedFooter
                {
                    Text = "InsanityBot 2020-2021"
                }
            };

            moderationEmbedBuilder.AddField("Moderator", ctx.Member.Mention, true)
            .AddField("Channel", channel.Mention, true)
            .AddField("Reason", UnlockReason, true);

            try
            {
                List <DiscordOverwrite> overwrites = channel.GetChannelData();
                ChannelData             cachedData = channel.GetCachedChannelData();

                UInt64 exemptRole;
                if ((exemptRole = Convert.ToUInt64(InsanityBot.Config["insanitybot.identifiers.moderation.lock_exempt_role_id"])) != 0)
                {
                    await channel.AddOverwriteAsync(InsanityBot.HomeGuild.GetRole(exemptRole), allow : DSharpPlus.Permissions.None, reason :
                                                    "InsanityBot - unlocking channel, removing whitelist");
                }

                foreach (UInt64 v in cachedData.LockedRoles)
                {
                    await channel.AddOverwriteAsync(InsanityBot.HomeGuild.GetRole(v), deny : DSharpPlus.Permissions.None, reason : "InsanityBot - unlocking channel, removing permission overwrites");
                }

                foreach (UInt64 v in cachedData.LockedRoles)
                {
                    await channel.AddOverwriteAsync(InsanityBot.HomeGuild.GetRole(v), allow : DSharpPlus.Permissions.None, reason : "InsanityBot - unlocking channel, removing permission overwrites");
                }

                foreach (DiscordOverwrite v in overwrites)
                {
                    await channel.AddOverwriteAsync(await v.GetRoleAsync(), v.Allowed, v.Denied, "InsanityBot - unlocking channel, restoring previous permissions");
                }

                embedBuilder = new DiscordEmbedBuilder
                {
                    Description = GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.unlock.success"], ctx),
                    Color       = DiscordColor.Blue,
                    Footer      = new DiscordEmbedBuilder.EmbedFooter
                    {
                        Text = "InsanityBot 2020-2021"
                    }
                };
            }
            catch (Exception e)
            {
                embedBuilder = new DiscordEmbedBuilder
                {
                    Description = GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.unlock.failure"], ctx),
                    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());
                }
            }
        }
    }
}
Ejemplo n.º 30
0
        private async Task WhoIsPreset(CommandContext context, ulong userId)
        {
            var user = await context.Guild.GetMemberAsync(userId);

            var nickname     = string.IsNullOrWhiteSpace(user.Nickname) ? string.Empty : $"({user.Nickname})";
            var thumbnailUrl = user.AvatarUrl;

            var description = new StringBuilder().AppendLine($"User identity: `{user.Id}`").AppendLine($"Registered: {await user.CreatedAtLongDateTimeString()}");

            if (user.Verified.HasValue)
            {
                description.AppendLine($"Verified account: {user.Verified.Value}");
            }

            if (user.PremiumType.HasValue)
            {
                switch (user.PremiumType.Value)
                {
                case PremiumType.Nitro:
                    description.AppendLine("Premium: Nitro");

                    break;

                case PremiumType.NitroClassic:
                    description.AppendLine("Premium: Nitro Classic");

                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }

            var author = new DiscordEmbedBuilder.EmbedAuthor
            {
                Name    = $"{user.GetUsertag()} {nickname}",
                IconUrl = user.AvatarUrl
            };

            var fields = new List <EmbedField>
            {
                new EmbedField
                {
                    Inline = true, Name = "Joined Server at", Value = await user.JoinedAtLongDateTimeString()
                }
            };

            if (user.PremiumSince.GetValueOrDefault().Offset != null)
            {
                fields.Add(new EmbedField
                {
                    Inline = true,
                    Name   = "Boosting since",
                    Value  = await user.PremiumSinceLongDateTimeString()
                });
            }

            fields.Add(new EmbedField
            {
                Inline = true,
                Name   = "Server Infractions",
                Value  = "stfu its not ready now"
            });

            var roles = string.Empty;

            if (user.Roles.Any())
            {
                var rolesSorted = user.Roles.ToList().OrderByDescending(x => x.Position);

                roles = rolesSorted.Aggregate(roles, (current, role) => current + $"<@&{role.Id}> ");
            }
            else
            {
                roles = "None";
            }

            fields.Add(new EmbedField
            {
                Inline = false,
                Name   = "Roles",
                Value  = roles
            });

            fields.Add(new EmbedField
            {
                Inline = false,
                Name   = "Server Permissions",
                Value  = $"{user.Guild.Permissions.GetValueOrDefault()}"
            });

            var footer = new DiscordEmbedBuilder.EmbedFooter
            {
                Text = $"Requested by {context.User.GetUsertag()} | {context.User.Id}"
            };
            await context.EmbeddedMessage(description : description.ToString(), author : author, fields : fields, thumbnailUrl : thumbnailUrl, footer : footer, timestamp : DateTimeOffset.UtcNow);
        }