Example #1
0
        public async Task ScriptEval(CommandContext ctx, [RemainingText] string code)
        {
            code     = code.ExtractCode();
            this.ctx = ctx;
            await ctx.Message.CreateReactionAsync(CustomEmoji.Loading);

            try
            {
                using var eval = CSharpScript.EvaluateAsync(code, _scriptOptions, this);
                var result = await eval;
                Log.Info($"Successfully executed:\n {code}");
                await ctx.AutoReactAsync(true);

                if (result is not null)
                {
                    await ctx.RespondAsync($"```\n{result.ToString().Truncate(1990)}```");
                }
            }
            catch (Exception e)
            {
                Log.Info($"Eval - {e}");
                await ctx.AutoReactAsync(false);

                await ctx.RespondAsync($"```\n{e.Message}```");
            }
            finally
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
            }

            await ctx.Message.DeleteOwnReactionAsync(CustomEmoji.Loading);
        }
Example #2
0
        public async Task LeaveUno(CommandContext ctx)
        {
            var game = Game(ctx);

            if (game is null)
            {
                await ctx.ReplyAsync($"There's no Uno game in this channel! Use `uno` to start.");

                return;
            }
            if (!game.UserId.Contains(ctx.User.Id))
            {
                await ctx.ReplyAsync($"You're not in the game.");

                return;
            }

            await game.RemovePlayerAsync(ctx.User);

            if (game.State == GameState.Cancelled)
            {
                await UpdateGameMessageAsync(ctx);

                EndGame(ctx);
            }
            else
            {
                await DeleteGameMessageAsync(ctx);
                await RespondGameAsync(ctx);
            }

            await ctx.AutoReactAsync();
        }
Example #3
0
        public async Task DoGarbageCollect(CommandContext ctx)
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            await ctx.AutoReactAsync();
        }
Example #4
0
        public async Task RunBrainf(CommandContext ctx, [RemainingText] string userInput)
        {
            await ctx.Message.CreateReactionAsync(CustomEmoji.Loading);

            var    slice        = userInput.ExtractCode().Split('!', 2);
            string program      = slice[0];
            string programInput = slice.Length > 1 ? slice[1] : "";

            var message = new StringBuilder();
            var bf      = new Brainfuck(program, programInput);

            try
            {
                message.Append(await bf.RunAsync(3000));
                await ctx.AutoReactAsync(true);
            }
            catch (Exception e)
            {
                switch (e)
                {
                case Brainfuck.BrainfuckException be:
                    message.AppendLine($"Runtime exception: {be.Message}");
                    if (e.InnerException is not null)
                    {
                        message.AppendLine($"Inner exception: {e.InnerException}\n");
                    }
                    message.AppendLine($"Memory at this point: {be.Memory}\n");
                    message.AppendLine($"Output up to this point:\n{bf.Output}");
                    break;

                case ArgumentException _:
                    message.AppendLine("The provided program has invalid syntax.");
                    break;

                default:
                    throw;
                }
                await ctx.AutoReactAsync(false);
            }

            await ctx.Message.DeleteOwnReactionAsync(CustomEmoji.Loading);

            await ctx.RespondAsync(message.Length == 0? "*No output*" : $"```\n{message.ToString().Truncate(1990)}```");
        }
Example #5
0
        public async Task ReplyFeedback(CommandContext ctx, ulong userId, [RemainingText] string message)
        {
            try
            {
                string pre = "```diff\n+The following message was sent to you by this bot's owner." +
                             "\n-To reply to this message, use the 'feedback' command.```\n";

                await ShardedClient.DmUserAsync(userId, pre + message);

                await ctx.AutoReactAsync();
            }
            catch (Exception e)
            {
                Log.Debug($"{e.Message}");
                await ctx.AutoReactAsync(false);

                await ctx.RespondAsync($"```{e.Message}```");
            }
        }
Example #6
0
        public async Task ShardRetry(CommandContext ctx)
        {
            foreach (var shard in ShardedClient.ShardClients.Values)
            {
                Input.StopListening(shard);
                Input.StartListening(shard);
            }

            await ctx.AutoReactAsync();
        }
Example #7
0
        public async Task SqlQuery(CommandContext ctx, [RemainingText] string query)
        {
            query = query.ExtractCode();

            bool success  = true;
            var  message  = new StringBuilder();
            var  table    = new StringBuilder();
            int  affected = -1;

            try
            {
                using var db        = new PacManDbContext(Config.dbConnectionString);
                using var command   = db.Database.GetDbConnection().CreateCommand();
                command.CommandText = query;
                db.Database.OpenConnection();
                using var result = command.ExecuteReader();
                affected         = result.RecordsAffected;
                while (result.Read())
                {
                    object[] values = new object[result.FieldCount];
                    result.GetValues(values);

                    for (int i = 0; i < values.Length; i++)
                    {
                        if (values[i] is string str && str.ContainsAny(" ", "\n"))
                        {
                            values[i] = $"\"{values[i]}\"";
                        }
                    }

                    table.AppendLine(values?.JoinString("  "));
                }
            }
            catch (SqliteException e)
            {
                success = false;
                message.Append($"```{e.Message}```");
            }

            if (affected >= 0)
            {
                message.Append($"`{affected} rows affected`\n");
            }
            if (table.Length > 0)
            {
                message.Append($"```{table.ToString().Truncate(1990 - message.Length)}```");
            }

            await ctx.AutoReactAsync(success);

            await ctx.RespondAsync(message);
        }
Example #8
0
        public async Task DoRemoteGameMoves(CommandContext ctx, params string[] moves)
        {
            var game = Games.GetForChannel <IMessagesGame>(ctx.Channel.Id);

            if (game is null)
            {
                await ctx.RespondAsync("How about you start a game first");

                return;
            }

            bool success = true;

            foreach (string move in moves)
            {
                try
                {
                    if (game.State == GameState.Active)
                    {
                        await game.InputAsync(move);
                    }
                    else
                    {
                        break;
                    }
                }
                catch (Exception e)
                {
                    Log.Debug($"While executing debug game input: {e}");
                    success = false;
                }
            }

            await game.UpdateMessageAsync();

            if (game is MultiplayerGame mgame && await mgame.IsBotTurnAsync())
            {
                await mgame.BotInputAsync();

                await Task.Delay(1000);

                await mgame.UpdateMessageAsync();
            }

            if (game.State != GameState.Active)
            {
                Games.Remove(game);
            }

            await ctx.AutoReactAsync(success);
        }
Example #9
0
        public async Task ChangeGameDisplay(CommandContext ctx)
        {
            if (Game(ctx) is null)
            {
                await ctx.ReplyAsync("There is no active Pac-Man game in this channel!");

                return;
            }

            Game(ctx).slimDisplay = !Game(ctx).slimDisplay;
            await UpdateGameMessageAsync(ctx);

            await ctx.AutoReactAsync();
        }
Example #10
0
        public async Task ReloadContent(CommandContext ctx)
        {
            try
            {
                Config.LoadContent(File.ReadAllText(Files.Contents));
            }
            catch (Exception e)
            {
                Log.Error($"Failed to load bot content: {e}");
                await ctx.RespondAsync($"```{e.Message}```");
            }

            Log.Info("Reloaded bot content");
            await ctx.AutoReactAsync();
        }
Example #11
0
        public async Task KickUno(CommandContext ctx, DiscordMember member = null)
        {
            var game = Game(ctx);

            if (game is null)
            {
                await ctx.ReplyAsync($"There's no Uno game in this channel! Use `{ctx.Prefix}uno` to start.");

                return;
            }
            if (member is null)
            {
                await ctx.ReplyAsync($"You must specify a user to kick from the game.");

                return;
            }
            if (!game.UserId.Contains(member.Id))
            {
                await ctx.ReplyAsync($"That user is not in the game.");

                return;
            }
            if (!member.IsBot && (game.UserId[Game(ctx).Turn] != member.Id || (DateTime.Now - game.LastPlayed) < TimeSpan.FromMinutes(1)))
            {
                await ctx.ReplyAsync("To remove another user they must be inactive for at least 1 minute during their turn.");
            }

            await game.RemovePlayerAsync(member);

            if (game.State == GameState.Cancelled)
            {
                await UpdateGameMessageAsync(ctx);

                EndGame(ctx);
            }
            else
            {
                await DeleteGameMessageAsync(ctx);
                await RespondGameAsync(ctx);
            }

            await ctx.AutoReactAsync();
        }
Example #12
0
        public async Task UpdateAndShutDown(CommandContext ctx)
        {
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                await ctx.RespondAsync("This command is currently only available on Linux systems.");

                return;
            }


            var process = new Process()
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName               = "/bin/bash",
                    Arguments              = $"-c \"git pull\"",
                    WorkingDirectory       = Environment.CurrentDirectory,
                    RedirectStandardOutput = true,
                    UseShellExecute        = false,
                    CreateNoWindow         = true,
                }
            };

            process.Start();
            string result = process.StandardOutput.ReadToEnd();

            process.WaitForExit();

            bool updated = result.Contains("Updating");

            if (!updated)
            {
                await ctx.AutoReactAsync(false);
            }

            await ctx.RespondAsync($"```\n{result.Truncate(1990)}```");

            if (updated)
            {
                await ShutDown(ctx);
            }
        }
Example #13
0
        public async Task CancelGame(CommandContext ctx)
        {
            var game = Game(ctx);

            if (game is null)
            {
                await ctx.ReplyAsync("There is no active game in this channel!");

                return;
            }

            if (ctx.Guild is null || game.UserId.Contains(ctx.User.Id) || ctx.UserCan(Permissions.ManageMessages) ||
                DateTime.Now - game.LastPlayed > TimeSpan.FromSeconds(60))
            {
                var msg = await game.GetMessageAsync();

                EndGame(ctx);
                if (msg is not null)
                {
                    await game.UpdateMessageAsync();
                }

                if (game is PacManGame pacManGame)
                {
                    if (ctx.Guild is not null)
                    {
                        await ctx.RespondAsync($"Game ended.\n**Result:** {pacManGame.score} points in {pacManGame.Time} turns");
                    }
                    if (msg is not null && ctx.BotCan(Permissions.ManageMessages))
                    {
                        try { await msg.DeleteAllReactionsAsync(); }
                        catch (NotFoundException) { }
                    }
                }
                else
                {
                    await ctx.AutoReactAsync();
                }
            }
Example #14
0
        public async Task RubiksCube(CommandContext ctx, [RemainingText] string input = "")
        {
            var game = Game(ctx);

            if (game is null)
            {
                game = StartNewGame(new RubiksGame(ctx.Channel.Id, ctx.User.Id, Services));
            }

            bool removeOld = false;

            switch (input.ToLowerInvariant())
            {
            case "h":
            case "help":
            case "moves":
            case "notation":
                string moveHelp =
                    $"You can input a sequence of turns using the `rubik [input]` command, " +
                    $"with turns separated by spaces.\nYou can do `help rubik` to see a few more commands.\n\n" +
                    "**Simple turns:** U, D, L, R, F, B\nThese are the basic clockwise turns of the cube. " +
                    "They stand for the Up, Down, Left, Right, Front and Back sides.\n" +
                    "**Counterclockwise turns:** Add `'`. Example: U', R'\n" +
                    "**Double turns:** Add `2`. Example: F2, D2\n" +
                    "**Wide turns:** Add `w`. Example: Dw, Lw2, Uw'\n" +
                    "These rotate two layers at the same time in the direction of the given face.\n\n" +
                    "**Slice turns:** M E S\n" +
                    "These rotate the middle layer corresponding with L, D and B respectively.\n\n" +
                    "**Cube rotations:** x, y, z\n" +
                    "These rotate the entire cube in the direction of R, U and F respectively. " +
                    "They can also be counterclockwise or double.";

                await ctx.RespondAsync(moveHelp);

                return;


            case "reset":
            case "solve":
                EndGame(ctx);
                await ctx.AutoReactAsync();

                return;


            case "scramble":
            case "shuffle":
                game.Scramble();
                removeOld = true;
                break;


            case "showguide":
                game.ShowHelp = !game.ShowHelp;
                if (game.ShowHelp)
                {
                    await ctx.AutoReactAsync();
                }
                else
                {
                    await ctx.RespondAsync("❗ You just disabled the help displayed below the cube.\n" +
                                           "Consider re-enabling it if you're not used to the game.");
                }
                break;


            default:
                if (!string.IsNullOrEmpty(input))
                {
                    if (!game.TryDoMoves(input))
                    {
                        await ctx.RespondAsync($"{CustomEmoji.Cross} Invalid sequence of moves. " +
                                               $"Do `{Storage.GetPrefix(ctx)}help rubik` for commands.");

                        return;
                    }
                }
                removeOld = true;
                break;
            }

            await SaveGameAsync(ctx);

            if (removeOld && game.ChannelId == ctx.Channel.Id)
            {
                await DeleteGameMessageAsync(ctx);
            }
            await RespondGameAsync(ctx);
        }
Example #15
0
        public async Task SetStatus(CommandContext ctx, ActivityType type, [RemainingText] string status)
        {
            await ShardedClient.UpdateStatusAsync(new DiscordActivity(status, type));

            await ctx.AutoReactAsync();
        }
Example #16
0
 public async Task DoLog(CommandContext ctx, [RemainingText] string message)
 {
     Log.Info(message);
     await ctx.AutoReactAsync();
 }
Example #17
0
        public async Task SetStatus(CommandContext ctx, UserStatus status)
        {
            await ShardedClient.UpdateStatusAsync(userStatus : status);

            await ctx.AutoReactAsync();
        }