From 084895af50d27e1f72d93a0f14a3c6a77fb4d5ae Mon Sep 17 00:00:00 2001 From: Noowz Date: Tue, 13 Aug 2024 02:47:56 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=89=20Initial=20commit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 2 + LICENSE | 21 +++++++++ README.md | 77 +++++++++++++++++++++++++++++++ package.json | 47 +++++++++++++++++++ src/config.json | 15 ++++++ src/events/ready.js | 15 ++++++ src/index.js | 26 +++++++++++ src/rpc/rpc.js | 91 +++++++++++++++++++++++++++++++++++++ src/utils/handlers.js | 28 ++++++++++++ src/utils/logger.js | 35 ++++++++++++++ src/utils/updateNotifier.js | 39 ++++++++++++++++ src/utils/utils.js | 13 ++++++ src/utils/verifyConfig.js | 24 ++++++++++ 13 files changed, 433 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 package.json create mode 100644 src/config.json create mode 100644 src/events/ready.js create mode 100644 src/index.js create mode 100644 src/rpc/rpc.js create mode 100644 src/utils/handlers.js create mode 100644 src/utils/logger.js create mode 100644 src/utils/updateNotifier.js create mode 100644 src/utils/utils.js create mode 100644 src/utils/verifyConfig.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f52e6f5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +node_modules +pnpm-lock.yaml \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..464df56 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Noowz + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..f50066a --- /dev/null +++ b/README.md @@ -0,0 +1,77 @@ +![CRRPC](https://socialify.git.ci/noowz/CRRPC/image?description=1&forks=1&issues=1&language=1&name=1&owner=1&pattern=Solid&pulls=1&stargazers=1&theme=Auto) + +--- + +

+ About | + Preview | + Installation | + How to use | + Contribute | + License | + Disclaimer | +

+ +--- + +## **πŸ“™ About** + +**CRRPC** is a Discord Rich Presence that shows on your profile your Clash Royale statistics. + +--- + +## **πŸ–ΌοΈ Preview** + +![Discord RPC](https://i.imgur.com/c0YGSaz.png) + +--- + +## **βš’οΈ Installation** + +1. Download [Node.js](https://nodejs.org/en/download/prebuilt-installer). +2. Download [CRRPC](https://github.com/noowz/CRRPC/releases/latest). + +--- + +## **πŸš€ How to use** + +1. Open **Clash Royale** and follow the steps to get your player tag: + + ![Clash Royale Player Tag](https://i.imgur.com/u8s9nAf.gif) + +2. Go to the `config.json` file and replace **YOUR PLAYER TAG** with your Clash Royale player tag. +3. Go to the [Clash Royale API Dashboard](https://developer.clashroyale.com) and create an account or log in to your account. +4. Create a [new API key](https://developer.clashroyale.com/#/new-key). You will need to allow your IP Address. To find out your IP Address, [click here](https://nordvpn.com/what-is-my-ip). +5. Go to the `config.json` file and replace **YOUR API KEY** with your API key. +6. Open the CMD/Terminal and go to the place where you saved the files with the `cd` command. +7. Install all the required dependencies: + + ```cmd + npm install + ``` + +8. Run the RPC: + + ```cmd + node . + ``` + +--- + +## πŸ› **Contribute** + +If you have a bug or an idea, browse the open [issues](https://github.com/noowz/CRRPC/issues) before opening a new one. + +If you know how to fix an [issue](https://github.com/noowz/CRRPC/issues), consider opening a [pull request](https://github.com/noowz/CRRPC/pulls) for it. + +--- + +## πŸ“ **License** + +This project is licensed under the [MIT](./LICENSE) license. + +--- + +## πŸ“Œ **Disclaimer** + +> This material is unofficial and is not endorsed by Supercell. For more information see Supercell's Fan Content Policy: [Supercell’s Fan Content Policy](https://supercell.com/fan-content-policy). diff --git a/package.json b/package.json new file mode 100644 index 0000000..792dfc4 --- /dev/null +++ b/package.json @@ -0,0 +1,47 @@ +{ + "name": "crrpc", + "version": "1.0.0", + "description": "Discord Rich Presence that shows on your profile your Clash Royale statistics.", + "main": "src/index.js", + "scripts": { + "start": "node ." + }, + "keywords": [ + "discord", + "discordapp", + "rpc", + "clash-royale", + "discord-js", + "supercell", + "clash-royale-api", + "djs", + "rich-presence", + "supercell-clash-royale" + ], + "author": { + "name": "Noowz", + "email": "danieeel.dev@gmail.com", + "url": "https://github.com/noowz" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/noowz/CRRPC" + }, + "bugs": { + "url": "https://github.com/noowz/CRRPC/issues" + }, + "homepage": "https://github.com/noowz/CRRPC#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/noowz" + } + ], + "dependencies": { + "axios": "^1.7.3", + "chalk": "^4.1.2", + "discord-rpc": "^4.0.1", + "google-play-scraper": "^9.2.0" + } +} \ No newline at end of file diff --git a/src/config.json b/src/config.json new file mode 100644 index 0000000..4a436c4 --- /dev/null +++ b/src/config.json @@ -0,0 +1,15 @@ +{ + "auth": { + "discord": { + "client_id": "844279952387866674" + }, + "clashroyale": { + "token": "YOUR API KEY" + } + }, + "settings": { + "user": { + "player_tag": "YOUR PLAYER TAG" + } + } +} \ No newline at end of file diff --git a/src/events/ready.js b/src/events/ready.js new file mode 100644 index 0000000..f56e36c --- /dev/null +++ b/src/events/ready.js @@ -0,0 +1,15 @@ +const { rpc } = require("../rpc/rpc.js"); + +const ready = { + name: "ready", + + async execute(client) { + rpc(client); + + setInterval(() => { + rpc(client); + }, 60000); + } +}; + +module.exports = ready; \ No newline at end of file diff --git a/src/index.js b/src/index.js new file mode 100644 index 0000000..4e06051 --- /dev/null +++ b/src/index.js @@ -0,0 +1,26 @@ +const { auth } = require("./config.json"); +const { logger } = require("./utils/logger.js"); +const { updateNotifier } = require("./utils/updateNotifier.js"); +const { verifyConfig } = require("./utils/verifyConfig.js"); +const { eventsHandler } = require("./utils/handlers.js"); +const { Client } = require("discord-rpc"); + +const client = new Client({ transport: "ipc" }); + +async function initializeClient() { + try { + await updateNotifier(); + await verifyConfig(); + await eventsHandler(client); + + await client.login({ + clientId: auth.discord.client_id + }).then(() => { + logger.info("RPC connected to Discord!"); + }); + } catch (error) { + logger.error(error); + }; +}; + +initializeClient(); \ No newline at end of file diff --git a/src/rpc/rpc.js b/src/rpc/rpc.js new file mode 100644 index 0000000..28b6b4a --- /dev/null +++ b/src/rpc/rpc.js @@ -0,0 +1,91 @@ +const { name, version, bugs, repository } = require("../../package.json"); +const { auth, settings } = require("../config.json"); +const { logger } = require("../utils/logger.js"); +const axios = require("axios"); +const gplay = require("google-play-scraper"); + +let firstTimeRunningRPC = true; +let startDate; + +if (firstTimeRunningRPC) { + startDate = Date.now(); +} else { + startDate = startDate; +}; + +const rpc = async function setActivity(client) { + const response = await axios({ + method: "GET", + url: `https://api.clashroyale.com/v1/players/%23${settings.user.player_tag.replace("#", "")}`, + headers: { + "Authorization": `Bearer ${auth.clashroyale.token}`, + "Content-Type": "application/json", + "User-Agent": `${name.toUpperCase()}/${version}` + } + }).catch(error => { + if (error.response.status === 400) { + logger.error(`The Client is providing incorrect parameters for the request. Report this at ${bugs.url} !`); + logger.error(`ERROR: ${error.response.status} - ${error.response.statusText} (${error.response.data.reason})`); + } else if (error.response.status === 403 && error.response.data.reason === "accessDenied") { + logger.error(`You provided an invalid API key. Check if it is correct in the config file, or go to https://developer.clashroyale.com/#/new-key to create a new one.`); + logger.error(`ERROR: ${error.response.status} - ${error.response.statusText} (${error.response.data.reason})`); + } else if (error.response.status === 403 && error.response.data.reason === "accessDenied.invalidIp") { + logger.error(`The API key does not allow access for your IP. Check if your IP is in the list of authorized IPs to access the API with your API key at https://developer.clashroyale.com/#/account. To check your IP, go to https://nordvpn.com/what-is-my-ip !`); + logger.error(`ERROR: ${error.response.status} - ${error.response.statusText} (${error.response.data.reason})`); + } else if (error.response.status === 404) { + logger.error(`You provided an invalid player tag. Check if it is correct in the config file.`); + logger.error(`ERROR: ${error.response.status} - ${error.response.statusText} (${error.response.data.reason})`); + } else if (error.response.status === 429) { + logger.error(`The API is at its maximum capacity. Please, try again later!`); + logger.error(`ERROR: ${error.response.status} - ${error.response.statusText} (${error.response.data.reason})`); + } else if (error.response.status === 500) { + logger.error(`An unknown error happened when handling the request. Please, try again! If the error persists, please try again later!`); + logger.error(`ERROR: ${error.response.status} - ${error.response.statusText} (${error.response.data.reason})`); + } else if (error.response.status === 503) { + logger.error(`Clash Royale is currently under maintenance, so it is not possible to access the API. Wait for the maintenance to finish before you can access the API.`); + logger.error(`ERROR: ${error.response.status} - ${error.response.statusText} (${error.response.data.reason})`); + } else { + logger.error(`An error has occurred. Report this at ${bugs.url} !`); + logger.error(`ERROR: ${error.response.status} - ${error.response.statusText} (${error.response.data.reason})`); + }; + + process.exit(0); + }); + + const player = await response.data; + + const app = await gplay.app({ + appId: "com.supercell.clashroyale" + }); + + client.request("SET_ACTIVITY", { + pid: process.pid, + activity: { + details: `⭐ Level: ${player.expLevel} β€’ πŸ† Trophies: ${player.trophies}/${player.bestTrophies}`, + state: `πŸ›• Arena: ${player.arena.name} β€’ πŸ₯Š Wins: ${player.wins}`, + timestamps: { + start: startDate + }, + assets: { + large_image: app.icon, + large_text: `${name.toUpperCase()} v${version}`, + small_image: "player", + small_text: `${player.name} (${player.tag})` + }, + buttons: [ + { + label: "πŸš€ Download", + url: repository.url + } + ] + } + }).catch(error => { + logger.error(error); + + process.exit(0); + }); +}; + +firstTimeRunningRPC = false; + +module.exports = { rpc }; \ No newline at end of file diff --git a/src/utils/handlers.js b/src/utils/handlers.js new file mode 100644 index 0000000..79592b5 --- /dev/null +++ b/src/utils/handlers.js @@ -0,0 +1,28 @@ +const { logger } = require("../utils/logger.js"); +const { join } = require("node:path"); +const { readdirSync } = require("node:fs"); +const chalk = require("chalk"); + +async function eventsHandler(client) { + const eventsPath = join(__dirname, "../events"); + const eventFiles = readdirSync(eventsPath).filter(file => file.endsWith(".js")); + + let index = 0; + + for (const file of eventFiles) { + index++; + + const filePath = join(eventsPath, file); + const event = require(filePath); + + if (event.once) { + client.once(event.name, (...args) => event.execute(client, ...args)); + } else { + client.on(event.name, (...args) => event.execute(client, ...args)); + }; + + logger.info(`Loaded ${chalk.yellowBright(file.slice(0, -3))} event ${chalk.bold.white(`(${index}/${eventFiles.length})`)}!`); + }; +}; + +module.exports = { eventsHandler }; \ No newline at end of file diff --git a/src/utils/logger.js b/src/utils/logger.js new file mode 100644 index 0000000..0552998 --- /dev/null +++ b/src/utils/logger.js @@ -0,0 +1,35 @@ +const chalk = require("chalk"); + +const levels = { + debug: chalk.bold.blueBright, + info: chalk.bold.cyanBright, + warn: chalk.bold.hex("#F0AD4E"), + error: chalk.bold.redBright, + fatal: chalk.bold.red +}; + +function logMessage(level, message) { + const logColor = levels[level]; + const logDate = chalk.gray(`[${new Date().toLocaleDateString()} - ${new Date().toLocaleTimeString()}]`); + const logLevel = `[${level.toUpperCase()}]`; + + if (level === "debug") { + return console.debug(logColor(`${logDate} ${logLevel}`), message); + } else if (level === "info") { + return console.info(logColor(`${logDate} ${logLevel}`), message); + } else if (level === "warn") { + return console.warn(logColor(`${logDate} ${logLevel}`), message); + } else if (level === "error" || level === "fatal") { + return console.error(logColor(`${logDate} ${logLevel}`), message); + }; +}; + +const logger = { + debug: (message) => logMessage("debug", message), + info: (message) => logMessage("info", message), + warn: (message) => logMessage("warn", message), + error: (message) => logMessage("error", message), + fatal: (message) => logMessage("fatal", message) +}; + +module.exports = { logger }; \ No newline at end of file diff --git a/src/utils/updateNotifier.js b/src/utils/updateNotifier.js new file mode 100644 index 0000000..f98b914 --- /dev/null +++ b/src/utils/updateNotifier.js @@ -0,0 +1,39 @@ +const { name, version, author, bugs } = require("../../package.json"); +const { logger } = require("../utils/logger.js"); +const chalk = require("chalk"); +const axios = require("axios"); + +async function updateNotifier() { + const response = await axios({ + method: "GET", + url: `https://api.github.com/repos/${author.name}/${name.toUpperCase()}/releases/latest`, + headers: { + "Content-Type": "application/json", + "User-Agent": `${name.toUpperCase()}/${version}` + } + }).catch(error => { + logger.error(`An error has occurred. Report this at ${bugs.url} !`); + logger.error(`ERROR: ${error.response.status} - ${error.response.statusText}`); + + process.exit(0); + }); + + const release = await response.data; + + const currentVersion = version; + const latestVersion = release.tag_name.replace("v", ""); + + if (currentVersion !== latestVersion) { + console.log(chalk.white("β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”")); + console.log(chalk.white("β”‚ ") + chalk.green(`πŸš€ A new version of ${name.toUpperCase()} is available!`) + " " + chalk.white("β”‚")); + console.log(chalk.white("β”‚") + " " + chalk.white("β”‚")); + console.log(chalk.white("β”‚ ") + chalk.redBright(`β€’ Current version: ${currentVersion}`) + " " + chalk.white("β”‚")); + console.log(chalk.white("β”‚ ") + chalk.greenBright(`β€’ Latest version: ${latestVersion.replace("v", "")}`) + " " + chalk.white("β”‚")); + console.log(chalk.white("β”‚") + " " + chalk.white("β”‚")); + console.log(chalk.white("β”‚ ") + chalk.blueBright(release.html_url) + " " + chalk.white("β”‚")); + console.log(chalk.white("β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜")); + console.log("\n"); + }; +}; + +module.exports = { updateNotifier }; \ No newline at end of file diff --git a/src/utils/utils.js b/src/utils/utils.js new file mode 100644 index 0000000..ff3f0a6 --- /dev/null +++ b/src/utils/utils.js @@ -0,0 +1,13 @@ +const { logger } = require("../utils/logger.js"); + +function logErrorAndExit(message) { + logger.error(message); + + process.exit(0); +}; + +function getNumberInString(string) { + return /\d/.test(string); +}; + +module.exports = { logErrorAndExit, getNumberInString }; \ No newline at end of file diff --git a/src/utils/verifyConfig.js b/src/utils/verifyConfig.js new file mode 100644 index 0000000..2413883 --- /dev/null +++ b/src/utils/verifyConfig.js @@ -0,0 +1,24 @@ +const { auth, settings } = require("../config.json"); +const { logErrorAndExit, getNumberInString } = require("./utils.js"); + +const CRRPC_CLIENT_ID = "844279952387866674"; + +async function verifyConfig() { + if (!auth.discord.client_id) { + logErrorAndExit("No Discord client ID provided. Please update the 'client_id' field in the config file with your Discord client ID."); + } else if (!getNumberInString(auth.discord.client_id)) { + logErrorAndExit("The provided Discord client ID is invalid. Ensure the 'client_id' field in the config file contains a valid numeric ID."); + } else if (auth.discord.client_id !== CRRPC_CLIENT_ID) { + logErrorAndExit(`The provided Discord client ID does not match the required CRRPC client ID. Update the 'client_id' field in the config file to ${CRRPC_CLIENT_ID}.`); + }; + + if (!auth.clashroyale.token || auth.clashroyale.token === "YOUR API KEY") { + logErrorAndExit("No Clash Royale API key provided. Please update the 'token' field in the config file with your Clash Royale API key."); + }; + + if (!settings.user.player_tag || settings.user.player_tag === "YOUR PLAYER TAG") { + logErrorAndExit("No Clash Royale player tag provided. Please update the 'player_tag' field in the config file with your Clash Royale player tag."); + }; +}; + +module.exports = { verifyConfig }; \ No newline at end of file