How do I run my discord.py bot without a hardcoded token?
Question:
I have been coding a discord bot for a while now, but have not figured out how to load my bot’s token from somewhere else than by bot’s python file. I’d want to use a text file (config.txt) for this, but anything of the sort works.
I have python 3.11.1 if that matters 😀
imports blahblah
intents blahblah
...
client.run('token here')
Answers:
What you want to look into is environment variables.
Environments can be your local development environment, where you are obviously working at the moment, and there can be a staging environment, which is an environment that is like your production environment so you can see how your application behaves in a none local environment, which is important to know before you push it to production.
To use environment variables, the standard library in Python is, e.g. os
from os import getenv
With the getenv
method, you can get the value of an environment variable, which needs to be populated in your current environment before you can call them.
Calling your token could look like this:
getenv("TOKEN")
This only can work if you before running something like
$ export TOKEN='token here'
in your Terminal.
Found a better solution on my own:
to your imports add
import json
add this code
with open("./config.json") as config:
configData = json.load(config)
token = configData["Token"]
to the bottom
client.run(token)
this is the config.json
{"Token": "token here"}
I have been coding a discord bot for a while now, but have not figured out how to load my bot’s token from somewhere else than by bot’s python file. I’d want to use a text file (config.txt) for this, but anything of the sort works.
I have python 3.11.1 if that matters 😀
imports blahblah
intents blahblah
...
client.run('token here')
What you want to look into is environment variables.
Environments can be your local development environment, where you are obviously working at the moment, and there can be a staging environment, which is an environment that is like your production environment so you can see how your application behaves in a none local environment, which is important to know before you push it to production.
To use environment variables, the standard library in Python is, e.g. os
from os import getenv
With the getenv
method, you can get the value of an environment variable, which needs to be populated in your current environment before you can call them.
Calling your token could look like this:
getenv("TOKEN")
This only can work if you before running something like
$ export TOKEN='token here'
in your Terminal.
Found a better solution on my own:
to your imports add
import json
add this code
with open("./config.json") as config:
configData = json.load(config)
token = configData["Token"]
to the bottom
client.run(token)
this is the config.json
{"Token": "token here"}