Пример #1
0
        private Task PrintGameAsync(LocalizationService lcs, DiscordMessage msg, Participant?toMove = null)
        {
            var sb = new StringBuilder();

            sb.AppendLine(Formatter.Bold($"{lcs.GetString(this.Channel.GuildId, "str-house")}: {this.HandValue(this.hand)}"));
            if (this.hand.Any())
            {
                sb.AppendJoin(" | ", this.hand).AppendLine();
            }
            else
            {
                sb.AppendLine(Emojis.Question).AppendLine();
            }

            foreach (Participant participant in this.participants)
            {
                sb.Append(participant.User.Mention).Append(": ");
                sb.AppendLine(Formatter.Bold(this.HandValue(participant.Hand).ToString()));
                sb.AppendJoin(" | ", participant.Hand);
                sb.AppendLine().AppendLine();
            }

            var emb = new LocalizedEmbedBuilder(lcs, this.Channel.GuildId);

            emb.WithLocalizedTitle("fmt-casino-blackjack", Emojis.Cards.Suits[0], Emojis.Cards.Suits[0]);
            emb.WithColor(DiscordColor.DarkGreen);
            emb.WithDescription(sb);

            if (!this.gameOver)
            {
                emb.AddLocalizedTitleField("str-casino-blackjack-hit", toMove?.User.Mention ?? lcs.GetString(this.Channel.GuildId, "str-house"));
            }

            return(msg.ModifyAsync(embed: emb.Build()));
        }
Пример #2
0
        public LocalizedEmbedBuilder AddToEmbed(LocalizedEmbedBuilder emb, MovieInfo info)
        {
            emb.WithTitle(info.Title);
            emb.WithDescription(info.Plot);
            emb.WithColor(DiscordColor.Yellow);
            emb.WithUrl(this.Service.GetUrl(info.IMDbId));

            emb.AddLocalizedTitleField("str-type", info.Type, inline: true, unknown: false);
            emb.AddLocalizedTitleField("str-year", info.Year, inline: true, unknown: false);
            emb.AddLocalizedTitleField("str-id", info.IMDbId, inline: true, unknown: false);
            emb.AddLocalizedTitleField("str-genre", info.Genre, inline: true, unknown: false);
            emb.AddLocalizedTitleField("str-rel-date", info.ReleaseDate, inline: true, unknown: false);
            emb.AddLocalizedField("str-score", "fmt-rating-imdb", inline: true, contentArgs: new[] { info.IMDbRating, info.IMDbVotes });
            emb.AddLocalizedTitleField("str-rating", info.Rated, inline: true, unknown: false);
            emb.AddLocalizedTitleField("str-duration", info.Duration, inline: true, unknown: false);
            emb.AddLocalizedTitleField("str-writer", info.Writer, inline: true, unknown: false);
            emb.AddLocalizedTitleField("str-director", info.Director, inline: true, unknown: false);
            emb.AddLocalizedTitleField("str-actors", info.Actors, inline: true, unknown: false);
            if (!string.IsNullOrWhiteSpace(info.Poster) && info.Poster != "N/A")
            {
                emb.WithThumbnail(info.Poster);
            }

            emb.WithLocalizedFooter("fmt-powered-by", null, "OMDb");
            return(emb);
        }
Пример #3
0
        public async Task EvaluateAsync(CommandContext ctx,
                                        [RemainingText, Description("desc-code")] string code)
        {
            if (string.IsNullOrWhiteSpace(code))
            {
                throw new InvalidCommandUsageException(ctx, "cmd-err-cmd-add-cb");
            }

            DiscordMessage msg = await ctx.RespondWithLocalizedEmbedAsync(emb => {
                emb.WithLocalizedTitle("str-eval");
                emb.WithColor(this.ModuleColor);
            });

            Script <object>?snippet = CSharpCompilationService.Compile(code, out ImmutableArray <Diagnostic> diag, out Stopwatch compileTime);

            if (snippet is null)
            {
                await msg.DeleteAsync();

                throw new InvalidCommandUsageException(ctx, "cmd-err-cmd-add-cb");
            }

            var emb = new LocalizedEmbedBuilder(this.Localization, ctx.Guild?.Id);

            if (diag.Any(d => d.Severity == DiagnosticSeverity.Error))
            {
                emb.WithLocalizedTitle("str-eval-fail-compile");
                emb.WithLocalizedDescription("fmt-eval-fail-compile", compileTime.ElapsedMilliseconds, diag.Length);
                emb.WithColor(DiscordColor.Red);

                foreach (Diagnostic d in diag.Take(3))
                {
                    FileLinePositionSpan ls = d.Location.GetLineSpan();
                    emb.AddLocalizedTitleField("fmt-eval-err", Formatter.InlineCode(d.GetMessage()),
                                               titleArgs: new object[] { ls.StartLinePosition.Line, ls.StartLinePosition.Character }
                                               );
                }

                if (diag.Length > 3)
                {
                    emb.AddLocalizedField("str-eval-omit", "fmt-eval-omit", contentArgs: new object[] { diag.Length - 3 });
                }

                await UpdateOrRespondAsync();

                return;
            }

            Exception?           exc = null;
            ScriptState <object>?res = null;
            var runTime = Stopwatch.StartNew();

            try {
                res = await snippet.RunAsync(new EvaluationEnvironment(ctx));
            } catch (Exception e) {
                exc = e;
            }
            runTime.Stop();

            if (exc is { } || res is null)
Пример #4
0
        public static async Task <bool> SendFeedUpdateAsync(TheGodfatherBot shard, RssSubscription sub, SyndicationItem latest)
        {
            DiscordChannel?chn;

            try {
                chn = await shard.Client.GetShard(sub.GuildId).GetChannelAsync(sub.ChannelId);
            } catch (NotFoundException) {
                return(false);
            }

            if (chn is null)
            {
                return(false);
            }

            var emb = new LocalizedEmbedBuilder(shard.Services.GetRequiredService <LocalizationService>(), sub.GuildId);

            emb.WithTitle(latest.Title.Text);
            emb.WithUrl(sub.Feed.LastPostUrl);
            emb.WithColor(DiscordColor.Gold);
            emb.WithLocalizedTimestamp(latest.LastUpdatedTime > latest.PublishDate ? latest.LastUpdatedTime : latest.PublishDate);

            if (latest.Content is TextSyndicationContent content)
            {
                string?imageUrl = RedditService.GetImageUrl(content);
                if (imageUrl is { })
Пример #5
0
        private async Task CreateWebhookAsync(CommandContext ctx, DiscordChannel channel, string name, Uri?avatarUrl, string?reason)
        {
            // TODO what about other channel types? news, store etc?
            if (channel?.Type != ChannelType.Text)
            {
                throw new InvalidCommandUsageException(ctx, "cmd-err-chn-type-text");
            }

            if (string.IsNullOrWhiteSpace(name) || name.Length > DiscordLimits.NameLimit)
            {
                throw new CommandFailedException(ctx, "cmd-err-name", DiscordLimits.NameLimit);
            }

            DiscordWebhook wh;

            if (avatarUrl is null)
            {
                wh = await channel.CreateWebhookAsync(name, reason : ctx.BuildInvocationDetailsString(reason));
            }
            else
            {
                (_, HttpContentHeaders headers) = await HttpService.HeadAsync(avatarUrl);

                if (!headers.ContentTypeHeaderIsImage() || headers.ContentLength.GetValueOrDefault() > 8 * 1024 * 1024)
                {
                    throw new CommandFailedException(ctx, "err-url-image-8mb");
                }
                try {
                    using MemoryStream ms = await HttpService.GetMemoryStreamAsync(avatarUrl);

                    wh = await channel.CreateWebhookAsync(name, ms, reason : ctx.BuildInvocationDetailsString(reason));
                } catch (WebException e) {
                    throw new CommandFailedException(ctx, "err-url-image-fail", e);
                }
            }

            if (await ctx.WaitForBoolReplyAsync("q-send-token"))
            {
                try {
                    DiscordDmChannel?dm = await ctx.Client.CreateDmChannelAsync(ctx.User.Id);

                    if (dm is { })
                    {
                        var emb = new LocalizedEmbedBuilder(this.Localization, ctx.Guild.Id);
                        emb.WithLocalizedTitle("fmt-wh-add", Formatter.Bold(Formatter.Strip(wh.Name)), channel.Mention);
                        emb.WithDescription($"||{wh.BuildUrlString()}||");
                        emb.WithColor(this.ModuleColor);
                        emb.WithThumbnail(wh.AvatarUrl);
                        emb.AddLocalizedTitleField("str-id", wh.Id, inline: true);
                        emb.AddLocalizedTitleField("str-name", wh.Name, inline: true);
                        emb.AddLocalizedTitleField("str-token", $"||{wh.Token}||");
                        await dm.SendMessageAsync(embed : emb.Build());
                    }
                    else
                    {
                        await ctx.FailAsync("err-dm-fail");
                    }
                } catch {
Пример #6
0
 private LocalizedEmbedBuilder AddDataToEmbed(LocalizedEmbedBuilder emb, PartialWeatherData data)
 {
     emb.WithColor(this.ModuleColor);
     emb.AddLocalizedTitleField("str-w-condition", data.Weather.Select(w => w.Main).JoinWith(", "), inline: true, titleArgs: Emojis.Cloud);
     emb.AddLocalizedTitleField("str-w-humidity", $"{data.Main.Humidity}%", inline: true, titleArgs: Emojis.Drops);
     emb.AddLocalizedTitleField("str-w-temp", $"{data.Main.Temp:F1}°C", inline: true, titleArgs: Emojis.Thermometer);
     emb.AddLocalizedTitleField("str-w-temp-minmax", $"{data.Main.TempMin:F1}°C / {data.Main.TempMax:F1}°C", inline: true, titleArgs: Emojis.Thermometer);
     emb.AddLocalizedTitleField("str-w-wind", $"{data.Wind.Speed} m/s", inline: true, titleArgs: Emojis.Wind);
     emb.WithThumbnail(WeatherService.GetWeatherIconUrl(data.Weather[0]));
     emb.WithLocalizedFooter("fmt-powered-by", null, "openweathermap.org");
     return(emb);
 }
Пример #7
0
        private async Task AdvanceAsync(LocalizationService lcs)
        {
            this.DealDamage();
            await this.WaitForPotionUseAsync();

            this.UpdateHpBars();

            string header = $"{this.player1.Mention} {this.hp1str} {Emojis.DuelSwords} {this.hp2str} {this.player2.Mention}";
            var    emb    = new LocalizedEmbedBuilder(lcs, this.Channel.GuildId);

            emb.WithDescription($"{header}\n\n{this.eb}");
            emb.WithColor(DiscordColor.Teal);

            this.msgHandle = await this.msgHandle.ModifyOrResendAsync(this.Channel, emb.Build());
        }
Пример #8
0
        public DiscordEmbed EmbedResults(LocalizationService lcs, IEnumerable <KeyValuePair <DiscordUser, int> > results)
        {
            var sb = new StringBuilder();

            foreach ((DiscordUser user, int result) in results)
            {
                sb.AppendLine(lcs.GetString(this.Channel.GuildId, "fmt-game-tr-errors", user.Mention, result));
            }

            var emb = new LocalizedEmbedBuilder(lcs, this.Channel.GuildId);

            emb.WithLocalizedTitle("fmt-game-tr-res");
            emb.WithDescription(sb);
            emb.WithColor(DiscordColor.Teal);
            return(emb.Build());
        }
Пример #9
0
        public static DiscordEmbed ToDiscordEmbed(this Poll poll, LocalizationService lcs)
        {
            var emb = new LocalizedEmbedBuilder(lcs, poll.Channel.GuildId);

            emb.WithTitle(poll.Question);
            emb.WithLocalizedDescription("str-vote-text");
            emb.WithColor(DiscordColor.Orange);

            for (int i = 0; i < poll.Options.Count; i++)
            {
                if (!string.IsNullOrWhiteSpace(poll.Options[i]))
                {
                    emb.AddField($"{i + 1} : {poll.Options[i]}", $"{poll.Results.Count(kvp => kvp.Value == i)}");
                }
            }

            if (poll.EndTime is { })
Пример #10
0
        public static DiscordEmbed ToEmbed(this ReactionsPoll poll, LocalizationService lcs)
        {
            var emb = new LocalizedEmbedBuilder(lcs, poll.Channel.GuildId);

            emb.WithTitle(poll.Question);
            emb.WithLocalizedDescription("str-vote-react");
            emb.WithColor(DiscordColor.Orange);

            for (int i = 0; i < poll.Options.Count; i++)
            {
                if (!string.IsNullOrWhiteSpace(poll.Options[i]))
                {
                    emb.AddField($"{i + 1}", poll.Options[i], inline: true);
                }
            }

            if (poll.EndTime is { })
Пример #11
0
        public static DiscordEmbed ToStarboardEmbed(this DiscordMessage msg, LocalizationService lcs, DiscordEmoji star, int count)
        {
            var emb = new LocalizedEmbedBuilder(lcs, msg.Channel.Guild.Id);

            emb.WithColor(DiscordColor.Gold);
            emb.WithUrl(msg.JumpLink);
            emb.WithAuthor(msg.Author.ToDiscriminatorString(), iconUrl: msg.Author.AvatarUrl);
            emb.WithDescription(msg.Content.Truncate(DiscordLimits.EmbedDescriptionLimit - 5, " ..."));
            emb.AddLocalizedTitleField("str-votes", $"{Formatter.Bold(count.ToString())} {star}", inline: true);
            emb.AddLocalizedTitleField("str-chn", msg.Channel.Mention, inline: true);

            string jumplink = Formatter.MaskedUrl(lcs.GetString(msg.Channel.Guild.Id, "str-jumplink"), msg.JumpLink);

            emb.AddLocalizedTitleField("str-link", jumplink, inline: true);

            string?url = msg.Attachments
                         .Select(a => a.Url)
                         .FirstOrDefault(u => u.EndsWith(".jpg") || u.EndsWith(".png") || u.EndsWith(".jpeg") || u.EndsWith(".gif"))
            ;

            if (url is { })
Пример #12
0
        private Task PrintGameAsync(LocalizationService lcs, DiscordMessage msg, IEnumerable <int> numbers, int step)
        {
            var sb = new StringBuilder();

            sb.Append(Formatter.Bold(lcs.GetString(this.Channel.GuildId, "str-casino-lottery-drawn"))).Append(' ');
            sb.AppendLine(Formatter.Bold(numbers.Take(step).JoinWith(" "))).AppendLine();

            foreach (Participant participant in this.participants)
            {
                sb.Append(participant.User.Mention).Append(" | ");
                sb.AppendLine(Formatter.Bold(participant.Numbers.JoinWith(" ")));
                sb.AppendLine();
            }

            var emb = new LocalizedEmbedBuilder(lcs, this.Channel.GuildId);

            emb.WithLocalizedTitle("fmt-casino-lottery", Emojis.MoneyBag, Emojis.MoneyBag);
            emb.WithColor(DiscordColor.DarkGreen);
            emb.WithDescription(sb);

            return(msg.ModifyAsync(embed: emb.Build()));
        }
Пример #13
0
        public async Task AnnounceAsync(CommandContext ctx,
                                        [RemainingText, Description("desc-announcement")] string message)
        {
            if (!await ctx.WaitForBoolReplyAsync("q-announcement", args: Formatter.Strip(message)))
            {
                return;
            }

            var emb = new LocalizedEmbedBuilder(this.Localization, ctx.Guild?.Id);

            emb.WithLocalizedTitle("str-announcement");
            emb.WithDescription(message);
            emb.WithColor(DiscordColor.Red);

            var eb = new StringBuilder();
            IEnumerable <(int, IEnumerable <DiscordGuild>)> shardGuilds = TheGodfather.Bot !.Client.ShardClients
                                                                          .Select(kvp => (kvp.Key, kvp.Value.Guilds.Values));

            foreach ((int shardId, IEnumerable <DiscordGuild> guilds) in shardGuilds)
            {
                foreach (DiscordGuild guild in guilds)
                {
                    try {
                        await guild.GetDefaultChannel().SendMessageAsync(embed: emb.Build());
                    } catch {
                        eb.AppendLine(this.Localization.GetString(ctx.Guild?.Id, "cmd-err-announce", shardId, guild.Name, guild.Id));
                    }
                }
            }

            if (eb.Length > 0)
            {
                await ctx.ImpInfoAsync(this.ModuleColor, "fmt-err", eb.ToString());
            }
            else
            {
                await ctx.InfoAsync(this.ModuleColor);
            }
        }
Пример #14
0
        public async Task InfoAsync(CommandContext ctx,
                                    [Description("desc-emoji-info")] DiscordEmoji emoji)
        {
            try {
                DiscordGuildEmoji gemoji = await ctx.Guild.GetEmojiAsync(emoji.Id);

                var emb = new LocalizedEmbedBuilder(this.Localization, ctx.Guild.Id);
                emb.WithColor(this.ModuleColor);
                emb.WithLocalizedTitle("str-emoji-details");
                emb.WithDescription($"{gemoji.GetDiscordName()} ({gemoji.Id})");
                emb.WithThumbnail(gemoji.Url);

                emb.AddLocalizedTitleField("str-created-by", gemoji.User?.ToDiscriminatorString(), inline: true);
                emb.AddLocalizedTitleField("str-animated", gemoji.IsAnimated, inline: true);
                emb.AddLocalizedTitleField("str-managed", gemoji.IsManaged, inline: true);
                emb.AddLocalizedTitleField("str-url", gemoji.Url);
                emb.AddLocalizedTimestampField("str-created-at", gemoji.CreationTimestamp);

                await ctx.RespondAsync(embed : emb.Build());
            } catch (NotFoundException) {
                throw new CommandFailedException(ctx, "cmd-err-emoji-404");
            }
        }
        public override async Task RunAsync(LocalizationService lcs)
        {
            this.Started = true;

            var rng = new SecureRandom();

            for (int round = 1; round <= 5 && this.ParticipantCount > 1; round++)
            {
                DiscordMessage msg = await this.Channel.LocalizedEmbedAsync(lcs, Emojis.Gun, DiscordColor.DarkRed, "fmt-game-rr-starting", round);

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

                var eb = new StringBuilder();
                foreach (DiscordUser participant in this.participants)
                {
                    if (rng.NextBool(round))
                    {
                        eb.AppendLine($"{participant.Mention} {Emojis.Dead} {Emojis.Blast} {Emojis.Gun}");
                        this.participants.TryRemove(participant);
                    }
                    else
                    {
                        eb.AppendLine($"{participant.Mention} {Emojis.Relieved} {Emojis.Gun}");
                    }

                    var emb = new LocalizedEmbedBuilder(lcs, this.Channel.GuildId);
                    emb.WithLocalizedTitle("fmt-game-rr-round", round);
                    emb.WithDescription(eb.ToString());
                    emb.WithColor(DiscordColor.DarkRed);
                    msg = await msg.ModifyOrResendAsync(this.Channel, emb.Build());

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

            this.Survivors = this.participants.ToList().AsReadOnly();
        }
Пример #16
0
 public static LocalizedEmbedBuilder WithSuccessColor(this LocalizedEmbedBuilder builder)
 => builder.WithColor(Config.SuccessColor);
Пример #17
0
 public static LocalizedEmbedBuilder WithWarnColor(this LocalizedEmbedBuilder builder)
 => builder.WithColor(Config.WarnColor);
Пример #18
0
 public static LocalizedEmbedBuilder WithErrorColor(this LocalizedEmbedBuilder builder)
 => builder.WithColor(Config.ErrorColor);
Пример #19
0
        public override async Task RunAsync(LocalizationService lcs)
        {
            int timeouts = 0;

            foreach ((QuizQuestion question, int i) in this.questions.Select((q, i) => (q, i)))
            {
                var emb = new LocalizedEmbedBuilder(lcs, this.Channel.GuildId);
                emb.WithLocalizedTitle("fmt-game-quiz-q", i + 1);
                emb.WithDescription(Formatter.Bold(question.Content));
                emb.WithColor(DiscordColor.Teal);
                emb.AddLocalizedTitleField("str-category", question.Category, inline: false);

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

                foreach ((string answer, int index) in answers.Select((a, i) => (a, i)))
                {
                    emb.AddLocalizedTitleField("fmt-game-quiz-a", answer, inline: true, titleArgs: index + 1);
                }

                var            options = Emojis.Numbers.All.Skip(1).Take(4).ToList();
                DiscordMessage msg     = await this.Channel.SendMessageAsync(embed : emb.Build());

                foreach (DiscordEmoji emoji in options)
                {
                    await msg.CreateReactionAsync(emoji);
                }

                bool timeout = true;
                var  failed  = new ConcurrentHashSet <ulong>();
                InteractivityResult <MessageReactionAddEventArgs> res = await this.Interactivity.WaitForReactionAsync(
                    e => {
                    if (e.User.IsBot || failed.Contains(e.User.Id) || e.Message != msg)
                    {
                        return(false);
                    }
                    int opt = options.IndexOf(e.Emoji);
                    if (opt == -1)
                    {
                        return(false);
                    }
                    if (answers[opt].Equals(question.CorrectAnswer))
                    {
                        return(true);
                    }
                    else
                    {
                        failed.Add(e.User.Id);
                    }
                    return(false);
                },
                    TimeSpan.FromSeconds(10)
                    );

                if (res.TimedOut)
                {
                    if (!failed.Any())
                    {
                        timeouts = timeout ? timeouts + 1 : 0;
                        if (timeouts == 3)
                        {
                            this.IsTimeoutReached = true;
                            return;
                        }
                    }
                    else
                    {
                        timeouts = 0;
                    }
                    await this.Channel.LocalizedEmbedAsync(lcs, Emojis.AlarmClock, DiscordColor.Teal, "fmt-game-quiz-timeout", question.CorrectAnswer);
                }
                else
                {
                    await this.Channel.LocalizedEmbedAsync(lcs, Emojis.CheckMarkSuccess, DiscordColor.Teal, "fmt-game-quiz-correct", res.Result.User.Mention);

                    this.results.AddOrUpdate(res.Result.User, u => 1, (u, v) => v + 1);
                }

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