Skip to content

Instantly share code, notes, and snippets.

@Sv443
Last active June 15, 2021 06:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sv443/3b899d102e45badabd8a629c77b84ab9 to your computer and use it in GitHub Desktop.
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
// 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;
@Sv443
Copy link
Author

Sv443 commented Jan 18, 2021

Usage example:

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment