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..bdab150 --- /dev/null +++ b/README.md @@ -0,0 +1,77 @@ +![BSRPC](https://socialify.git.ci/noowz/BSRPC/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** + +**BSRPC** is a Discord Rich Presence that shows on your profile your Brawl Stars statistics. + +--- + +## **πŸ–ΌοΈ Preview** + +![Discord RPC](https://i.imgur.com/mKPDkoU.png) + +--- + +## **βš’οΈ Installation** + +1. Download [Node.js](https://nodejs.org/en/download/prebuilt-installer). +2. Download [BSRPC](https://github.com/noowz/BSRPC/releases/latest). + +--- + +## **πŸš€ How to use** + +1. Open **Brawl Stars** and follow the steps to get your player tag: + + ![Brawl Stars Player Tag](https://i.imgur.com/wnNhtJW.gif) + +2. Go to the `config.json` file and replace **YOUR PLAYER TAG** with your Brawl Stars player tag. +3. Go to the [Brawl Stars API Dashboard](https://developer.brawlstars.com) and create an account or log in to your account. +4. Create a [new API key](https://developer.brawlstars.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 Terminal and go to the folder 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/BSRPC/issues) before opening a new one. + +If you know how to fix an [issue](https://github.com/noowz/BSRPC/issues), consider opening a [pull request](https://github.com/noowz/BSRPC/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..57d0371 --- /dev/null +++ b/package.json @@ -0,0 +1,47 @@ +{ + "name": "bsrpc", + "version": "1.0.0", + "description": "Discord Rich Presence that shows on your profile your Brawl Stars statistics.", + "main": "src/index.js", + "scripts": { + "start": "node ." + }, + "keywords": [ + "discord", + "discordapp", + "rpc", + "discord-js", + "supercell", + "djs", + "rich-presence", + "brawl-stars", + "supercell-brawl-stars", + "brawl-stars-api" + ], + "author": { + "name": "Noowz", + "email": "danieeel.dev@gmail.com", + "url": "https://github.com/noowz" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/noowz/BSRPC" + }, + "bugs": { + "url": "https://github.com/noowz/BSRPC/issues" + }, + "homepage": "https://github.com/noowz/BSRPC#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..2185861 --- /dev/null +++ b/src/config.json @@ -0,0 +1,15 @@ +{ + "auth": { + "discord": { + "client_id": "839894528953810944" + }, + "brawlstars": { + "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..1c7aaf1 --- /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.brawlstars.com/v1/players/%23${settings.user.player_tag.replace("#", "")}`, + headers: { + "Authorization": `Bearer ${auth.brawlstars.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.brawlstars.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.brawlstars.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(`Brawl Stars 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.brawlstars" + }); + + client.request("SET_ACTIVITY", { + pid: process.pid, + activity: { + details: `πŸ† Trophies: ${player.trophies}/${player.highestTrophies}`, + state: `πŸ₯Š 3v3 Wins: ${player["3vs3Victories"]} β€’ πŸ‘€ Solo Wins: ${player.soloVictories} β€’ πŸ‘₯ Duo Wins: ${player.duoVictories}`, + timestamps: { + start: startDate + }, + assets: { + large_image: app.icon, + large_text: `${name.toUpperCase()} v${version}`, + small_image: `https://cdn-old.brawlify.com/profile/${player.icon.id}.png`, + 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..b94febd --- /dev/null +++ b/src/utils/verifyConfig.js @@ -0,0 +1,24 @@ +const { auth, settings } = require("../config.json"); +const { logErrorAndExit, getNumberInString } = require("./utils.js"); + +const BSRPC_CLIENT_ID = "839894528953810944"; + +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 !== BSRPC_CLIENT_ID) { + logErrorAndExit(`The provided Discord client ID does not match the required BSRPC client ID. Update the 'client_id' field in the config file to ${BSRPC_CLIENT_ID}.`); + }; + + if (!auth.brawlstars.token || auth.brawlstars.token === "YOUR API KEY") { + logErrorAndExit("No Brawl Stars API key provided. Please update the 'token' field in the config file with your Brawl Stars API key."); + }; + + if (!settings.user.player_tag || settings.user.player_tag === "YOUR PLAYER TAG") { + logErrorAndExit("No Brawl Stars player tag provided. Please update the 'player_tag' field in the config file with your Brawl Stars player tag."); + }; +}; + +module.exports = { verifyConfig }; \ No newline at end of file