Skip to content

Instantly share code, notes, and snippets.

@jb3
Created October 22, 2018 22:54
Show Gist options
  • Save jb3/4fe9b5f0e900733eb40e92eaa6ddcc9d to your computer and use it in GitHub Desktop.
Save jb3/4fe9b5f0e900733eb40e92eaa6ddcc9d to your computer and use it in GitHub Desktop.
#include <array>
#include <cstdio>
#include <cstring>
#include <discord_rpc.h>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <thread>
/*
* Utility functions
*/
std::string exec(const char* cmd) {
std::array<char, 128> buffer;
std::string result;
std::shared_ptr<FILE> pipe(popen(cmd, "r"), pclose);
if (!pipe) throw std::runtime_error("popen() failed!");
while (!feof(pipe.get())) {
if (fgets(buffer.data(), 128, pipe.get()) != nullptr)
result += buffer.data();
}
return result;
}
std::string formatSong(std::string songName, std::string songArtist) {
if (songArtist == (std::string)"") {
return songName;
}
std::string sep = " - ";
return songName + sep + songArtist;
}
/*
* Discord Callbacks
*/
void handleDiscordReady(const DiscordUser* user) {
std::cout << "Connected to " << user->username << std::endl;
}
void handleDiscordError(int _errorCode, const char* message) {
std::cout << "Errored with error: " << message << std::endl;
}
void InitDiscord() {
DiscordEventHandlers handlers;
memset(&handlers, 0, sizeof(handlers));
handlers.ready = handleDiscordReady;
handlers.errored = handleDiscordError;
handlers.disconnected = handleDiscordError;
Discord_Initialize("503540314506657792", &handlers, 1, NULL);
}
/*
* End Discord Callbacks
*/
void presenceLoop() {
std::string current_song;
long start_time;
while (true) {
std::string song_name = exec("playerctl metadata xesam:title");
std::string artist = exec("playerctl metadata xesam:artist");
std::string song = formatSong(song_name, artist);
if (current_song != song) {
DiscordRichPresence discordPresence;
memset(&discordPresence, 0, sizeof(discordPresence));
std::cout << "NEW SONG! Updating presence.." << std::endl;
discordPresence.details = song.c_str();
discordPresence.largeImageKey = "smiley";
discordPresence.largeImageText = "Dank tunes";
Discord_UpdatePresence(&discordPresence);
current_song = song;
}
std::this_thread::sleep_for(std::chrono::seconds(3));
std::cout << "Polling..." << std::endl;
}
}
int main() {
std::cout << "Preparing to start Discord handlers..." << std::endl;
InitDiscord();
presenceLoop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment