go into command manager
Signed-off-by: Aleksey Selihov <faumaray@gmail.com>
This commit is contained in:
1 parent
b94b634a87
commit
1153721546
19 files changed
+752
-229
No files matched your search
@@ -0,0 +1,73 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string_view>
|
||||
#include <teamspeak/public_definitions.h>
|
||||
#include <ts3_functions.h>
|
||||
#include <ts6bot/MusicManager.hpp>
|
||||
|
||||
enum class CommandCategory { Music, Session, Utility };
|
||||
|
||||
inline std::string to_string(CommandCategory category)
|
||||
{
|
||||
switch (category) {
|
||||
|
||||
case CommandCategory::Music:
|
||||
return "Music";
|
||||
case CommandCategory::Session:
|
||||
return "Session";
|
||||
case CommandCategory::Utility:
|
||||
return "Utility";
|
||||
}
|
||||
return "Utility";
|
||||
}
|
||||
/**
|
||||
* @brief Context passed to every command execution.
|
||||
* Wraps all dependencies required to perform an action.
|
||||
*/
|
||||
struct CommandContext {
|
||||
std::uint64_t serverConnectionHandlerID;
|
||||
anyID clientID;
|
||||
std::string args; // Arguments excluding the command name
|
||||
std::string_view invokerName;
|
||||
|
||||
// Dependencies
|
||||
std::shared_ptr<TS3Functions> ts3;
|
||||
std::weak_ptr<MusicManager> musicManager; // Non-owning reference
|
||||
|
||||
// Helper to reply to the user
|
||||
void reply(std::string_view message) const;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Interface that all commands must implement.
|
||||
*/
|
||||
class Command
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~Command() = default;
|
||||
|
||||
/**
|
||||
* @brief The logic of the command.
|
||||
*/
|
||||
virtual void execute(const CommandContext& ctx) = 0;
|
||||
|
||||
/**
|
||||
* @brief Returns the description used for .help generation.
|
||||
*/
|
||||
virtual std::string_view getDescription() const = 0;
|
||||
|
||||
/**
|
||||
* @brief Returns usage syntax (e.g., "<url>").
|
||||
*/
|
||||
virtual std::string_view getUsage() const = 0;
|
||||
|
||||
virtual CommandCategory getCategory() const
|
||||
{
|
||||
return CommandCategory::Utility;
|
||||
}
|
||||
|
||||
// Commands can now define their own aliases for the help menu
|
||||
virtual std::vector<std::string_view> getAliases() const { return {}; }
|
||||
};
|
||||
@@ -0,0 +1,81 @@
|
||||
#pragma once
|
||||
#include <Command/Interface.hpp>
|
||||
#include <Logger.hpp>
|
||||
#include <format>
|
||||
#include <ts6bot/MusicManager.hpp>
|
||||
|
||||
// --- Play Command ---
|
||||
class Play : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
if (ctx.musicManager.expired()) {
|
||||
LOG_ERROR("MusicManager is expired");
|
||||
return;
|
||||
}
|
||||
|
||||
std::string args(ctx.args);
|
||||
std::string invoker(ctx.invokerName);
|
||||
|
||||
// 1. Handle Direct URL
|
||||
if (args.find("http") == 0) {
|
||||
if (ctx.musicManager.lock()->playUrl(args, invoker)) {
|
||||
ctx.reply("Added URL to queue.");
|
||||
} else {
|
||||
ctx.reply("Failed to add URL.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. Handle Search
|
||||
auto results = ctx.musicManager.lock()->search(args, 5);
|
||||
if (results.empty()) {
|
||||
ctx.reply("No results found.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (results.size() == 1) {
|
||||
if (ctx.musicManager.lock()->playUrl(results[0].url, invoker)) {
|
||||
ctx.reply(std::format("Added: [{}]({})", results[0].name,
|
||||
results[0].shortUrl));
|
||||
} else {
|
||||
ctx.reply("Failed to add result.");
|
||||
}
|
||||
} else {
|
||||
for (auto& result : results)
|
||||
{
|
||||
LOG_INFO("storing result: {}", result.url);
|
||||
}
|
||||
ctx.musicManager.lock()->storePendingSearch(ctx.clientID,
|
||||
results);
|
||||
|
||||
std::string list =
|
||||
"Multiple results found. Use .select\\.sel <number>:\n";
|
||||
for (size_t i = 0; i < results.size(); ++i) {
|
||||
list += std::format("{}. [{}]({}) [{}]\n", (i + 1),
|
||||
results[i].name, results[i].shortUrl,
|
||||
results[i].length);
|
||||
}
|
||||
ctx.reply(list);
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Plays a URL or searches YouTube.";
|
||||
}
|
||||
std::string_view getUsage() const override
|
||||
{
|
||||
return "<url | search term>";
|
||||
}
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Music;
|
||||
}
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"p", "add"};
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,45 @@
|
||||
#pragma once
|
||||
#include <Command/Interface.hpp>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
#include <ts6bot/MusicManager.hpp>
|
||||
|
||||
class Playlist : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
if (ctx.musicManager.expired()) {
|
||||
LOG_ERROR("MusicManager is expired");
|
||||
return;
|
||||
}
|
||||
|
||||
std::string args(ctx.args);
|
||||
std::string invoker(ctx.invokerName);
|
||||
|
||||
if (args.find("http") == 0) {
|
||||
if (auto plId =
|
||||
ctx.musicManager.lock()->extractPlaylistId(args)) {
|
||||
if (ctx.musicManager.lock()->playPlaylist(*plId, invoker)) {
|
||||
ctx.reply("Added PlayList to queue.");
|
||||
} else {
|
||||
ctx.reply("Failed to add playlist into the queue");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Music;
|
||||
}
|
||||
std::vector<std::string_view> getAliases() const override { return {}; }
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Plays all songs from URL of YouTube playlist";
|
||||
}
|
||||
std::string_view getUsage() const override
|
||||
{
|
||||
return "<url which contains \"list=\">";
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,51 @@
|
||||
#pragma once
|
||||
#include <Command/Interface.hpp>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
#include <ts6bot/MusicManager.hpp>
|
||||
|
||||
class Queue : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
if (ctx.musicManager.expired()) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto q = ctx.musicManager.lock()->getQueue();
|
||||
auto current = ctx.musicManager.lock()->getCurrent();
|
||||
|
||||
std::string str;
|
||||
if (current) {
|
||||
str =
|
||||
std::format("Now playing: [{}]({}) [{}]\n\n", current->name,
|
||||
current->shortUrl, current->length);
|
||||
}
|
||||
|
||||
if (q.empty() && str.empty()) {
|
||||
ctx.reply("Queue is empty.");
|
||||
return;
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < q.size(); ++i) {
|
||||
str += std::format("{}. [{}]({}) [{}]\n", i + 1, q[i].name,
|
||||
q[i].shortUrl, q[i].length);
|
||||
}
|
||||
ctx.reply(str);
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Shows the current queue.";
|
||||
}
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Music;
|
||||
}
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"list", "q", "l"};
|
||||
}
|
||||
std::string_view getUsage() const override { return ""; }
|
||||
};
|
||||
@@ -0,0 +1,45 @@
|
||||
#pragma once
|
||||
#include <Command/Interface.hpp>
|
||||
#include <charconv>
|
||||
#include <ts6bot/MusicManager.hpp>
|
||||
|
||||
class Select : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
if (ctx.musicManager.expired()) {
|
||||
return;
|
||||
}
|
||||
|
||||
int idx = 0;
|
||||
// High-performance string-to-int conversion
|
||||
auto res = std::from_chars(ctx.args.data(),
|
||||
ctx.args.data() + ctx.args.size(), idx);
|
||||
|
||||
if (res.ec == std::errc()) {
|
||||
if (ctx.musicManager.lock()->selectSearchResult(
|
||||
ctx.clientID, idx, std::string(ctx.invokerName))) {
|
||||
ctx.reply("Selected song added to queue.");
|
||||
} else {
|
||||
ctx.reply("Invalid selection index.");
|
||||
}
|
||||
} else {
|
||||
ctx.reply("Please provide a valid number.");
|
||||
}
|
||||
}
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Music;
|
||||
}
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"sel"};
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Selects a song from search results.";
|
||||
}
|
||||
std::string_view getUsage() const override { return "<number>"; }
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
#pragma once
|
||||
#include <Command/Interface.hpp>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
#include <ts6bot/MusicManager.hpp>
|
||||
|
||||
class Skip : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
if (!ctx.musicManager.expired()) {
|
||||
ctx.musicManager.lock()->skip();
|
||||
ctx.reply("Skipped current track.");
|
||||
}
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Skips current playing track.";
|
||||
}
|
||||
std::string_view getUsage() const override { return ""; }
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Music;
|
||||
}
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"next"};
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
#include <Command/Interface.hpp>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
#include <ts6bot/MusicManager.hpp>
|
||||
|
||||
class Stop : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
if (!ctx.musicManager.expired()) {
|
||||
ctx.musicManager.lock()->stop();
|
||||
ctx.reply("Playback stopped and queue cleared.");
|
||||
}
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Stops playback and clears queue.";
|
||||
}
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Music;
|
||||
}
|
||||
std::vector<std::string_view> getAliases() const override { return {}; }
|
||||
std::string_view getUsage() const override { return ""; }
|
||||
};
|
||||
@@ -0,0 +1,41 @@
|
||||
#pragma once
|
||||
#include <Command/Interface.hpp>
|
||||
#include <Logger.hpp>
|
||||
#include <format>
|
||||
#include <ts6bot/MusicManager.hpp>
|
||||
|
||||
// --- Play Command ---
|
||||
class Subscribe : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
if (ctx.musicManager.expired()) {
|
||||
LOG_ERROR("MusicManager is expired");
|
||||
return;
|
||||
}
|
||||
|
||||
std::string args(ctx.args);
|
||||
std::string invoker(ctx.invokerName);
|
||||
|
||||
if (ctx.musicManager.lock()->subscribe(ctx.clientID)) {
|
||||
ctx.reply("You are now subscribed to the music bot.");
|
||||
} else {
|
||||
ctx.reply("Already subscribed to the music bot.");
|
||||
}
|
||||
}
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Session;
|
||||
}
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"sub"};
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Subscribe on playback from bot.";
|
||||
}
|
||||
std::string_view getUsage() const override { return ""; }
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
#pragma once
|
||||
#include <Command/Interface.hpp>
|
||||
#include <Logger.hpp>
|
||||
#include <format>
|
||||
#include <ts6bot/MusicManager.hpp>
|
||||
|
||||
// --- Play Command ---
|
||||
class UnSubscribe : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
if (ctx.musicManager.expired()) {
|
||||
LOG_ERROR("MusicManager is expired");
|
||||
return;
|
||||
}
|
||||
|
||||
if (ctx.musicManager.lock()->unSubscribe(ctx.clientID)) {
|
||||
ctx.reply("Unsubscribed.");
|
||||
} else {
|
||||
ctx.reply("Already not subscribed.");
|
||||
}
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Session;
|
||||
}
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"unsub"};
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "UnSubscribe from playback from bot.";
|
||||
}
|
||||
std::string_view getUsage() const override { return ""; }
|
||||
};
|
||||
@@ -0,0 +1,57 @@
|
||||
#pragma once
|
||||
|
||||
#include <Command/Interface.hpp>
|
||||
#include <PluginInterface.hpp>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
class CommandManager
|
||||
{
|
||||
public:
|
||||
|
||||
explicit CommandManager(std::shared_ptr<TS3Functions> ts3);
|
||||
|
||||
/**
|
||||
* @brief Registers a command class.
|
||||
* @tparam T The command class (must inherit ICommand).
|
||||
* @param names List of triggers (e.g., {"play", "p"}).
|
||||
*/
|
||||
template <typename T>
|
||||
void registerCommand(const std::string& primaryName)
|
||||
{
|
||||
auto cmd = std::make_shared<T>();
|
||||
|
||||
// Register primary
|
||||
m_commands[primaryName] = cmd;
|
||||
m_uniqueCommands.push_back({primaryName, cmd});
|
||||
|
||||
// Register aliases automatically from the class itself
|
||||
for (auto alias : cmd->getAliases()) {
|
||||
m_commands[std::string(alias)] = cmd;
|
||||
}
|
||||
}
|
||||
|
||||
bool dispatch(uint64 scHandlerID, anyID clientID,
|
||||
std::string_view invokerName, std::string_view message,
|
||||
std::weak_ptr<MusicManager> musicManager);
|
||||
|
||||
private:
|
||||
|
||||
struct CommandEntry {
|
||||
std::string primaryName;
|
||||
std::shared_ptr<Command> instance;
|
||||
};
|
||||
void registerAllDefaults();
|
||||
|
||||
// Internal Help Command (defined inside manager to access registry)
|
||||
class HelpCommand;
|
||||
|
||||
std::shared_ptr<TS3Functions> m_ts3;
|
||||
|
||||
// Map for fast lookup: "play" -> PlayCommand*
|
||||
std::unordered_map<std::string, std::shared_ptr<Command>> m_commands;
|
||||
|
||||
// List for generating help: {"play", PlayCommand*}
|
||||
std::vector<CommandEntry> m_uniqueCommands;
|
||||
};
|
||||
@@ -1,4 +1,5 @@
|
||||
#pragma once
|
||||
#include "CommandManager.hpp"
|
||||
#include "PluginInterface.hpp"
|
||||
// #include "Youtube/Client.hpp"
|
||||
#include "ts6bot/AudioDecoder.hpp"
|
||||
@@ -14,13 +15,15 @@ class EchoionCore : public IEchoionPlugin
|
||||
{
|
||||
// Dependencies
|
||||
std::shared_ptr<TS3Functions> m_ts3;
|
||||
std::unique_ptr<MusicManager> m_musicManager;
|
||||
std::shared_ptr<MusicManager> m_musicManager;
|
||||
std::unique_ptr<CommandManager> m_commandManager;
|
||||
|
||||
public:
|
||||
|
||||
explicit EchoionCore(std::shared_ptr<TS3Functions> funcs)
|
||||
{
|
||||
m_ts3 = std::move(funcs);
|
||||
m_commandManager = std::make_unique<CommandManager>(m_ts3);
|
||||
}
|
||||
|
||||
void Initialize(bool start = true) override;
|
||||
@@ -633,10 +636,10 @@ class EchoionCore : public IEchoionPlugin
|
||||
};
|
||||
|
||||
extern "C" {
|
||||
IEchoionPlugin *CreatePlugin(const TS3Functions *funcs)
|
||||
IEchoionPlugin *CreatePlugin(const TS3Functions *funcs)
|
||||
{
|
||||
return new EchoionCore(std::make_shared<TS3Functions>(*funcs));
|
||||
}
|
||||
|
||||
void DestroyPlugin(const IEchoionPlugin *plugin) { delete plugin; }
|
||||
void DestroyPlugin(const IEchoionPlugin *plugin) { delete plugin; }
|
||||
}
|
||||
@@ -2,7 +2,6 @@
|
||||
// Standard Library
|
||||
#include <expected>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
@@ -49,37 +49,6 @@ namespace ts6bot
|
||||
MusicConfig music{};
|
||||
ProxyConfiguration proxy{};
|
||||
};
|
||||
|
||||
class Configuration : public Singleton<Configuration>
|
||||
{
|
||||
friend class Singleton<Configuration>;
|
||||
|
||||
public:
|
||||
|
||||
const Config getConfig() const noexcept { return m_config; }
|
||||
|
||||
Configuration(std::string path)
|
||||
{
|
||||
auto config = Config();
|
||||
std::string buffer;
|
||||
auto ec = glz::read_file_json(config, path, buffer);
|
||||
if (ec) {
|
||||
std::string descriptive_error =
|
||||
glz::format_error(ec, buffer);
|
||||
std::cerr << "Not found configuration in " << path
|
||||
<< " using default" << std::endl;
|
||||
std::cerr << descriptive_error << std::endl;
|
||||
std::cerr << ec.ec << std::endl;
|
||||
m_config = Config();
|
||||
}
|
||||
this->m_config = config;
|
||||
}
|
||||
|
||||
Config m_config{};
|
||||
};
|
||||
|
||||
// Glaze meta (explicit, stable)
|
||||
|
||||
} // namespace ts6bot
|
||||
template <> struct glz::meta<ProxyType> {
|
||||
using enum ProxyType;
|
||||
@@ -88,7 +57,7 @@ template <> struct glz::meta<ProxyType> {
|
||||
template <> struct glz::meta<ts6bot::LogLevel> {
|
||||
using enum ts6bot::LogLevel;
|
||||
static constexpr auto value =
|
||||
enumerate(Critical, Error, Warning, Info, Trace);
|
||||
enumerate(Trace, Debug, Info, Warning, Error, Critical, None);
|
||||
};
|
||||
template <> struct glz::meta<ts6bot::ServerQueryConfig> {
|
||||
using T = ts6bot::ServerQueryConfig;
|
||||
@@ -124,3 +93,37 @@ template <> struct glz::meta<ts6bot::Config> {
|
||||
"password", &T::password, "loggingLevel", &T::loggingLevel, "afk",
|
||||
&T::afk, "music", &T::music, "proxy", &T::proxy);
|
||||
};
|
||||
namespace ts6bot
|
||||
{
|
||||
class Configuration : public Singleton<Configuration>
|
||||
{
|
||||
friend class Singleton<Configuration>;
|
||||
|
||||
public:
|
||||
|
||||
const Config getConfig() const noexcept { return m_config; }
|
||||
|
||||
Configuration(std::string path)
|
||||
{
|
||||
auto config = Config();
|
||||
std::string buffer;
|
||||
auto ec = glz::read_file_json(config, path, buffer);
|
||||
if (ec) {
|
||||
std::string descriptive_error =
|
||||
glz::format_error(ec, buffer);
|
||||
std::cerr << "Not found configuration in " << path
|
||||
<< " using default" << std::endl;
|
||||
std::cerr << descriptive_error << std::endl;
|
||||
std::cerr << ec.ec << std::endl;
|
||||
m_config = Config();
|
||||
}
|
||||
this->m_config = config;
|
||||
}
|
||||
|
||||
Config m_config{};
|
||||
};
|
||||
|
||||
// Glaze meta (explicit, stable)
|
||||
|
||||
} // namespace ts6bot
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
#include <CommandManager.hpp>
|
||||
#include <Command/Play.hpp>
|
||||
#include <Command/Playlist.hpp>
|
||||
#include <Command/Queue.hpp>
|
||||
#include <Command/Select.hpp>
|
||||
#include <Command/Skip.hpp>
|
||||
#include <Command/Stop.hpp>
|
||||
#include <Command/Subscribe.hpp>
|
||||
#include <Command/Unsubscribe.hpp>
|
||||
#include <Logger.hpp>
|
||||
|
||||
// Implement Context Reply Helper
|
||||
void CommandContext::reply(std::string_view message) const
|
||||
{
|
||||
if (!ts3) {
|
||||
return;
|
||||
}
|
||||
std::string safeMsg(message);
|
||||
ts3->requestSendPrivateTextMsg(serverConnectionHandlerID, safeMsg.c_str(),
|
||||
clientID, nullptr);
|
||||
}
|
||||
|
||||
// --- Dynamic Help Command ---
|
||||
class CommandManager::HelpCommand : public Command
|
||||
{
|
||||
CommandManager& m_manager;
|
||||
|
||||
public:
|
||||
|
||||
explicit HelpCommand(CommandManager& mgr) : m_manager(mgr) {}
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
// Use # for large headers and ** for emphasis
|
||||
std::string helpMsg = "# 🎵 Echoion Bot Manual\n\n";
|
||||
|
||||
// Grouping logic remains the same
|
||||
std::map<
|
||||
CommandCategory,
|
||||
std::vector<std::pair<std::string, std::shared_ptr<Command>>>>
|
||||
grouped;
|
||||
for (const auto& [name, cmd] : m_manager.m_uniqueCommands) {
|
||||
grouped[cmd->getCategory()].push_back({name, cmd});
|
||||
}
|
||||
|
||||
for (auto const& [cat, cmds] : grouped) {
|
||||
std::string catName = to_string(cat);
|
||||
helpMsg += std::format("## {} Commands\n\n", catName);
|
||||
|
||||
for (const auto& [name, cmd] : cmds) {
|
||||
// Formatting: **.command** `usage`
|
||||
if (!cmd->getUsage().empty()) {
|
||||
helpMsg += std::format("** .{} ** ` {} `\n", name,
|
||||
cmd->getUsage());
|
||||
} else {
|
||||
helpMsg += std::format("** .{} **\n", name);
|
||||
}
|
||||
|
||||
// Description in a separate line
|
||||
helpMsg += std::format("{}\n", cmd->getDescription());
|
||||
|
||||
// Aliases using the standard italic/bold combo
|
||||
auto aliases = cmd->getAliases();
|
||||
if (!aliases.empty()) {
|
||||
helpMsg += "__Aliases:__ ";
|
||||
for (size_t i = 0; i < aliases.size(); ++i) {
|
||||
helpMsg += std::format(
|
||||
"**{}**{}", aliases[i],
|
||||
(i == aliases.size() - 1 ? "" : ", "));
|
||||
}
|
||||
helpMsg += "\n";
|
||||
}
|
||||
|
||||
// Double newline for spacing between commands
|
||||
helpMsg += "\n";
|
||||
}
|
||||
}
|
||||
|
||||
ctx.reply(helpMsg);
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Displays this help message.";
|
||||
}
|
||||
std::string_view getUsage() const override { return ""; }
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"commands", "h"};
|
||||
}
|
||||
};
|
||||
|
||||
// --- Manager Implementation ---
|
||||
|
||||
CommandManager::CommandManager(std::shared_ptr<TS3Functions> ts3)
|
||||
: m_ts3(std::move(ts3))
|
||||
{
|
||||
registerAllDefaults();
|
||||
}
|
||||
|
||||
void CommandManager::registerAllDefaults()
|
||||
{
|
||||
registerCommand<Play>("play");
|
||||
registerCommand<Playlist>("playlist");
|
||||
registerCommand<Select>("select");
|
||||
registerCommand<Stop>("stop");
|
||||
registerCommand<Queue>("queue");
|
||||
registerCommand<Subscribe>("subscribe");
|
||||
registerCommand<UnSubscribe>("unsubscribe");
|
||||
|
||||
// Manually register Help because it needs a reference to *this
|
||||
auto helpCmd = std::make_shared<HelpCommand>(*this);
|
||||
|
||||
// Register aliases automatically from the class itself
|
||||
|
||||
m_commands["help"] = helpCmd;
|
||||
m_uniqueCommands.push_back({"help", helpCmd});
|
||||
for (auto alias : helpCmd->getAliases()) {
|
||||
m_commands[std::string(alias)] = helpCmd;
|
||||
}
|
||||
|
||||
// You can add others like SkipCommand, SubCommand here...
|
||||
}
|
||||
|
||||
bool CommandManager::dispatch(uint64 scID, anyID clientID,
|
||||
std::string_view invokerName,
|
||||
std::string_view message,
|
||||
std::weak_ptr<MusicManager> musicManager)
|
||||
{
|
||||
if (message.empty() || message[0] != '.') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Split ".play link" -> "play", "link"
|
||||
std::string_view input = message.substr(1); // Skip '.'
|
||||
auto spacePos = input.find(' ');
|
||||
|
||||
std::string_view cmdStr = input.substr(0, spacePos);
|
||||
std::string argsStr =
|
||||
(spacePos == std::string_view::npos) ? "" : input.substr(spacePos + 1).data();
|
||||
|
||||
// Lookup
|
||||
std::string cmdKey(cmdStr); // Map requires std::string key
|
||||
if (auto it = m_commands.find(cmdKey); it != m_commands.end()) {
|
||||
CommandContext ctx{.serverConnectionHandlerID = scID,
|
||||
.clientID = clientID,
|
||||
.args = argsStr,
|
||||
.invokerName = invokerName,
|
||||
.ts3 = m_ts3,
|
||||
.musicManager = musicManager};
|
||||
|
||||
try {
|
||||
it->second->execute(ctx);
|
||||
} catch (const std::exception& e) {
|
||||
LOG_ERROR("Command Execution Error [{}]: {}", cmdKey, e.what());
|
||||
ctx.reply("An internal error occurred executing that command.");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
+20
-17
@@ -6,8 +6,6 @@
|
||||
#include <format>
|
||||
#include <glaze/json/read.hpp>
|
||||
#include <optional>
|
||||
#include <print>
|
||||
#include <ranges>
|
||||
#include <regex>
|
||||
#include <utility>
|
||||
|
||||
@@ -131,15 +129,16 @@ std::vector<definitions::SearchResultItem>
|
||||
thumbUrl = video.snippet.thumbnails.begin()->second.url;
|
||||
}
|
||||
}
|
||||
std::string url = "https://youtube.com/watch?v=" + video.id;
|
||||
auto shortUrl =
|
||||
m_client->ShortUrl("https://youtube.com/watch?v=" + video.id);
|
||||
|
||||
m_client->ShortUrl(url);
|
||||
LOG_DEBUG("url: {}",url);
|
||||
resultItems.push_back(
|
||||
{.name = video.snippet.title,
|
||||
.length = formatDuration(video.contentDetails.duration),
|
||||
.thumbnail = thumbUrl,
|
||||
.viewCount = video.statistics.viewCount,
|
||||
.url = "https://youtube.com/watch?v=" + video.id,
|
||||
.url = std::move(url),
|
||||
.shortUrl = shortUrl.value_or(""),
|
||||
.videoId = video.id});
|
||||
}
|
||||
@@ -569,18 +568,22 @@ void MusicManager::storePendingSearch(
|
||||
}
|
||||
|
||||
bool MusicManager::selectSearchResult(const anyID clientId, const int index,
|
||||
const std::string &requesterName)
|
||||
const std::string &requesterName)
|
||||
{
|
||||
std::lock_guard lock(m_pendingMtx);
|
||||
const auto it = m_pendingSearches.find(clientId);
|
||||
if (it == m_pendingSearches.end()) {
|
||||
return false;
|
||||
}
|
||||
std::lock_guard lock(m_pendingMtx);
|
||||
const auto it = m_pendingSearches.find(clientId);
|
||||
if (it == m_pendingSearches.end()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (int vecIndex = index - 1;
|
||||
vecIndex >= 0 && vecIndex < static_cast<int>(it->second.size())) {
|
||||
m_pendingSearches.erase(it);
|
||||
return playUrl(it->second[vecIndex].url, requesterName);
|
||||
}
|
||||
return false;
|
||||
if (int vecIndex = index - 1;
|
||||
vecIndex >= 0 && vecIndex < static_cast<int>(it->second.size())) {
|
||||
|
||||
std::string selectedUrl = it->second[vecIndex].url;
|
||||
|
||||
m_pendingSearches.erase(it);
|
||||
|
||||
return playUrl(selectedUrl, requesterName);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
+13
-156
@@ -16,7 +16,8 @@ void EchoionCore::Initialize(bool start)
|
||||
->getConfig();
|
||||
|
||||
if (start) {
|
||||
m_musicManager = std::make_unique<MusicManager>(m_ts3);
|
||||
LOG_INFO("creating music manager");
|
||||
m_musicManager = std::make_shared<MusicManager>(m_ts3);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,7 +67,7 @@ std::string EchoionCore::SerializeState()
|
||||
state.serverConnection = m_musicManager->getServerConnectionHandlerID();
|
||||
|
||||
std::string buf;
|
||||
glz::write_json(state, buf);
|
||||
[[maybe_unused]] auto res = glz::write_json(state, buf);
|
||||
return buf;
|
||||
}
|
||||
|
||||
@@ -75,8 +76,9 @@ void EchoionCore::DeserializeState(const std::string &jsonState)
|
||||
definitions::PluginState state;
|
||||
if (auto err = glz::read_json(state, jsonState); !err) {
|
||||
if (!m_musicManager) {
|
||||
LOG_INFO("creating music manager from state");
|
||||
m_musicManager =
|
||||
std::make_unique<MusicManager>(m_ts3, state.serverConnection);
|
||||
std::make_shared<MusicManager>(m_ts3, state.serverConnection);
|
||||
}
|
||||
for (auto s : state.onlineSubscribers) {
|
||||
m_musicManager->addSubscriberToOnline(s);
|
||||
@@ -95,20 +97,14 @@ void EchoionCore::DeserializeState(const std::string &jsonState)
|
||||
}
|
||||
|
||||
int EchoionCore::onTextMessageEvent(uint64 serverConnectionHandlerID,
|
||||
anyID targetMode, anyID toID, anyID fromID,
|
||||
anyID targetMode, [[maybe_unused]] anyID toID, anyID fromID,
|
||||
const char *fromName,
|
||||
const char *fromUniqueIdentifier,
|
||||
const char *message, int ffIgnored)
|
||||
[[maybe_unused]] const char *fromUniqueIdentifier,
|
||||
const char *message, [[maybe_unused]] int ffIgnored)
|
||||
{
|
||||
if (!m_musicManager) {
|
||||
if (!m_musicManager || !m_commandManager) {
|
||||
return 1;
|
||||
}
|
||||
auto reply = [this](const uint64 sc, const anyID toId,
|
||||
const std::string &text) {
|
||||
const char *returnCode = nullptr;
|
||||
this->m_ts3->requestSendPrivateTextMsg(sc, text.c_str(), toId,
|
||||
returnCode);
|
||||
};
|
||||
// 1. Only react to Direct Messages (Private Chats)
|
||||
if (targetMode != TextMessageTarget_CLIENT) {
|
||||
return 0;
|
||||
@@ -120,154 +116,15 @@ int EchoionCore::onTextMessageEvent(uint64 serverConnectionHandlerID,
|
||||
if (fromID == myID) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::string msgStr = message;
|
||||
if (msgStr.empty() || msgStr[0] != '.') {
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::stringstream ss(msgStr);
|
||||
std::string command;
|
||||
ss >> command;
|
||||
|
||||
std::string args;
|
||||
std::getline(ss, args);
|
||||
if (!args.empty() && args[0] == ' ') {
|
||||
args.erase(0, 1);
|
||||
}
|
||||
|
||||
if (command == ".play") {
|
||||
if (args.find("http") == 0) {
|
||||
if (this->m_musicManager->playUrl(args, fromName)) {
|
||||
this->m_ts3->requestSendPrivateTextMsg(
|
||||
serverConnectionHandlerID, "Added URL to queue.", fromID,
|
||||
nullptr);
|
||||
} else {
|
||||
this->m_ts3->requestSendPrivateTextMsg(
|
||||
serverConnectionHandlerID, "Not added", fromID, nullptr);
|
||||
}
|
||||
} else {
|
||||
auto results = this->m_musicManager->search(args, 5);
|
||||
if (results.empty()) {
|
||||
this->m_ts3->requestSendPrivateTextMsg(
|
||||
serverConnectionHandlerID, "No results found.", fromID,
|
||||
nullptr);
|
||||
} else if (results.size() == 1) {
|
||||
if (this->m_musicManager->playUrl(results[0].url, fromName)) {
|
||||
this->m_ts3->requestSendPrivateTextMsg(
|
||||
serverConnectionHandlerID,
|
||||
std::format("Added: [{}]({})", results[0].name,
|
||||
results[0].shortUrl)
|
||||
.c_str(),
|
||||
fromID, nullptr);
|
||||
} else {
|
||||
this->m_ts3->requestSendPrivateTextMsg(
|
||||
serverConnectionHandlerID,
|
||||
std::format("Failed to add: [{}]({})", results[0].name,
|
||||
results[0].shortUrl)
|
||||
.c_str(),
|
||||
fromID, nullptr);
|
||||
}
|
||||
} else {
|
||||
this->m_musicManager->storePendingSearch(fromID, results);
|
||||
std::string list =
|
||||
"Multiple results found. Use .select <number>:\n";
|
||||
for (size_t i = 0; i < results.size(); ++i) {
|
||||
list += std::format("{}. [{}]({}) [{}]\n", (i + 1),
|
||||
results[i].name, results[i].shortUrl,
|
||||
results[i].length);
|
||||
}
|
||||
this->m_ts3->requestSendPrivateTextMsg(
|
||||
serverConnectionHandlerID, list.c_str(), fromID, nullptr);
|
||||
}
|
||||
}
|
||||
} else if (command == ".playlist") {
|
||||
if (args.find("http") == 0) {
|
||||
if (auto plId = this->m_musicManager->extractPlaylistId(args)) {
|
||||
if (this->m_musicManager->playPlaylist(*plId, fromName)) {
|
||||
this->m_ts3->requestSendPrivateTextMsg(
|
||||
serverConnectionHandlerID, "Added PlayList to queue.",
|
||||
fromID, nullptr);
|
||||
} else {
|
||||
this->m_ts3->requestSendPrivateTextMsg(
|
||||
serverConnectionHandlerID, "Not added", fromID,
|
||||
nullptr);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (command == ".select") {
|
||||
try {
|
||||
int idx = std::stoi(args);
|
||||
if (this->m_musicManager->selectSearchResult(fromID, idx,
|
||||
fromName)) {
|
||||
this->m_ts3->requestSendPrivateTextMsg(
|
||||
serverConnectionHandlerID, "Selected song added to queue.",
|
||||
fromID, nullptr);
|
||||
} else {
|
||||
this->m_ts3->requestSendPrivateTextMsg(
|
||||
serverConnectionHandlerID, "Invalid selection.", fromID,
|
||||
nullptr);
|
||||
}
|
||||
} catch (...) {
|
||||
this->m_ts3->requestSendPrivateTextMsg(
|
||||
serverConnectionHandlerID, "Please provide a valid number.",
|
||||
fromID, nullptr);
|
||||
}
|
||||
} else if (command == ".stop") {
|
||||
this->m_musicManager->stop();
|
||||
reply(serverConnectionHandlerID, fromID,
|
||||
"Playback stopped and queue cleared.");
|
||||
} else if (command == ".skip" || command == ".next") {
|
||||
this->m_musicManager->skip();
|
||||
reply(serverConnectionHandlerID, fromID, "Skipped current track.");
|
||||
} else if (command == ".queue" || command == ".list") {
|
||||
auto q = this->m_musicManager->getQueue();
|
||||
auto current = this->m_musicManager->getCurrent();
|
||||
std::string str =
|
||||
current
|
||||
? std::format("Now playing: [{}]({}) [{}]\n\n",
|
||||
current.value().name, current.value().shortUrl,
|
||||
current.value().length)
|
||||
: "";
|
||||
if (q.empty() && str.empty()) {
|
||||
reply(serverConnectionHandlerID, fromID, "Queue is empty");
|
||||
}
|
||||
|
||||
for (auto i = 0; i < q.size(); i++) {
|
||||
LOG_DEBUG("Adding to list {}", q.at(i).name);
|
||||
str += std::format("{}. [{}]({}) [{}]\n", i + 1, q.at(i).name,
|
||||
q.at(i).shortUrl, q.at(i).length);
|
||||
}
|
||||
reply(serverConnectionHandlerID, fromID, str);
|
||||
} else if (command == ".sub") {
|
||||
if (this->m_musicManager->subscribe(fromID)) {
|
||||
reply(serverConnectionHandlerID, fromID,
|
||||
"You are now subscribed to the music bot.");
|
||||
} else {
|
||||
reply(serverConnectionHandlerID, fromID,
|
||||
"Already subscribed to the music bot.");
|
||||
}
|
||||
} else if (command == ".unsub") {
|
||||
if (this->m_musicManager->unSubscribe(fromID)) {
|
||||
reply(serverConnectionHandlerID, fromID, "Unsubscribed.");
|
||||
} else {
|
||||
reply(serverConnectionHandlerID, fromID, "Not subscribed.");
|
||||
}
|
||||
} else if (command == ".help") {
|
||||
reply(serverConnectionHandlerID, fromID,
|
||||
".play <ссылка или название>\n.select "
|
||||
"<#>\n.playlist <ссылка в которой есть "
|
||||
"\"list=\">\n.stop\n.skip\\next\n.queue\\list\n.sub\n"
|
||||
".unsub");
|
||||
}
|
||||
|
||||
m_commandManager->dispatch(serverConnectionHandlerID, fromID, fromName,
|
||||
message, m_musicManager);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void EchoionCore::onClientMoveEvent(uint64 serverConnectionHandlerID,
|
||||
anyID clientID, uint64 oldChannelID,
|
||||
uint64 newChannelID, int visibility,
|
||||
const char *moveMessage)
|
||||
uint64 newChannelID,[[maybe_unused]] int visibility,
|
||||
[[maybe_unused]] const char *moveMessage)
|
||||
{
|
||||
|
||||
if (!m_musicManager) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#include "Logger.hpp"
|
||||
#include "Spotify/Client.hpp"
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
#include <glaze/glaze.hpp>
|
||||
#include <print>
|
||||
@@ -267,8 +267,8 @@ namespace Spotify
|
||||
{
|
||||
Request::RequestBody body{ids};
|
||||
std::string json;
|
||||
glz::write_json(body, json);
|
||||
|
||||
auto res = glz::write_json(body, json);
|
||||
LOG_DEBUG("{}", res.custom_error_message);
|
||||
auto response =
|
||||
PerformRequest(BuildUrl("/me/albums"), HttpMethod::PUT, json);
|
||||
if (!response) {
|
||||
|
||||
+21
-16
@@ -7,14 +7,11 @@
|
||||
#include "cpr/proxyauth.h"
|
||||
#include "cpr/response.h"
|
||||
#include "cpr/session.h"
|
||||
#include <algorithm>
|
||||
#include <curl/curl.h>
|
||||
#include <curl/easy.h>
|
||||
#include <format>
|
||||
#include <glaze/glaze.hpp>
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <print>
|
||||
#include <ranges>
|
||||
#include <regex>
|
||||
|
||||
@@ -478,37 +475,45 @@ namespace YouTube
|
||||
}
|
||||
|
||||
auto Client::ExtractVideoId(std::string_view url) const
|
||||
-> std::optional<std::string>
|
||||
-> std::optional<std::string>
|
||||
{
|
||||
// Pattern 1: Standard youtube.com watch URL
|
||||
// https://www.youtube.com/watch?v=VIDEO_ID or
|
||||
// https://youtube.com/watch?v=VIDEO_ID
|
||||
std::string url_str(url);
|
||||
LOG_WARN("extract url: {}", url_str);
|
||||
LOG_WARN("extract found: {}", url_str.contains("faumaray.ru"));
|
||||
if (url_str.contains("faumaray.ru")) {
|
||||
cpr::Response r = cpr::Get(
|
||||
cpr::Url{url_str},
|
||||
cpr::Redirect{0L}
|
||||
);
|
||||
LOG_WARN("Status code: {}", r.status_code);
|
||||
LOG_WARN("url: {}", url_str);
|
||||
if (r.status_code >= 300 && r.status_code < 400) {
|
||||
if (r.header.count("Location")) {
|
||||
url_str = r.header["Location"];
|
||||
} else if (r.header.count("location")) {
|
||||
url_str = r.header["location"];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static const std::regex watch_pattern(
|
||||
R"((?:https?://)?(?:www\.)?youtube\.com/watch\?.*v=([a-zA-Z0-9_-]{11}))",
|
||||
std::regex::icase);
|
||||
|
||||
// Pattern 2: Shortened youtu.be URL
|
||||
// https://youtu.be/VIDEO_ID
|
||||
static const std::regex short_pattern(
|
||||
R"((?:https?://)?(?:www\.)?youtu\.be/([a-zA-Z0-9_-]{11}))",
|
||||
std::regex::icase);
|
||||
|
||||
// Pattern 3: Embedded URL
|
||||
// https://www.youtube.com/embed/VIDEO_ID
|
||||
static const std::regex embed_pattern(
|
||||
R"((?:https?://)?(?:www\.)?youtube\.com/embed/([a-zA-Z0-9_-]{11}))",
|
||||
std::regex::icase);
|
||||
|
||||
// Pattern 4: YouTube shorts
|
||||
// https://www.youtube.com/shorts/VIDEO_ID
|
||||
static const std::regex shorts_pattern(
|
||||
R"((?:https?://)?(?:www\.)?youtube\.com/shorts/([a-zA-Z0-9_-]{11}))",
|
||||
std::regex::icase);
|
||||
|
||||
std::cmatch match;
|
||||
std::string url_str(url);
|
||||
|
||||
// Try each pattern
|
||||
if (std::regex_search(url_str.c_str(), match, watch_pattern) ||
|
||||
std::regex_search(url_str.c_str(), match, short_pattern) ||
|
||||
std::regex_search(url_str.c_str(), match, embed_pattern) ||
|
||||
@@ -562,7 +567,7 @@ namespace YouTube
|
||||
|
||||
// 4. Find Best Audio Stream
|
||||
std::string bestUrl = "";
|
||||
int maxBitrate = 0;
|
||||
[[maybe_unused]] int maxBitrate = 0;
|
||||
|
||||
// adaptiveFormats contains separate audio and video streams
|
||||
for (const auto &format : playerResp.streamingData.formats) {
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
#include <dlfcn.h>
|
||||
#include <filesystem>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
#include "SignalShutdown.hpp"
|
||||
@@ -64,7 +65,8 @@ void UnloadCore(const bool saveState, std::string &stateOut)
|
||||
}
|
||||
|
||||
if (libHandle) {
|
||||
dlclose(libHandle);
|
||||
auto result = dlclose(libHandle);
|
||||
LogLoader("Closing dll " + std::to_string(result));
|
||||
libHandle = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user