mirror of
https://github.com/HappyTanuki/BumbleCee.git
synced 2025-10-25 17:35:58 +00:00
중간저장(다시 큐 방식으로 돌아가되, 실시간 스트리밍 방식으로 비동기 처리를 구현할 것임)
This commit is contained in:
4
.gitignore
vendored
4
.gitignore
vendored
@@ -4,4 +4,6 @@ out/
|
||||
.idea/
|
||||
tmp/
|
||||
config.json
|
||||
Music
|
||||
Music
|
||||
*.info.json
|
||||
yt-dlp
|
||||
3
.vscode/c_cpp_properties.json
vendored
3
.vscode/c_cpp_properties.json
vendored
@@ -3,7 +3,8 @@
|
||||
{
|
||||
"name": "Linux",
|
||||
"includePath": [
|
||||
"${workspaceFolder}/**"
|
||||
"${workspaceFolder}/**",
|
||||
"${workspaceFolder}/include"
|
||||
],
|
||||
"defines": [
|
||||
"DDPP_CORO=on"
|
||||
|
||||
6
.vscode/settings.json
vendored
6
.vscode/settings.json
vendored
@@ -75,6 +75,10 @@
|
||||
"set": "cpp",
|
||||
"regex": "cpp",
|
||||
"format": "cpp",
|
||||
"span": "cpp"
|
||||
"span": "cpp",
|
||||
"strstream": "cpp",
|
||||
"complex": "cpp",
|
||||
"source_location": "cpp",
|
||||
"typeindex": "cpp"
|
||||
}
|
||||
}
|
||||
@@ -17,12 +17,10 @@ set_target_properties(${BOT_NAME} PROPERTIES
|
||||
CXX_STANDARD_REQUIRED ON
|
||||
)
|
||||
|
||||
target_compile_definitions(${BOT_NAME} PUBLIC DPP_CORO)
|
||||
target_compile_features(${BOT_NAME} PUBLIC cxx_std_20)
|
||||
|
||||
set(THREADS_PREFER_PTHREAD_FLAG TRUE)
|
||||
find_package(Threads REQUIRED)
|
||||
find_package(DPP)
|
||||
find_package(VLC)
|
||||
if(APPLE)
|
||||
if(CMAKE_APPLE_SILICON_PROCESSOR)
|
||||
set(OPENSSL_ROOT_DIR "/opt/homebrew/opt/openssl")
|
||||
@@ -44,8 +42,11 @@ target_link_libraries(${BOT_NAME}
|
||||
dl
|
||||
dpp
|
||||
opus
|
||||
opusfile
|
||||
ogg
|
||||
oggz
|
||||
mariadbcpp
|
||||
curl
|
||||
${CMAKE_THREAD_LIBS_INIT}
|
||||
${OPENSSL_CRYPTO_LIBRARY}
|
||||
${OPENSSL_SSL_LIBRARY}
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
W8UNLOOogU4
|
||||
749DIRUHhNY
|
||||
o75PUTiHEXU
|
||||
pS5d77DQHOI
|
||||
65xX7zyr-fA
|
||||
2eNEQ0cQtkI
|
||||
UgS7vgquBvo
|
||||
IFCDLIKSArs
|
||||
yPdqcADl5U4
|
||||
6aEglYFwjrA
|
||||
n8F-E5f-cos
|
||||
1zwaZkOXXqw
|
||||
vjSrFwbwu6w
|
||||
vwZAqxL8rgs
|
||||
zOkIe3RcTCs
|
||||
mzVbYUBo8_Y
|
||||
rgNdeflYdYw
|
||||
CjaM8qWzssk
|
||||
kNDbaYEp0tU
|
||||
smObR_8q5UQ
|
||||
27NtZwyog7g
|
||||
vHfAjfKVMew
|
||||
b_bjtIeqIR4
|
||||
YTaX7BWlk9g
|
||||
BBj3SCImk_A
|
||||
Yb_IhN4TGp8
|
||||
-m-crWZHLi0
|
||||
4ciZKNHSoUs
|
||||
4tlUwgtgdZA
|
||||
oPGtAA2HaS8
|
||||
dLlD-dZNACM
|
||||
9LW9DpmhrPE
|
||||
pMTRBNMX2mw
|
||||
Kt451YtL-Vs
|
||||
tc0FL9JROGQ
|
||||
NinLIDs9qmU
|
||||
KMdTrqzEI0I
|
||||
HbXaUmWaU5Q
|
||||
xtFAmapbTbY
|
||||
B7luArOaIl0
|
||||
HMqhXxH5-RQ
|
||||
mQFokUq9LYs
|
||||
HyL8Z94W6es
|
||||
prAnOH-q_Bo
|
||||
LRPGqNeav_M
|
||||
M4-XU0a2hf0
|
||||
BryspbM6s3E
|
||||
JVTS3fyoAEQ
|
||||
KAaUyVJoNAE
|
||||
40
include/AsyncDownloadManager.hpp
Normal file
40
include/AsyncDownloadManager.hpp
Normal file
@@ -0,0 +1,40 @@
|
||||
#pragma once
|
||||
#ifndef _ASYNCDOWNLOADMANAGER_HPP_
|
||||
#define _ASYNCDOWNLOADMANAGER_HPP_
|
||||
#include <queue>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <condition_variable>
|
||||
#include <curl/curl.h>
|
||||
|
||||
#define WORKER_COUNT 5
|
||||
|
||||
namespace bumbleBee {
|
||||
class AsyncDownloadManager {
|
||||
public:
|
||||
static void enqueue(std::string query) {
|
||||
static AsyncDownloadManager dl;
|
||||
std::thread th(&bumbleBee::AsyncDownloadManager::enqueueAsyncDL, &dl, query);
|
||||
th.detach();
|
||||
}
|
||||
private:
|
||||
AsyncDownloadManager(){
|
||||
for (int i=0; i<WORKER_COUNT; i++) {
|
||||
std::thread th(&bumbleBee::AsyncDownloadManager::downloadWorker, &(*this));
|
||||
th.detach();
|
||||
}
|
||||
}
|
||||
~AsyncDownloadManager(){}
|
||||
AsyncDownloadManager(const AsyncDownloadManager& ref) = delete;
|
||||
AsyncDownloadManager& operator=(const AsyncDownloadManager& ref) = delete;
|
||||
|
||||
void enqueueAsyncDL(std::string query);
|
||||
void downloadWorker();
|
||||
|
||||
std::queue<std::string> downloadQueue;
|
||||
std::condition_variable dlQueueCondition;
|
||||
std::mutex dlQueueMutex;
|
||||
};
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,27 +0,0 @@
|
||||
#pragma once
|
||||
#include <Commands/CommandType.hpp>
|
||||
#include <dpp/dpp.h>
|
||||
#include <memory>
|
||||
#include <mariadb/conncpp.hpp>
|
||||
|
||||
class IBot {
|
||||
public:
|
||||
IBot(std::string token, int clusterCount = 0);
|
||||
virtual void start();
|
||||
virtual void onCommand(const dpp::slashcommand_t &event);
|
||||
virtual void onReady(const dpp::ready_t &event);
|
||||
|
||||
std::shared_ptr<dpp::cluster> botCluster;
|
||||
std::vector<std::shared_ptr<commands::ICommand>> commandsArray;
|
||||
|
||||
std::function<void(const dpp::log_t&)> logger() {
|
||||
return [&](const dpp::log_t& event){
|
||||
if (event.severity >= dpp::ll_error)
|
||||
std::cerr << "[" << dpp::utility::current_date_time() << "] " << dpp::utility::loglevel(event.severity) << ": " << event.message << std::endl;
|
||||
else if (event.severity - logLevel >= 0)
|
||||
std::clog << "[" << dpp::utility::current_date_time() << "] " << dpp::utility::loglevel(event.severity) << ": " << event.message << std::endl;
|
||||
};
|
||||
};
|
||||
|
||||
dpp::loglevel logLevel = dpp::ll_debug;
|
||||
};
|
||||
71
include/BumbleBee.hpp
Normal file
71
include/BumbleBee.hpp
Normal file
@@ -0,0 +1,71 @@
|
||||
#pragma once
|
||||
#ifndef _BUMBLEBEE_HPP_
|
||||
#define _BUMBLEBEE_HPP_
|
||||
#include <dpp/dpp.h>
|
||||
#include <dpp/nlohmann/json.hpp>
|
||||
#include <boost/asio.hpp>
|
||||
#include <memory>
|
||||
#include <BumbleBeeCommand.hpp>
|
||||
#include <MusicQueue.hpp>
|
||||
#include <mariadb/conncpp.hpp>
|
||||
|
||||
namespace bumbleBee {
|
||||
/**
|
||||
* @file BumbleBee.hpp
|
||||
* @brief 메인 봇 클래스
|
||||
**/
|
||||
class BumbleBee {
|
||||
public:
|
||||
/**
|
||||
* @fn BumbleBee(nlohmann::json settings)
|
||||
* @brief 생성자
|
||||
* @param settings 설정 json
|
||||
**/
|
||||
BumbleBee(nlohmann::json settings);
|
||||
/**
|
||||
* @fn ~BumbleBee()
|
||||
* @brief 파괴자
|
||||
* @details BumbleBee의 모든 Property를 책임지고 파괴합니다
|
||||
**/
|
||||
~BumbleBee();
|
||||
|
||||
/**
|
||||
* @fn void start()
|
||||
* @brief 봇 시작
|
||||
**/
|
||||
void start();
|
||||
/**
|
||||
* @fn bool addCommand(commands::ICommand cmd)
|
||||
* @brief ICommand 인터페이스에 맞는 커맨드를 추가
|
||||
* @warning 이 메소드는 start()메소드가 호출되기 전에 호출되어야 함
|
||||
**/
|
||||
bool addCommand(commands::ICommand cmd);
|
||||
|
||||
/**
|
||||
* @fn void on_slashcommand(const dpp::slashcommand_t& event)
|
||||
* @brief slashcommand 이벤트 인지시 콜백되는 함수
|
||||
* @param event
|
||||
**/
|
||||
void on_slashcommand(const dpp::slashcommand_t& event);
|
||||
/**
|
||||
* @fn void on_ready(const dpp::ready_t &event)
|
||||
* @brief ready 이벤트 인지시 콜백되는 함수
|
||||
* @param event
|
||||
**/
|
||||
void on_ready(const dpp::ready_t &event);
|
||||
private:
|
||||
/// @brief DPP 기본 클러스터 객체
|
||||
std::unique_ptr<dpp::cluster> cluster;
|
||||
/// @brief db 드라이버
|
||||
sql::Driver* dbDriver;
|
||||
/// @brief db 접속 URL
|
||||
std::shared_ptr<sql::SQLString> dbURL;
|
||||
/// @brief db 접속 속성
|
||||
std::shared_ptr<sql::Properties> dbProperties;
|
||||
/// @brief Command 목록
|
||||
std::vector<commands::ICommand> commands;
|
||||
/// @brief 음악 큐
|
||||
std::shared_ptr<MusicQueue> queue;
|
||||
};
|
||||
}
|
||||
#endif
|
||||
91
include/BumbleBeeCommand.hpp
Normal file
91
include/BumbleBeeCommand.hpp
Normal file
@@ -0,0 +1,91 @@
|
||||
#pragma once
|
||||
#ifndef _BUMBLEBEECOMMAND_HPP_
|
||||
#define _BUMBLEBEECOMMAND_HPP_
|
||||
#include <dpp/dpp.h>
|
||||
#include <MusicQueue.hpp>
|
||||
|
||||
namespace bumbleBee::commands {
|
||||
class ICommand {
|
||||
public:
|
||||
/// @brief 기본 생성자
|
||||
/// @param botID 명령어 등록을 위한 봇 아이디
|
||||
/// @param queue 음악이 저장되어 있는 큐
|
||||
ICommand(dpp::snowflake botID, std::weak_ptr<MusicQueue> queue) {
|
||||
this->botID = botID;
|
||||
this->queue = queue;
|
||||
}
|
||||
/// @brief 명령어 호출 시에 콜백되는 함수
|
||||
/// @param event
|
||||
virtual void operator()(const dpp::slashcommand_t &event){};
|
||||
|
||||
/// @brief 봇 명령어들의 이름과 별명들을 저장하는 벡터
|
||||
std::vector<dpp::slashcommand> nameAndAliases;
|
||||
|
||||
private:
|
||||
/// @brief 봇 ID
|
||||
dpp::snowflake botID;
|
||||
/// @brief 음악 큐에 대한 약한 포인터
|
||||
std::weak_ptr<MusicQueue> queue;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @fn _DECLARE_BUMBLEBEE_COMMAND_one_PARAM_one_ALIAS(name, alias, description, option_name, option_desc)
|
||||
* @brief 명령어 인자가 없는 명령어의 boilerplate 대체 매크로
|
||||
* @param name 명령어 이름 및 클래스명
|
||||
* @param alias 명령어 별명
|
||||
* @param description 명령어 설명
|
||||
**/
|
||||
#define _DECLARE_BUMBLEBEE_COMMAND_one_ALIAS(name, alias, description) \
|
||||
namespace bumbleBee::commands { \
|
||||
class name : public ICommand { \
|
||||
public: \
|
||||
name (dpp::snowflake botID, std::weak_ptr<MusicQueue> q) \
|
||||
: ICommand(botID, q) { \
|
||||
dpp::slashcommand command = dpp::slashcommand(#name, description, botID); \
|
||||
dpp::slashcommand aliasCommand = dpp::slashcommand(alias, description, botID); \
|
||||
nameAndAliases.push_back(command); \
|
||||
nameAndAliases.push_back(aliasCommand); \
|
||||
} \
|
||||
virtual void operator()(const dpp::slashcommand_t &event) override; \
|
||||
}; \
|
||||
}
|
||||
|
||||
/**
|
||||
* @fn _DECLARE_BUMBLEBEE_COMMAND_one_PARAM_one_ALIAS(name, alias, description, option_name, option_desc)
|
||||
* @brief 명령어 인자를 하나 갖는 명령어의 boilerplate 대체 매크로
|
||||
* @param name 명령어 이름 및 클래스명
|
||||
* @param alias 명령어 별명
|
||||
* @param description 명령어 설명
|
||||
* @param option_name 명령어 인자 이름
|
||||
* @param option_desc 명령어 인자 설명
|
||||
**/
|
||||
#define _DECLARE_BUMBLEBEE_COMMAND_one_PARAM_one_ALIAS(name, alias, description, option_name, option_desc) \
|
||||
namespace bumbleBee::commands { \
|
||||
class name : public ICommand { \
|
||||
public: \
|
||||
name (dpp::snowflake botID, std::weak_ptr<MusicQueue> q) \
|
||||
: ICommand(botID, q) { \
|
||||
dpp::slashcommand command = dpp::slashcommand(#name, description, botID); \
|
||||
dpp::slashcommand aliasCommand = dpp::slashcommand(alias, description, botID); \
|
||||
command.add_option( \
|
||||
dpp::command_option(dpp::co_string, option_name, option_desc, botID) \
|
||||
); \
|
||||
aliasCommand.add_option( \
|
||||
dpp::command_option(dpp::co_string, option_name, option_desc, botID) \
|
||||
); \
|
||||
nameAndAliases.push_back(command); \
|
||||
nameAndAliases.push_back(aliasCommand); \
|
||||
} \
|
||||
virtual void operator()(const dpp::slashcommand_t &event) override; \
|
||||
}; \
|
||||
}
|
||||
|
||||
_DECLARE_BUMBLEBEE_COMMAND_one_PARAM_one_ALIAS(Delete, "d", "큐의 해당하는 번호의 노래를 지웁니다", "pos", "큐 번호")
|
||||
_DECLARE_BUMBLEBEE_COMMAND_one_ALIAS(Leave, "l", "음성 채팅방을 떠납니다")
|
||||
_DECLARE_BUMBLEBEE_COMMAND_one_PARAM_one_ALIAS(Play, "p", "노래 재생", "query", "링크 또는 검색어")
|
||||
_DECLARE_BUMBLEBEE_COMMAND_one_ALIAS(Queue, "q", "노래 예약 큐를 출력합니다")
|
||||
_DECLARE_BUMBLEBEE_COMMAND_one_ALIAS(Repeat, "r", "반복을 켜거나 끕니다")
|
||||
_DECLARE_BUMBLEBEE_COMMAND_one_ALIAS(Skip, "s", "현재 재생중인 곡을 스킵합니다")
|
||||
|
||||
#endif
|
||||
@@ -1,38 +0,0 @@
|
||||
#pragma once
|
||||
#include <string>
|
||||
#include <Bot.hpp>
|
||||
#include <dpp/dpp.h>
|
||||
#include <memory>
|
||||
#include <unordered_map>
|
||||
#include <FQueueElement.hpp>
|
||||
|
||||
class BumbleCeepp : public IBot {
|
||||
public:
|
||||
BumbleCeepp(std::string token, std::string DBURL, std::string DBID, std::string DBPassword, int clusterCount = 0);
|
||||
~BumbleCeepp();
|
||||
|
||||
void enqueueMusic(FQueueElement item, dpp::discord_voice_client* vc);
|
||||
std::shared_ptr<dpp::embed> findEmbed(std::string musicID);
|
||||
bool insertDB(
|
||||
std::string webpage_url,
|
||||
std::string title,
|
||||
std::string uploader,
|
||||
std::string id,
|
||||
std::string thumbnail,
|
||||
time_t duration);
|
||||
std::shared_ptr<dpp::embed> makeEmbed(
|
||||
std::string webpage_url,
|
||||
std::string title,
|
||||
std::string uploader,
|
||||
std::string id,
|
||||
std::string thumbnail,
|
||||
time_t duration);
|
||||
|
||||
bool repeat;
|
||||
std::string nowPlayingMusic;
|
||||
|
||||
private:
|
||||
//<guild_id, queueMutex> 쌍임.
|
||||
std::unordered_map<dpp::snowflake, std::mutex> enqueuingMutexMap;
|
||||
sql::Connection* conn;
|
||||
};
|
||||
@@ -1,22 +0,0 @@
|
||||
#pragma once
|
||||
#include <dpp/dpp.h>
|
||||
#include <vector>
|
||||
#include <list>
|
||||
|
||||
class BumbleCeepp;
|
||||
|
||||
namespace commands {
|
||||
class ICommand {
|
||||
public:
|
||||
ICommand(dpp::snowflake botID, BumbleCeepp* Bot)
|
||||
{
|
||||
this->botID = botID;
|
||||
this->Bot = Bot;
|
||||
}
|
||||
virtual void operator()(const dpp::slashcommand_t &event) = 0;
|
||||
|
||||
std::vector<dpp::slashcommand> commandObjectVector;
|
||||
dpp::snowflake botID;
|
||||
BumbleCeepp* Bot;
|
||||
};
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
#pragma once
|
||||
#include <Commands/Play.hpp>
|
||||
#include <Commands/Repeat.hpp>
|
||||
#include <Commands/Queue.hpp>
|
||||
#include <Commands/Skip.hpp>
|
||||
#include <Commands/Leave.hpp>
|
||||
#include <Commands/Delete.hpp>
|
||||
@@ -1,13 +0,0 @@
|
||||
#pragma once
|
||||
#include <Commands/CommandType.hpp>
|
||||
#include <BumbleCeepp.hpp>
|
||||
#include <memory>
|
||||
|
||||
namespace commands {
|
||||
class Delete : public ICommand {
|
||||
public:
|
||||
Delete(dpp::snowflake botID, BumbleCeepp* Bot);
|
||||
|
||||
void operator()(const dpp::slashcommand_t& event);
|
||||
};
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
#pragma once
|
||||
#include <Commands/CommandType.hpp>
|
||||
#include <BumbleCeepp.hpp>
|
||||
#include <memory>
|
||||
|
||||
namespace commands {
|
||||
class Leave : public ICommand {
|
||||
public:
|
||||
Leave(dpp::snowflake botID, BumbleCeepp* Bot);
|
||||
|
||||
void operator()(const dpp::slashcommand_t& event);
|
||||
};
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
#pragma once
|
||||
#include <Commands/CommandType.hpp>
|
||||
#include <BumbleCeepp.hpp>
|
||||
#include <memory>
|
||||
|
||||
namespace commands {
|
||||
class Play : public ICommand {
|
||||
public:
|
||||
Play(dpp::snowflake botID, BumbleCeepp* Bot);
|
||||
|
||||
void operator()(const dpp::slashcommand_t& event);
|
||||
void on_DLCompleted(std::string musicID, dpp::embed embed, const dpp::slashcommand_t& event);
|
||||
};
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
#pragma once
|
||||
#include <Commands/CommandType.hpp>
|
||||
#include <BumbleCeepp.hpp>
|
||||
#include <memory>
|
||||
|
||||
namespace commands {
|
||||
class Queue : public ICommand {
|
||||
public:
|
||||
Queue(dpp::snowflake botID, BumbleCeepp* Bot);
|
||||
|
||||
void operator()(const dpp::slashcommand_t& event);
|
||||
};
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
#pragma once
|
||||
#include <Commands/CommandType.hpp>
|
||||
#include <BumbleCeepp.hpp>
|
||||
#include <memory>
|
||||
|
||||
namespace commands {
|
||||
class Repeat : public ICommand {
|
||||
public:
|
||||
Repeat(dpp::snowflake botID, BumbleCeepp* Bot);
|
||||
|
||||
void operator()(const dpp::slashcommand_t& event);
|
||||
};
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
#pragma once
|
||||
#include <Commands/CommandType.hpp>
|
||||
#include <BumbleCeepp.hpp>
|
||||
#include <memory>
|
||||
|
||||
namespace commands {
|
||||
class Skip : public ICommand {
|
||||
public:
|
||||
Skip(dpp::snowflake botID, BumbleCeepp* Bot);
|
||||
|
||||
void operator()(const dpp::slashcommand_t& event);
|
||||
};
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
#pragma once
|
||||
#include <string>
|
||||
#include <dpp/dpp.h>
|
||||
|
||||
struct FQueueElement {
|
||||
std::string ID;
|
||||
dpp::embed embed;
|
||||
bool skip = false;
|
||||
};
|
||||
11
include/MusicQueue.hpp
Normal file
11
include/MusicQueue.hpp
Normal file
@@ -0,0 +1,11 @@
|
||||
#pragma once
|
||||
#ifndef _MUSICQUEUE_HPP_
|
||||
#define _MUSICQUEUE_HPP_
|
||||
|
||||
namespace bumbleBee {
|
||||
class MusicQueue {
|
||||
public:
|
||||
};
|
||||
}
|
||||
|
||||
#endif
|
||||
25
src/AsyncDownloadManager.cpp
Normal file
25
src/AsyncDownloadManager.cpp
Normal file
@@ -0,0 +1,25 @@
|
||||
#include <AsyncDownloadManager.hpp>
|
||||
|
||||
namespace bumbleBee {
|
||||
|
||||
void AsyncDownloadManager::enqueueAsyncDL(std::string query) {
|
||||
dlQueueMutex.lock();
|
||||
downloadQueue.push(query);
|
||||
dlQueueMutex.unlock();
|
||||
dlQueueCondition.notify_one();
|
||||
}
|
||||
|
||||
void AsyncDownloadManager::downloadWorker() {
|
||||
std::unique_lock<std::mutex> dlQueueLock(dlQueueMutex);
|
||||
while (true) {
|
||||
//mutex lock
|
||||
dlQueueLock.lock();
|
||||
dlQueueCondition.wait(dlQueueLock, [&]{ return !downloadQueue.empty(); });
|
||||
|
||||
system(("./yt-dlp --no-clean-info-json --write-info-json --default-search ytsearch \
|
||||
--flat-playlist --skip-download --quiet --ignore-errors -f ba* " + downloadQueue.front()).c_str());
|
||||
downloadQueue.pop();
|
||||
dlQueueLock.unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
39
src/Bot.cpp
39
src/Bot.cpp
@@ -1,39 +0,0 @@
|
||||
#include <Bot.hpp>
|
||||
#include <Commands/CommandType.hpp>
|
||||
|
||||
IBot::IBot(std::string token, int clusterCount)
|
||||
{
|
||||
botCluster = std::make_shared<dpp::cluster>(token, dpp::i_default_intents, clusterCount);
|
||||
|
||||
botCluster->on_log(logger());
|
||||
botCluster->on_slashcommand([&](const dpp::slashcommand_t& event){onCommand(event);});
|
||||
botCluster->on_ready([&](const dpp::ready_t &event){onReady(event);});
|
||||
}
|
||||
|
||||
void IBot::onCommand(const dpp::slashcommand_t &event)
|
||||
{
|
||||
auto _event = event;
|
||||
for (auto command : commandsArray)
|
||||
for (auto alias : command->commandObjectVector)
|
||||
if (event.command.get_command_name() == alias.name)
|
||||
(*command)(_event);
|
||||
}
|
||||
|
||||
void IBot::onReady(const dpp::ready_t &event)
|
||||
{
|
||||
if (!dpp::run_once<struct register_bot_commands>())
|
||||
return;
|
||||
|
||||
//BotCluster->global_bulk_command_delete();
|
||||
|
||||
for (auto command : commandsArray)
|
||||
for (auto alias : command->commandObjectVector)
|
||||
botCluster->global_command_create(alias);
|
||||
|
||||
botCluster->log(dpp::loglevel::ll_info, "Command added to all clusters.");
|
||||
}
|
||||
|
||||
void IBot::start()
|
||||
{
|
||||
botCluster->start(dpp::st_wait);
|
||||
}
|
||||
36
src/BumbleBee.cpp
Normal file
36
src/BumbleBee.cpp
Normal file
@@ -0,0 +1,36 @@
|
||||
#include <BumbleBee.hpp>
|
||||
|
||||
namespace bumbleBee{
|
||||
BumbleBee::BumbleBee(nlohmann::json settings) {
|
||||
this->cluster = std::make_unique<dpp::cluster>(settings["token"]);
|
||||
dbDriver = sql::mariadb::get_driver_instance();
|
||||
this->dbURL = std::make_shared<sql::SQLString>(settings["dbURL"]);
|
||||
sql::Properties pro({
|
||||
{"user", std::string(settings["user"])},
|
||||
{"password", std::string(settings["password"])}
|
||||
});
|
||||
this->dbProperties = std::make_shared<sql::Properties>(pro);
|
||||
|
||||
cluster->on_log(dpp::utility::cout_logger());
|
||||
cluster->on_slashcommand([this](const dpp::slashcommand_t& event){on_slashcommand(event);});
|
||||
cluster->on_ready([this](const dpp::ready_t &event){on_ready(event);});
|
||||
}
|
||||
|
||||
BumbleBee::~BumbleBee() {
|
||||
}
|
||||
|
||||
void BumbleBee::start() { this->cluster->start(dpp::st_wait); }
|
||||
|
||||
bool BumbleBee::addCommand(commands::ICommand cmd) {
|
||||
commands.push_back(cmd);
|
||||
return false;
|
||||
}
|
||||
|
||||
void BumbleBee::on_slashcommand(const dpp::slashcommand_t &event) {
|
||||
|
||||
}
|
||||
void BumbleBee::on_ready(const dpp::ready_t &event) {
|
||||
cluster->log(dpp::loglevel::ll_info, "Bot ready.");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,245 +0,0 @@
|
||||
#include "BumbleCeepp.hpp"
|
||||
#include <string>
|
||||
#include <FQueueElement.hpp>
|
||||
#include <Commands/Commands.hpp>
|
||||
#include <oggz/oggz.h>
|
||||
|
||||
BumbleCeepp::BumbleCeepp(std::string token, std::string DBURL, std::string DBID, std::string DBPassword, int clusterCount)
|
||||
: IBot(token, clusterCount)
|
||||
{
|
||||
sql::Properties pro({
|
||||
{"user", DBID},
|
||||
{"password", DBPassword}
|
||||
});
|
||||
|
||||
conn = sql::mariadb::get_driver_instance()->connect(DBURL, pro);
|
||||
|
||||
commandsArray.push_back(std::make_shared<commands::Play>(botCluster->me.id, this));
|
||||
commandsArray.push_back(std::make_shared<commands::Repeat>(botCluster->me.id, this));
|
||||
commandsArray.push_back(std::make_shared<commands::Queue>(botCluster->me.id, this));
|
||||
commandsArray.push_back(std::make_shared<commands::Skip>(botCluster->me.id, this));
|
||||
commandsArray.push_back(std::make_shared<commands::Leave>(botCluster->me.id, this));
|
||||
commandsArray.push_back(std::make_shared<commands::Delete>(botCluster->me.id, this));
|
||||
|
||||
botCluster->on_voice_track_marker([&](const dpp::voice_track_marker_t &marker)
|
||||
{
|
||||
marker.voice_client->log(dpp::loglevel::ll_debug, "nowPlaying " + nowPlayingMusic);
|
||||
std::shared_ptr<dpp::embed> embed;
|
||||
if (nowPlayingMusic == "") {
|
||||
nowPlayingMusic = marker.track_meta;
|
||||
embed = findEmbed(nowPlayingMusic);
|
||||
}
|
||||
else {
|
||||
embed = findEmbed(nowPlayingMusic);
|
||||
nowPlayingMusic = marker.track_meta;
|
||||
}
|
||||
auto voice_members = dpp::find_guild(marker.voice_client->server_id)->voice_members;
|
||||
dpp::snowflake connectedChannel = marker.voice_client->channel_id;
|
||||
int memberCount = 0;
|
||||
for (auto member : voice_members)
|
||||
if ( member.second.channel_id == connectedChannel )
|
||||
memberCount++;
|
||||
|
||||
if (!memberCount)
|
||||
{
|
||||
auto joinedShard = marker.from;
|
||||
std::cout << "voicechat is empty.";
|
||||
marker.voice_client->stop_audio();
|
||||
joinedShard->disconnect_voice(marker.voice_client->server_id);
|
||||
return;
|
||||
}
|
||||
|
||||
<<<<<<< HEAD
|
||||
if (!memberCount)
|
||||
{
|
||||
auto joinedShard = marker.from;
|
||||
marker.voice_client->log(dpp::loglevel::ll_info, "voicechat is empty.");
|
||||
=======
|
||||
marker.voice_client->log(dpp::loglevel::ll_debug, "Playing " + marker.track_meta + "on channel id " + marker.voice_client->channel_id.str() + ".");
|
||||
|
||||
int remainingSongsCount = marker.voice_client->get_tracks_remaining();
|
||||
marker.voice_client->log(dpp::loglevel::ll_debug, "Marker count : " + std::to_string(remainingSongsCount));
|
||||
|
||||
if (remainingSongsCount <= 1 && !marker.voice_client->is_playing())
|
||||
{
|
||||
auto joinedShard = marker.from;
|
||||
std::cout << "Queue ended\n";
|
||||
if (!joinedShard)
|
||||
return;
|
||||
|
||||
if (repeat) {
|
||||
std::shared_ptr<dpp::embed> embed = findEmbed(nowPlayingMusic);
|
||||
enqueueMusic({nowPlayingMusic, *embed}, marker.voice_client);
|
||||
}
|
||||
else {
|
||||
>>>>>>> 68b6105ac3ddf1c27f40e0e552780171352e734d
|
||||
marker.voice_client->stop_audio();
|
||||
joinedShard->disconnect_voice(marker.voice_client->server_id);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
<<<<<<< HEAD
|
||||
|
||||
marker.voice_client->log(dpp::loglevel::ll_debug, "Playing " + marker.track_meta + "on channel id " + marker.voice_client->channel_id.str() + ".");
|
||||
|
||||
int remainingSongsCount = marker.voice_client->get_tracks_remaining();
|
||||
marker.voice_client->log(dpp::loglevel::ll_info, "Marker count : " + remainingSongsCount);
|
||||
|
||||
if (remainingSongsCount <= 1 && !marker.voice_client->is_playing())
|
||||
{
|
||||
auto joinedShard = marker.from;
|
||||
marker.voice_client->log(dpp::loglevel::ll_info, "Queue ended");
|
||||
if (!joinedShard)
|
||||
return;
|
||||
marker.voice_client->stop_audio();
|
||||
joinedShard->disconnect_voice(marker.voice_client->server_id);
|
||||
=======
|
||||
if (repeat) {
|
||||
if (!embed) {
|
||||
botCluster->log(dpp::loglevel::ll_error, std::string("알 수 없는 오류 발생!"));
|
||||
>>>>>>> 68b6105ac3ddf1c27f40e0e552780171352e734d
|
||||
return;
|
||||
}
|
||||
|
||||
enqueueMusic({nowPlayingMusic, *embed}, marker.voice_client);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
BumbleCeepp::~BumbleCeepp()
|
||||
{
|
||||
conn->close();
|
||||
}
|
||||
|
||||
void BumbleCeepp::enqueueMusic(FQueueElement item, dpp::discord_voice_client* vc)
|
||||
{
|
||||
vc->insert_marker(item.ID);
|
||||
vc->log(dpp::loglevel::ll_debug, "Enqueueuing " + item.ID + "on channel id " + vc->channel_id.str() + ".");
|
||||
std::lock_guard<std::mutex> lock(enqueuingMutexMap[vc->server_id]);
|
||||
|
||||
OGGZ *track_og = oggz_open(("Music/" + item.ID + ".ogg").c_str(), OGGZ_READ);
|
||||
|
||||
/* If there was an issue reading the file, tell the user and stop */
|
||||
if (!track_og) {
|
||||
fprintf(stderr, "Error opening file\n");
|
||||
return;
|
||||
}
|
||||
|
||||
/* set read callback, this callback will be called on packets with the serialno,
|
||||
* -1 means every packet will be handled with this callback.
|
||||
*/
|
||||
oggz_set_read_callback(
|
||||
track_og, -1,
|
||||
[](OGGZ *oggz, oggz_packet *packet, long serialno, void *user_data) {
|
||||
dpp::discord_voice_client *vc = (dpp::discord_voice_client *)user_data;
|
||||
|
||||
/* send the audio */
|
||||
vc->send_audio_opus(packet->op.packet, packet->op.bytes);
|
||||
|
||||
/* make sure to always return 0 here, read more on oggz documentation */
|
||||
return 0;
|
||||
},
|
||||
/* this will be the value of void *user_data */
|
||||
(void *)vc
|
||||
);
|
||||
|
||||
// read loop
|
||||
while (vc && !vc->terminating) {
|
||||
/* you can tweak this to whatever. Here I use BUFSIZ, defined in
|
||||
* stdio.h as 8192.
|
||||
*/
|
||||
static const constexpr long CHUNK_READ = BUFSIZ * 2;
|
||||
|
||||
const long read_bytes = oggz_read(track_og, CHUNK_READ);
|
||||
|
||||
/* break on eof */
|
||||
if (!read_bytes) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/* Don't forget to free the memory */
|
||||
oggz_close(track_og);
|
||||
|
||||
vc->log(dpp::loglevel::ll_debug, "Enqueued " + item.ID + "on channel id " + vc->channel_id.str() + ".");
|
||||
}
|
||||
|
||||
std::shared_ptr<dpp::embed> BumbleCeepp::findEmbed(std::string musicID)
|
||||
{
|
||||
sql::ResultSet* res;
|
||||
std::shared_ptr<dpp::embed> returnValue;
|
||||
try {
|
||||
std::unique_ptr<sql::PreparedStatement> stmnt(conn->prepareStatement("SELECT * FROM songs_info WHERE ID = ?"));
|
||||
stmnt->setString(1, musicID);
|
||||
res = stmnt->executeQuery();
|
||||
|
||||
if (!res->next()) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
returnValue = makeEmbed(
|
||||
res->getString("webpage_url").c_str(),
|
||||
res->getString("title").c_str(),
|
||||
res->getString("uploader").c_str(),
|
||||
musicID,
|
||||
res->getString("thumbnail").c_str(),
|
||||
res->getInt("duration"));
|
||||
}
|
||||
catch(sql::SQLException& e){
|
||||
botCluster->log(dpp::loglevel::ll_error, std::string("SQLError: ") + e.what());
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
return returnValue;
|
||||
}
|
||||
|
||||
bool BumbleCeepp::insertDB(
|
||||
std::string webpage_url, std::string title, std::string uploader, std::string id, std::string thumbnail, time_t duration)
|
||||
{
|
||||
try {
|
||||
std::unique_ptr<sql::PreparedStatement> stmnt(
|
||||
conn->prepareStatement("REPLACE INTO songs_info (ID, webpage_url, title, uploader, thumbnail, duration) VALUE (?, ?, ?, ?, ?, ?)"));
|
||||
stmnt->setString(1, id);
|
||||
stmnt->setString(2, webpage_url);
|
||||
stmnt->setString(3, title);
|
||||
stmnt->setString(4, uploader);
|
||||
stmnt->setString(5, thumbnail);
|
||||
stmnt->setInt(6, duration);
|
||||
stmnt->executeQuery();
|
||||
|
||||
return true;
|
||||
}
|
||||
catch(sql::SQLException& e){
|
||||
botCluster->log(dpp::loglevel::ll_debug, std::string("SQLError: ") + e.what());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
std::shared_ptr<dpp::embed> BumbleCeepp::makeEmbed(
|
||||
std::string webpage_url, std::string title, std::string uploader, std::string id, std::string thumbnail, time_t duration)
|
||||
{
|
||||
char SongLengthStr[10];
|
||||
tm t;
|
||||
t.tm_mday = duration / 86400;
|
||||
t.tm_hour = (duration % 86400)/3600;
|
||||
t.tm_min = (duration % 3600)/60;
|
||||
t.tm_sec = duration%60;
|
||||
strftime(SongLengthStr, sizeof(SongLengthStr), "%X", &t);
|
||||
|
||||
dpp::embed returnValue = dpp::embed()
|
||||
.set_color(dpp::colors::sti_blue)
|
||||
.set_title(title)
|
||||
.set_description(uploader)
|
||||
.set_url(webpage_url)
|
||||
.set_image(thumbnail)
|
||||
.add_field(
|
||||
"길이",
|
||||
SongLengthStr,
|
||||
true
|
||||
);
|
||||
|
||||
insertDB(webpage_url, title, uploader, id, thumbnail, duration);
|
||||
|
||||
return std::make_shared<dpp::embed>(returnValue);
|
||||
}
|
||||
@@ -1,58 +1,7 @@
|
||||
#include <Commands/Delete.hpp>
|
||||
#include <iostream>
|
||||
#include <BumbleBeeCommand.hpp>
|
||||
|
||||
commands::Delete::Delete(dpp::snowflake botID, BumbleCeepp* Bot)
|
||||
: ICommand(botID, Bot)
|
||||
{
|
||||
dpp::slashcommand Command = dpp::slashcommand("d", "큐의 해당하는 번호의 노래를 지웁니다", botID);
|
||||
namespace bumbleBee::commands {
|
||||
void Delete::operator()(const dpp::slashcommand_t &event) {
|
||||
|
||||
Command.add_option(
|
||||
dpp::command_option(dpp::co_string, "pos", "큐 번호", botID)
|
||||
);
|
||||
|
||||
commandObjectVector.push_back(Command);
|
||||
}
|
||||
|
||||
void commands::Delete::operator()(const dpp::slashcommand_t& event)
|
||||
{
|
||||
if (std::holds_alternative<std::monostate>(event.get_parameter("pos"))) {
|
||||
event.reply("삭제할 노래의 인덱스가 정확하지 않습니다.");
|
||||
return;
|
||||
}
|
||||
std::string Pos = std::get<std::string>(event.get_parameter("pos"));
|
||||
event.thinking();
|
||||
|
||||
auto index = atoi(Pos.c_str());
|
||||
|
||||
auto vc = event.from->connecting_voice_channels.find(event.command.guild_id)->second->voiceclient;
|
||||
int remainingSongsCount = vc->get_tracks_remaining() - 1;
|
||||
std::vector<std::string> queuedSongs = vc->get_marker_metadata();
|
||||
|
||||
vc->log(dpp::loglevel::ll_info, "Queue size : " + remainingSongsCount);
|
||||
|
||||
if (index < 0 || remainingSongsCount+1 < index || (!vc->is_playing() && index == 0)) {
|
||||
std::cout << "invalid index : " << index << ", " + Pos + "\n";
|
||||
|
||||
event.edit_original_response(dpp::message(event.command.channel_id, "이상한 인덱스 위치. Pos : " + Pos));
|
||||
return;
|
||||
}
|
||||
|
||||
dpp::embed embed = (*Bot->findEmbed(queuedSongs[index - 1]))
|
||||
.set_timestamp(time(0));
|
||||
|
||||
dpp::message msg(event.command.channel_id, "다음 항목을 큐에서 삭제했습니다!:");
|
||||
|
||||
if (index == 0) {
|
||||
dpp::voiceconn* v = event.from->get_voice(event.command.guild_id);
|
||||
|
||||
if (!v || !v->voiceclient || !v->voiceclient->is_ready()) {
|
||||
return;
|
||||
}
|
||||
|
||||
v->voiceclient->skip_to_next_marker();
|
||||
}
|
||||
|
||||
msg.add_embed(embed);
|
||||
|
||||
event.edit_original_response(msg);
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
#include <Commands/Leave.hpp>
|
||||
#include <iostream>
|
||||
|
||||
commands::Leave::Leave(dpp::snowflake botID, BumbleCeepp* Bot)
|
||||
: ICommand(botID, Bot)
|
||||
{
|
||||
dpp::slashcommand command = dpp::slashcommand("l", "음챗을 떠납니다", botID);
|
||||
|
||||
commandObjectVector.push_back(command);
|
||||
}
|
||||
|
||||
void commands::Leave::operator()(const dpp::slashcommand_t& event)
|
||||
{
|
||||
dpp::voiceconn* v = event.from->get_voice(event.command.guild_id);
|
||||
|
||||
if (!v || !v->voiceclient || !v->voiceclient->is_ready()) {
|
||||
return;
|
||||
}
|
||||
v->voiceclient->stop_audio();
|
||||
event.from->disconnect_voice(event.command.guild_id);
|
||||
|
||||
dpp::message msg(event.command.channel_id, "음성 채팅방을 떠납니다!");
|
||||
|
||||
event.reply(msg);
|
||||
}
|
||||
@@ -1,212 +0,0 @@
|
||||
#include <Commands/Play.hpp>
|
||||
#include <dpp/dpp.h>
|
||||
#include <dpp/nlohmann/json.hpp>
|
||||
#include <string>
|
||||
#include <filesystem>
|
||||
#include <ctime>
|
||||
#include <thread>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
std::string getResultFromCommand(std::string cmd) {
|
||||
std::string result;
|
||||
FILE* stream;
|
||||
const int maxBuffer = 256; // 버퍼의 크기는 적당하게
|
||||
char buffer[maxBuffer];
|
||||
cmd.append(" 2>&1"); // 표준에러를 표준출력으로 redirect
|
||||
|
||||
stream = popen(cmd.c_str(), "r"); // 주어진 command를 shell로 실행하고 파이프 연결 (fd 반환)
|
||||
if (stream) {
|
||||
while (fgets(buffer, maxBuffer, stream) != NULL) result.append(buffer); // fgets: fd (stream)를 길이 (maxBuffer)만큼 읽어 버퍼 (buffer)에 저장
|
||||
pclose(stream); // 파이프 닫는 것 잊지 마시고요!
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
commands::Play::Play(dpp::snowflake botID, BumbleCeepp* Bot)
|
||||
: ICommand(botID, Bot)
|
||||
{
|
||||
dpp::slashcommand command = dpp::slashcommand("p", "노래 재생", botID);
|
||||
|
||||
command.add_option(
|
||||
dpp::command_option(dpp::co_string, "query", "링크 또는 검색어", botID)
|
||||
);
|
||||
|
||||
commandObjectVector.push_back(command);
|
||||
}
|
||||
|
||||
<<<<<<< HEAD
|
||||
static void _Internal_Enqueue_Func(const dpp::slashcommand_t& event, BumbleCeepp* Bot){
|
||||
std::string Query = std::get<std::string>(event.get_parameter("query"));
|
||||
|
||||
event.from->log(dpp::loglevel::ll_info, "음악 다운로드 시작");
|
||||
std::system(("python3 yt-download.py \"" + Query + "\" & wait").c_str());
|
||||
event.from->log(dpp::loglevel::ll_info, "음악 다운로드 완료");
|
||||
=======
|
||||
void commands::Play::operator()(const dpp::slashcommand_t& event)
|
||||
{
|
||||
if (std::holds_alternative<std::monostate>(event.get_parameter("query")))
|
||||
{
|
||||
event.reply("노래를 재생하려면 검색어 또는 링크를 입력해 주십시오.");
|
||||
return;
|
||||
}
|
||||
|
||||
/* Attempt to connect to a voice channel, returns false if we fail to connect. */
|
||||
if (!event.from->get_voice(event.command.guild_id))
|
||||
{
|
||||
dpp::guild* g = dpp::find_guild(event.command.guild_id);
|
||||
bool memberIsInVoice = g->connect_member_voice(event.command.get_issuing_user().id);
|
||||
if (!memberIsInVoice)
|
||||
{
|
||||
event.reply("노래를 재생할 음성 채팅방에 먼저 참가하고 신청해야 합니다!");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
std::string Query = std::get<std::string>(event.get_parameter("query"));
|
||||
|
||||
event.thinking();
|
||||
|
||||
event.from->log(dpp::loglevel::ll_debug, "음악 ID 쿼리: " + Query);
|
||||
>>>>>>> 68b6105ac3ddf1c27f40e0e552780171352e734d
|
||||
|
||||
std::string musicIDs = getResultFromCommand(("python3 youtube-search.py \"" + Query + "\" & wait").c_str());
|
||||
|
||||
if (!musicIDs.length())
|
||||
{
|
||||
<<<<<<< HEAD
|
||||
event.from->log(dpp::loglevel::ll_info, "Red ID : " + ID);
|
||||
infofile.open("Music/" + ID + ".info.json");
|
||||
infofile >> document;
|
||||
infofile.close();
|
||||
|
||||
FQueueElement Data = {
|
||||
ID,
|
||||
Bot->makeEmbed(
|
||||
document["webpage_url"],
|
||||
document["title"],
|
||||
document["uploader"],
|
||||
document["id"],
|
||||
document["thumbnail"],
|
||||
int(document["duration"]))
|
||||
};
|
||||
|
||||
RequestedMusic.push(Data);
|
||||
=======
|
||||
event.from->log(dpp::loglevel::ll_debug, "유튜브 검색 결과 없음");
|
||||
event.edit_response("검색 결과가 없습니다.");
|
||||
return;
|
||||
>>>>>>> 68b6105ac3ddf1c27f40e0e552780171352e734d
|
||||
}
|
||||
|
||||
std::stringstream sstream(musicIDs);
|
||||
std::string musicID;
|
||||
while (getline(sstream, musicID, '\n')) {
|
||||
event.from->log(dpp::loglevel::ll_debug, "musicID: " + musicID);
|
||||
event.from->log(dpp::loglevel::ll_debug, "DB쿼리 시도..");
|
||||
std::shared_ptr<dpp::embed> embed = Bot->findEmbed(musicID);
|
||||
|
||||
if (embed == nullptr) {
|
||||
event.from->log(dpp::loglevel::ll_debug, "DB쿼리 실패");
|
||||
event.from->log(dpp::loglevel::ll_debug, "다운로드 시작");
|
||||
std::system(("python3 yt-download.py \"" + musicID + "\" & wait").c_str());
|
||||
|
||||
<<<<<<< HEAD
|
||||
if (v && v->voiceclient && v->voiceclient->is_ready())
|
||||
{
|
||||
auto _copiedQueue = RequestedMusic;
|
||||
while (!_copiedQueue.empty())
|
||||
{
|
||||
Bot->enqueueMusic(_copiedQueue.front(), v->voiceclient);
|
||||
_copiedQueue.pop();
|
||||
=======
|
||||
event.from->log(dpp::loglevel::ll_debug, "musicID: " + musicID);
|
||||
std::ifstream infofile;
|
||||
infofile.open((std::string("Music/") + musicID + ".info.json").c_str());
|
||||
event.from->log(dpp::loglevel::ll_debug, std::string("json file name: ") + "Music/" + musicID + ".info.json");
|
||||
json document;
|
||||
infofile >> document;
|
||||
infofile.close();
|
||||
|
||||
embed = Bot->makeEmbed(
|
||||
document["webpage_url"],
|
||||
document["title"],
|
||||
document["uploader"],
|
||||
document["id"],
|
||||
document["thumbnail"],
|
||||
int(document["duration"]));
|
||||
|
||||
on_DLCompleted(musicID, *embed, event);
|
||||
}
|
||||
else {
|
||||
event.from->log(dpp::loglevel::ll_debug, "DB쿼리 완료");
|
||||
on_DLCompleted(musicID, *embed, event);
|
||||
>>>>>>> 68b6105ac3ddf1c27f40e0e552780171352e734d
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
void commands::Play::on_DLCompleted(std::string musicID, dpp::embed embed, const dpp::slashcommand_t& event)
|
||||
{
|
||||
static std::string raw_event;
|
||||
if (raw_event != event.raw_event){
|
||||
raw_event = event.raw_event;
|
||||
|
||||
dpp::message msg(event.command.channel_id, "큐에 다음 곡을 추가했습니다:");
|
||||
msg.add_embed(embed);
|
||||
event.edit_response(msg);
|
||||
}
|
||||
else {
|
||||
dpp::message followMsg(event.command.channel_id, "");
|
||||
|
||||
dpp::embed followEmbed = dpp::embed()
|
||||
.add_field(
|
||||
embed.title,
|
||||
embed.description,
|
||||
true
|
||||
)
|
||||
.add_field(
|
||||
"",
|
||||
""
|
||||
);
|
||||
|
||||
followMsg.add_embed(followEmbed);
|
||||
|
||||
event.from->creator->message_create(followMsg);
|
||||
}
|
||||
}
|
||||
|
||||
void commands::Play::operator()(const dpp::slashcommand_t& event)
|
||||
{
|
||||
if (std::holds_alternative<std::monostate>(event.get_parameter("query")))
|
||||
{
|
||||
event.reply("노래를 재생하려면 검색어 또는 링크를 입력해 주십시오.");
|
||||
return;
|
||||
}
|
||||
|
||||
/* Attempt to connect to a voice channel, returns false if we fail to connect. */
|
||||
if (!event.from->get_voice(event.command.guild_id))
|
||||
{
|
||||
if (!dpp::find_guild(event.command.guild_id)->connect_member_voice(event.command.get_issuing_user().id))
|
||||
{
|
||||
return event.reply("노래를 재생할 음성 채팅방에 먼저 참가하고 신청해야 합니다!");
|
||||
}
|
||||
}
|
||||
|
||||
event.thinking();
|
||||
|
||||
std::thread t1(_Internal_Enqueue_Func, event, Bot);
|
||||
t1.detach();
|
||||
|
||||
auto voiceconn = event.from->get_voice(event.command.guild_id);
|
||||
|
||||
if (!voiceconn || !voiceconn->voiceclient || !voiceconn->voiceclient->is_ready()) {
|
||||
event.from->creator->on_voice_ready([this, musicID, embed](const dpp::voice_ready_t& Voice){
|
||||
this->Bot->enqueueMusic({musicID, embed}, Voice.voice_client);
|
||||
});
|
||||
}
|
||||
else {
|
||||
Bot->enqueueMusic({musicID, embed}, voiceconn->voiceclient);
|
||||
}
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
#include <Commands/Queue.hpp>
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <cmath>
|
||||
|
||||
commands::Queue::Queue(dpp::snowflake botID, BumbleCeepp* Bot)
|
||||
: ICommand(botID, Bot)
|
||||
{
|
||||
dpp::slashcommand command = dpp::slashcommand("q", "노래 예약 큐 확인", botID);
|
||||
|
||||
commandObjectVector.push_back(command);
|
||||
}
|
||||
|
||||
void commands::Queue::operator()(const dpp::slashcommand_t& event) {
|
||||
dpp::message msg;
|
||||
msg.set_channel_id(event.command.channel_id);
|
||||
|
||||
auto voiceconn = event.from->get_voice(event.command.guild_id);
|
||||
|
||||
if (!voiceconn || !voiceconn->voiceclient) {
|
||||
event.reply("음성 채팅방에 참가하지 않은 상태입니다.");
|
||||
return;
|
||||
}
|
||||
auto vc = voiceconn->voiceclient;
|
||||
|
||||
int remainingSongsCount = vc->get_tracks_remaining() - 1;
|
||||
if (remainingSongsCount <= 0 && !vc->is_playing()) {
|
||||
//재생 중인 노래가 없고 큐에 노래가 없는 상황
|
||||
dpp::embed embed = dpp::embed()
|
||||
.set_color(dpp::colors::sti_blue)
|
||||
.set_title("큐가 비었습니다!")
|
||||
.set_timestamp(time(0));
|
||||
|
||||
if (Bot->repeat)
|
||||
embed.add_field(":repeat:","");
|
||||
|
||||
msg.add_embed(embed);
|
||||
}
|
||||
else {
|
||||
msg.set_content("지금 재생 중:");
|
||||
dpp::embed curMusicEmbed = *Bot->findEmbed(Bot->nowPlayingMusic);
|
||||
msg.add_embed(curMusicEmbed);
|
||||
}
|
||||
|
||||
event.reply(msg, [&](const dpp::confirmation_callback_t& _event) {
|
||||
auto shard_id = dpp::find_guild(event.command.guild_id)->shard_id;
|
||||
dpp::cluster* cluster = const_cast<dpp::cluster *>(_event.bot);
|
||||
auto shard = cluster->get_shard(shard_id);
|
||||
auto iter = shard->connecting_voice_channels.find(event.command.guild_id);
|
||||
std::vector<std::string> queuedSongs = iter->second->voiceclient->get_marker_metadata();
|
||||
|
||||
int j;
|
||||
for (int i = 0; i < (queuedSongs.size()+4) / 5; i++)
|
||||
{
|
||||
dpp::embed followEmbed = dpp::embed();
|
||||
for (j = i * 5; j < i * 5 + 5 && j < queuedSongs.size(); j++)
|
||||
{
|
||||
dpp::embed originalEmbed = *Bot->findEmbed(queuedSongs[j]);
|
||||
|
||||
followEmbed.add_field(
|
||||
std::to_string(j + 1),
|
||||
"",
|
||||
true
|
||||
)
|
||||
.add_field(
|
||||
originalEmbed.title,
|
||||
originalEmbed.description,
|
||||
true
|
||||
)
|
||||
.add_field(
|
||||
"",
|
||||
""
|
||||
);
|
||||
}
|
||||
|
||||
if (j >= queuedSongs.size())
|
||||
{
|
||||
followEmbed.set_timestamp(time(0));
|
||||
if (Bot->repeat)
|
||||
followEmbed.add_field(":repeat:","");
|
||||
}
|
||||
|
||||
dpp::message followMsg;
|
||||
followMsg.channel_id = event.command.channel_id;
|
||||
|
||||
followMsg.add_embed(followEmbed);
|
||||
event.from->creator->message_create(followMsg);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
#include <Commands/Repeat.hpp>
|
||||
#include <dpp/dpp.h>
|
||||
#include <string>
|
||||
|
||||
commands::Repeat::Repeat(dpp::snowflake botID, BumbleCeepp* Bot)
|
||||
: ICommand(botID, Bot)
|
||||
{
|
||||
dpp::slashcommand command = dpp::slashcommand("r", "반복 켜기/끄기", botID);
|
||||
|
||||
commandObjectVector.push_back(command);
|
||||
}
|
||||
|
||||
void commands::Repeat::operator()(const dpp::slashcommand_t& event) {
|
||||
|
||||
if (Bot->repeat) {
|
||||
event.reply("반복을 껐습니다.");
|
||||
Bot->repeat = false;
|
||||
}
|
||||
else {
|
||||
event.reply("반복을 켰습니다.");
|
||||
Bot->repeat = true;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
#include <Commands/Skip.hpp>
|
||||
#include <dpp/dpp.h>
|
||||
#include <string>
|
||||
|
||||
commands::Skip::Skip(dpp::snowflake botID, BumbleCeepp* Bot)
|
||||
: ICommand(botID, Bot)
|
||||
{
|
||||
dpp::slashcommand command = dpp::slashcommand("s", "현재곡 스킵", botID);
|
||||
|
||||
commandObjectVector.push_back(command);
|
||||
}
|
||||
|
||||
void commands::Skip::operator()(const dpp::slashcommand_t& event) {
|
||||
dpp::voiceconn* v = event.from->get_voice(event.command.guild_id);
|
||||
|
||||
if (!v || !v->voiceclient || !v->voiceclient->is_ready()) {
|
||||
return;
|
||||
}
|
||||
v->voiceclient->skip_to_next_marker();
|
||||
|
||||
event.reply("스킵했습니다!");
|
||||
|
||||
return;
|
||||
}
|
||||
19
src/main.cpp
19
src/main.cpp
@@ -1,19 +1,12 @@
|
||||
#include <BumbleCeepp.hpp>
|
||||
#include <dpp/nlohmann/json.hpp>
|
||||
#include <memory>
|
||||
#include <iostream>
|
||||
#include <BumbleBee.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
json configdocument;
|
||||
int main() {
|
||||
nlohmann::json configdocument;
|
||||
std::ifstream configfile("config.json");
|
||||
configfile >> configdocument;
|
||||
|
||||
std::shared_ptr<BumbleCeepp> bumbleBee = std::make_shared<BumbleCeepp>(
|
||||
configdocument["token"], configdocument["dbURL"], configdocument["user"], configdocument["password"]);
|
||||
bumbleBee::BumbleBee bot(configdocument);
|
||||
|
||||
bumbleBee->start();
|
||||
|
||||
return 0;
|
||||
bot.start();
|
||||
}
|
||||
20
src/test.py
20
src/test.py
@@ -1,20 +0,0 @@
|
||||
import yt_dlp
|
||||
import json
|
||||
import sys
|
||||
|
||||
if len(sys.argv) != 2:
|
||||
sys.exit()
|
||||
|
||||
ydl_opts = {
|
||||
'quiet': True,
|
||||
'clean_infojson': False,
|
||||
'default_search': 'ytsearch',
|
||||
'format': '251',
|
||||
'outtmpl': {'default': 'Temp/%(id)s.temp'},
|
||||
'overwrites': False,
|
||||
'writeinfojson': True }
|
||||
|
||||
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
||||
info = ydl.extract_info(sys.argv[1], download=False)
|
||||
with open("out", "w") as f:
|
||||
f.write(json.dumps(ydl.sanitize_info(info)))
|
||||
@@ -1,47 +0,0 @@
|
||||
import yt_dlp
|
||||
import sys
|
||||
import os
|
||||
import json
|
||||
|
||||
if len(sys.argv) != 2:
|
||||
sys.exit()
|
||||
|
||||
ydl_opts = {
|
||||
'quiet': True,
|
||||
'clean_infojson': False,
|
||||
'default_search': 'ytsearch',
|
||||
'format': '251',
|
||||
'outtmpl': {'default': 'Temp/%(id)s.temp'},
|
||||
'overwrites': False,
|
||||
'writeinfojson': True }
|
||||
|
||||
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
||||
info = ydl.extract_info(sys.argv[1], download=False)
|
||||
id = list()
|
||||
with open("out", "w") as f:
|
||||
f.write(json.dumps(ydl.sanitize_info(info)))
|
||||
with open("Music/Archive", "r") as f:
|
||||
ArchiveList = f.read().split("\n")
|
||||
if "entries" in info:
|
||||
if len(info["entries"]) != 0:
|
||||
for entry in info["entries"]:
|
||||
if entry["id"] not in ArchiveList:
|
||||
ydl.download(entry["webpage_url"])
|
||||
os.system("echo " + entry["id"] + " >> Music/Archive")
|
||||
os.system("yes n 2>/dev/null | ffmpeg -hide_banner -loglevel error -i \"" + "Temp/" + entry["id"] + ".temp" + "\" -c copy Music/" + entry["id"] + ".ogg")
|
||||
os.system("mv Temp/" + entry["id"] + ".temp.info.json Music/" + entry["id"] + ".info.json")
|
||||
id.append(entry["id"])
|
||||
else:
|
||||
if info["id"] not in ArchiveList:
|
||||
ydl.download(info["webpage_url"])
|
||||
os.system("echo " + info["id"] + " >> Music/Archive")
|
||||
os.system("yes n 2>/dev/null | ffmpeg -hide_banner -loglevel error -i \"" + "Temp/" + info["id"] + ".temp" + "\" -c copy Music/" + info["id"] + ".ogg")
|
||||
os.system("mv Temp/" + info["id"] + ".temp.info.json Music/" + info["id"] + ".info.json")
|
||||
id.append(info["id"])
|
||||
|
||||
os.system("rm -f Temp/*.temp")
|
||||
os.system("rm -f Temp/*.json")
|
||||
|
||||
with open("Temp/CurMusic", "w") as f:
|
||||
for item in id:
|
||||
f.write(item + "\n")
|
||||
@@ -1,54 +0,0 @@
|
||||
import sys
|
||||
|
||||
if len(sys.argv) != 2:
|
||||
sys.exit()
|
||||
|
||||
import urllib.parse
|
||||
|
||||
def uri_validator(x):
|
||||
try:
|
||||
result = urllib.parse.urlparse(x)
|
||||
return all([result.scheme, result.netloc])
|
||||
except AttributeError:
|
||||
return False
|
||||
|
||||
#URL인 경우
|
||||
if uri_validator(sys.argv[1]) == True:
|
||||
result = urllib.parse.urlparse(sys.argv[1])
|
||||
|
||||
#youtu.be짧은 주소인 경우
|
||||
if (result.netloc == 'youtu.be'):
|
||||
print(result.path[1:13])
|
||||
|
||||
#플레이리스트인 경우
|
||||
if result.path == '/playlist':
|
||||
import re, requests
|
||||
|
||||
response = requests.get("https://www.youtube.com/playlist?" + result.query)
|
||||
|
||||
pattern = re.compile('"videoId":"(.{11})"')
|
||||
|
||||
IDlist = set(pattern.findall(response.text))
|
||||
|
||||
# list_to_return = list()
|
||||
# list_to_return.append(IDlist[0])
|
||||
# list_to_return_count = 0
|
||||
# for it in range(0, len(list_to_return)):
|
||||
# if (list_to_return[list_to_return_count] == IDlist[it]):
|
||||
# continue
|
||||
# else:
|
||||
# list_to_return[list_to_return_count] = IDlist[it]
|
||||
# list_to_return_count += 1
|
||||
|
||||
for it in IDlist:
|
||||
print(it)
|
||||
#영상인 경우
|
||||
elif result.path == '/watch':
|
||||
print(result.query[2:13])
|
||||
else:
|
||||
from youtube_search import YoutubeSearch
|
||||
|
||||
results = YoutubeSearch(sys.argv[1], max_results=10).to_dict()
|
||||
|
||||
#검색 결과가 없는 경우 확인 불가
|
||||
print(results[0]["id"])
|
||||
@@ -1,19 +0,0 @@
|
||||
import yt_dlp
|
||||
import sys
|
||||
import os
|
||||
|
||||
if len(sys.argv) != 2:
|
||||
sys.exit()
|
||||
|
||||
ydl_opts = {
|
||||
'quiet': True,
|
||||
'format': '251',
|
||||
'outtmpl': {'default': 'Temp/' + sys.argv[1]},
|
||||
'writeinfojson': True
|
||||
}
|
||||
|
||||
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
||||
info = ydl.extract_info("https://www.youtube.com/watch?v=" + sys.argv[1])
|
||||
os.system("yes n 2>/dev/null | ffmpeg -hide_banner -loglevel error -i \"" + "Temp/" + sys.argv[1] + "\" -c copy Music/" + sys.argv[1] + ".ogg > /dev/null 2> /dev/null")
|
||||
os.system("mv Temp/" + sys.argv[1] + ".info.json Music/" + sys.argv[1] + ".info.json > /dev/null 2> /dev/null")
|
||||
os.system("rm -rf Temp/ > /dev/null 2> /dev/null")
|
||||
Reference in New Issue
Block a user