Search code examples
herokudiscord.pyapi-key

How can I safely hide my discord bot API key using Heroku?


To Give Some Background: I have been working on a very simple discord bot in python for a while. It was run on my computer, and I had used been using a python file called config.py (Stored in a .gitignore) to keep my API key secret:

from config import * #retrieve file and it's variables
bot.run(api_key)

Then, as my bot progressed, I looked into Heroku, to host my bot 24/7 without having to run it on my own computer.
However, Heroku was connected to my Github, and because of my .gitignore file, my Heroku app was unable to retrieve the API variable.

Is there any way I can let my Heroku app retrieve my API key, without it being published on my Repository?
Thanks so much!

-mficco


Solution

  • There are many methods.

    Using configparser will be in repo

    in your code it should be like this

    from configparser import ConfigParser
    
    config = ConfigParser()
    config.read("config.ini")
    
    token = ["BOT"]["NAMEHERE]
    

    Your config.ini file in the same directory, you can skip the [BOT] but just to organize if your have more then one thing

    [BOT]
    NAMEHERE = abjigaoi1654165
    

    keep in mind you have to include the file above in the repo.

    Other method using Heroku environment variable.

    You can also edit config vars from your app’s Settings tab in the Heroku Dashboard add a BOT_TOKEN then import it as follows.

    import os
    token = os.environ.get('BOT_TOKEN')