Skip to content

Commit

Permalink
🎉 Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
noowz committed Aug 13, 2024
0 parents commit ea10d40
Show file tree
Hide file tree
Showing 13 changed files with 433 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
pnpm-lock.yaml
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -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.
77 changes: 77 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -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)

---

<p align="center">
<a href="#-about">About</a> |
<a href="#%EF%B8%8F-preview">Preview</a> |
<a href="#%EF%B8%8F-installation">Installation</a> |
<a href="#-how-to-use">How to use</a> |
<a href="#-contribute">Contribute</a> |
<a href="#-license">License</a> |
<a href="#-disclaimer">Disclaimer</a> |
</p>

---

## **📙 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).
47 changes: 47 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -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"
}
}
15 changes: 15 additions & 0 deletions src/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"auth": {
"discord": {
"client_id": "839894528953810944"
},
"brawlstars": {
"token": "YOUR API KEY"
}
},
"settings": {
"user": {
"player_tag": "YOUR PLAYER TAG"
}
}
}
15 changes: 15 additions & 0 deletions src/events/ready.js
Original file line number Diff line number Diff line change
@@ -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;
26 changes: 26 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -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();
91 changes: 91 additions & 0 deletions src/rpc/rpc.js
Original file line number Diff line number Diff line change
@@ -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 };
28 changes: 28 additions & 0 deletions src/utils/handlers.js
Original file line number Diff line number Diff line change
@@ -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 };
35 changes: 35 additions & 0 deletions src/utils/logger.js
Original file line number Diff line number Diff line change
@@ -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 };
Loading

0 comments on commit ea10d40

Please sign in to comment.