improve code organisation, add .rc file

This commit is contained in:
Syping 2024-02-26 11:33:39 +01:00
parent 5191dcbefc
commit 87961fe611
26 changed files with 92 additions and 83 deletions

126
src/core/database.cpp Normal file
View file

@ -0,0 +1,126 @@
/*****************************************************************************
* dtranslatebot Discord Translate Bot
* Copyright (C) 2024 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/
#ifndef NDEBUG
#include <iostream>
#endif
#include "database.h"
using namespace bot::database;
database::database()
{
}
database::~database()
{
}
void database::add_channel_target(dpp::snowflake guild_id, dpp::snowflake channel_id, const bot::settings::target &target)
{
#ifndef NDEBUG
std::cerr << "[Debug] database::add_channel_target(dpp::snowflake, dpp::snowflake, const bot::settings::target&) have being called." << std::endl;
#endif
}
void database::delete_channel(dpp::snowflake guild_id, dpp::snowflake channel_id)
{
#ifndef NDEBUG
std::cerr << "[Debug] database::delete_channel(dpp::snowflake, dpp::snowflake) have being called." << std::endl;
#endif
}
void database::delete_channel_target(dpp::snowflake guild_id, dpp::snowflake channel_id, const std::string &target)
{
#ifndef NDEBUG
std::cerr << "[Debug] database::delete_channel_target(dpp::snowflake, dpp::snowflake, const std::string&) have being called." << std::endl;
#endif
}
void database::delete_guild(dpp::snowflake guild_id)
{
#ifndef NDEBUG
std::cerr << "[Debug] database::delete_guild(dpp::snowflake) have being called." << std::endl;
#endif
}
/*
std::variant<std::monostate,bot::settings::target> database::find_channel_target(dpp::snowflake guild_id, dpp::snowflake channel_id, const std::string &target)
{
#ifndef NDEBUG
std::cerr << "[Debug] database::find_channel_target(dpp::snowflake, dpp::snowflake, const std::string&) have being called." << std::endl;
#endif
return {};
}
*/
bot::settings::channel database::get_channel(dpp::snowflake guild_id, dpp::snowflake channel_id)
{
#ifndef NDEBUG
std::cerr << "[Debug] database::get_channel(dpp::snowflake, dpp::snowflake) have being called." << std::endl;
#endif
return {};
}
std::vector<dpp::snowflake> database::get_channels(dpp::snowflake guild_id)
{
#ifndef NDEBUG
std::cerr << "[Debug] database::get_channels(dpp::snowflake) have being called." << std::endl;
#endif
return {};
}
/*
std::string database::get_channel_source(dpp::snowflake guild_id, dpp::snowflake channel_id)
{
#ifndef NDEBUG
std::cerr << "[Debug] database::get_channel_source(dpp::snowflake, dpp::snowflake) have being called." << std::endl;
#endif
return {};
}
std::vector<bot::settings::target> database::get_channel_targets(dpp::snowflake guild_id, dpp::snowflake channel_id)
{
#ifndef NDEBUG
std::cerr << "[Debug] database::get_channel_targets(dpp::snowflake, dpp::snowflake) have being called." << std::endl;
#endif
return {};
}
*/
std::vector<dpp::snowflake> database::get_guilds()
{
#ifndef NDEBUG
std::cerr << "[Debug] database::get_guilds() have being called." << std::endl;
#endif
return {};
}
void database::set_channel_source(dpp::snowflake guild_id, dpp::snowflake channel_id, const std::string &source)
{
#ifndef NDEBUG
std::cerr << "[Debug] database::set_channel_source(dpp::snowflake, dpp::snowflake, const std::string&) have being called." << std::endl;
#endif
}
bool database::sync()
{
#ifndef NDEBUG
std::cerr << "[Debug] database::sync() have being called." << std::endl;
#endif
return false;
}

55
src/core/database.h Normal file
View file

@ -0,0 +1,55 @@
/*****************************************************************************
* dtranslatebot Discord Translate Bot
* Copyright (C) 2024 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/
#ifndef DATABASE_H
#define DATABASE_H
#include "settings_types.h"
namespace bot {
namespace database {
struct guild {
dpp::snowflake id;
std::vector<dpp::snowflake> channel;
};
class database {
public:
explicit database();
virtual ~database();
virtual void add_channel_target(dpp::snowflake guild_id, dpp::snowflake channel_id, const bot::settings::target &target);
virtual void delete_channel(dpp::snowflake guild_id, dpp::snowflake channel_id);
virtual void delete_channel_target(dpp::snowflake guild_id, dpp::snowflake channel_id, const std::string &target);
virtual void delete_guild(dpp::snowflake guild_id);
/* unused atm.
virtual std::variant<std::monostate,bot::settings::target> find_channel_target(dpp::snowflake guild_id, dpp::snowflake channel_id, const std::string &target);
*/
virtual bot::settings::channel get_channel(dpp::snowflake guild_id, dpp::snowflake channel_id);
virtual std::vector<dpp::snowflake> get_channels(dpp::snowflake guild_id);
/* unused atm.
virtual std::string get_channel_source(dpp::snowflake guild_id, dpp::snowflake channel_id);
virtual std::vector<bot::settings::target> get_channel_targets(dpp::snowflake guild_id, dpp::snowflake channel_id);
*/
virtual std::vector<dpp::snowflake> get_guilds();
virtual void set_channel_source(dpp::snowflake guild_id, dpp::snowflake channel_id, const std::string &source);
virtual bool sync();
};
}
}
#endif // DATABASE_H

75
src/core/main.cpp Normal file
View file

@ -0,0 +1,75 @@
/*****************************************************************************
* dtranslatebot Discord Translate Bot
* Copyright (C) 2023-2024 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/
#include <dpp/cluster.h>
#include <dpp/once.h>
#include <iostream>
#include <vector>
#include <thread>
#include "message_queue.h"
#include "settings.h"
#include "slashcommands.h"
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cout << "Usage: " << argv[0] << " [json]" << std::endl;
return 0;
}
std::cout << "[Launch] Processing configuration..." << std::endl;
bot::settings::settings settings;
if (!settings.parse_file(argv[1]))
return 1;
std::cout << "[Launch] Requesting supported languages..." << std::endl;
if (settings.get_translator()->get_languages().empty()) {
std::cerr << "[Error] Failed to initialise translateable languages" << std::endl;
return 1;
}
dpp::cluster bot(settings.token(), dpp::i_default_intents | dpp::i_message_content);
bot.on_log([&bot](const dpp::log_t &event) {
std::cerr << "[Log] " << event.message << std::endl;
});
bot::submit_queue submit_queue;
std::thread submit_queue_loop(&bot::submit_queue::run, &submit_queue, &bot);
bot::message_queue message_queue;
std::thread message_queue_loop(&bot::message_queue::run, &message_queue, &settings, &submit_queue);
bot.on_message_create(std::bind(&bot::message_queue::process_message_event, &message_queue, &bot, &settings, std::placeholders::_1));
bot.on_slashcommand(std::bind(&bot::slashcommands::process_command_event, &bot, &settings, std::placeholders::_1));
bot.on_ready([&bot, &settings](const dpp::ready_t &event) {
if (dpp::run_once<struct register_bot_commands>()) {
bot::slashcommands::register_commands(&bot, &settings);
}
});
std::cout << "[Launch] Starting bot..." << std::endl;
bot.start(dpp::st_wait);
// It's unneccessary, but we choose to exit clean anyway
message_queue.terminate();
message_queue_loop.join();
submit_queue.terminate();
submit_queue_loop.join();
return 0;
}

105
src/core/message_queue.cpp Normal file
View file

@ -0,0 +1,105 @@
/*****************************************************************************
* dtranslatebot Discord Translate Bot
* Copyright (C) 2023-2024 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/
#include <thread>
#include "message_queue.h"
#include "settings.h"
using namespace bot;
using namespace std::chrono_literals;
void message_queue::add(const message &message)
{
const std::lock_guard<std::mutex> guard(m_mutex);
m_queue.push(message);
}
void message_queue::add(message &&message)
{
const std::lock_guard<std::mutex> guard(m_mutex);
m_queue.push(message);
}
void message_queue::process_message_event(dpp::cluster *bot, bot::settings::settings *settings, const dpp::message_create_t &event)
{
// We check for conditions we want to skip translation for
if (event.msg.author.id == bot->me.id || event.msg.content.empty() || event.msg.has_thread())
return;
if (event.msg.webhook_id) {
const std::lock_guard<bot::settings::settings> guard(*settings);
// We will not translate messages from our own bot
if (settings->is_translatebot(event.msg.webhook_id))
return;
}
const std::lock_guard<bot::settings::settings> guard(*settings);
if (const bot::settings::channel *channel = settings->get_channel(event.msg.guild_id, event.msg.channel_id)) {
bot::message message;
message.id = event.msg.id;
message.author = event.msg.member.get_nickname();
if (message.author.empty())
message.author = event.msg.author.global_name;
message.avatar = event.msg.member.get_avatar_url(settings->avatar_size());
if (message.avatar.empty())
message.avatar = event.msg.author.get_avatar_url(settings->avatar_size());
message.message = event.msg.content;
message.source = channel->source;
message.targets = channel->targets;
add(std::move(message));
}
}
void message_queue::run(bot::settings::settings *settings, submit_queue *submit_queue)
{
m_running = true;
while (m_running) {
m_mutex.lock();
if (!m_queue.empty()) {
const message message = m_queue.front();
m_queue.pop();
m_mutex.unlock();
auto translator = settings->get_translator();
for (auto target = message.targets.begin(); target != message.targets.end(); target++) {
translated_message tr_message;
tr_message.author = message.author;
tr_message.avatar = message.avatar;
tr_message.message = translator->translate(message.message, message.source, target->target);
tr_message.webhook = target->webhook;
submit_queue->add(std::move(tr_message));
}
std::this_thread::yield();
}
else {
m_mutex.unlock();
std::this_thread::sleep_for(100ms);
}
}
}
void message_queue::terminate()
{
m_running = false;
}

54
src/core/message_queue.h Normal file
View file

@ -0,0 +1,54 @@
/*****************************************************************************
* dtranslatebot Discord Translate Bot
* Copyright (C) 2023-2024 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/
#ifndef MESSAGE_QUEUE_H
#define MESSAGE_QUEUE_H
#include <dpp/cluster.h>
#include <mutex>
#include <string>
#include <queue>
#include <vector>
#include "settings.h"
#include "submit_queue.h"
namespace bot {
struct message {
uint64_t id;
std::string author;
std::string avatar;
std::string message;
std::string source;
std::vector<bot::settings::target> targets;
};
class message_queue {
public:
void add(const message &message);
void add(message &&message);
void process_message_event(dpp::cluster *bot, bot::settings::settings *settings, const dpp::message_create_t &event);
void run(bot::settings::settings *settings, submit_queue *submit_queue);
void terminate();
private:
bool m_running;
std::mutex m_mutex;
std::queue<message> m_queue;
};
}
#endif // MESSAGE_QUEUE_H

43
src/core/regex.h Normal file
View file

@ -0,0 +1,43 @@
/*****************************************************************************
* dtranslatebot Discord Translate Bot
* Copyright (C) 2023-2024 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/
#ifndef REGEX_H
#define REGEX_H
#ifdef DTRANSLATEBOT_USE_BOOST_REGEX
#include <boost/regex.hpp>
#else
#include <regex>
#endif
#include <string_view>
namespace bot {
#ifdef DTRANSLATEBOT_USE_BOOST_REGEX
using boost::regex;
using boost::regex_match;
using boost::match_results;
typedef boost::match_results<std::string_view::const_iterator> svmatch;
#else
using std::regex;
using std::regex_match;
using std::match_results;
typedef std::match_results<std::string_view::const_iterator> svmatch;
#endif
}
#endif // REGEX_H

530
src/core/settings.cpp Normal file
View file

@ -0,0 +1,530 @@
/*****************************************************************************
* dtranslatebot Discord Translate Bot
* Copyright (C) 2023-2024 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/
#include <dpp/json.h>
#include <fstream>
#include <iostream>
#include "settings.h"
#include "../database/file/file.h"
#include "../translator/libretranslate/libretranslate.h"
using namespace bot::settings;
void process_database_channels(std::shared_ptr<bot::database::database> database, bot::settings::guild *guild, std::vector<dpp::snowflake> *webhookIds)
{
const std::vector<dpp::snowflake> db_channels = database->get_channels(guild->id);
for (auto db_channel_id = db_channels.begin(); db_channel_id != db_channels.end(); db_channel_id++) {
bool channel_found = false;
for (auto channel = guild->channel.begin(); channel != guild->channel.end(); channel++) {
if (channel->id == *db_channel_id) {
const bot::settings::channel db_channel = database->get_channel(guild->id, channel->id);
if (!db_channel.source.empty())
channel->source = db_channel.source;
for (auto db_target = db_channel.targets.begin(); db_target != db_channel.targets.end(); db_target++) {
bool target_found = false;
for (auto target = channel->targets.begin(); target != channel->targets.end(); target++) {
if (target->target == db_target->target) {
target->webhook = db_target->webhook;
webhookIds->push_back(db_target->webhook.id);
target_found = true;
break;
}
}
if (!target_found) {
channel->targets.push_back(*db_target);
webhookIds->push_back(db_target->webhook.id);
}
}
channel_found = true;
break;
}
}
if (!channel_found) {
const bot::settings::channel db_channel = database->get_channel(guild->id, *db_channel_id);
guild->channel.push_back(db_channel);
for (auto db_target = db_channel.targets.begin(); db_target != db_channel.targets.end(); db_target++)
webhookIds->push_back(db_target->webhook.id);
}
}
}
void process_database(std::shared_ptr<bot::database::database> database, std::vector<guild> *guilds, std::vector<dpp::snowflake> *webhookIds)
{
std::cout << "[Launch] Loading database..." << std::endl;
const std::vector<dpp::snowflake> db_guilds = database->get_guilds();
for (auto db_guild_id = db_guilds.begin(); db_guild_id != db_guilds.end(); db_guild_id++) {
bool guild_found = false;
for (auto guild = guilds->begin(); guild != guilds->end(); guild++) {
if (guild->id == *db_guild_id) {
process_database_channels(database, &*guild, webhookIds);
guild_found = true;
break;
}
}
if (!guild_found) {
bot::settings::guild guild;
guild.id = *db_guild_id;
process_database_channels(database, &guild, webhookIds);
guilds->push_back(std::move(guild));
}
}
}
void process_guild_settings(const dpp::json &json, std::vector<guild> *guilds, std::vector<dpp::snowflake> *webhookIds)
{
for (auto json_guild = json.begin(); json_guild != json.end(); json_guild++) {
if (json_guild->is_object()) {
guild guild;
auto json_guild_id = json_guild->find("id");
if (json_guild_id != json_guild->end()) {
if (json_guild_id->is_number())
guild.id = static_cast<uint64_t>(*json_guild_id);
else if (json_guild_id->is_string())
guild.id = std::stoull(std::string(*json_guild_id));
else
throw std::invalid_argument("Guild id is not a number or a string");
}
else
guild.id = std::stoull(json_guild.key());
for (auto json_channel = json_guild->begin(); json_channel != json_guild->end(); json_channel++) {
if (json_channel->is_object()) {
channel channel;
auto json_channel_id = json_channel->find("id");
if (json_channel_id != json_channel->end()) {
if (json_channel_id->is_number())
channel.id = static_cast<uint64_t>(*json_channel_id);
else if (json_channel_id->is_string())
channel.id = std::stoull(std::string(*json_channel_id));
else
throw std::invalid_argument("Channel id is not a number or a string");
}
else
channel.id = std::stoull(json_channel.key());
auto json_channel_source = json_channel->find("source");
if (json_channel_source != json_channel->end())
channel.source = *json_channel_source;
auto json_channel_target = json_channel->find("target");
if (json_channel_target != json_channel->end()) {
if (json_channel_target->is_string()) {
target target;
target.target = *json_channel_target;
target.webhook = dpp::webhook(json_channel->at("webhook"));
webhookIds->push_back(target.webhook.id);
channel.targets.push_back(std::move(target));
}
else if (json_channel_target->is_object()) {
for (auto json_target = json_channel_target->begin(); json_target != json_channel_target->end(); json_target++) {
target target;
target.target = json_target.key();
target.webhook = dpp::webhook(*json_target);
webhookIds->push_back(target.webhook.id);
channel.targets.push_back(std::move(target));
}
}
}
if (!channel.source.empty() && !channel.targets.empty())
guild.channel.push_back(std::move(channel));
}
}
guilds->push_back(std::move(guild));
}
}
}
void process_preflang_settings(const dpp::json &json, std::vector<std::string> *preferred_langs)
{
for (auto json_preferred_lang = json.begin(); json_preferred_lang != json.end(); json_preferred_lang++) {
if (std::distance(json.begin(), json_preferred_lang) >= 25) {
std::cerr << "[Error] Value preferred_lang is limited to 25 languages" << std::endl;
break;
}
preferred_langs->push_back(*json_preferred_lang);
}
}
void process_user_settings(const dpp::json &json, uint16_t *avatar_size)
{
auto json_avatar_size = json.find("avatar_size");
if (json_avatar_size != json.end()) {
*avatar_size = *json_avatar_size;
if (*avatar_size < 16)
*avatar_size = 16;
else if (*avatar_size > 4096)
*avatar_size = 4096;
}
}
void process_url(const std::string &url, translator *translator)
{
std::string_view url_v = url;
if (url_v.substr(0, 7) == "http://") {
translator->tls = false;
if (!translator->port)
translator->port = 80;
url_v = url_v.substr(7);
}
else if (url_v.substr(0, 8) == "https://") {
translator->tls = true;
if (!translator->port)
translator->port = 443;
url_v = url_v.substr(8);
}
else {
translator->tls = false;
if (!translator->port)
translator->port = 80;
}
auto slash_pos = url_v.find_first_of('/');
if (slash_pos != std::string_view::npos) {
translator->url = url_v.substr(slash_pos);
url_v = url_v.substr(0, slash_pos);
}
else {
translator->url = "/";
url_v = url_v.substr(0, slash_pos);
}
// We don't have IPv6 support here yet
auto colon_pos = url_v.find_last_of(':');
if (colon_pos != std::string_view::npos) {
translator->hostname = url_v.substr(0, colon_pos);
const int port = std::stoi(std::string(url_v.substr(colon_pos + 1)));
if (port > 0 && port < 65536)
translator->port = static_cast<uint16_t>(port);
else
throw std::invalid_argument("Port is out of range");
}
else {
translator->hostname = url_v;
}
}
bool process_translator_settings(const dpp::json &json, translator *translator)
{
if (!json.is_object()) {
std::cerr << "[Error] Value translator needs to be a object" << std::endl;
return false;
}
auto json_translate_hostname = json.find("hostname");
if (json_translate_hostname != json.end())
translator->hostname = *json_translate_hostname;
else
translator->hostname = {};
auto json_translate_tls = json.find("tls");
if (json_translate_tls != json.end())
translator->tls = *json_translate_tls;
else
translator->tls = false;
auto json_translate_port = json.find("port");
if (json_translate_port != json.end())
translator->port = *json_translate_port;
else
translator->port = 0;
auto json_translate_url = json.find("url");
if (json_translate_url == json.end()) {
std::cerr << "[Error] Value url not found in translator object" << std::endl;
return false;
}
if (translator->hostname.empty()) {
process_url(*json_translate_url, translator);
}
else {
translator->url = *json_translate_url;
}
auto json_translate_apiKey = json.find("apiKey");
if (json_translate_apiKey != json.end())
translator->apiKey = *json_translate_apiKey;
else
translator->apiKey.clear();
return true;
}
void settings::add_channel(const channel &channel, dpp::snowflake guild_id)
{
const std::lock_guard<std::recursive_mutex> guard(m_mutex);
for (auto guild = m_guilds.begin(); guild != m_guilds.end(); guild++) {
if (guild->id == guild_id) {
guild->channel.push_back(channel);
return;
}
}
// We will create the guild structure when it is not in memory
m_guilds.push_back({ guild_id, { channel } });
}
bool settings::add_target(const target &target, dpp::snowflake guild_id, dpp::snowflake channel_id)
{
const std::lock_guard<std::recursive_mutex> guard(m_mutex);
for (auto guild = m_guilds.begin(); guild != m_guilds.end(); guild++) {
if (guild->id == guild_id) {
for (auto channel = guild->channel.begin(); channel != guild->channel.end(); channel++) {
if (channel->id == channel_id) {
channel->targets.push_back(target);
return true;
}
}
return false;
}
}
return false;
}
void settings::add_translatebot_webhook(dpp::snowflake webhook_id)
{
const std::lock_guard<std::recursive_mutex> guard(m_mutex);
m_webhookIds.push_back(webhook_id);
}
void settings::erase_translatebot_webhook(dpp::snowflake webhook_id)
{
const std::lock_guard<std::recursive_mutex> guard(m_mutex);
auto webhook_it = std::find(m_webhookIds.begin(), m_webhookIds.end(), webhook_id);
if (webhook_it != m_webhookIds.end())
m_webhookIds.erase(webhook_it);
}
uint16_t settings::avatar_size()
{
const std::lock_guard<std::recursive_mutex> guard(m_mutex);
return m_avatarSize;
}
channel* settings::get_channel(guild *guild, dpp::snowflake channel_id)
{
for (auto channel = guild->channel.begin(); channel != guild->channel.end(); channel++) {
if (channel->id == channel_id)
return &*channel;
}
return nullptr;
}
channel* settings::get_channel(dpp::snowflake guild_id, dpp::snowflake channel_id)
{
if (!m_externallyLockedCount) {
#ifndef NDEBUG
std::cerr << "[Debug] settings::get_channel(dpp::snowflake, dpp::snowflake) have being called without settings being locked." << std::endl;
#endif
return nullptr;
}
for (auto guild = m_guilds.begin(); guild != m_guilds.end(); guild++) {
if (guild->id == guild_id) {
for (auto channel = guild->channel.begin(); channel != guild->channel.end(); channel++) {
if (channel->id == channel_id)
return &*channel;
}
return nullptr;
}
}
return nullptr;
}
guild* settings::get_guild(dpp::snowflake guild_id)
{
if (!m_externallyLockedCount) {
#ifndef NDEBUG
std::cerr << "[Debug] settings::get_guild(dpp::snowflake) have being called without settings being locked." << std::endl;
#endif
return nullptr;
}
for (auto guild = m_guilds.begin(); guild != m_guilds.end(); guild++) {
if (guild->id == guild_id)
return &*guild;
}
return nullptr;
}
target* settings::get_target(dpp::snowflake guild_id, dpp::snowflake channel_id, const std::string &target)
{
if (!m_externallyLockedCount) {
#ifndef NDEBUG
std::cerr << "[Debug] settings::get_target(dpp::snowflake, dpp::snowflake, const std::string&) have being called without settings being locked." << std::endl;
#endif
return nullptr;
}
for (auto guild = m_guilds.begin(); guild != m_guilds.end(); guild++) {
if (guild->id == guild_id) {
for (auto channel = guild->channel.begin(); channel != guild->channel.end(); channel++) {
if (channel->id == channel_id) {
for (auto _target = channel->targets.begin(); _target != channel->targets.end(); _target++) {
if (_target->target == target)
return &*_target;
}
return nullptr;
}
}
return nullptr;
}
}
return nullptr;
}
target* settings::get_target(channel *channel, const std::string &target)
{
for (auto _target = channel->targets.begin(); _target != channel->targets.end(); _target++) {
if (_target->target == target)
return &*_target;
}
return nullptr;
}
const target* settings::get_target(const channel *channel, const std::string &target)
{
for (auto _target = channel->targets.begin(); _target != channel->targets.end(); _target++) {
if (_target->target == target)
return &*_target;
}
return nullptr;
}
const std::vector<std::string> settings::preferred_languages() const
{
const std::lock_guard<std::recursive_mutex> guard(m_mutex);
return m_prefLangs;
}
std::shared_ptr<bot::database::database> settings::get_database() const
{
const std::lock_guard<std::recursive_mutex> guard(m_mutex);
return m_database;
}
std::unique_ptr<bot::translator::translator> settings::get_translator() const
{
const std::lock_guard<std::recursive_mutex> guard(m_mutex);
return std::make_unique<bot::translator::libretranslate>(m_translator.hostname, m_translator.port, m_translator.url, m_translator.tls, m_translator.apiKey);
}
const std::string settings::token() const
{
const std::lock_guard<std::recursive_mutex> guard(m_mutex);
return m_token;
}
bool settings::is_translatebot(dpp::snowflake webhook_id) const
{
const std::lock_guard<std::recursive_mutex> guard(m_mutex);
for (auto id = m_webhookIds.begin(); id != m_webhookIds.end(); id++) {
if (*id == webhook_id)
return true;
}
return false;
}
void settings::lock()
{
m_mutex.lock();
m_externallyLockedCount++;
}
bool settings::parse(const std::string &data, bool initialize)
{
try {
dpp::json json;
try {
json = dpp::json::parse(data);
}
catch (const std::exception &exception) {
std::cerr << "[Exception] " << exception.what() << std::endl;
std::cerr << "[Error] Exception while parsing JSON" << std::endl;
return false;
}
const std::lock_guard<std::recursive_mutex> guard(m_mutex);
auto json_token = json.find("token");
if (json_token != json.end())
m_token = *json_token;
else if (char *token = getenv("DTRANSLATEBOT_TOKEN"))
m_token = token;
if (m_token.empty()) {
std::cerr << "[Error] Discord Bot Token is not configured" << std::endl;
return false;
}
std::filesystem::path storage_path;
auto json_storage = json.find("storage");
if (json_storage != json.end())
storage_path = std::string(*json_storage);
else if (char *storagepath = getenv("DTRANSLATEBOT_STORAGE"))
storage_path = storagepath;
if (storage_path.empty())
storage_path = std::filesystem::current_path();
m_database = std::make_shared<bot::database::file>(storage_path);
auto json_translator = json.find("translator");
if (json_translator == json.end()) {
std::cerr << "[Error] Value translator not found" << std::endl;
return false;
}
if (!process_translator_settings(*json_translator, &m_translator))
return false;
auto json_guilds = json.find("guilds");
if (json_guilds != json.end() && json_guilds->is_object())
process_guild_settings(*json_guilds, &m_guilds, &m_webhookIds);
auto json_preflangs = json.find("preferred_lang");
if (json_preflangs != json.end() && json_preflangs->is_array())
process_preflang_settings(*json_preflangs, &m_prefLangs);
auto json_user = json.find("user");
if (json_user != json.end() && json_user->is_object())
process_user_settings(*json_user, &m_avatarSize);
process_database(m_database, &m_guilds, &m_webhookIds);
return true;
}
catch (const std::exception &exception) {
std::cerr << "[Exception] " << exception.what() << std::endl;
}
return false;
}
bool settings::parse_file(const std::string &filename, bool initialize)
{
std::ifstream ifs(filename, std::ios::in | std::ios::binary);
if (!ifs.is_open()) {
std::cerr << "[Error] Failed to open JSON configuration file located at " << filename << std::endl;
return false;
}
std::string sdata(std::istreambuf_iterator<char>{ifs}, {});
ifs.close();
return parse(sdata, initialize);
}
void settings::unlock()
{
m_mutex.unlock();
m_externallyLockedCount--;
}

76
src/core/settings.h Normal file
View file

@ -0,0 +1,76 @@
/*****************************************************************************
* dtranslatebot Discord Translate Bot
* Copyright (C) 2023-2024 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/
#ifndef SETTINGS_H
#define SETTINGS_H
#include <mutex>
#include "database.h"
#include "settings_types.h"
#include "translator.h"
namespace bot {
namespace settings {
class settings {
public:
/* add functions */
void add_channel(const channel &channel, dpp::snowflake guild_id);
bool add_target(const target &target, dpp::snowflake guild_id, dpp::snowflake channel_id);
void add_translatebot_webhook(dpp::snowflake webhook_id);
/* erase functions */
void erase_translatebot_webhook(dpp::snowflake webhook_id);
/* get functions */
uint16_t avatar_size();
static channel* get_channel(guild *guild, dpp::snowflake channel_id);
channel* get_channel(dpp::snowflake guild_id, dpp::snowflake channel_id);
guild* get_guild(dpp::snowflake guild_id);
target* get_target(dpp::snowflake guild_id, dpp::snowflake channel_id, const std::string &target);
static target* get_target(channel *channel, const std::string &target);
static const target* get_target(const channel *channel, const std::string &target);
const std::vector<std::string> preferred_languages() const;
std::shared_ptr<bot::database::database> get_database() const;
std::unique_ptr<bot::translator::translator> get_translator() const;
const std::string token() const;
/* is functions */
bool is_translatebot(dpp::snowflake webhook_id) const;
/* lock functions */
void lock();
void unlock();
/* parse functions */
bool parse(const std::string &data, bool initialize = true);
bool parse_file(const std::string &filename, bool initialize = true);
private:
mutable std::recursive_mutex m_mutex;
size_t m_externallyLockedCount = 0;
uint16_t m_avatarSize = 256;
std::shared_ptr<bot::database::database> m_database;
std::vector<guild> m_guilds;
std::vector<std::string> m_prefLangs;
bot::settings::translator m_translator;
std::string m_token;
std::vector<dpp::snowflake> m_webhookIds;
};
}
}
#endif // SETTINGS_H

53
src/core/settings_types.h Normal file
View file

@ -0,0 +1,53 @@
/*****************************************************************************
* dtranslatebot Discord Translate Bot
* Copyright (C) 2023-2024 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/
#ifndef SETTINGS_TYPES_H
#define SETTINGS_TYPES_H
#include <cstdint>
#include <dpp/snowflake.h>
#include <dpp/webhook.h>
#include <string>
#include <vector>
namespace bot {
namespace settings {
struct target {
std::string target;
dpp::webhook webhook;
};
struct channel {
dpp::snowflake id;
std::string source;
std::vector<bot::settings::target> targets;
};
struct guild {
dpp::snowflake id;
std::vector<bot::settings::channel> channel;
};
struct translator {
std::string hostname;
uint16_t port;
std::string url;
bool tls;
std::string apiKey;
};
}
}
#endif // SETTINGS_TYPES_H

482
src/core/slashcommands.cpp Normal file
View file

@ -0,0 +1,482 @@
/*****************************************************************************
* dtranslatebot Discord Translate Bot
* Copyright (C) 2024 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/
#include <sstream>
#include "slashcommands.h"
using namespace std::string_literals;
void bot::slashcommands::process_command_event(dpp::cluster *bot, bot::settings::settings *settings, const dpp::slashcommand_t &event)
{
if (event.command.get_command_name() == "edit")
bot::slashcommands::process_edit_command(bot, settings, event);
else if (event.command.get_command_name() == "list")
bot::slashcommands::process_list_command(bot, settings, event);
else if (event.command.get_command_name() == "translate" || event.command.get_command_name() == "translate_pref")
bot::slashcommands::process_translate_command(bot, settings, event);
}
void bot::slashcommands::process_edit_command(dpp::cluster *bot, bot::settings::settings *settings, const dpp::slashcommand_t &event)
{
try {
dpp::permission user_permissions = event.command.get_resolved_permission(event.command.usr.id);
if (!user_permissions.has(dpp::p_manage_webhooks))
throw dpp::exception("Unauthorized to use command");
dpp::command_interaction interaction = event.command.get_command_interaction();
if (interaction.options[0].name == "delete") {
const std::lock_guard<bot::settings::settings> guard(*settings);
if (bot::settings::channel *channel = settings->get_channel(event.command.guild_id, event.command.channel_id)) {
const std::string target = std::get<std::string>(event.get_parameter("target"));
std::shared_ptr<bot::database::database> database = settings->get_database();
const bot::settings::channel db_channel = database->get_channel(event.command.guild_id, event.command.channel_id);
if (db_channel.targets.empty()) {
event.reply(dpp::message("The current channel has no deleteable targets!").set_flags(dpp::m_ephemeral));
}
else if (target == "**") {
std::vector<std::string> targets;
for (auto db_target = db_channel.targets.begin(); db_target != db_channel.targets.end(); db_target++) {
targets.push_back(db_target->target);
}
for (auto target = channel->targets.begin(); target != channel->targets.end();) {
if (std::find(targets.begin(), targets.end(), target->target) != targets.end()) {
bot->delete_webhook(target->webhook.id, std::bind(&bot::slashcommands::process_deleted_webhook, settings, target->webhook.id, std::placeholders::_1));
target = channel->targets.erase(target);
}
else {
target++;
}
}
database->delete_channel(event.command.guild_id, event.command.channel_id);
database->sync();
event.reply(dpp::message("Deleteable targets have being deleted!").set_flags(dpp::m_ephemeral));
}
else {
bool target_found = false;
for (auto db_target = db_channel.targets.begin(); db_target != db_channel.targets.end(); db_target++) {
if (db_target->target == target) {
target_found = true;
break;
}
}
if (target_found) {
for (auto _target = channel->targets.begin(); _target != channel->targets.end(); _target++) {
if (_target->target == target) {
bot->delete_webhook(_target->webhook.id, std::bind(&bot::slashcommands::process_deleted_webhook, settings, _target->webhook.id, std::placeholders::_1));
channel->targets.erase(_target);
break;
}
}
if (db_channel.targets.size() == 1)
database->delete_channel(event.command.guild_id, event.command.channel_id);
else
database->delete_channel_target(event.command.guild_id, event.command.channel_id, target);
database->sync();
event.reply(dpp::message("Target have being deleted!").set_flags(dpp::m_ephemeral));
}
else {
event.reply(dpp::message("Target language is not being found or deleteable!").set_flags(dpp::m_ephemeral));
}
}
}
else {
event.reply(dpp::message("The current channel is not being translated!").set_flags(dpp::m_ephemeral));
}
}
else if (interaction.options[0].name == "source") {
const std::lock_guard<bot::settings::settings> guard(*settings);
if (bot::settings::channel *channel = settings->get_channel(event.command.guild_id, event.command.channel_id)) {
const std::string source = std::get<std::string>(event.get_parameter("source"));
const std::vector<bot::translator::language> languages = settings->get_translator()->get_languages();
std::ostringstream language_codes;
bool source_valid = false;
for (const bot::translator::language &language : languages) {
if (language.code == source) {
source_valid = true;
break;
}
language_codes << ' ' << language.code;
}
if (source_valid) {
channel->source = source;
std::shared_ptr<bot::database::database> database = settings->get_database();
database->set_channel_source(event.command.guild_id, event.command.channel_id, source);
database->sync();
event.reply(dpp::message("Source language have being updated!").set_flags(dpp::m_ephemeral));
}
else {
event.reply(dpp::message("Source language is not valid!\nAvailable languages are:" + language_codes.str()).set_flags(dpp::m_ephemeral));
}
}
else {
event.reply(dpp::message("The current channel is not being translated!").set_flags(dpp::m_ephemeral));
}
}
else {
throw std::invalid_argument("Option " + interaction.options[0].name + " is not known");
}
}
catch (const std::exception &exception) {
std::cerr << "[Exception] " << exception.what() << std::endl;
event.reply(dpp::message("Exception while processing command:\n"s + exception.what()).set_flags(dpp::m_ephemeral));
}
}
void bot::slashcommands::process_deleted_webhook(bot::settings::settings *settings, dpp::snowflake webhook_id, const dpp::confirmation_callback_t &callback)
{
if (callback.is_error()) {
std::cerr << "[Error] Failed to delete Webhook " << webhook_id << std::endl;
return;
}
settings->erase_translatebot_webhook(webhook_id);
}
void bot::slashcommands::process_list_command(dpp::cluster *bot, bot::settings::settings *settings, const dpp::slashcommand_t &event)
{
try {
dpp::command_interaction interaction = event.command.get_command_interaction();
if (interaction.options[0].name == "channel") {
const std::lock_guard<bot::settings::settings> guard(*settings);
if (const bot::settings::channel *channel = settings->get_channel(event.command.guild_id, event.command.channel_id)) {
std::ostringstream reply_translated;
reply_translated << "**Channel <#" << channel->id << ">**\n";
reply_translated << "Source: " << channel->source << '\n';
reply_translated << "Targets: " << channel->targets.size();
// We want give more information to users who can Manage Webhooks
dpp::permission user_permissions = event.command.get_resolved_permission(event.command.usr.id);
if (user_permissions.has(dpp::p_manage_webhooks)) {
std::shared_ptr<bot::database::database> database = settings->get_database();
const bot::settings::channel db_channel = database->get_channel(event.command.guild_id, event.command.channel_id);
for (auto target = channel->targets.begin(); target != channel->targets.end(); target++) {
reply_translated << "\n\n";
reply_translated << "**Target " << target->target << "**\n";
bool db_found = false;
for (auto db_target = db_channel.targets.begin(); db_target != db_channel.targets.end(); db_target++) {
if (db_target->target == target->target) {
db_found = true;
break;
}
}
reply_translated << "Deleteable: " << (db_found ? "Yes" : "No") << '\n';
reply_translated << "Webhook: " << target->webhook.id;
}
}
event.reply(dpp::message(reply_translated.str()).set_flags(dpp::m_ephemeral));
}
else {
event.reply(dpp::message("The current channel is not being translated!").set_flags(dpp::m_ephemeral));
}
}
else if (interaction.options[0].name == "guild") {
const std::lock_guard<bot::settings::settings> guard(*settings);
if (const bot::settings::guild *guild = settings->get_guild(event.command.guild_id)) {
if (!guild->channel.empty()) {
std::ostringstream reply_translated;
for (auto channel = guild->channel.begin(); channel != guild->channel.end();) {
reply_translated << "**Channel <#" << channel->id << ">**\n";
reply_translated << "Source: " << channel->source << '\n';
reply_translated << "Targets: " << channel->targets.size();
if (++channel != guild->channel.end())
reply_translated << "\n\n";
}
event.reply(dpp::message(reply_translated.str()).set_flags(dpp::m_ephemeral));
}
else {
event.reply(dpp::message("The current guild have no translated channel!").set_flags(dpp::m_ephemeral));
}
}
else {
event.reply(dpp::message("The current guild have no translated channel!").set_flags(dpp::m_ephemeral));
}
}
else if (interaction.options[0].name == "languages") {
dpp::permission user_permissions = event.command.get_resolved_permission(event.command.usr.id);
if (user_permissions.has(dpp::p_manage_webhooks)) {
const std::vector<bot::translator::language> languages = settings->get_translator()->get_languages();
std::ostringstream reply_languages;
reply_languages << "**Available Languages**\n";
for (auto language = languages.begin(); language != languages.end();) {
reply_languages << language->name << ": " << language->code;
if (++language != languages.end())
reply_languages << '\n';
}
if (reply_languages.str().length() <= 2000) {
event.reply(dpp::message(reply_languages.str()).set_flags(dpp::m_ephemeral));
}
else {
reply_languages.str({});
reply_languages << "Available Languages:";
for (auto language = languages.begin(); language != languages.end(); language++) {
reply_languages << ' ' << language->code;
}
event.reply(dpp::message(reply_languages.str()).set_flags(dpp::m_ephemeral));
}
}
else {
event.reply(dpp::message("Unauthorized to list available languages!").set_flags(dpp::m_ephemeral));
}
}
else {
throw std::invalid_argument("Option " + interaction.options[0].name + " is not known");
}
}
catch (const std::exception &exception) {
std::cerr << "[Exception] " << exception.what() << std::endl;
event.reply(dpp::message("Exception while processing command:\n"s + exception.what()).set_flags(dpp::m_ephemeral));
}
}
void bot::slashcommands::process_translate_command(dpp::cluster *bot, bot::settings::settings *settings, const dpp::slashcommand_t &event)
{
try {
dpp::permission user_permissions = event.command.get_resolved_permission(event.command.usr.id);
if (!user_permissions.has(dpp::p_manage_webhooks))
throw dpp::exception("Unauthorized to use command");
std::variant<dpp::channel,dpp::webhook> v_target;
const std::string source = std::get<std::string>(event.get_parameter("source"));
const std::string target = std::get<std::string>(event.get_parameter("target"));
dpp::command_interaction interaction = event.command.get_command_interaction();
if (interaction.options[0].name == "channel") {
v_target = event.command.get_resolved_channel(
std::get<dpp::snowflake>(event.get_parameter("channel")));
}
else if (interaction.options[0].name == "webhook") {
v_target = dpp::webhook(std::get<std::string>(event.get_parameter("webhook")));
}
const std::vector<bot::translator::language> languages = settings->get_translator()->get_languages();
std::ostringstream language_codes;
bool source_valid = false, target_valid = false;
for (const bot::translator::language &language : languages) {
if (language.code == source)
source_valid = true;
if (language.code == target)
target_valid = true;
if (source_valid && target_valid)
break;
language_codes << ' ' << language.code;
}
if (source_valid && target_valid) {
const std::lock_guard<bot::settings::settings> guard(*settings);
const bot::settings::channel *channel = settings->get_channel(event.command.guild_id, event.command.channel_id);
if (!channel) {
if (dpp::channel *channel = std::get_if<dpp::channel>(&v_target)) {
dpp::webhook webhook;
webhook.channel_id = channel->id;
webhook.guild_id = channel->guild_id;
webhook.name = "Translate Bot Webhook <" + std::to_string(event.command.channel_id) + ":" + source + ":" + target + ">";
bot->create_webhook(webhook, std::bind(&bot::slashcommands::process_translate_webhook_new_channel, settings, event, source, target, std::placeholders::_1));
}
else if (dpp::webhook *webhook = std::get_if<dpp::webhook>(&v_target)) {
const bot::settings::target s_target = { target, *webhook };
const bot::settings::channel s_channel = { event.command.channel_id, source, { s_target } };
settings->add_channel(s_channel, event.command.guild_id);
settings->add_translatebot_webhook(webhook->id);
std::shared_ptr<bot::database::database> database = settings->get_database();
database->set_channel_source(event.command.guild_id, event.command.channel_id, source);
database->add_channel_target(event.command.guild_id, event.command.channel_id, s_target);
database->sync();
event.reply(dpp::message("Channel will be now translated!").set_flags(dpp::m_ephemeral));
}
}
else if (!settings->get_target(channel, target)) {
if (channel->source != source) {
event.reply(dpp::message("The current channel is already being translated from a different source language!").set_flags(dpp::m_ephemeral));
}
else if (dpp::channel *channel = std::get_if<dpp::channel>(&v_target)) {
dpp::webhook webhook;
webhook.channel_id = channel->id;
webhook.guild_id = channel->guild_id;
webhook.name = "Translate Bot Webhook <" + std::to_string(event.command.channel_id) + ":" + source + ":" + target + ">";
bot->create_webhook(webhook, std::bind(&bot::slashcommands::process_translate_webhook_add_target, settings, event, target, std::placeholders::_1));
}
else if (dpp::webhook *webhook = std::get_if<dpp::webhook>(&v_target)) {
const bot::settings::target s_target = { target, *webhook };
settings->add_target(s_target, event.command.guild_id, event.command.channel_id);
settings->add_translatebot_webhook(webhook->id);
std::shared_ptr<bot::database::database> database = settings->get_database();
database->add_channel_target(event.command.guild_id, event.command.channel_id, s_target);
database->sync();
event.reply(dpp::message("Channel will be now translated!").set_flags(dpp::m_ephemeral));
}
}
else {
event.reply(dpp::message("The current channel is already being translated to the target language!").set_flags(dpp::m_ephemeral));
}
}
else if (!source_valid && !target_valid) {
event.reply(dpp::message("Source and target languages are not valid!\nAvailable languages are:" + language_codes.str()).set_flags(dpp::m_ephemeral));
}
else if (!source_valid) {
event.reply(dpp::message("Source language is not valid!\nAvailable languages are:" + language_codes.str()).set_flags(dpp::m_ephemeral));
}
else if (!target_valid) {
event.reply(dpp::message("Target language is not valid!\nAvailable languages are:" + language_codes.str()).set_flags(dpp::m_ephemeral));
}
}
catch (const std::exception &exception) {
std::cerr << "[Exception] " << exception.what() << std::endl;
event.reply(dpp::message("Exception while processing command:\n"s + exception.what()).set_flags(dpp::m_ephemeral));
}
}
void bot::slashcommands::process_translate_webhook_add_target(bot::settings::settings *settings, const dpp::slashcommand_t &event, const std::string &target, const dpp::confirmation_callback_t &callback)
{
if (callback.is_error()) {
event.reply(dpp::message("Failed to generate webhook!").set_flags(dpp::m_ephemeral));
return;
}
const dpp::webhook webhook = callback.get<dpp::webhook>();
const bot::settings::target s_target = { target, webhook };
const std::lock_guard<bot::settings::settings> guard(*settings);
settings->add_target(s_target, event.command.guild_id, event.command.channel_id);
settings->add_translatebot_webhook(webhook.id);
std::shared_ptr<bot::database::database> database = settings->get_database();
database->add_channel_target(event.command.guild_id, event.command.channel_id, s_target);
database->sync();
event.reply(dpp::message("Channel will be now translated!").set_flags(dpp::m_ephemeral));
}
void bot::slashcommands::process_translate_webhook_new_channel(bot::settings::settings *settings, const dpp::slashcommand_t &event, const std::string &source, const std::string &target, const dpp::confirmation_callback_t &callback)
{
if (callback.is_error()) {
event.reply(dpp::message("Failed to generate webhook!").set_flags(dpp::m_ephemeral));
return;
}
const dpp::webhook webhook = callback.get<dpp::webhook>();
const bot::settings::target s_target = { target, webhook };
const bot::settings::channel s_channel = { event.command.channel_id, source, { s_target } };
const std::lock_guard<bot::settings::settings> guard(*settings);
settings->add_channel(s_channel, event.command.guild_id);
settings->add_translatebot_webhook(webhook.id);
std::shared_ptr<bot::database::database> database = settings->get_database();
database->set_channel_source(event.command.guild_id, event.command.channel_id, source);
database->add_channel_target(event.command.guild_id, event.command.channel_id, s_target);
database->sync();
event.reply(dpp::message("Channel will be now translated!").set_flags(dpp::m_ephemeral));
}
void bot::slashcommands::register_commands(dpp::cluster *bot, bot::settings::settings *settings)
{
settings->lock();
const std::vector<bot::translator::language> languages = settings->get_translator()->get_languages();
const std::vector<std::string> preferred_languages = settings->preferred_languages();
settings->unlock();
std::vector<dpp::slashcommand> commands;
dpp::command_option source_option(dpp::co_string, "source", "Source language (ISO 639-1)", true);
source_option.set_max_length(static_cast<int64_t>(2)).set_min_length(static_cast<int64_t>(2));
dpp::command_option target_option(dpp::co_string, "target", "Target language (ISO 639-1)", true);
target_option.set_max_length(static_cast<int64_t>(2)).set_min_length(static_cast<int64_t>(2));
dpp::slashcommand command_edit("edit", "Edit current channel settings", bot->me.id);
command_edit.set_default_permissions(dpp::p_manage_webhooks);
dpp::command_option delete_edit_subcommand(dpp::co_sub_command, "delete", "Delete current channel target language");
dpp::command_option source_edit_subcommand(dpp::co_sub_command, "source", "Edit current channel source language");
delete_edit_subcommand.add_option(target_option);
source_edit_subcommand.add_option(source_option);
command_edit.add_option(delete_edit_subcommand);
command_edit.add_option(source_edit_subcommand);
commands.push_back(command_edit);
dpp::slashcommand command_list("list", "List translation settings", bot->me.id);
dpp::command_option channel_list_subcommand(dpp::co_sub_command, "channel", "List current channel translation settings");
dpp::command_option guild_list_subcommand(dpp::co_sub_command, "guild", "List current guild translation settings");
dpp::command_option languages_list_subcommand(dpp::co_sub_command, "languages", "List available languages to translate");
command_list.add_option(channel_list_subcommand);
command_list.add_option(guild_list_subcommand);
command_list.add_option(languages_list_subcommand);
commands.push_back(command_list);
dpp::slashcommand command_translate("translate", "Translate current channel", bot->me.id);
command_translate.set_default_permissions(dpp::p_manage_webhooks);
dpp::command_option channel_translate_subcommand(dpp::co_sub_command, "channel", "Translate current channel to a channel");
dpp::command_option webhook_translate_subcommand(dpp::co_sub_command, "webhook", "Translate current channel to a webhook");
dpp::command_option channel_option(dpp::co_channel, "channel", "Target channel", true);
channel_option.add_channel_type(dpp::CHANNEL_TEXT);
dpp::command_option webhook_option(dpp::co_string, "webhook", "Target webhook", true);
channel_translate_subcommand.add_option(source_option);
channel_translate_subcommand.add_option(target_option);
channel_translate_subcommand.add_option(channel_option);
webhook_translate_subcommand.add_option(source_option);
webhook_translate_subcommand.add_option(target_option);
webhook_translate_subcommand.add_option(webhook_option);
command_translate.add_option(channel_translate_subcommand);
command_translate.add_option(webhook_translate_subcommand);
commands.push_back(command_translate);
if (preferred_languages.size() > 1) {
dpp::slashcommand command_translate_pref("translate_pref", "Translate current channel (Preferred languages)", bot->me.id);
command_translate_pref.set_default_permissions(dpp::p_manage_webhooks);
dpp::command_option channel_pref_subcommand(dpp::co_sub_command, "channel", "Translate current channel to a channel (Preferred languages)");
dpp::command_option webhook_pref_subcommand(dpp::co_sub_command, "webhook", "Translate current channel to a webhook (Preferred languages)");
dpp::command_option source_pref_option(dpp::co_string, "source", "Source language", true);
dpp::command_option target_pref_option(dpp::co_string, "target", "Target language", true);
for (const bot::translator::language &language : languages) {
if (std::find(preferred_languages.begin(), preferred_languages.end(), language.code) != preferred_languages.end()) {
source_pref_option.add_choice(dpp::command_option_choice(language.name, language.code));
target_pref_option.add_choice(dpp::command_option_choice(language.name, language.code));
}
}
channel_pref_subcommand.add_option(source_pref_option);
channel_pref_subcommand.add_option(target_pref_option);
channel_pref_subcommand.add_option(channel_option);
webhook_pref_subcommand.add_option(source_pref_option);
webhook_pref_subcommand.add_option(target_pref_option);
webhook_pref_subcommand.add_option(webhook_option);
command_translate_pref.add_option(channel_pref_subcommand);
command_translate_pref.add_option(webhook_pref_subcommand);
commands.push_back(command_translate_pref);
}
bot->global_bulk_command_create(commands);
}

38
src/core/slashcommands.h Normal file
View file

@ -0,0 +1,38 @@
/*****************************************************************************
* dtranslatebot Discord Translate Bot
* Copyright (C) 2024 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/
#ifndef SLASHCOMMANDS_H
#define SLASHCOMMANDS_H
#include <dpp/cluster.h>
#include "settings.h"
namespace bot {
namespace slashcommands {
extern void process_command_event(dpp::cluster *bot, bot::settings::settings *settings, const dpp::slashcommand_t &event);
extern void process_edit_command(dpp::cluster *bot, bot::settings::settings *settings, const dpp::slashcommand_t &event);
extern void process_deleted_webhook(bot::settings::settings *settings, dpp::snowflake webhook_id, const dpp::confirmation_callback_t &callback);
extern void process_list_command(dpp::cluster *bot, bot::settings::settings *settings, const dpp::slashcommand_t &event);
extern void process_translate_command(dpp::cluster *bot, bot::settings::settings *settings, const dpp::slashcommand_t &event);
extern void process_translate_webhook_add_target(bot::settings::settings *settings, const dpp::slashcommand_t &event, const std::string &target, const dpp::confirmation_callback_t &callback);
extern void process_translate_webhook_new_channel(bot::settings::settings *settings, const dpp::slashcommand_t &event, const std::string &source, const std::string &target, const dpp::confirmation_callback_t &callback);
extern void register_commands(dpp::cluster *bot, bot::settings::settings *settings);
}
}
#endif // SLASHCOMMANDS_H

61
src/core/submit_queue.cpp Normal file
View file

@ -0,0 +1,61 @@
/*****************************************************************************
* dtranslatebot Discord Translate Bot
* Copyright (C) 2024 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/
#include <thread>
#include "submit_queue.h"
#include "webhook_push.h"
using namespace bot;
using namespace std::chrono_literals;
void submit_queue::add(const translated_message &message)
{
const std::lock_guard<std::mutex> guard(m_mutex);
m_queue.push(message);
}
void submit_queue::add(translated_message &&message)
{
const std::lock_guard<std::mutex> guard(m_mutex);
m_queue.push(message);
}
void submit_queue::run(dpp::cluster *bot)
{
m_running = true;
while (m_running) {
m_mutex.lock();
if (!m_queue.empty()) {
const translated_message message = m_queue.front();
m_queue.pop();
m_mutex.unlock();
webhook_push::run(message, bot);
std::this_thread::yield();
}
else {
m_mutex.unlock();
std::this_thread::sleep_for(100ms);
}
}
}
void submit_queue::terminate()
{
m_running = false;
}

49
src/core/submit_queue.h Normal file
View file

@ -0,0 +1,49 @@
/*****************************************************************************
* dtranslatebot Discord Translate Bot
* Copyright (C) 2024 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/
#ifndef SUBMIT_QUEUE_H
#define SUBMIT_QUEUE_H
#include <dpp/cluster.h>
#include <dpp/webhook.h>
#include <mutex>
#include <string>
#include <queue>
namespace bot {
struct translated_message {
std::string author;
std::string avatar;
std::string message;
dpp::webhook webhook;
};
class submit_queue {
public:
void add(const translated_message &message);
void add(translated_message &&message);
void run(dpp::cluster *bot);
void terminate();
private:
bool m_running;
std::mutex m_mutex;
std::queue<translated_message> m_queue;
};
}
#endif // SUBMIT_QUEUE_H

47
src/core/translator.cpp Normal file
View file

@ -0,0 +1,47 @@
/*****************************************************************************
* dtranslatebot Discord Translate Bot
* Copyright (C) 2024 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/
#ifndef NDEBUG
#include <iostream>
#endif
#include "translator.h"
using namespace bot::translator;
translator::translator()
{
}
translator::~translator()
{
}
const std::vector<language> translator::get_languages()
{
#ifndef NDEBUG
std::cerr << "[Debug] translator::get_languages() have being called." << std::endl;
#endif
return {};
}
const std::string translator::translate(const std::string &text, const std::string &source, const std::string &target)
{
#ifndef NDEBUG
std::cerr << "[Debug] translator:translate(const std::string&, const std::string&, const std::string&) have being called." << std::endl;
#endif
return {};
}

42
src/core/translator.h Normal file
View file

@ -0,0 +1,42 @@
/*****************************************************************************
* dtranslatebot Discord Translate Bot
* Copyright (C) 2024 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/
#ifndef TRANSLATOR_H
#define TRANSLATOR_H
#include <string>
#include <vector>
namespace bot {
namespace translator {
struct language {
std::string code;
std::string name;
};
class translator {
public:
explicit translator();
virtual ~translator();
virtual const std::vector<language> get_languages();
virtual const std::string translate(const std::string &text, const std::string &source, const std::string &target);
};
}
}
#endif // TRANSLATOR_H

92
src/core/webhook_push.cpp Normal file
View file

@ -0,0 +1,92 @@
/*****************************************************************************
* dtranslatebot Discord Translate Bot
* Copyright (C) 2024 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/
#include <future>
#include "regex.h"
#include "webhook_push.h"
using namespace std::string_literals;
using namespace std::string_view_literals;
void bot::webhook_push::run(const bot::translated_message &message, dpp::cluster *bot)
{
dpp::json json_body = {
{"username"s, message.author}
};
if (!message.avatar.empty())
json_body["avatar_url"] = message.avatar;
// We will split too long messages into multiple messages
if (message.message.length() > 2000) {
std::string_view message_v = message.message;
while (!message_v.empty()) {
const std::string_view message_eov = message_v.substr(1333, 666);
const std::string_view::size_type pos = message_eov.rfind('\n');
if (pos != std::string_view::npos) {
json_body["content"] = message_v.substr(0, 1333 + pos);
message_v = message_v.substr(1333 + pos);
}
else {
bot::svmatch match;
if (bot::regex_match(message_eov.begin(), message_eov.end(), match, bot::regex("^.*(\\.|\\?|\\!|\\。)\\s.*$"s))) {
json_body["content"] = message_v.substr(0, 1334 + match.position(1));
message_v = message_v.substr(1334 + match.position(1));
}
else if (bot::regex_match(message_eov.begin(), message_eov.end(), match, bot::regex("^.*(\\,)\\s.*$"s))) {
json_body["content"] = message_v.substr(0, 1334 + match.position(1));
message_v = message_v.substr(1334 + match.position(1));
}
else if (bot::regex_match(message_eov.begin(), message_eov.end(), match, bot::regex("^.*()\\s.*$"s))) {
json_body["content"] = message_v.substr(0, 1334 + match.position(1));
message_v = message_v.substr(1334 + match.position(1));
}
else {
json_body["content"] = message_v.substr(0, 1333);
message_v = message_v.substr(1333);
}
}
push_request(message.webhook.id, message.webhook.token, json_body.dump(), bot);
if (message_v.length() <= 2000) {
json_body["content"] = message_v;
message_v = {};
push_request(message.webhook.id, message.webhook.token, json_body.dump(), bot);
}
}
}
else {
json_body["content"] = message.message;
push_request(message.webhook.id, message.webhook.token, json_body.dump(), bot);
}
}
void webhook_request_completed(std::promise<dpp::http_request_completion_t> &promise, dpp::json &json, const dpp::http_request_completion_t &event)
{
if (event.status != 204)
std::cerr << "[Warning] Webhook push returned unexpected code " << event.status << std::endl;
promise.set_value(event);
}
void bot::webhook_push::push_request(dpp::snowflake webhook_id, const std::string &webhook_token, const std::string &json, dpp::cluster *bot)
{
std::promise<dpp::http_request_completion_t> promise;
std::future<dpp::http_request_completion_t> future = promise.get_future();
bot->post_rest(API_PATH "/webhooks", std::to_string(webhook_id), dpp::utility::url_encode(webhook_token), dpp::m_post, json,
std::bind(&webhook_request_completed, std::ref(promise), std::placeholders::_1, std::placeholders::_2));
future.wait();
}

36
src/core/webhook_push.h Normal file
View file

@ -0,0 +1,36 @@
/*****************************************************************************
* dtranslatebot Discord Translate Bot
* Copyright (C) 2024 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/
#ifndef WEBHOOK_PUSH_H
#define WEBHOOK_PUSH_H
#include <dpp/cluster.h>
#include <dpp/snowflake.h>
#include "submit_queue.h"
namespace bot {
class webhook_push {
public:
static void run(const bot::translated_message &message, dpp::cluster *bot);
private:
static void push_request(dpp::snowflake webhook_id, const std::string &webhook_token, const std::string &json, dpp::cluster *bot);
};
}
#endif // WEBHOOK_PUSH_H