public async Task SqlQuery([Remainder] 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(Bot.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 AutoReactAsync(success); await ReplyAsync(message); }
public async Task ScriptEval([Remainder] string code) { code = code.Trim(' ', '`', '\n'); if (code.StartsWith("cs\n")) { code = code.Remove(0, 3); // C# code block in Discord } var dbProperty = typeof(StorageService).GetProperty("Db", BindingFlags.NonPublic | BindingFlags.Instance); Db = (PacManDbContext)dbProperty.GetValue(Storage); // If I need to access the database from a script await Context.Message.AddReactionAsync(CustomEmoji.ELoading, DefaultOptions); object result; try { result = await Scripting.EvalAsync(code, this); await Logger.Log(LogSeverity.Debug, LogSource.Eval, $"Successfully executed:\n {code}"); await AutoReactAsync(true); } catch (Exception e) { result = e.Message; await Logger.Log(LogSeverity.Debug, LogSource.Eval, $"{e}"); await AutoReactAsync(false); } await Context.Message.RemoveReactionAsync(CustomEmoji.ELoading, Context.Client.CurrentUser, DefaultOptions); if (result != null) { await ReplyAsync($"```\n{result.ToString().Truncate(1990)}```"); } }