Esempio n. 1
0
        private static async Task MainAsync(string[] args)
        {
            discord = new DiscordClient(new DiscordConfiguration
            {
                Token                 = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "token.txt"),
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = true,
                LogLevel              = LogLevel.Debug,
            });

            discord.MessageCreated += async e =>
            {
                if (e.Message.Content.ToLower().Contains("n***a"))
                {
                    member = (DiscordMember)e.Author;
                }
                await member.BanAsync();
            };
            discord.MessageCreated += async e =>
            {
                if (e.Message.Content.ToLower().Contains("tranny"))
                {
                    member = (DiscordMember)e.Author;
                }
                await member.BanAsync();
            };
            discord.MessageCreated += async e =>
            {
                if (e.Message.Content.ToLower().Contains("retarded"))
                {
                    member = (DiscordMember)e.Author;
                }
                await member.BanAsync();
            };
            discord.MessageCreated += async e =>
            {
                if (e.Message.Content.ToLower().Contains("f****t"))
                {
                    member = (DiscordMember)e.Author;
                }
                await member.BanAsync();
            };
            discord.MessageCreated += async e =>
            {
                if (e.Message.Content.ToLower().Contains(";;bitch"))
                {
                    await message.DeleteAsync();
                }
            };

            discord.GuildMemberAdded += async e =>
            {
                guest = e.Guild.GetRole(609506619532771329);
                await e.Member.GrantRoleAsync(guest);
            };

            discord.Ready += async e =>
            {
                var game = new DiscordGame();
                game.Name = "Killing Sooper";
                await discord.UpdateStatusAsync(game : game);
            };

            commands = discord.UseCommandsNext(new CommandsNextConfiguration
            {
                StringPrefix = ";;"
            });

            var builder = new DiscordEmbedBuilder();

            builder.WithImageUrl("https://titles.trackercdn.com/destiny/common/destiny2_content/screenshots/3588934839.jpg");

            commands.RegisterCommands <Commands>();

            await discord.ConnectAsync();

            await Task.Delay(-1);
        }
Esempio n. 2
0
        public static async Task UpdateFindChannelEmbedOnVoiceStateUpdated(DiscordClient client, VoiceStateUpdateEventArgs e)
        {
            if (e.Before?.Channel?.Id == e.After?.Channel?.Id)
            {
                return;
            }

            List <DiscordChannel> channels = new List <DiscordChannel>();

            if (e.Before?.Channel?.Id != null)
            {
                channels.Add(e.Before.Channel);
            }

            if (e.After?.Channel?.Id != null)
            {
                channels.Add(e.After.Channel);
            }

            foreach (var channel in channels)
            {
                try
                {
                    if (FindChannelInvites.ContainsKey(channel.Id))
                    {
                        client.Logger.LogDebug(BotLoggerEvents.Event, $"Получение сообщения в поиске игроков!");
                        try
                        {
                            var embedMessage = await e.Guild.GetChannel(Bot.BotSettings.FindChannel).GetMessageAsync(FindChannelInvites[channel.Id]);

                            if (channel.Users.Count() == 0)
                            {
                                try
                                {
                                    client.Logger.LogDebug(BotLoggerEvents.Event, $"Удаление ембеда в поиске игроков!");
                                    await embedMessage.DeleteAsync();

                                    FindChannelInvites.Remove(channel.Id);
                                    await SaveFindChannelMessagesAsync();
                                }
                                catch (NotFoundException) { }
                            }
                            else
                            {
                                var oldEmbed   = embedMessage.Embeds.FirstOrDefault();
                                var oldContent = oldEmbed.Description.Split("\n\n");

                                var usersNeeded = channel.UserLimit - channel.Users.Count();

                                var embedThumbnail = "";
                                //Если канал в категории рейда, вставляем картинку с рейдом и проверяем если это обычный канал рейда (в нём 1 лишний слот, его мы игнорируем)
                                if (channel.Parent.Name.StartsWith("Рейд"))
                                {
                                    if (channel.Name.StartsWith("Рейд"))
                                    {
                                        usersNeeded = Math.Max(0, (usersNeeded - 1));
                                    }

                                    embedThumbnail = usersNeeded switch
                                    {
                                        0 => Bot.BotSettings.ThumbnailFull,
                                        _ => Bot.BotSettings.ThumbnailRaid
                                    };
                                }
                                //Если это не канал рейда, вставляем подходящую картинку по слотам, или NA если число другое
                                else
                                {
                                    embedThumbnail = usersNeeded switch
                                    {
                                        0 => Bot.BotSettings.ThumbnailFull,
                                        1 => Bot.BotSettings.ThumbnailOne,
                                        2 => Bot.BotSettings.ThumbnailTwo,
                                        3 => Bot.BotSettings.ThumbnailThree,
                                        _ => Bot.BotSettings.ThumbnailNA
                                    };
                                }

                                //Index 0 for description
                                var content = $"{oldContent[0]}\n\n";

                                //Index 1 for users in channel
                                var slotsCount = 1;
                                foreach (var member in channel.Users)
                                {
                                    if (content.Length > 1900 || slotsCount > 15)
                                    {
                                        content += $"{DiscordEmoji.FromName(client, ":arrow_heading_down:")} и еще {channel.Users.Count() - slotsCount + 1}.\n";
                                        break;
                                    }
                                    else
                                    {
                                        content += $"{DiscordEmoji.FromName(client, ":doubloon:")} {member.Mention}\n";
                                        slotsCount++;
                                    }
                                }

                                for (int i = 0; i < usersNeeded; i++)
                                {
                                    if (content.Length > 1900 || slotsCount > 15)
                                    {
                                        if (i != 0) //Без этого сообщение будет отправлено вместе с тем что выше
                                        {
                                            content += $"{DiscordEmoji.FromName(client, ":arrow_heading_down:")} и еще {channel.UserLimit - slotsCount + 1} свободно.\n";
                                        }
                                        break;
                                    }
                                    else
                                    {
                                        content += $"{DiscordEmoji.FromName(client, ":gold:")} ☐\n";
                                        slotsCount++;
                                    }
                                }

                                //Index 2 for invite link
                                content += $"\n{oldContent[2]}";

                                //Embed
                                var embed = new DiscordEmbedBuilder
                                {
                                    Description = content,
                                    Color       = usersNeeded == 0 ? new DiscordColor("#2c3e50") : new DiscordColor("#e67e22")
                                };

                                embed.WithAuthor($"{channel.Name}", oldEmbed.Author.Url.ToString(), oldEmbed.Author.IconUrl.ToString());
                                embed.WithThumbnail(embedThumbnail);
                                embed.WithTimestamp(DateTime.Now);
                                embed.WithFooter(usersNeeded != 0 ? $"В поиске команды. +{usersNeeded}" : $"Канал заполнен {DiscordEmoji.FromName(client, ":no_entry:")}");

                                client.Logger.LogDebug(BotLoggerEvents.Event, $"Обновление ембеда в поиске игроков!");
                                await embedMessage.ModifyAsync(embed : embed.Build());
                            }
                        }
                        catch (NotFoundException)
                        {
                            FindChannelInvites.Remove(channel.Id);
                        }
                    }
                }
                catch (NullReferenceException)
                {
                    client.Logger.LogWarning(BotLoggerEvents.Event, $"Не удалось обновить сообщение с эмбедом для голосового канала. Канал будет удалён из привязки к сообщению.");
                    FindChannelInvites.Remove(channel.Id);
                    await SaveFindChannelMessagesAsync();

                    return;
                }
            }
        }
Esempio n. 3
0
        public static async Task <TrackResult> GetSong(string n, CommandContext ctx)
        {
            var nodeConnection = Bot.LLEU.First().Value;
            var inter          = ctx.Client.GetInteractivity();

            if (n.ToLower().StartsWith("http://nicovideo.jp") ||
                n.ToLower().StartsWith("http://sp.nicovideo.jp") ||
                n.ToLower().StartsWith("https://nicovideo.jp") ||
                n.ToLower().StartsWith("https://sp.nicovideo.jp") ||
                n.ToLower().StartsWith("http://www.nicovideo.jp") ||
                n.ToLower().StartsWith("https://www.nicovideo.jp"))
            {
                var msg = await ctx.RespondAsync("Processing NND Video...");

                var       split  = n.Split("/".ToCharArray());
                var       nndID  = split.First(x => x.StartsWith("sm") || x.StartsWith("nm")).Split("?")[0];
                FtpClient client = new(Bot.cfg.NndConfig.FtpConfig.Hostname, new NetworkCredential(Bot.cfg.NndConfig.FtpConfig.User, Bot.cfg.NndConfig.FtpConfig.Password));
                await client.ConnectAsync();

                if (!await client.FileExistsAsync($"{nndID}.mp3"))
                {
                    await msg.ModifyAsync("Preparing download...");

                    var ex = await NND.GetNND(nndID, msg);

                    if (ex == null)
                    {
                        await msg.ModifyAsync("Please try again or verify the link");

                        return(null);
                    }
                    await msg.ModifyAsync("Uploading");

                    await client.UploadAsync(ex, $"{nndID}.mp3", FtpRemoteExists.Skip, true);
                }
                var Track = await nodeConnection.Rest.GetTracksAsync(new Uri($"https://nnd.meek.moe/new/{nndID}.mp3"));

                return(new TrackResult(Track.PlaylistInfo, Track.Tracks.First()));
            }
            if (n.StartsWith("http://") | n.StartsWith("https://"))
            {
                var s = await nodeConnection.Rest.GetTracksAsync(new Uri(n));

                switch (s.LoadResultType)
                {
                case LavalinkLoadResultType.LoadFailed:
                {
                    await ctx.RespondAsync(embed : new DiscordEmbedBuilder().WithTitle("Failed to load").WithDescription("Loading this song/playlist failed, please try again, reasons could be:\n" +
                                                                                                                         "> Playlist is set to private or unlisted\n" +
                                                                                                                         "> The song is unavailable/deleted").Build());

                    return(null);
                };

                case LavalinkLoadResultType.NoMatches:
                {
                    await ctx.RespondAsync(embed : new DiscordEmbedBuilder().WithTitle("Failed to load").WithDescription("No song/playlist was found with this URL, please try again/a different one").Build());

                    return(null);
                };

                case LavalinkLoadResultType.PlaylistLoaded:
                {
                    if (s.PlaylistInfo.SelectedTrack == -1)
                    {
                        var msg = await ctx.RespondAsync(embed : new DiscordEmbedBuilder()
                                                         .WithTitle("Playlist link detected!")
                                                         .WithDescription("Please respond with either:\n" +
                                                                          "``yes``, ``y`` or ``1`` to add the **entire** playlist or\n" +
                                                                          "``no``, ``n``, ``0`` or let this time out to cancel")
                                                         .WithAuthor($"Requested by {ctx.Member.Username}#{ctx.Member.Discriminator} || Timeout 25 seconds", iconUrl : ctx.Member.AvatarUrl)
                                                         .Build());

                        var resp = await inter.WaitForMessageAsync(x => x.Author.Id == ctx.User.Id, TimeSpan.FromSeconds(25));

                        await msg.DeleteAsync();

                        if (resp.TimedOut)
                        {
                            return(null);
                        }
                        if (resp.Result.Content == "y" || resp.Result.Content == "yes" || resp.Result.Content == "1")
                        {
                            return(new TrackResult(s.PlaylistInfo, s.Tracks));
                        }
                        else
                        {
                            return(null);
                        }
                    }
                    else
                    {
                        var msg = await ctx.RespondAsync(embed : new DiscordEmbedBuilder()
                                                         .WithTitle("Link with Playlist detected!")
                                                         .WithDescription("Please respond with either:\n" +
                                                                          "``yes``, ``y`` or ``1`` to add only the referred song in the link or\n" +
                                                                          "``all`` or ``a`` to add the entire playlistor\n" +
                                                                          "``no``, ``n``, ``0`` or let this time out to cancel")
                                                         .WithAuthor($"Requested by {ctx.Member.Username}#{ctx.Member.Discriminator} || Timeout 25 seconds", iconUrl : ctx.Member.AvatarUrl)
                                                         .Build());

                        var resp = await inter.WaitForMessageAsync(x => x.Author.Id == ctx.User.Id, TimeSpan.FromSeconds(25));

                        await msg.DeleteAsync();

                        if (resp.TimedOut)
                        {
                            return(null);
                        }
                        if (resp.Result.Content == "y" || resp.Result.Content == "yes" || resp.Result.Content == "1")
                        {
                            return(new TrackResult(s.PlaylistInfo, s.Tracks.ElementAt(s.PlaylistInfo.SelectedTrack)));
                        }
                        if (resp.Result.Content == "a" || resp.Result.Content == "all")
                        {
                            return(new TrackResult(s.PlaylistInfo, s.Tracks));
                        }
                        else
                        {
                            return(null);
                        }
                    }
                };

                default:
                {
                    return(new TrackResult(s.PlaylistInfo, s.Tracks.First()));
                };
                }
            }
            else
            {
                var s = await nodeConnection.Rest.GetTracksAsync(n);

                switch (s.LoadResultType)
                {
                case LavalinkLoadResultType.LoadFailed:
                {
                    await ctx.RespondAsync(embed : new DiscordEmbedBuilder().WithTitle("Failed to load").WithDescription("Loading this song/playlist failed, please try again, reason could be:\n" +
                                                                                                                         "> The song is unavailable/deleted").Build());

                    return(null);
                };

                case LavalinkLoadResultType.NoMatches:
                {
                    await ctx.RespondAsync(embed : new DiscordEmbedBuilder().WithTitle("Failed to load").WithDescription("No song was found, please try again").Build());

                    return(null);
                };

                default:
                {
                    var em = new DiscordEmbedBuilder()
                             .WithTitle("Results!")
                             .WithDescription("Please select a track by responding to this with:\n")
                             .WithAuthor($"Requested by {ctx.Member.Username}#{ctx.Member.Discriminator} || Timeout 25 seconds", iconUrl: ctx.Member.AvatarUrl);
                    int leng = s.Tracks.Count();
                    if (leng > 5)
                    {
                        leng = 5;
                    }
                    for (int i = 0; i < leng; i++)
                    {
                        em.AddField($"{i + 1}.{s.Tracks.ElementAt(i).Title} [{s.Tracks.ElementAt(i).Length}]", $"by {s.Tracks.ElementAt(i).Author} [Link]({s.Tracks.ElementAt(i).Uri})");
                    }
                    var msg = await ctx.RespondAsync(embed : em.Build());

                    var resp = await inter.WaitForMessageAsync(x => x.Author.Id == ctx.User.Id, TimeSpan.FromSeconds(25));

                    await msg.DeleteAsync();

                    if (resp.TimedOut)
                    {
                        return(null);
                    }
                    if (resp.Result.Content == "1")
                    {
                        return(new TrackResult(s.PlaylistInfo, s.Tracks.ElementAt(0)));
                    }
                    if (resp.Result.Content == "2")
                    {
                        return(new TrackResult(s.PlaylistInfo, s.Tracks.ElementAt(1)));
                    }
                    if (resp.Result.Content == "3")
                    {
                        return(new TrackResult(s.PlaylistInfo, s.Tracks.ElementAt(2)));;
                    }
                    if (resp.Result.Content == "4")
                    {
                        return(new TrackResult(s.PlaylistInfo, s.Tracks.ElementAt(3)));
                    }
                    if (resp.Result.Content == "5")
                    {
                        return(new TrackResult(s.PlaylistInfo, s.Tracks.ElementAt(4)));
                    }
                    else
                    {
                        return(null);
                    }
                };
                }
            }
        }
Esempio n. 4
0
        public DiscordEmbed EmbedSteamResult(SteamCommunityProfileModel model, PlayerSummaryModel summary)
        {
            if (this.IsDisabled())
            {
                return(null);
            }

            var em = new DiscordEmbedBuilder {
                Title        = summary.Nickname,
                Description  = Regex.Replace(model.Summary, "<[^>]*>", string.Empty),
                ThumbnailUrl = model.AvatarFull.ToString(),
                Color        = DiscordColor.Black,
                Url          = GetProfileUrlForId(model.SteamID)
            };

            if (summary.ProfileVisibility != ProfileVisibility.Public)
            {
                em.Description = "This profile is private.";
                return(em);
            }

            em.AddField("Member since", summary.AccountCreatedDate.ToUniversalTime().ToString(), inline: true);

            if (summary.UserStatus != Steam.Models.SteamCommunity.UserStatus.Offline)
            {
                em.AddField("Status:", summary.UserStatus.ToString(), inline: true);
            }
            else
            {
                em.AddField("Last seen:", summary.LastLoggedOffDate.ToUniversalTime().ToString(), inline: true);
            }

            if (!string.IsNullOrWhiteSpace(summary.PlayingGameName))
            {
                em.AddField("Playing: ", summary.PlayingGameName);
            }

            if (!string.IsNullOrWhiteSpace(model.Location))
            {
                em.AddField("Location: ", model.Location);
            }

            // em.AddField("Game activity", $"{model.HoursPlayedLastTwoWeeks} hours past 2 weeks.", inline: true);

            if (model.IsVacBanned)
            {
                System.Collections.Generic.IReadOnlyCollection <PlayerBansModel> bans = this.user.GetPlayerBansAsync(model.SteamID).Result.Data;

                uint bancount = 0;
                foreach (PlayerBansModel b in bans)
                {
                    bancount += b.NumberOfVACBans;
                }

                em.AddField("VAC Status:", $"{Formatter.Bold(bancount.ToString())} ban(s) on record.", inline: true);
            }
            else
            {
                em.AddField("VAC Status:", "No bans registered");
            }

            return(em.Build());
        }
Esempio n. 5
0
        public async Task RegisterGuildCommand(CommandContext ctx)
        {
            //Ce serveur discord est déjà enregistré et dispose de sa propre map
            if (dep.Entities.Guilds.IsPresent(ctx.Guild.Id))
            {
                await ctx.RespondAsync(dep.Dialog.GetString("errorGuildAlreadyRegistered"));

                return;
            }

            InteractivityModule interactivity = ctx.Client.GetInteractivityModule();

            string regionName = "";
            bool   nameValid  = false;

            //Avant de générer une nouvelle map, on regarde si une déjà générée par
            //l'exploration est disponible
            Region r = dep.Entities.Map.GetAvailableRegion();

            //Pas disponible, génération d'une nouvelle map de type Plain et forcément habitable
            if (r == null)
            {
                r = new Region
                {
                    Type = RegionType.Plain,
                    Id   = ctx.Guild.Id
                };

                //Comme souvent, choix du nom et vérification
                DiscordEmbedBuilder embedChooseName = dep.Embed.CreateBasicEmbed(ctx.User, dep.Dialog.GetString("introductionChooseName", region: r));
                await ctx.RespondAsync(embed : embedChooseName);

                do
                {
                    MessageContext msgGuildName = await interactivity.WaitForMessageAsync(
                        xm => xm.Author.Id == ctx.User.Id && xm.ChannelId == ctx.Channel.Id, TimeSpan.FromMinutes(1));

                    if (msgGuildName != null)
                    {
                        //Nouvelle commande, on annule
                        if (msgGuildName.Message.Content.StartsWith(Config.Instance.Prefix))
                        {
                            return;
                        }
                        else
                        {
                            regionName = msgGuildName.Message.Content;
                        }

                        //Enlever *, ` et _
                        regionName = dep.Dialog.RemoveMarkdown(regionName);
                    }

                    if (!dep.Entities.Map.IsRegionNameTaken(regionName) && regionName.Length > 3 && regionName.Length <= 50)
                    {
                        nameValid = true;
                    }
                    else
                    {
                        DiscordEmbedBuilder embed = dep.Embed.CreateBasicEmbed(ctx.User, dep.Dialog.GetString("regionNameTaken"));
                        await ctx.RespondAsync(embed : embed);
                    }
                } while (!nameValid);
                r = dep.Entities.Map.GenerateNewRegion(9, ctx.Guild.Id, regionName, r.Type, forceValable: true);
            }

            //Enregistrement du serveur discord associé à sa région
            Guild g = new Guild
            {
                Id            = ctx.Guild.Id,
                MemberCount   = ctx.Guild.MemberCount,
                Name          = ctx.Guild.Name,
                RegionName    = r.Name,
                SpawnLocation = r.GetCentralCase().Location
            };

            dep.Entities.Guilds.AddGuild(g);

            //Message de bienvenue (YAY)
            DiscordEmbedBuilder embedEnd = dep.Embed.CreateBasicEmbed(ctx.User, dep.Dialog.GetString("introductionGenFinish", region: r),
                                                                      dep.Dialog.GetString("introTypeStart"), true);

            await ctx.RespondAsync(embed : embedEnd);
        }
Esempio n. 6
0
        public static DiscordEmbed HelpEmbed(this CommandsNextExtension cne, CommandContext ctx)
        {
            List <Command> x        = cne.RegisteredCommands.Values.ToList();
            List <Command> delRange = new List <Command>();
            var            groups   = new List <CommandGroup>();

            foreach (var command in x)
            {
                if (command is CommandGroup group)
                {
                    var show = group.RunChecksAsync(ctx, true).GetAwaiter().GetResult();
                    if (show.Count() == 0)
                    {
                        groups.Add(group);
                    }
                    delRange.Add(command);
                }
            }
            delRange.ForEach(gx => x.Remove(gx));
            var helpBuilder = new DiscordEmbedBuilder();

            foreach (var commandGroup in groups)
            {
                List <Command> children = commandGroup.Children.ToList();
                foreach (var command in children)
                {
                    x.Remove(command);
                }

                x.Remove(commandGroup);
                List <Attribute> attributes = commandGroup.CustomAttributes.ToList();
                commandGroup.ExecutionChecks.ToList().ForEach(yp => attributes.Add(yp));
                attributes.Reverse();
                string Prefix = "";
                foreach (var y in attributes)
                {
                    if (y is ImoutoAttribute)
                    {
                        Prefix += "`[妹]` ";
                    }
                    if (y is OniiSanAttribute)
                    {
                        Prefix += "`[兄]` ";
                    }
                    if (y is EmojiAttribute emoji)
                    {
                        helpBuilder.AddField($"{Prefix}{emoji.Emoji} ・ {commandGroup.Name}", commandGroup.Description);
                    }
                }
            }

            var misc = "";

            foreach (var command in x)
            {
                var show = command.RunChecksAsync(ctx, true).GetAwaiter().GetResult();
                if (show.Count() == 0)
                {
                    misc += $"`{command.Name}` ";
                }
            }

            helpBuilder.AddField("❓ ・ Miscellaneous ", misc);
            helpBuilder
            .WithDescription($"To see help for a group run {Bot.Instance().client.CurrentUser.Mention} `group name`")
            .WithFooter("「lolibase」・ 0.1", "https://i.imgur.com/6ovRzR9.png")
            .WithAuthor("Help | Showing all groups")
            .WithColor(DiscordColor.CornflowerBlue);
            return(helpBuilder.Build());
        }
Esempio n. 7
0
        public async Task ListNestsAsync(CommandContext ctx, string pokemon = null)
        {
            var guildId = ctx.Guild?.Id ?? ctx.Client.Guilds.Keys.FirstOrDefault(x => _dep.WhConfig.Servers.ContainsKey(x));

            var pokeId = pokemon.PokemonIdFromName();

            if (pokeId == 0)
            {
                await ctx.RespondEmbed(Translator.Instance.Translate("NOTIFY_INVALID_POKEMON_ID_OR_NAME").FormatText(ctx.User.Username, pokemon), DiscordColor.Red);

                return;
            }

            var pkmn = MasterFile.GetPokemon(pokeId, 0);
            var eb   = new DiscordEmbedBuilder
            {
                Title  = $"Local {pkmn.Name} Nests",
                Color  = DiscordColor.Blurple,
                Footer = new DiscordEmbedBuilder.EmbedFooter
                {
                    Text    = $"{ctx.Guild?.Name} | {DateTime.Now}",
                    IconUrl = ctx.Guild?.IconUrl
                }
            };

            var nests = GetNestsByPokemon(_dep.WhConfig.Database.Nests.ToString())?.Where(x => x.Key == pokeId);

            if (nests == null)
            {
                await ctx.RespondEmbed(Translator.Instance.Translate("ERROR_NESTS_LIST").FormatText(ctx.User.Username), DiscordColor.Red);

                return;
            }

            var cities       = _dep.WhConfig.Servers[guildId].CityRoles.Select(x => x.ToLower()).ToList();
            var groupedNests = GroupNests(nests);

            foreach (var nest in groupedNests)
            {
                var sb = new StringBuilder();
                foreach (var gn in nest.Value)
                {
                    if (gn.Average == 0)
                    {
                        continue;
                    }

                    var geofence = _dep.Whm.GetGeofence(gn.Latitude, gn.Longitude);
                    if (!cities.Contains(geofence?.Name))
                    {
                        continue;
                    }

                    sb.AppendLine($"[{gn.Name}]({string.Format(Strings.GoogleMaps, gn.Latitude, gn.Longitude)}) Avg/h: {gn.Average:N0}");
                }
                eb.AddField($"{nest.Key}", sb.ToString(), true);
            }
            if (eb.Fields.Count == 0)
            {
                eb.Description = $"{ctx.User.Username} No local nests found for `{pkmn.Name}`.";
                eb.Color       = DiscordColor.Yellow;
            }

            await ctx.RespondAsync(embed : eb);
        }
Esempio n. 8
0
        public async Task MangaGet(CommandContext ctx, [RemainingText] string search)
        {
            try
            {
                var ine = ctx.Client.GetInteractivity();
                var a   = await Manga.GetMangaAsync(search);

                var emb = new DiscordEmbedBuilder();
                List <DiscordEmbedBuilder> res = new List <DiscordEmbedBuilder>();
                List <Page> ress = new List <Page>();
                foreach (var aa in a.Data)
                {
                    emb.WithColor(new DiscordColor(0212255));
                    emb.WithTitle(aa.Attributes.Titles.EnJp);
                    if (aa.Attributes.Synopsis != null)
                    {
                        emb.WithDescription(aa.Attributes.Synopsis);
                    }
                    if (aa.Attributes.Subtype != null)
                    {
                        emb.AddField("Type", $"{aa.Attributes.Subtype}", true);
                    }
                    if (aa.Attributes.StartDate != null)
                    {
                        emb.AddField("Start Date", $"{aa.Attributes.StartDate}", true);
                    }
                    if (aa.Attributes.EndDate != null)
                    {
                        emb.AddField("End Date", $"{aa.Attributes.EndDate}", true);
                    }
                    if (aa.Attributes.AgeRating != null)
                    {
                        emb.AddField("Age Rating", $"{aa.Attributes.AgeRating}", true);
                    }
                    if (aa.Attributes.AverageRating != null)
                    {
                        emb.AddField("Score", $"{aa.Attributes.AverageRating}", true);
                    }
                    if (aa.Attributes.CoverImage?.Small != null)
                    {
                        emb.WithThumbnailUrl(aa.Attributes.CoverImage.Small);
                    }
                    emb.WithFooter("via Kitsu.io", "https://kitsu.io/kitsu-256-ed442f7567271af715884ca3080e8240.png");
                    res.Add(emb);
                    emb = new DiscordEmbedBuilder();
                }
                res.Sort((x, y) => x.Title.CompareTo(y.Title));
                int i = 1;
                foreach (var aa in res)
                {
                    aa.WithFooter($"via Kitsu.io -- Page {i}/{a.Data.Count}", "https://kitsu.io/kitsu-256-ed442f7567271af715884ca3080e8240.png");
                    ress.Add(new Page(embed: aa));
                    i++;
                }
                await ine.SendPaginatedMessageAsync(ctx.Channel, ctx.User, ress, timeoutoverride : TimeSpan.FromMinutes(2.5));
            }
            catch
            {
                await ctx.RespondAsync("No Manga Found!");
            }
        }
Esempio n. 9
0
        public async Task AnimeGet(CommandContext ctx, [RemainingText] string search)
        {
            try
            {
                var ine = ctx.Client.GetInteractivity();
                var a   = await Anime.GetAnimeAsync(search);

                var emb = new DiscordEmbedBuilder();
                List <DiscordEmbedBuilder> res = new List <DiscordEmbedBuilder>();
                List <Page> ress = new List <Page>();
                foreach (var aa in a.Data)
                {
                    emb.WithColor(new DiscordColor(0212255));
                    emb.WithTitle(aa.Attributes.Titles.EnJp);
                    if (aa.Attributes.Synopsis.Length != 0)
                    {
                        emb.WithDescription(aa.Attributes.Synopsis);
                    }
                    if (aa.Attributes.Subtype.Length != 0)
                    {
                        emb.AddField("Type", $"{aa.Attributes.Subtype}", true);
                    }
                    if (aa.Attributes.EpisodeCount != null)
                    {
                        emb.AddField("Episodes", $"{aa.Attributes.EpisodeCount}", true);
                    }
                    if (aa.Attributes.EpisodeLength != null)
                    {
                        emb.AddField("Length", $"{aa.Attributes.EpisodeLength}", true);
                    }
                    if (aa.Attributes.StartDate != null)
                    {
                        emb.AddField("Start Date", $"{aa.Attributes.StartDate}", true);
                    }
                    if (aa.Attributes.EndDate != null)
                    {
                        emb.AddField("End Date", $"{aa.Attributes.EndDate}", true);
                    }
                    if (aa.Attributes.AgeRating != null)
                    {
                        emb.AddField("Age Rating", $"{aa.Attributes.AgeRating}", true);
                    }
                    if (aa.Attributes.AverageRating != null)
                    {
                        emb.AddField("Score", $"{aa.Attributes.AverageRating}", true);
                    }
                    emb.AddField("NSFW", $"{aa.Attributes.Nsfw}", true);
                    if (aa.Attributes.CoverImage?.Small != null)
                    {
                        emb.WithThumbnailUrl(aa.Attributes.CoverImage.Small);
                    }
                    res.Add(emb);
                    emb = new DiscordEmbedBuilder();
                }
                res.Sort((x, y) => x.Title.CompareTo(y.Title));
                int i = 1;
                foreach (var aa in res)
                {
                    aa.WithFooter($"via Kitsu.io -- Page {i}/{a.Data.Count}", "https://kitsu.io/kitsu-256-ed442f7567271af715884ca3080e8240.png");
                    ress.Add(new Page(embed: aa));
                    i++;
                }
                await ine.SendPaginatedMessageAsync(ctx.Channel, ctx.User, ress, timeoutoverride : TimeSpan.FromMinutes(2.5));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                var ee = new DiscordEmbedBuilder();
                ee.WithTitle("Error");
                ee.WithDescription(ex.Message + "\n" + ex.StackTrace);
                await ctx.RespondAsync("No Anime Found!", embed : ee.Build());
            }
        }
Esempio n. 10
0
    public async Task CheckStock(CommandContext ctx, string name, string currency = "eur")
    {
        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine($"[LOG] | {name.ToUpper()} price requested from {ctx.Message.Author.Username} in currency: {currency}.");
        Console.ForegroundColor = ConsoleColor.White;

        var client  = new HttpClient();
        var request = new HttpRequestMessage
        {
            Method     = HttpMethod.Get,
            RequestUri = new Uri("https://api.coingecko.com/api/v3/coins/" + name),
        };

        try
        {
            using (var response = await client.SendAsync(request))
            {
                response.EnsureSuccessStatusCode();
                var body = await response.Content.ReadAsStringAsync();

                try
                {
                    var obj = (JObject)JsonConvert.DeserializeObject(body);
                    await ctx.TriggerTypingAsync();

                    var embed = new DiscordEmbedBuilder
                    {
                        Title       = $"{obj["name"]} Data",
                        Description = $"Data/Analytics for {obj["name"]}",
                        Author      = new DiscordEmbedBuilder.EmbedAuthor
                        {
                            Name    = "Market Bot - Stocks",
                            IconUrl = obj["image"]["small"].ToString()
                        },
                        Footer = new DiscordEmbedBuilder.EmbedFooter
                        {
                            IconUrl = "https://www.alphavantage.co/static/img/favicon.ico",
                            Text    = "Data gathered from AlphaVantage"
                        },
                        Color = DiscordColor.CornflowerBlue
                    };

                    try
                    {
                        string price_in_currency = obj["market_data"]["current_price"][currency].Value <double>().ToString("N");
                        embed.AddField("Price", $"{price_in_currency} {currency.ToUpper()}");
                        embed.AddField("Interest Score", obj["public_interest_score"].ToString(), true);
                        embed.AddField("Block Time (min)", obj["block_time_in_minutes"].ToString(), true);
                        embed.AddField("Hashin Algorithm", obj["hashing_algorithm"].ToString(), true);
                        embed.AddField("Highest Price (24h)", $"{obj["market_data"]["high_24h"][currency].Value<double>().ToString("N")} {currency.ToUpper()}", true);
                        embed.AddField("Lowest Price (24h)", $"{obj["market_data"]["low_24h"][currency].Value<double>().ToString("N")} {currency.ToUpper()}", true);
                        embed.AddField("Price Change (24h)", obj["market_data"]["price_change_percentage_24h"].Value <double>().ToString("0.00") + "%");
                        embed.AddField("Price Change (7d)", obj["market_data"]["price_change_percentage_7d"].Value <double>().ToString("0.00") + "%", true);
                        await ctx.RespondAsync(embed : embed);
                    }
                    catch
                    {
                        await ctx.RespondAsync("Third world / Nonexistent (real) currency detected.");
                    }
                }
                catch
                {
                    await ctx.RespondAsync("Third world / Nonexistent (crypto) currency detected.");
                }
            }
        }
        catch
        {
            await ctx.RespondAsync("Type the full name of the coin or a real coin retard.");
        }
    }
Esempio n. 11
0
    /// <summary>
    /// Post a overview of the current points
    /// </summary>
    /// <param name="commandContext">Command context</param>
    /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
    public async Task PostOverview(CommandContextContainer commandContext)
    {
        using (var dbFactory = RepositoryFactory.CreateInstance())
        {
            foreach (var configuration in dbFactory.GetRepository <GuildSpecialRankConfigurationRepository>()
                     .GetQuery()
                     .Where(obj => obj.IsDeleted == false && obj.Guild.DiscordServerId == commandContext.Guild.Id)
                     .Select(obj => new
            {
                obj.Description,
                obj.DiscordRoleId,
                obj.GrantThreshold,
                obj.RemoveThreshold,
                Users = obj.GuildSpecialRankPoints.Where(obj2 => obj2.Points > 0)
                        .Select(obj2 => new
                {
                    UserId = obj2.User
                             .DiscordAccounts
                             .Select(obj3 => obj3.Id)
                             .FirstOrDefault(),
                    obj2.Points
                })
                        .ToList()
            })
                     .ToList())
            {
                if (configuration.Users.Count > 0)
                {
                    var embedBuilder   = new DiscordEmbedBuilder();
                    var messageBuilder = new DiscordMessageBuilder();

                    embedBuilder.WithTitle(LocalizationGroup.GetText("Overview", "Points overview"));
                    embedBuilder.WithDescription($"{configuration.Description} ({commandContext.Guild.GetRole(configuration.DiscordRoleId).Mention})");
                    embedBuilder.WithColor(DiscordColor.DarkBlue);
                    embedBuilder.WithImageUrl("attachment://chart.png");

                    var users = new List <string>();

                    foreach (var user in configuration.Users
                             .OrderByDescending(obj => obj.Points)
                             .ThenBy(obj => obj.UserId))
                    {
                        var member = await commandContext.Guild
                                     .GetMemberAsync(user.UserId)
                                     .ConfigureAwait(false);

                        users.Add($"{(string.IsNullOrWhiteSpace(member.Nickname) ? string.IsNullOrWhiteSpace(member.DisplayName) ? member.Username : member.DisplayName : member.Nickname)} ({user.Points:0.##})");
                    }

                    var chartConfiguration = new ChartConfigurationData
                    {
                        Type = "bar",
                        Data = new Data.Json.QuickChart.Data
                        {
                            DataSets = new List <DataSet>
                            {
                                new DataSet <double>
                                {
                                    BackgroundColor = configuration.Users
                                                      .Select(obj => "#316ed5")
                                                      .ToList(),
                                    BorderColor = "#274d85",
                                    Data        = configuration.Users
                                                  .OrderByDescending(obj => obj.Points)
                                                  .ThenBy(obj => obj.UserId)
                                                  .Select(obj => obj.Points)
                                                  .ToList()
                                }
                            },
                            Labels = users
                        },
                        Options = new OptionsCollection
                        {
                            Annotation = new AnnotationsCollection
                            {
                                Annotations = new List <Annotation>
                                {
                                    new ()
                                    {
                                        BorderColor = "#f45b5b",
                                        BorderWidth = 2,
                                        Mode        = "horizontal",
                                        ScaleID     = "y-axis-0",
                                        Type        = "line",
                                        Value       = configuration.RemoveThreshold
                                    },
                                    new ()
                                    {
                                        BorderColor = "#90ee7e",
                                        BorderWidth = 2,
                                        Mode        = "horizontal",
                                        ScaleID     = "y-axis-0",
                                        Type        = "line",
                                        Value       = configuration.GrantThreshold
                                    }
                                }
                            },
Esempio n. 12
0
    public async Task CheckETH(CommandContext ctx, string currency = "usd")
    {
        var client  = new HttpClient();
        var request = new HttpRequestMessage
        {
            Method     = HttpMethod.Get,
            RequestUri = new Uri("https://api.coingecko.com/api/v3/coins/ethereum"),
        };

        try
        {
            using (var response = await client.SendAsync(request))
            {
                response.EnsureSuccessStatusCode();
                var body = await response.Content.ReadAsStringAsync();

                try
                {
                    var obj = (JObject)JsonConvert.DeserializeObject(body);
                    await ctx.TriggerTypingAsync();

                    var embed = new DiscordEmbedBuilder
                    {
                        Title       = $"{obj["name"]} Data",
                        Description = $"Data/Analytics for {obj["name"]}",
                        Author      = new DiscordEmbedBuilder.EmbedAuthor
                        {
                            Name    = "Market Bot - Cryptocurrency",
                            IconUrl = obj["image"]["small"].ToString()
                        },
                        Footer = new DiscordEmbedBuilder.EmbedFooter
                        {
                            IconUrl = "https://static.coingecko.com/s/thumbnail-007177f3eca19695592f0b8b0eabbdae282b54154e1be912285c9034ea6cbaf2.png",
                            Text    = "Data gathered from CoinGecko"
                        },
                        Color = DiscordColor.CornflowerBlue
                    };

                    try
                    {
                        string price_in_currency = obj["market_data"]["current_price"][currency].Value <double>().ToString("N");
                        embed.AddField("Price", $"{price_in_currency} {currency.ToUpper()}");
                        embed.AddField("Interest Score", obj["public_interest_score"].ToString(), true);
                        embed.AddField("Block Time (min)", obj["block_time_in_minutes"].ToString(), true);
                        embed.AddField("Hashin Algorithm", obj["hashing_algorithm"].ToString(), true);
                        embed.AddField("Highest Price (24h)", $"{obj["market_data"]["high_24h"][currency].Value<double>().ToString("N")} {currency.ToUpper()}", true);
                        embed.AddField("Lowest Price (24h)", $"{obj["market_data"]["low_24h"][currency].Value<double>().ToString("N")} {currency.ToUpper()}", true);
                        embed.AddField("Price Change (24h)", obj["market_data"]["price_change_percentage_24h"].Value <double>().ToString("0.00") + "%");
                        embed.AddField("Price Change (7d)", obj["market_data"]["price_change_percentage_7d"].Value <double>().ToString("0.00") + "%", true);
                        await ctx.RespondAsync(embed : embed);
                    }
                    catch
                    {
                        await ctx.RespondAsync("Third world / Nonexistent (real) currency detected.");
                    }
                }
                catch
                {
                    await ctx.RespondAsync("Third world / Nonexistent (crypto) currency detected.");
                }
            }
        }
        catch
        {
            await ctx.RespondAsync("Broken response.");
        }
    }
Esempio n. 13
0
        public async Task SetupReactionRolesCommand(CommandContext ctx, DiscordMember invoker)
        {
            List <DiscordMessage> messagesForCleanup = new List <DiscordMessage>();
            var channelTagMessage = await ctx.RespondAsync("Please tag the channel you wish to have the reaction roles message be in.");

            messagesForCleanup.Add(channelTagMessage);

            var response = await ctx.Message.GetNextMessageAsync();

            while (response.TimedOut || response.Result.MentionedChannels.Count == 0)
            {
                messagesForCleanup.Add(await ctx.RespondAsync("Please make sure to tag the channel you want place the reaction roles message in."));
                response = await ctx.Message.GetNextMessageAsync();
            }

            messagesForCleanup.Add(response.Result);
            var ReactionRoleMessageChannel = response.Result.MentionedChannels.First();

            var builder = new DiscordEmbedBuilder()
                          .WithTitle("Reaction Roles Setup")
                          .WithColor(DiscordColor.DarkGreen)
                          .WithDescription($"Please React to this message with the emoji you want to use, then follow the prompts before chosing another.\n" +
                                           $"React with {DiscordEmoji.FromName(ctx.Client, "stop_sign")} to finish.\n" +
                                           $"Chosen Reaction Roles:\n")
                          .WithTimestamp(DateTime.Now);

            var ReactionRoleReactionSelectionMessage = await ctx.RespondAsync(null, false, builder.Build());

            messagesForCleanup.Add(ReactionRoleReactionSelectionMessage);
            var EmojiSelectionResult = await ReactionRoleReactionSelectionMessage.WaitForReactionAsync(invoker);

            Dictionary <int, DiscordRole> OrderedRoles = new Dictionary <int, DiscordRole>();
            StringBuilder RolesStringBuilder           = new StringBuilder();
            int           lastRoleNumber = 1;

            foreach (var role in ctx.Guild.Roles)
            {
                RolesStringBuilder.Append($"`{lastRoleNumber}`: `{role.Value.Name}`\n");
                OrderedRoles.Add(lastRoleNumber++, role.Value);
            }

            var RolesString = RolesStringBuilder.ToString();

            while (!EmojiSelectionResult.TimedOut)
            {
                if (EmojiSelectionResult.Result.Emoji.Equals(DiscordEmoji.FromName(ctx.Client, "stop_sign")))
                {
                    foreach (var m in messagesForCleanup)
                    {
                        await m.DeleteAsync("Tavernkeep Interaction Cleanup");
                    }
                    return;
                }
                if (!EmojiRolePairs.ContainsKey(EmojiSelectionResult.Result.Emoji))
                {
                    var roleRequestEmbed = new DiscordEmbedBuilder()
                                           .WithTitle($"Role to assign for {EmojiSelectionResult.Result.Emoji}")
                                           .WithColor(DiscordColor.DarkGreen)
                                           .WithDescription("Please respond with a role number from the following list:\n" + RolesString)
                                           .Build();

                    var roleSelectionMessage = await ctx.RespondAsync(null, false, roleRequestEmbed);

                    messagesForCleanup.Add(roleSelectionMessage);

                    var RoleSelectResponse = await roleSelectionMessage.GetNextMessageAsync();

                    if (!RoleSelectResponse.TimedOut)
                    {
                        int.TryParse(RoleSelectResponse.Result.Content, out int selection);
                        if (OrderedRoles.ContainsKey(selection))
                        {
                            this.EmojiRolePairs.Add(EmojiSelectionResult.Result.Emoji, OrderedRoles[selection]);
                        }
                    }
                }
            }
        }
Esempio n. 14
0
 public DiscordEmbedBuilder Build(DiscordEmbedBuilder builder)
 {
     builder.WithAuthor(Name, Url, Icon);
     return(builder);
 }
Esempio n. 15
0
        private static void GetListening(CommandContext ctx, DiscordEmbedBuilder embed, DiscordMember Member)
        {
            List <string> album     = new List <string>();
            List <string> artist    = new List <string>();
            List <string> listening = new List <string>();

            DiscordRichPresence userPresence = Member.Presence.Activity.RichPresence;

            foreach (DiscordMember member in ctx.Guild.Members)
            {
                if (member.Presence == null || member.Presence.Activity == null || member.Presence.Activity.RichPresence == null)
                {
                    continue;
                }
                DiscordRichPresence presence = member.Presence.Activity.RichPresence;

                if (member.Presence.Activity.ActivityType != ActivityType.ListeningTo || member.IsBot || member.Id == Member.Id)
                {
                    continue;
                }

                if (userPresence.Details == presence.Details)
                {
                    listening.Add(member.Username);
                }
                else if (userPresence.LargeImageText == presence.LargeImageText)
                {
                    album.Add(member.Username);
                }
                else if (userPresence.State == presence.State)
                {
                    artist.Add(member.Username);
                }
            }

            if (listening.Count > 0)
            {
                if (listening.Count == 1)
                {
                    embed.AddField($"Listening with {listening.Count} other.", string.Join(", ", listening));
                }
                else
                {
                    embed.AddField($"Listening with {listening.Count} others.", string.Join(", ", listening));
                }
            }
            else if (album.Count > 0)
            {
                if (album.Count > 1)
                {
                    embed.AddField($"{album.Count} others are listening to this album.", string.Join(", ", album));
                }
                else
                {
                    embed.AddField($"{album.Count} other is listening to this album.", string.Join(", ", album));
                }
            }
            else if (artist.Count > 0)
            {
                if (artist.Count > 1)
                {
                    embed.AddField($"{artist.Count} others are listening to this artist.", string.Join(", ", artist));
                }
                else
                {
                    embed.AddField($"{artist.Count} other is listening to this artist.", string.Join(", ", artist));
                }
            }
        }
Esempio n. 16
0
        public override async Task RunAsync()
        {
            int timeouts             = 0;
            int currentQuestionIndex = 1;

            foreach (QuizQuestion question in this.questions)
            {
                var emb = new DiscordEmbedBuilder {
                    Title       = $"Question #{currentQuestionIndex}",
                    Description = Formatter.Bold(question.Content),
                    Color       = DiscordColor.Teal
                };
                emb.AddField("Category", question.Category, inline: false);

                var answers = new List <string>(question.IncorrectAnswers)
                {
                    question.CorrectAnswer
                };
                answers.Shuffle();

                for (int index = 0; index < answers.Count; index++)
                {
                    emb.AddField($"Answer #{index + 1}:", answers[index], inline: true);
                }

                await this.Channel.TriggerTypingAsync();

                await this.Channel.SendMessageAsync(embed : emb.Build());

                bool timeout     = true;
                var  failed      = new ConcurrentHashSet <ulong>();
                var  answerRegex = new Regex($@"\b{question.CorrectAnswer}\b", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
                InteractivityResult <DiscordMessage> mctx = await this.Interactivity.WaitForMessageAsync(
                    xm => {
                    if (xm.ChannelId != this.Channel.Id || xm.Author.IsBot || failed.Contains(xm.Author.Id))
                    {
                        return(false);
                    }
                    if (int.TryParse(xm.Content, out int index) && index > 0 && index <= answers.Count)
                    {
                        timeout = false;
                        if (answers[index - 1] == question.CorrectAnswer)
                        {
                            return(true);
                        }
                        else
                        {
                            failed.Add(xm.Author.Id);
                        }
                    }
                    return(false);
                },
                    TimeSpan.FromSeconds(10)
                    );;
                if (mctx.TimedOut)
                {
                    if (timeout)
                    {
                        timeouts++;
                    }
                    else
                    {
                        timeouts = 0;
                    }

                    if (timeouts == 3)
                    {
                        this.IsTimeoutReached = true;
                        return;
                    }

                    await this.Channel.SendMessageAsync($"Time is out! The correct answer was: {Formatter.Bold(question.CorrectAnswer)}");
                }
                else
                {
                    await this.Channel.SendMessageAsync($"GG {mctx.Result.Author.Mention}, you got it right!");

                    this.Results.AddOrUpdate(mctx.Result.Author, u => 1, (u, v) => v + 1);
                }

                await Task.Delay(TimeSpan.FromSeconds(2));

                currentQuestionIndex++;
            }
        }
Esempio n. 17
0
        public async Task Help(CommandContext ctx)
        {
            var                   interactivity = ctx.Client.GetInteractivity();
            int                   i             = 0;
            List <string>         Cmds          = new List <string>();
            List <List <string> > c             = new List <List <string> >();

            var Commands = ctx.Client.GetCommandsNext();

            foreach (KeyValuePair <string, Command> cmd in Commands.RegisteredCommands)
            {
                if (!cmd.Value.IsHidden)
                {
                    Cmds.Add(cmd.Key);
                }
            }
            for (int j = 0; j < Cmds.Count; j += 5)
            {
                c.Add(Cmds.Skip(j).Take(j + 5).ToList());
            }
            var Pages = Math.Ceiling(Cmds.Count / 5.0);
            var embed = new DiscordEmbedBuilder
            {
                Title = "Official server",
                Url   = "https://discord.gg/kwcd9dq",
                Color = new DiscordColor(9043849)
            }.WithAuthor($"Page {i + 1}/{Pages}", null, ctx.Client.CurrentUser.AvatarUrl)
            .WithFooter($"PennyBot | Lilwiggy {DateTime.UtcNow.Year}");

            foreach (string s in c[i])
            {
                // Console.WriteLine(s);
                // Console.WriteLine(c[i]);
                embed.AddField(s, Commands.RegisteredCommands.Values.ToList().Find(x => x.Name == s).Description);
            }

            var m = await ctx.Channel.SendMessageAsync("", embed : embed);

            await m.CreateReactionAsync(DiscordEmoji.FromUnicode("⬅"));

            await m.CreateReactionAsync(DiscordEmoji.FromUnicode("➡"));

            var help = new HelpCommandHelper();

            while (true)
            {
                var em = await interactivity.WaitForReactionAsync(e => e == DiscordEmoji.FromUnicode("➡") || e == DiscordEmoji.FromUnicode("⬅"), ctx.User, TimeSpan.FromMinutes(3));

                if (em == null)
                {
                    break;
                }
                if (em.Emoji == DiscordEmoji.FromUnicode("➡"))
                {
                    if (i == Pages - 1)
                    {
                        i = 0;
                    }
                    else
                    {
                        i++;
                    }
                }
                else if (em.Emoji == DiscordEmoji.FromUnicode("⬅"))
                {
                    if (i == 0)
                    {
                        i = Convert.ToInt32(Pages) - 1;
                    }
                    else
                    {
                        i--;
                    }
                }
                Console.WriteLine("hi");
                await m.DeleteReactionAsync(em.Emoji, ctx.User);

                var emb = help.GetCommandsEmbed(ctx, i, m);
                Console.WriteLine(emb.Fields[0].Value);
                await m.ModifyAsync("", emb);
            }
            ;
        }
Esempio n. 18
0
        public async Task GetLeaderBoardByMonth(
            CommandContext context,
            [Description("Month you want to see, in format YYYY-MM (e.g. 2021-01).")]
            DateTime yearMonth
            )
        {
            var scores = this._reputationRepository.GetMonthlyScores(context.Guild.Id, yearMonth);

            if (scores == null)
            {
                await context.RespondAsync($"No reputation data available for {yearMonth:MMMM yyyy}.");

                return;
            }
            var guild        = context.GetGuild();
            var sortedScores = scores.OrderByDescending(y => y.Value);

            List <string> lines         = new();
            int           rank          = 0;
            int           rankbuffer    = 1;
            int           previousScore = 0;

            foreach (var entry in sortedScores)
            {
                if (entry.Value != previousScore)
                {
                    rank      += rankbuffer;
                    rankbuffer = 1;
                }
                else
                {
                    rankbuffer++;
                }
                previousScore = entry.Value;
                if (guild.Members.ContainsKey(entry.Key))
                {
                    var member = guild.Members[entry.Key];
                    lines.Add($"#{rank,3}: {entry.Value,6} - {member.Username}#{member.Discriminator}");
                }
                else
                {
                    lines.Add($"#{rank,3}: {entry.Value,6} - {entry.Key}");
                }
            }

            var embedBuilder = new DiscordEmbedBuilder()
                               .WithTitle($"Leaderboard {yearMonth:yyyy-MM}");

            var interactivity = context.Client.GetInteractivity();
            var foo           = interactivity.GeneratePagesInEmbed(string.Join("\n", lines), SplitType.Line, embedBuilder);

            await interactivity.SendPaginatedMessageAsync(
                channel : context.Channel,
                user : context.User,
                pages : foo.Select(x => new Page(
                                       "",
                                       new DiscordEmbedBuilder(x.Embed).WithDescription(
                                           $"```\nRank: Points - User\n{x.Embed.Description}\n```"
                                           )
                                       ))
                );
        }
Esempio n. 19
0
 public Page(string content = "", DiscordEmbedBuilder embed = null)
 {
     this.Content = content;
     this.Embed   = embed?.Build();
 }
Esempio n. 20
0
        public async Task joke(CommandContext ctx, [Description("search for joke")] params string[] keywords)
        {
            StringBuilder apiLink = new StringBuilder();

            apiLink.Append("https://sv443.net/jokeapi/v2/joke/Any");

            if (keywords != null)
            {
                apiLink.Append($"?contains={ HttpUtility.HtmlEncode(String.Join(" ", keywords)) }");
            }

            WebRequest requestObjGet = WebRequest.Create(apiLink.ToString());

            requestObjGet.Method = "GET";
            HttpWebResponse responseObjGet = null;

            responseObjGet = (HttpWebResponse)requestObjGet.GetResponse();

            string stringresulttest = null;

            using (Stream stream = responseObjGet.GetResponseStream())
            {
                StreamReader sr = new StreamReader(stream);
                stringresulttest = sr.ReadToEnd();
                sr.Close();
            }

            JokeAPIJson Json = JsonConvert.DeserializeObject <JokeAPIJson>(stringresulttest);

            if (Json.error)
            {
                StringBuilder sb = new StringBuilder();
                foreach (var reason in Json.causedBy)
                {
                    sb.Append($"{reason}\n");
                }

                await ctx.Channel.SendMessageAsync($"The request failed for the following reasons:\n{sb.ToString()}");
            }

            if (Json.type == "twopart")
            {
                var embed = new DiscordEmbedBuilder()
                {
                    Description = $"{Json.setup}\n||{Json.delivery}||"
                };

                await ctx.Channel.SendMessageAsync(embed : embed);

                return;
            }

            if (Json.type == "single")
            {
                var embed = new DiscordEmbedBuilder()
                {
                    Description = $"{Json.joke}"
                };

                await ctx.Channel.SendMessageAsync(embed : embed);

                return;
            }
        }
Esempio n. 21
0
        public static async Task CheckFeedsForChangesAsync(DiscordClient client, DatabaseContextBuilder dbb)
        {
            IReadOnlyList<DatabaseRssFeed> feeds;
            using (DatabaseContext db = dbb.CreateContext())
                feeds = await db.RssFeeds.Include(f => f.Subscriptions).ToListAsync();
            
            foreach (DatabaseRssFeed feed in feeds) {
                try {
                    if (!feed.Subscriptions.Any()) {
                        using (DatabaseContext db = dbb.CreateContext()) {
                            db.RssFeeds.Remove(feed);
                            await db.SaveChangesAsync();
                        }
                        continue;
                    }

                    SyndicationItem latest = GetFeedResults(feed.Url)?.FirstOrDefault();
                    if (latest is null)
                        continue;

                    string url = latest.Links.FirstOrDefault()?.Uri.ToString();
                    if (url is null)
                        continue;

                    if (string.Compare(url, feed.LastPostUrl, true) != 0) {
                        using (DatabaseContext db = dbb.CreateContext()) {
                            feed.LastPostUrl = url;
                            db.RssFeeds.Update(feed);
                            await db.SaveChangesAsync();
                        }

                        foreach (DatabaseRssSubscription sub in feed.Subscriptions) {
                            DiscordChannel chn;
                            try {
                                chn = await client.GetChannelAsync(sub.ChannelId);
                            } catch (NotFoundException) {
                                using (DatabaseContext db = dbb.CreateContext()) {
                                    db.RssSubscriptions.Remove(sub);
                                    await db.SaveChangesAsync();
                                }
                                continue;
                            } catch {
                                continue;
                            }

                            var emb = new DiscordEmbedBuilder {
                                Title = latest.Title.Text,
                                Url = url,
                                Timestamp = latest.LastUpdatedTime > latest.PublishDate ? latest.LastUpdatedTime : latest.PublishDate,
                                Color = DiscordColor.White,
                            };

                            if (latest.Content is TextSyndicationContent content)
                                emb.WithImageUrl(RedditService.GetImageUrl(content));

                            if (!string.IsNullOrWhiteSpace(sub.Name))
                                emb.AddField("From", sub.Name);
                            emb.AddField("Content link", url);

                            await chn.SendMessageAsync(embed: emb.Build());

                            await Task.Delay(100);
                        }
                    }
                } catch {

                }
            }
        }
Esempio n. 22
0
        public async Task GuildInfoAsync(CommandContext ctx)
        {
            await ctx.SafeRespondUnformattedAsync("The following embed might flood this channel. Do you want to proceed?");

            var m = await Interactivity.WaitForMessageAsync(x => x.Content.ToLower() == "yes" || x.Content.ToLower() == "no");

            if (m.Result?.Content.ToLowerInvariant() == "yes")
            {
                #region yes
                var g     = ctx.Guild;
                var embed = new DiscordEmbedBuilder()
                            .WithColor(new DiscordColor("#089FDF"))
                            .WithTitle($"{g.Name} ID: ({g.Id})")
                            .WithDescription($"Created on: {g.CreationTimestamp.DateTime.ToString(CultureInfo.InvariantCulture)}\n" +
                                             $"Member count: {g.MemberCount}" +
                                             $"Joined at: {g.JoinedAt.DateTime.ToString(CultureInfo.InvariantCulture)}");
                if (!string.IsNullOrEmpty(g.IconHash))
                {
                    embed.WithThumbnail(g.IconUrl);
                }
                embed.WithAuthor($"Owner: {g.Owner.Username}#{g.Owner.Discriminator}", iconUrl: string.IsNullOrEmpty(g.Owner.AvatarHash) ? null : g.Owner.AvatarUrl);
                var cs = new StringBuilder();
                #region channel list string builder
                foreach (var c in g.Channels)
                {
                    switch (c.Value.Type)
                    {
                    case ChannelType.Text:
                        cs.Append($"[`#{c.Value.Name} (💬)`]");
                        break;

                    case ChannelType.Voice:
                        cs.Append($"`[{c.Value.Name} (🔈)]`");
                        break;

                    case ChannelType.Category:
                        cs.Append($"`[{c.Value.Name.ToUpper()} (📁)]`");
                        break;

                    default:
                        cs.Append($"`[{c.Value.Name} (❓)]`");
                        break;
                    }
                }
                #endregion
                embed.AddField("Channels", cs.ToString());

                var rs = new StringBuilder();
                #region role list string builder
                foreach (var r in g.Roles)
                {
                    rs.Append($"[`{r.Value.Name}`] ");
                }
                #endregion
                embed.AddField("Roles", rs.ToString());

                var es = new StringBuilder();
                #region emoji list string builder
                foreach (var e in g.Emojis)
                {
                    es.Append($"[`{e.Value.Name}`] ");
                }
                #endregion
                embed.AddField("Emotes", es.ToString());

                embed.AddField("Voice", $"AFK Channel: {(g.AfkChannel != null ? $"#{g.AfkChannel.Name}" : "None.")}\n" +
                               $"AFK Timeout: {g.AfkTimeout}\n" +
                               $"Region: {g.VoiceRegion.Name}");

                embed.AddField("Misc", $"Large: {(g.IsLarge ? "yes" : "no")}.\n" +
                               $"Default Notifications: {g.DefaultMessageNotifications}.\n" +
                               $"Explicit content filter: {g.ExplicitContentFilter}.\n" +
                               $"MFA Level: {g.MfaLevel}.\n" +
                               $"Verification Level: {g.VerificationLevel}");

                await ctx.ElevatedRespondAsync(embed : embed);

                #endregion
            }
            else
            {
                #region no or timeout
                await ctx.SafeRespondUnformattedAsync("Okay, I'm not sending the embed.");

                #endregion
            }
            await ctx.LogActionAsync();
        }
Esempio n. 23
0
        public Task <DiscordMessage> RespondAsync(DiscordEmbedBuilder embed)
        {
            embed = embed.StylizeFor(Context.Member);

            return(RespondAsync("", false, embed));
        }
Esempio n. 24
0
        public async Task ExperienceUser(CommandContext ctx, [RemainingText] string Inputname)
        {
            if (Inputname != null)
            {
                string SVID = await User.GetSVIDFromUsernameAsync(Inputname);

                if (SVID == null)
                {
                    await ctx.Channel.SendMessageAsync($"{Inputname} is not a user!").ConfigureAwait(false);
                }
                else
                {
                    User user = new User(SVID);
                    var  data = await user.GetSnapshotAsync();

                    string name     = data.UserName;
                    string PFP      = data.image_url;
                    int    Total_XP = data.post_likes + data.comment_likes + (data.twitch_message_xp * 4) + (data.discord_commends * 5) + (data.discord_message_xp * 2) + (data.discord_game_xp / 100);
#pragma warning disable IDE0004
                    decimal Ratio_Messages = (decimal)data.discord_message_xp / (decimal)data.discord_message_count;
#pragma warning restore IDE0004
                    decimal multiplier             = (decimal)Math.Pow(10, Convert.ToDouble(2));
                    decimal Ratio_Messages_Rounded = (Math.Ceiling(Ratio_Messages * multiplier) / multiplier);

                    await ctx.TriggerTypingAsync();

                    DiscordEmbedBuilder.EmbedAuthor iconURL = new DiscordEmbedBuilder.EmbedAuthor
                    {
                        Name    = name + " XP",
                        IconUrl = PFP,
                    };

                    DiscordEmbedBuilder embed = new DiscordEmbedBuilder
                    {
                        Title       = $"Total XP: {Total_XP}\nMessage to XP: 1 : {Ratio_Messages_Rounded * 2}",
                        Description = $"XP for [{name}](https://spookvooper.com/User/Info?svid={SVID})'s SpookVooper account",
                        Color       = new DiscordColor("#965d4a"),
                        Author      = iconURL
                    };
                    await ctx.RespondAsync(embed : embed).ConfigureAwait(false);
                }
            }
            else
            {
                string discordName = ctx.Member.Username;
                string discordPFP  = ctx.Member.AvatarUrl;
                ulong  discordID   = ctx.Member.Id;
                string SVID        = await User.GetSVIDFromDiscordAsync(discordID);

                User user = new User(SVID);
                var  data = await user.GetSnapshotAsync();

                int Total_XP = data.post_likes + data.comment_likes + (data.twitch_message_xp * 4) + (data.discord_commends * 5) + (data.discord_message_xp * 2) + (data.discord_game_xp / 100);
#pragma warning disable IDE0004
                decimal Ratio_Messages = (decimal)data.discord_message_xp / (decimal)data.discord_message_count;
#pragma warning restore IDE0004
                decimal multiplier             = (decimal)Math.Pow(10, Convert.ToDouble(2));
                decimal Ratio_Messages_Rounded = (Math.Ceiling(Ratio_Messages * multiplier) / multiplier);

                await ctx.TriggerTypingAsync();

                DiscordEmbedBuilder.EmbedAuthor iconURL = new DiscordEmbedBuilder.EmbedAuthor
                {
                    Name    = discordName + " XP",
                    IconUrl = discordPFP,
                };

                DiscordEmbedBuilder embed = new DiscordEmbedBuilder
                {
                    Title       = $"Total XP: {Total_XP}\nMessage to Message XP: 1 : {Ratio_Messages_Rounded * 2}",
                    Description = $"XP for [{discordName}](https://spookvooper.com/User/Info?svid={SVID})'s SpookVooper account",
                    Color       = new DiscordColor("#965d4a"),
                    Author      = iconURL
                };
                await ctx.RespondAsync(embed : embed).ConfigureAwait(false);
            }
        }
Esempio n. 25
0
        public override async Task <bool> ProcessStep(DiscordClient client, DiscordChannel channel, DiscordUser user)
        {
            var embedBuilder = new DiscordEmbedBuilder
            {
                Title       = $"Please Respond Below",
                Description = $"{user.Mention}, {_content}",
            };

            embedBuilder.AddField("To stop the dialogue", "Use the an.cancel command");

            if (_minLength.HasValue)
            {
                embedBuilder.AddField("Min Length:", $"{_minLength.Value} characters");
            }
            if (_maxLength.HasValue)
            {
                embedBuilder.AddField("Max Length:", $"{_maxLength.Value} characters");
            }

            var interactivity = client.GetInteractivity();

            while (true)
            {
                var embed = await channel.SendMessageAsync(embed : embedBuilder);

                OnMessageAdded(embed);

                var messageResult = await interactivity.WaitForMessageAsync(
                    x => x.ChannelId == channel.Id && x.Author.Id == user.Id).ConfigureAwait(false);

                OnMessageAdded(messageResult.Result);

                if (messageResult.Result.Content.Equals("an.cancel", StringComparison.OrdinalIgnoreCase))
                {
                    return(true);
                }

                if (_minLength.HasValue)
                {
                    if (messageResult.Result.Content.Length < _minLength.Value)
                    {
                        await TryAgain(channel, $"Your input is {_minLength.Value - messageResult.Result.Content.Length} characters");

                        continue;
                    }
                }

                if (_maxLength.HasValue)
                {
                    if (messageResult.Result.Content.Length > _maxLength.Value)
                    {
                        await TryAgain(channel, $"Your input is {_maxLength.Value - messageResult.Result.Content.Length} characters");

                        continue;
                    }
                }

                OnValidResult(messageResult.Result.Content);

                return(false);
            }
        }
Esempio n. 26
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.RespondAsync(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 DiscordEmbedBuilder
            {
                Title  = "KICK",
                Color  = DiscordColor.Red,
                Footer = new DiscordEmbedBuilder.EmbedFooter
                {
                    Text = "InsanityBot - ExaInsanity 2020-2021"
                }
            };

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

            try
            {
                member.AddModlogEntry(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 - ExaInsanity 2020-2021"
                    }
                };

                if (Invite || DmMember)
                {
                    var 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.HomeGuild.GetChannel(ToUInt64(InsanityBot.Config["insanitybot.identifiers.commands.modlog_channel_id"]))
                    .SendMessageAsync(embed: moderationEmbedBuilder.Build());
            }
            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 - ExaInsanity 2020-2021"
                    }
                };
                InsanityBot.Client.Logger.LogError($"{e}: {e.Message}");
            }
            finally
            {
                if (!Silent)
                {
                    await ctx.RespondAsync(embed : embedBuilder.Build());
                }
            }
        }
    }
Esempio n. 27
0
        public async Task GameIdea(CommandContext ctx)
        {
            // BASED ON THE BAFTA YGD GAME IDEA GENERATOR
            var environments = new string[]
            {
                "Ocean",
                "Cave",
                "Space",
                "Jungle",
                "Inside a Computer",
                "Supermarket",
                "City",
                "Castle",
                "Alternate Reality",
                "At Home"
            };

            var goals = new string[]
            {
                "Escape",
                "Survive",
                "Reach A Destination",
                "Find All Items",
                "Use All Items",
                "Complete The Puzzle",
                "Destroy Objects",
                "Remove All Enemies",
                "Rescue",
                "Capture"
            };

            var rules = new string[]
            {
                "Can't Touch The Floor",
                "Can't Do The Same Thing Twice In A Row",
                "Bounce Off Walls",
                "Can Only Select Connecting Itmes",
                "Can Only Move Forwards",
                "One Life Only",
                "Avoid #Enemies",
                "Must Not #Be Seen",
                "Limited Time",
                "Limited Inventory"
            };

            var genres = new string[]
            {
                "Puzzle",
                "Adventure",
                "Arcade",
                "Educational",
                "Strategy",
                "Casual",
                "Racing",
                "Action",
                "Role Play (RPG)",
                "Simulation"
            };

            var wildcards = new string[]
            {
                "Multiplayer",
                "Fruit",
                "Household Chores",
                "Something Spooky",
                "Colours",
                "Fairy Tale",
                "Music",
                "AR/VR",
                "Magic Spell",
                "Robots",
                "One Touch"
            };

            var r = new Random();

            var environment = environments[r.Next(0, environments.Length)];
            var goal        = goals[r.Next(0, goals.Length)];
            var rule        = rules[r.Next(0, rules.Length)];
            var genre       = genres[r.Next(0, genres.Length)];
            var wildcard    = wildcards[r.Next(0, wildcards.Length)];

            var output = $"***Environment:*** {environment}\n" +
                         $"***Goal:*** {goal}\n" +
                         $"***Rule:*** {rule}\n" +
                         $"***Genre:*** {genre}\n" +
                         $"***Wildcard:*** {wildcard}";


            var embed = new DiscordEmbedBuilder
            {
                Title       = "Game Idea",
                Description = output,
                Color       = DiscordColor.HotPink,
            }.Build();

            await ctx.Channel
            .SendMessageAsync(embed : embed)
            .ConfigureAwait(false);
        }
Esempio n. 28
0
        public async Task <IReadOnlyList <Page> > GetPaginatedResultsAsync(string query, int amount = 1, string type = null)
        {
            if (this.IsDisabled())
            {
                return(null);
            }

            if (string.IsNullOrWhiteSpace(query))
            {
                throw new ArgumentException("Query missing!", nameof(query));
            }

            if (amount < 1 || amount > 20)
            {
                throw new ArgumentException("Result amount out of range (max 20)", nameof(amount));
            }

            IReadOnlyList <SearchResult> results = await this.SearchAsync(query, amount, type);

            if (results is null || !results.Any())
            {
                return(null);
            }

            var pages = new List <Page>();

            foreach (SearchResult res in results.Take(10))
            {
                var emb = new DiscordEmbedBuilder {
                    Title       = res.Snippet.Title,
                    Description = Formatter.Italic(string.IsNullOrWhiteSpace(res.Snippet.Description) ? "No description provided" : res.Snippet.Description),
                    Color       = DiscordColor.Red
                };

                if (!(res.Snippet.Thumbnails is null))
                {
                    emb.WithThumbnailUrl(res.Snippet.Thumbnails.Default__.Url);
                }

                emb.AddField("Channel", res.Snippet.ChannelTitle, inline: true);
                emb.AddField("Published at", $"{res.Snippet.PublishedAt ?? DateTime.Now}", inline: true);

                switch (res.Id.Kind)
                {
                case "youtube#video":
                    emb.WithUrl($"{_ytUrl}/watch?v={res.Id.VideoId}");
                    break;

                case "youtube#channel":
                    emb.WithDescription($"{_ytUrl}/channel/{res.Id.ChannelId}");
                    break;

                case "youtube#playlist":
                    emb.WithDescription($"{_ytUrl}/playlist?list={res.Id.PlaylistId}");
                    break;
                }

                pages.Add(new Page(embed: emb));
            }

            return(pages.AsReadOnly());
        }
Esempio n. 29
0
        private async Task ExecuteBanCommand(CommandContext ctx,
                                             DiscordMember member,
                                             String Reason,
                                             Boolean Silent,
                                             Boolean DmMember)
        {
            if (!ctx.Member.HasPermission("insanitybot.moderation.ban"))
            {
                await ctx.Channel.SendMessageAsync(InsanityBot.LanguageConfig["insanitybot.error.lacking_permission"]);

                return;
            }

            //actually do something with the usedefault value
            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  = "BAN",
                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", BanReason, true);

            try
            {
                _            = 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.Build()
                });
            }
            catch (Exception e)
            {
                embedBuilder = new DiscordEmbedBuilder
                {
                    Description = GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.ban.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());
            }
        }
    }
Esempio n. 30
0
        public async Task Info(CommandContext ctx, [Description("The user in question. Leave blank to return your own info."), RemainingText] string userMention = null)
        {
            try {
                ulong userId = 0;
                var   member = ctx.Member;
                try
                {
                    if (userMention != null)
                    {
                        member = ctx.Guild.FindMemberAsync(userMention).Result;
                        userId = member.Id;
                    }
                }
                catch
                {
                    await ctx.RespondAsync("User not found or not a member of this guild!");

                    return;
                }
                var user = ctx.User;
                if (userId != 0)
                {
                    user = await Program.discord.ShardClients.First().Value.GetUserAsync(userId);
                }
                Logger.Log($"User info command: processing user {user.Username}");
                string type = "User";
                if (user.IsBot)
                {
                    type = "Bot";
                }

                /*if (user.Id == 366298290377195522)
                 *  type = "**Robot Overlord**";
                 * if (user.Id == Program.discord.CurrentUser.Id)
                 *  type = "Yours truly";*/
                var eb = new DiscordEmbedBuilder();
                eb.WithColor(Utils.CBGreen);

                //eb.WithFooter("© Mrcarrot 2018-21. All Rights Reserved.");
                eb.WithThumbnail(user.AvatarUrl);
                eb.WithTitle("User Info");
                //eb.WithDescription($"{user.Username + "#" + user.Discriminator}\nNickname: {nick}\nCreated At: {user.CreationTimestamp} (UTC)\nType: {type}\nStatus: {status}");
                eb.AddField("Username", $"{user.Username}#{user.Discriminator}");
                eb.AddField("Created", $"<t:{user.CreationTimestamp.ToUnixTimeSeconds()}:R> ({user.CreationTimestamp} UTC)", true);
                eb.AddField("Type", $"{type}", true);
                if (!ctx.Channel.IsPrivate)
                {
                    string nick = member.Nickname;
                    if (nick == null || nick == "")
                    {
                        nick = member.Username;
                    }
                    eb.AddField("Nickname", $"{nick}", true);
                }
                await ctx.RespondAsync(embed : eb.Build());
            }
            catch (Exception e)
            {
                Logger.Log(e.ToString(), Logger.CBLogLevel.EXC);
            }
        }