Last active
June 15, 2021 06:51
-
-
Save Sv443/3b899d102e45badabd8a629c77b84ab9 to your computer and use it in GitHub Desktop.
[Node.js] Get all currently available location IDs and names of the Discord servers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// By Sv443 ( https://github.com/Sv443 ) - licensed under the WTFPL license | |
// | |
// !>> To use this, you need to install the package "xmlhttprequest" <<! | |
// !>> Also, set the environment variable "BOT_TOKEN" to your Discord API token <<! | |
// | |
// API reference: https://discordapp.com/developers/docs/resources/voice#list-voice-regions | |
const { XMLHttpRequest } = require("xmlhttprequest"); | |
module.exports.locations = []; | |
/** | |
* @typedef {object} DiscordLocation | |
* @prop {string} id The ID of the location - something like "europe" or "us-east" | |
* @prop {string} name The name of the location - something like "Europe" or "US East" | |
*/ | |
/** | |
* Calls the Discord API to get all the server locations and exposes the variable `locations` after the Promise has resolved | |
* @returns {Promise<DiscordLocation[], string>} Resolves with the locations array or rejects with an error message | |
*/ | |
function init() | |
{ | |
return new Promise((resolve, reject) => { | |
const locations = []; | |
let xhr = new XMLHttpRequest(); | |
xhr.open("GET", "https://discordapp.com/api/voice/regions"); | |
xhr.setRequestHeader("Authorization", `Bot ${process.env.BOT_TOKEN}`); | |
xhr.onreadystatechange = () => { | |
if(xhr.readyState === 4) | |
{ | |
if(xhr.status < 300) | |
{ | |
const resp = JSON.parse(xhr.responseText.toString()); | |
resp.forEach(itm => { | |
if(!itm.deprecated) | |
{ | |
locations.push({ | |
id: itm.id, | |
name: itm.name | |
}); | |
} | |
}); | |
module.exports.locations = locations; | |
return resolve(locations); | |
} | |
else return reject(`Error ${xhr.status} - ${JSON.parse(xhr.responseText.toString()).message}`); | |
} | |
} | |
xhr.send(); | |
}); | |
} | |
module.exports.init = init; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage example: