85 lines
2.8 KiB
C++
85 lines
2.8 KiB
C++
#include "Base/SQL.hpp"
|
|
#include "Commands.hpp"
|
|
#include <cstdint>
|
|
#include <dpp/appcommand.h>
|
|
#include <dpp/dispatcher.h>
|
|
#include <dpp/exception.h>
|
|
#include <dpp/snowflake.h>
|
|
#include <string>
|
|
#include <variant>
|
|
|
|
void commandPing(const dpp::slashcommand_t &event) { event.reply("Pong"); }
|
|
void commandBalance(const dpp::slashcommand_t &event) {
|
|
std::string person, balance;
|
|
dpp::command_value id = event.get_parameter("user");
|
|
|
|
// Weirdest thing ever
|
|
if (std::holds_alternative<std::monostate>(id)) {
|
|
person = event.command.get_issuing_user().id;
|
|
balance = getUserBalance(person);
|
|
event.reply(COMMAND_BALANCE_SELF_RESPONSE(balance));
|
|
|
|
return;
|
|
}
|
|
|
|
person = std::get<dpp::snowflake>(id).str();
|
|
balance = getUserBalance(person);
|
|
event.reply(COMMAND_BALANCE_SOMEONE_ELSE_RESPONSE(person, balance));
|
|
}
|
|
|
|
void commandPay(const dpp::slashcommand_t &event) {
|
|
std::string recipient =
|
|
std::get<dpp::snowflake>(event.get_parameter("recipient")).str();
|
|
std::uint64_t amount = std::get<std::int64_t>(event.get_parameter("amount"));
|
|
|
|
// See if we can deduct the payment first
|
|
if (!deductFromUsersBalance(event.command.get_issuing_user().id, amount)) {
|
|
event.reply(COMMAND_PAY_FAIL_INSUFFICIENT_AMOUNT(recipient,
|
|
std::to_string(amount)));
|
|
return;
|
|
}
|
|
|
|
// Lets pay them
|
|
increaseFromUsersBalance(recipient, amount);
|
|
event.reply(COMMAND_PAY_SUCCESS(recipient, std::to_string(amount)));
|
|
}
|
|
|
|
inline void increaseFromUsersBalance(const dpp::snowflake userid,
|
|
std::uint64_t amount) {
|
|
std::uint64_t balance = std::stoi(getUserBalance(userid));
|
|
execSQL("UPDATE MONEY SET CASH=" + std::to_string(balance + amount) +
|
|
" WHERE UID=" + userid.str());
|
|
}
|
|
|
|
inline bool deductFromUsersBalance(const dpp::snowflake userid,
|
|
std::uint64_t amount) {
|
|
std::uint64_t balance = std::stoi(getUserBalance(userid));
|
|
if (balance < amount) {
|
|
return false;
|
|
}
|
|
|
|
execSQL("UPDATE MONEY SET CASH=" + std::to_string(balance - amount) +
|
|
" WHERE UID=" + userid.str());
|
|
|
|
return true;
|
|
}
|
|
|
|
inline std::string getUserBalance(const dpp::snowflake userid) {
|
|
std::string balance;
|
|
execSQL("SELECT CASH FROM MONEY WHERE UID=" + userid.str(), &balance);
|
|
|
|
if (balance.empty()) {
|
|
addUserToDatabase(userid);
|
|
execSQL("SELECT CASH FROM MONEY WHERE UID=" + userid.str(),
|
|
&balance); // We are rerunning it cus if the default starting cash
|
|
// changes I might forget to change it here
|
|
}
|
|
std::uint8_t begining = balance.find(':') + 1;
|
|
|
|
return balance.substr(begining, balance.find(';') - begining);
|
|
}
|
|
|
|
inline void addUserToDatabase(const dpp::snowflake userid) {
|
|
execSQL("INSERT INTO MONEY (UID) VALUES (" + userid.str() + ");");
|
|
}
|