1
0
Fork 0
mirror of https://gitlab.com/niansa/SomeBot.git synced 2025-03-06 20:48:26 +01:00

Basic functionallity

This commit is contained in:
niansa 2023-03-02 20:54:35 +01:00
parent 0c985f4bed
commit 6906af1d01

View file

@ -1,5 +1,7 @@
#include "../bot.hpp"
#include <string>
#include <string_view>
#include <thread>
#include <memory>
#include <ctime>
@ -26,7 +28,7 @@ class LuaExecution {
Bot *bot;
} baseContext;
struct Context : public BaseContext {
dpp::message *msg;
const dpp::message *msg;
};
public:
@ -56,6 +58,10 @@ public:
.addProperty("increment", &snowflake::get_increment)
.endClass()
.beginClass<message>("Message")
.addStaticFunction("new", [guild_id = baseContext.guild_id] () {
dpp::message o;
o.guild_id = guild_id;
})
.addProperty("id", &message::id, false)
.addProperty("channel_id", &message::channel_id, true)
.addProperty("guild_id", &message::guild_id, false)
@ -96,6 +102,9 @@ public:
.addProperty("is_dm", &message::is_dm)
.addFunction("add_component", &message::add_component)
.addFunction("add_embed", &message::add_embed)
.addFunction("send", [cluster = &baseContext.bot->cluster] (const message *o) {
return cluster->message_create_sync(*o);
})
.endClass()
.beginClass<message::message_ref>("MessageRef")
.addProperty("message_id", &message::message_ref::message_id, true)
@ -339,6 +348,35 @@ public:
// We can now enable sandboxing
luaL_sandbox(state);
}
std::string execute(const std::string& source, const dpp::message *msg) {
// Get state
auto state = this->state.get();
// We need bytecode
std::string bytecode = Luau::compile(source, Luau::CompileOptions());
// We can then load that bytecode
if (luau_load(state, "code.lua", bytecode.data(), bytecode.size(), 0) != 0) {
size_t len;
const char* msg = lua_tolstring(state, -1, &len);
std::string error(msg, len);
lua_pop(state, 1);
return error;
}
// Now, we call into the code
luabridge::LuaRef on_call = luabridge::getGlobal(state, "on_call");
if (!on_call.isCallable()) {
return "'on_call' is not callable";
}
luabridge::LuaResult result = on_call(Context{baseContext, msg});
// Finally, we need to return the result
return result.errorMessage();
}
};
class Custom {
@ -346,7 +384,27 @@ class Custom {
public:
Custom(Bot *_bot) : bot(_bot) {
//...
bot->add_messagecommand(Bot::MessageCommand({"Evaluate"}, "Evaluiere Lua code"), [&](const dpp::message_context_menu_t& event) {
// Continue in new thread...
std::thread([this, event] () {
// Construct lua execution
LuaExecution exec(bot, event.command.guild_id);
// Get code to execute
const auto& msg = event.get_message();
const auto& code = msg.content;
// Start execution
auto error = exec.execute(code, &msg);
// Report outcome
if (error.empty()) {
event.reply("Success.");
} else {
event.reply("Error:\n```lua\n"+error+"\n```");
}
}).detach();
});
}
};
BOT_ADD_MODULE(Custom);