Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save voiding/b1e6ed00c25b393116f4d364c9359aac to your computer and use it in GitHub Desktop.
Save voiding/b1e6ed00c25b393116f4d364c9359aac to your computer and use it in GitHub Desktop.
Some people just don't know how to keep their bot's token private, smh people. Here's a guide that'll hopefully help.

Okay so you've probably considered making your bot open-source and that's fine but there's one thing EVERYONE should note before pushing their current progress to GitHub:

HIDE YOUR TOKENS. THESE ARE A KEY TO LOGGING IN AND INTERACTING WITH THE DISCORD API. DON'T GIVE IT TO ANYONE YOU DON'T TRUST, LET ALONE GITHUB.

  1. Create a config file (JSON is frequently used for bot configs, YAML also works) in the root (root meaning the base of the folder) of your bot folder.
    I'll use JSON to demonstrate:

Make a file called config.json
Put the following in your file:

{
  "token": "YOUR_BOTS_TOKEN"
}
  1. Create a file on your repo called .gitignore, anything in this file (directory (folder) or file) will be ignored when pushing your code
  2. Add config.json to the .gitignore file
  3. Push your code! No more leaked tokens, yay!

As a sidenote, this is how you'd utilize your newly-made config file:
(JavaScript used in example below, works for any language that supports JSON)

// Basic bot that utilizes the configuration file
const Discord = require('discord.js');
const client = new Discord.Client();
const config = require('./config.json');
// You could also use the following:
// const { token } = require('./config.json');
// client.login(token);
// Either works

client.on('ready', () => {
  console.log('I am ready');
});

client.on('message', msg => {
  if(msg.content === 'ping') {
    msg.reply('pong');
  }
});

client.login(config.token); // Logs in with the token you specified in config.json

Storing your bot's token as an environment variable also works

NEW Official repository for this Gist: https://github.com/missingbinaries/protecting-bot-tokens

Copy link

ghost commented Aug 16, 2022

any clues on how to do this with python?

@voiding
Copy link
Author

voiding commented Aug 16, 2022

any clues on how to do this with python?

Import the json library and use:

# Opens the file in read-only mode and assigns the contents to the variable cfg to be accessed further down
with open('config.json', 'r') as cfg:
  # Deserialize the JSON data (essentially turning it into a Python dictionary object so we can use it in our code) 
  data = json.load(cfg) 

Then, where you'd normally log in, replace your token string with: data["token"]. And as stated in the original gist, add that config.json file to your gitignore.

Addendum: I forgot I had this, haha - never thought it'd prove useful to anyone. Glad you found it useful though!

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