예제 #1
0
        private async Task ExecuteScriptAsync(string code, VolteContext ctx)
        {
            ctx.Services.Get <EmojiService>(out var e);
            var sopts = ScriptOptions.Default.WithImports(_imports).WithReferences(
                AppDomain.CurrentDomain.GetAssemblies()
                .Where(x => !x.IsDynamic && !x.Location.IsNullOrWhitespace()));

            var embed = ctx.CreateEmbedBuilder();
            var msg   = await embed.WithTitle("Evaluating").WithDescription(Format.Code(code, "cs"))
                        .SendToAsync(ctx.Channel);

            try
            {
                var sw    = Stopwatch.StartNew();
                var state = await CSharpScript.RunAsync(code, sopts, CreateEvalEnvironment(ctx));

                sw.Stop();
                if (state.ReturnValue is null)
                {
                    await msg.DeleteAsync();

                    await ctx.Message.AddReactionAsync(new Emoji(e.BallotBoxWithCheck));
                }
                else
                {
                    var res = state.ReturnValue switch
                    {
                        string str => str,
                        IEnumerable enumerable => enumerable.Cast <object>().Select(x => $"{x}").Join(", "),
                        IUser user => $"{user} ({user.Id})",
                        ITextChannel channel => $"#{channel.Name} ({channel.Id})",
                        _ => state.ReturnValue.ToString()
                    };
                    await msg.ModifyAsync(m =>
                                          m.Embed = embed.WithTitle("Eval")
                                          .AddField("Elapsed Time", $"{sw.Elapsed.Humanize()}", true)
                                          .AddField("Return Type", state.ReturnValue.GetType(), true)
                                          .WithDescription(Format.Code(res, "ini")).Build());
                }
            }
            catch (Exception ex)
            {
                await msg.ModifyAsync(m =>
                                      m.Embed = embed
                                      .AddField("Exception Type", ex.GetType(), true)
                                      .AddField("Message", ex.Message, true)
                                      .WithTitle("Error")
                                      .Build()
                                      );
            }
        }
예제 #2
0
파일: EvalHelper.cs 프로젝트: Ultz/Volte
        private static async Task ExecuteScriptAsync(string code, VolteContext ctx)
        {
            var embed = ctx.CreateEmbedBuilder();
            var msg   = await embed.WithTitle("Evaluating").WithDescription(Format.Code(code, "cs"))
                        .SendToAsync(ctx.Channel);

            try
            {
                var env   = CreateEvalEnvironment(ctx);
                var sw    = Stopwatch.StartNew();
                var state = await CSharpScript.RunAsync(code, Options, env);

                sw.Stop();
                var shouldReply = true;
                if (state.ReturnValue != null)
                {
                    switch (state.ReturnValue)
                    {
                    case EmbedBuilder eb:
                        shouldReply = false;
                        await env.ReplyAsync(eb);

                        break;

                    case Embed e:
                        shouldReply = false;
                        await env.ReplyAsync(e);

                        break;
                    }

                    var res = state.ReturnValue switch
                    {
                        bool b => b.ToString().ToLower(),
                        IEnumerable enumerable when !(state.ReturnValue is string) => enumerable.Cast <object>().ToReadableString(),
                        IUser user => $"{user} ({user.Id})",
                        ITextChannel channel => $"#{channel.Name} ({channel.Id})",
                        IMessage message => env.Inspect(message),
                        _ => state.ReturnValue.ToString()
                    };
                    await(shouldReply switch
                    {
                        true => msg.ModifyAsync(m =>
                                                m.Embed = embed.WithTitle("Eval")
                                                          .AddField("Elapsed Time", $"{sw.Elapsed.Humanize()}", true)
                                                          .AddField("Return Type", state.ReturnValue.GetType().AsPrettyString(), true)
                                                          .WithDescription(Format.Code(res, res.IsNullOrEmpty() ? string.Empty : "ini")).Build()),
                        false => msg.DeleteAsync().ContinueWith(_ => env.ReactAsync(DiscordHelper.BallotBoxWithCheck))
                    });
                }
예제 #3
0
        /// <summary>
        ///     Starts a poll in the contextual channel using the specified <see cref="PollInfo"/> applied to the embed.
        ///     This method does not start or in any way support reaction tracking.
        ///     This message will have its poll emojis added in the background so it's not a long-running <see cref="Task"/>.
        /// </summary>
        /// <param name="context">The context to use</param>
        /// <param name="pollInfo">The <see cref="PollInfo"/> to apply</param>
        /// <returns>The sent poll message.</returns>
        public async ValueTask <IUserMessage> StartPollAsync(VolteContext context,
                                                             PollInfo pollInfo)
        {
            var m = await pollInfo.Apply(context.CreateEmbedBuilder()).SendToAsync(context.Channel);

            _ = Executor.ExecuteAsync(async() =>
            {
                _ = await context.Message.TryDeleteAsync("Poll invocation message.");
                await DiscordHelper.GetPollEmojis().GetRange(0, pollInfo.Fields.Count)
                .ForEachAsync(async emoji =>
                {
                    await m.AddReactionAsync(emoji);
                });
            });
            return(m);
        }
예제 #4
0
        private async Task ExecuteScriptAsync(string code, VolteContext ctx)
        {
            var sopts = ScriptOptions.Default.WithImports(_imports).WithReferences(
                AppDomain.CurrentDomain.GetAssemblies()
                .Where(x => !x.IsDynamic && !x.Location.IsNullOrWhitespace()));

            var embed = ctx.CreateEmbedBuilder();
            var msg   = await embed.WithTitle("Evaluating").WithDescription(Format.Code(code, "cs")).SendToAsync(ctx.Channel);

            try
            {
                var sw     = Stopwatch.StartNew();
                var result = await CSharpScript.EvaluateAsync(code, sopts, CreateEvalEnvironment(ctx));

                sw.Stop();
                if (result is null)
                {
                    await msg.DeleteAsync();

                    await ctx.ReactSuccessAsync();
                }
                else
                {
                    var res = result switch
                    {
                        string str => str,
                        IEnumerable enumerable => enumerable.Cast <object>().Select(x => $"{x}").Join(", "),
                        _ => result.ToString()
                    };
                    await msg.ModifyAsync(m =>
                                          m.Embed = embed.WithTitle("Eval")
                                          .AddField("Elapsed Time", $"{sw.Elapsed.Humanize()}", true)
                                          .AddField("Return Type", result.GetType(), true)
                                          .WithDescription(Format.Code(res, "ini")).Build());
                }
            }
            catch (Exception e)
            {
                await msg.ModifyAsync(m =>
                                      m.Embed = embed
                                      .AddField("Exception Type", e.GetType(), true)
                                      .AddField("Message", e.Message, true)
                                      .WithTitle("Error")
                                      .Build()
                                      );
            }
        }
예제 #5
0
 public EmbedBuilder AsEmbed(VolteContext ctx) => ctx.CreateEmbedBuilder(FormatContent(ctx))
 .WithAuthor(author: null)
 .WithFooter($"Requested by {ctx.User}.", ctx.User.GetEffectiveAvatarUrl());
예제 #6
0
파일: CommandHelper.cs 프로젝트: Ultz/Volte
        public static async ValueTask <EmbedBuilder> CreateCommandEmbedAsync(Command command, VolteContext ctx)
        {
            var embed = ctx.CreateEmbedBuilder()
                        .WithTitle(command.Name)
                        .WithDescription(command.Description ?? "No description provided.");
            var checks = CommandUtilities.EnumerateAllChecks(command).ToList();

            async Task AddSubcommandsFieldAsync()
            {
                embed.AddField("Subcommands", (await command.Module.Commands.WhereAccessibleAsync(ctx)
                                               .Where(x => !x.Attributes.Any(a => a is DummyCommandAttribute)).ToListAsync())
                               .Select(x => FormatCommandShort(x, false))
                               .Join(", "));
            }

            if (command.Attributes.Any(x => x is DummyCommandAttribute))
            {
                await AddSubcommandsFieldAsync();

                return(!checks.IsEmpty()
                    ? embed.AddField("Checks",
                                     (await Task.WhenAll(checks.Select(check => FormatCheckAsync(check, ctx)))).Join("\n"))
                    : embed);
            }

            if (command.Remarks != null)
            {
                embed.AppendDescription($" {command.Remarks}");
            }

            if (!command.FullAliases.IsEmpty())
            {
                embed.AddField("Aliases", command.FullAliases.Select(x => Format.Code(x)).Join(", "), true);
            }

            if (!command.Parameters.IsEmpty())
            {
                embed.AddField("Parameters", command.Parameters.Select(FormatParameter).Join("\n"));
            }

            if (command.CustomArgumentParserType is null)
            {
                embed.AddField("Usage", FormatUsage(ctx, command));
            }

            if (command.Attributes.Any(x => x is ShowPlaceholdersInHelpAttribute))
            {
                embed.AddField("Placeholders",
                               WelcomeOptions.ValidPlaceholders
                               .Select(x => $"{Format.Code($"{{{x.Key}}}")}: {Format.Italics(x.Value)}")
                               .Join("\n"));
            }

            if (command.Attributes.Any(x => x is ShowTimeFormatInHelpAttribute))
            {
                embed.AddField("Example Valid Time",
                               $"{Format.Code("4d3h2m1s")}: {Format.Italics("4 days, 3 hours, 2 minutes and one second.")}");
            }

            if (command.Attributes.Any(x => x is ShowSubcommandsInHelpOverrideAttribute))
            {
                await AddSubcommandsFieldAsync();
            }

            if (command.Attributes.AnyGet(x => x is ShowUnixArgumentsInHelpAttribute, out var unixAttr) &&
                unixAttr is ShowUnixArgumentsInHelpAttribute attr)
            {