From dee030984f4bf44acf59d8f93c37275ee108d068 Mon Sep 17 00:00:00 2001 From: Noowz Date: Tue, 25 Jun 2024 03:53:17 +0200 Subject: [PATCH] Initial commit --- .github/CODE_OF_CONDUCT.md | 128 ++++++++++++++++++++++++++ .github/CONTRIBUTING.md | 68 ++++++++++++++ .github/FUNDING.yml | 1 + .github/ISSUE_TEMPLATE/bug-report.md | 7 ++ .github/ISSUE_TEMPLATE/question.md | 7 ++ .github/ISSUE_TEMPLATE/suggestion.md | 7 ++ .github/PULL_REQUEST_TEMPLATE.md | 0 .github/SECURITY.md | 0 .github/SUPPORT.md | 0 .github/workflows/codeql-analysis.yml | 72 +++++++++++++++ .gitignore | 2 + LICENSE | 21 +++++ README.md | 81 ++++++++++++++++ config.json | 15 +++ index.js | 30 ++++++ package.json | 56 +++++++++++ src/events/ready.js | 19 ++++ src/rpc/rpc.js | 110 ++++++++++++++++++++++ src/utils/configVerificator.js | 37 ++++++++ src/utils/handlers.js | 28 ++++++ src/utils/logger.js | 24 +++++ src/utils/utils.js | 5 + 22 files changed, 718 insertions(+) create mode 100644 .github/CODE_OF_CONDUCT.md create mode 100644 .github/CONTRIBUTING.md create mode 100644 .github/FUNDING.yml create mode 100644 .github/ISSUE_TEMPLATE/bug-report.md create mode 100644 .github/ISSUE_TEMPLATE/question.md create mode 100644 .github/ISSUE_TEMPLATE/suggestion.md create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 .github/SECURITY.md create mode 100644 .github/SUPPORT.md create mode 100644 .github/workflows/codeql-analysis.yml create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 config.json create mode 100644 index.js create mode 100644 package.json create mode 100644 src/events/ready.js create mode 100644 src/rpc/rpc.js create mode 100644 src/utils/configVerificator.js create mode 100644 src/utils/handlers.js create mode 100644 src/utils/logger.js create mode 100644 src/utils/utils.js diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..d2132f4 --- /dev/null +++ b/.github/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +danieeel.dev@gmail.com. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. \ No newline at end of file diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md new file mode 100644 index 0000000..523c5fd --- /dev/null +++ b/.github/CONTRIBUTING.md @@ -0,0 +1,68 @@ +# 🀝 Contributing Guidelines + +Thank you for considering contributing to the project! We welcome contributions from everyone, and this document will guide you through the process. + +Pull requests, bug reports, and all other forms of contribution are welcomed and highly encouraged! + +> This guide serves to set clear expectations for everyone involved with the project so that we can improve it together while also creating a welcoming space for everyone to participate. Following these guidelines will help ensure a positive experience for contributors and maintainers. + +## πŸ“š Table of Contents + +- [🀝 Contributing Guidelines](#-contributing-guidelines) + - [πŸ“š Table of Contents](#-table-of-contents) + - [πŸ€” How to Contribute](#-how-to-contribute) + - [πŸš€ Getting Started](#-getting-started) + - [πŸ“‹ Coding Guidelines](#-coding-guidelines) + - [πŸŽ‰ Submitting a Pull Request](#-submitting-a-pull-request) + - [πŸ› Reporting Issues](#-reporting-issues) + - [πŸ”’ Reporting Security Issues](#-reporting-security-issues) + - [πŸ’‘ Asking Questions](#-asking-questions) + - [πŸ“– Code of Conduct](#-code-of-conduct) + +## πŸ€” How to Contribute + +There are several ways you can contribute to the project: + +- Reporting issues +- Contributing code +- Improving documentation +- Providing feedback +- Helping others by answering questions + +## πŸš€ Getting Started + +Before you start contributing, please follow these steps: + +1. Fork the repository to your GitHub account. +2. Clone the forked repository to your local machine. +3. Create a new branch for your changes: `git checkout -b feature/your-feature`. + +## πŸ“‹ Coding Guidelines + +Please adhere to the coding guidelines and style conventions used in this project. Refer to [link to coding guidelines] for more details. + +## πŸŽ‰ Submitting a Pull Request + +When submitting a pull request, please provide the following information: + +- A clear and descriptive title. +- A detailed description of the changes made. +- Any relevant issues or links to discussions related to your changes. + +## πŸ› Reporting Issues + +If you encounter any issues or have suggestions for improvements, please [create an issue](https://github.com/noowz/BSRPC/issues). Before creating an issue, ensure that you are using the latest project version, that you have checked existing issues to avoid duplication and that you have reviewed the documentation and the [Support Guide](SUPPORT.md). + +## πŸ”’ Reporting Security Issues + +If you have found a security vulnerability, do not create an issue. Take a look at the [Security Policy](SECURITY.md). + +## πŸ’‘ Asking Questions + +If you have any questions concerning the project, take a look at the [Support Guide](SUPPORT.md). + +## πŸ“– Code of Conduct + +Please note that this project follows a [Code of Conduct](CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. Please report any unacceptable behavior to danieeel.dev@gmail.com. + +Thank you for your contributions! \ No newline at end of file diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..8a83497 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +github: noowz \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/bug-report.md b/.github/ISSUE_TEMPLATE/bug-report.md new file mode 100644 index 0000000..6cd9c2f --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug-report.md @@ -0,0 +1,7 @@ +--- +name: Bug Report +about: Create a bug report to help us improve +title: "[BUG]" +labels: bug, help wanted, invalid +assignees: noowz +--- \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md new file mode 100644 index 0000000..2384c3b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/question.md @@ -0,0 +1,7 @@ +--- +name: Question +about: Ask a question if you have any doubts. +title: "[QUESTION]" +labels: question, help wanted +assignees: noowz +--- \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/suggestion.md b/.github/ISSUE_TEMPLATE/suggestion.md new file mode 100644 index 0000000..b670c11 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/suggestion.md @@ -0,0 +1,7 @@ +--- +name: Suggestion +about: Suggest an idea for this project. +title: "[SUGGESTION]" +labels: enhancement +assignees: noowz +--- \ No newline at end of file diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..e69de29 diff --git a/.github/SECURITY.md b/.github/SECURITY.md new file mode 100644 index 0000000..e69de29 diff --git a/.github/SUPPORT.md b/.github/SUPPORT.md new file mode 100644 index 0000000..e69de29 diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml new file mode 100644 index 0000000..a6982fe --- /dev/null +++ b/.github/workflows/codeql-analysis.yml @@ -0,0 +1,72 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +# +# ******** NOTE ******** +# We have attempted to detect the languages in your repository. Please check +# the `language` matrix defined below to confirm you have the correct set of +# supported CodeQL languages. +# +name: "CodeQL" + +on: + push: + branches: [ "main" ] + pull_request: + # The branches below must be a subset of the branches above + branches: [ "main" ] + schedule: + - cron: '22 18 * * 1' + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: [ 'javascript' ] + # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] + # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v2 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + + # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs + # queries: security-extended,security-and-quality + + + # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v2 + + # ℹ️ Command-line programs to run using the OS shell. + # πŸ“š See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun + + # If the Autobuild fails above, remove it and uncomment the following three lines. + # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. + + # - run: | + # echo "Run, Build Application using script" + # ./location_of_script_within_repo/buildscript.sh + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v2 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bbacd7f --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +node_modules +bun.lockb \ 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..6fbe52a --- /dev/null +++ b/README.md @@ -0,0 +1,81 @@ +

+ + BSRPC + +

+ +--- + +

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

+ +--- + +## **πŸ“™ About** + +**BSRPC** is a custom Discord Rich Presence that shows on your profile your Brawl Stars statistics. + +--- + +## **πŸ–ΌοΈ Preview:** + +![Discord RPC](https://i.imgur.com/KehUf4x.png) + +--- + +## **βš’οΈ Installation** + +1. Download [Node.js](https://nodejs.org/en/download). +2. Download [BSRPC](https://github.com/noowz/BSRPC/archive/refs/heads/main.zip). + +--- + +## **πŸš€ How to use** + +1. Open **Brawl Stars** and follow the steps to get your Tag: + + ![Brawl Stars Player Tag](https://i.imgur.com/zaFFD4E.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 CMD/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/config.json b/config.json new file mode 100644 index 0000000..77e820a --- /dev/null +++ b/config.json @@ -0,0 +1,15 @@ +{ + "auth": { + "discord": { + "clientID": "839894528953810944" + }, + "brawlstars": { + "token": "YOUR API KEY" + } + }, + "settings": { + "user": { + "playerTag": "YOUR PLAYER TAG" + } + } +} \ No newline at end of file diff --git a/index.js b/index.js new file mode 100644 index 0000000..49510e6 --- /dev/null +++ b/index.js @@ -0,0 +1,30 @@ +const { auth } = require("./config.json"); +const logger = require("./src/utils/logger.js"); +const configVerificator = require("./src/utils/configVerificator.js"); +const { eventsHandler } = require("./src/utils/handlers.js"); +const { Client } = require("discord-rpc"); + +const client = new Client({ + transport: "ipc" +}); + +configVerificator(); +eventsHandler(client); + +process.on("uncaughtException", (error) => { + console.error(`${logger.categories.error} ${logger.messages.error(error)}`); + + process.exit(1); +}); + +process.on("unhandledRejection", (error) => { + console.error(`${logger.categories.error} ${logger.messages.error(error)}`); + + process.exit(1); +}); + +client.login({ + clientId: auth.discord.client_id +}).catch(error => { + console.error(`${logger.categories.error} ${logger.messages.error(error)}`); +}); \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..0597393 --- /dev/null +++ b/package.json @@ -0,0 +1,56 @@ +{ + "name": "bsrpc", + "version": "1.0.3", + "description": "Discord Rich Presence that shows on your profile your Brawl Stars statistics.", + "main": "index.js", + "scripts": { + "dev": "node ." + }, + "keywords": [ + "discord", + "rpc", + "discordjs", + "djs", + "brawlstars", + "brawl", + "stars", + "bs", + "brawlstarsapi", + "api", + "supercell", + "data", + "info", + "stats", + "profile", + "overview", + "javascript", + "js", + "node", + "npm" + ], + "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.2", + "chalk": "^4.1.2", + "discord-rpc": "^4.0.1" + } +} \ No newline at end of file diff --git a/src/events/ready.js b/src/events/ready.js new file mode 100644 index 0000000..4a8631f --- /dev/null +++ b/src/events/ready.js @@ -0,0 +1,19 @@ +const logger = require("../utils/logger.js"); +const rpc = require("../rpc/rpc.js"); + +const ready = { + name: "ready", + once: true, + + async execute(client) { + rpc(client); + + setInterval(() => { + rpc(client); + }, 60000); + + console.log(`${logger.categories.info} ${logger.messages.success("RPC connected to Discord!")}`); + } +}; + +module.exports = ready; \ No newline at end of file diff --git a/src/rpc/rpc.js b/src/rpc/rpc.js new file mode 100644 index 0000000..5f6b4ff --- /dev/null +++ b/src/rpc/rpc.js @@ -0,0 +1,110 @@ +const { name, version, bugs, repository } = require("../../package.json"); +const { auth, settings } = require("../../config.json"); +const logger = require("../utils/logger.js"); +const axios = require("axios"); + +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(function (error) { + if (error.response.status === 400) { + console.error(`${logger.categories.error} ${logger.messages.error(`The Client is providing incorrect parameters for the request. Report this at ${bugs.url} !`)}`); + + console.error(`${logger.categories.error} ${logger.messages.error(`ERROR: ${error.response.status} - ${error.response.statusText} (${error.response.data.reason})`)}`); + + process.exit(1); + } else if (error.response.status === 403 && error.response.data.reason === "accessDenied") { + console.error(`${logger.categories.error} ${logger.messages.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.`)}`); + + console.error(`${logger.categories.error} ${logger.messages.error(`ERROR: ${error.response.status} - ${error.response.statusText} (${error.response.data.reason})`)}`); + + process.exit(1); + } else if (error.response.status === 403 && error.response.data.reason === "accessDenied.invalidIp") { + console.error(`${logger.categories.error} ${logger.messages.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 !`)}`); + + console.error(`${logger.categories.error} ${logger.messages.error(`ERROR: ${error.response.status} - ${error.response.statusText} (${error.response.data.reason})`)}`); + + process.exit(1); + } else if (error.response.status === 404) { + console.error(`${logger.categories.error} ${logger.messages.error(`You provided an invalid player tag. Check if it is correct in the config file.`)}`); + + console.error(`${logger.categories.error} ${logger.messages.error(`ERROR: ${error.response.status} - ${error.response.statusText} (${error.response.data.reason})`)}`); + + process.exit(1); + } else if (error.response.status === 429) { + console.error(`${logger.categories.error} ${logger.messages.error(`The API is at its maximum capacity. Please, try again later!`)}`); + + console.error(`${logger.categories.error} ${logger.messages.error(`ERROR: ${error.response.status} - ${error.response.statusText} (${error.response.data.reason})`)}`); + + process.exit(1); + } else if (error.response.status === 500) { + console.error(`${logger.categories.error} ${logger.messages.error(`An unknown error happened when handling the request. Please, try again! If the error persists, please try again later!`)}`); + + console.error(`${logger.categories.error} ${logger.messages.error(`ERROR: ${error.response.status} - ${error.response.statusText} (${error.response.data.reason})`)}`); + + process.exit(1); + } else if (error.response.status === 503) { + console.error(`${logger.categories.error} ${logger.messages.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.`)}`); + + console.error(`${logger.categories.error} ${logger.messages.error(`ERROR: ${error.response.status} - ${error.response.statusText} (${error.response.data.reason})`)}`); + + process.exit(1); + } else { + console.error(`${logger.categories.error} ${logger.messages.error(`An error has occurred. Report this at ${bugs.url} !`)}`); + + console.error(`${logger.categories.error} ${logger.messages.error(`ERROR: ${error.response.status} - ${error.response.statusText} (${error.response.data.reason})`)}`); + + process.exit(1); + }; + }); + + const player = await response.data; + + 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: "https://i.imgur.com/nUjDFg9.png", + 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 => { + if (error.message === "RPC_CONNECTION_TIMEOUT") { + console.error(`${logger.categories.error} ${logger.messages.error(error)}`); + + process.exit(1); + }; + }); +}; + +firstTimeRunningRPC = false; + +module.exports = rpc; \ No newline at end of file diff --git a/src/utils/configVerificator.js b/src/utils/configVerificator.js new file mode 100644 index 0000000..18ce513 --- /dev/null +++ b/src/utils/configVerificator.js @@ -0,0 +1,37 @@ +const { auth, settings } = require("../../config.json"); +const logger = require("../utils/logger.js"); +const { getNumberInString } = require("./utils.js"); + +const configVerificator = () => { + if (!auth.discord.client_id) { + console.error(`${logger.categories.error} ${logger.messages.error("No client ID provided. Please provide a client ID.")}`); + + process.exit(1); + }; + + if (auth.discord.client_id && !getNumberInString(auth.discord.client_id)) { + console.error(`${logger.categories.error} ${logger.messages.error("The client ID provided is not valid. Please provide a valid client ID.")}`); + + process.exit(1); + }; + + if (auth.discord.client_id !== "839894528953810944") { + console.error(`${logger.categories.error} ${logger.messages.error("The client ID provided is not the BSRPC one. Please provide the BSRPC client ID by going to the config file and changing the 'client_id' value to 839894528953810944")}`); + + process.exit(1); + }; + + if (!auth.brawlstars.token || auth.brawlstars.token === "YOUR API KEY") { + console.error(`${logger.categories.error} ${logger.messages.error("No Brawl Stars API key provided. Please provide a Brawl Stars API key.")}`); + + process.exit(1); + }; + + if (!settings.user.player_tag || settings.user.player_tag === "YOUR PLAYER TAG") { + console.error(`${logger.categories.error} ${logger.messages.error("No Brawl Stars player tag provided. Please provide a Brawl Stars player tag.")}`); + + process.exit(1); + }; +}; + +module.exports = configVerificator; \ No newline at end of file diff --git a/src/utils/handlers.js b/src/utils/handlers.js new file mode 100644 index 0000000..2c0861f --- /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"); + +const eventsHandler = async (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)); + }; + + console.info(`${logger.categories.info} ${logger.messages.success(`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..8739839 --- /dev/null +++ b/src/utils/logger.js @@ -0,0 +1,24 @@ +const chalk = require("chalk"); + +const date = chalk.gray(`[${new Date().toLocaleDateString()} - ${new Date().toLocaleTimeString()}]`); + +const logger = { + categories: { + debug: chalk.bold.blueBright(`${date} [DEBUG]`), + info: chalk.bold.cyanBright(`${date} [INFO]`), + warn: chalk.bold.hex("#F0AD4E")(`${date} [WARN]`), + error: chalk.bold.redBright(`${date} [ERROR]`), + fatal: chalk.bold.red(`${date} [FATAL]`) + }, + messages: { + fail: chalk.redBright, + success: chalk.greenBright, + debug: chalk.blueBright, + info: chalk.white, + warn: chalk.hex("#F0AD4E"), + error: chalk.redBright, + fatal: chalk.red + } +}; + +module.exports = logger; \ No newline at end of file diff --git a/src/utils/utils.js b/src/utils/utils.js new file mode 100644 index 0000000..9422aa0 --- /dev/null +++ b/src/utils/utils.js @@ -0,0 +1,5 @@ +const getNumberInString = (string) => { + return /\d/.test(string); +}; + +module.exports = { getNumberInString }; \ No newline at end of file