Initialize Discord Bot
Last updated
Last updated
You will be creating the code that will make your bot startup and output a startup message.
You will need to create an environment variable to house your Discord bot's token. This token is what tells the Discord API which Discord bot is yours. Keep your token a secret, as it can allow others to take control of your bot. This is why we will be storing it in an environment variable.
Head back to the Discord developer page where you created the bot. Under the bot tab click "COPY" under the token header.
Now head back to your Repl, and select the lock icon on the left side. This is where you can add, delete, or edit your environment variables. Set the key as "token" and set the value as the token you copied and select "Add New Secret".
Now you will need to reference this token in your code. This is an example of a variable.
The word inside the brackets and quotes indicates the key of the environment variable. The os.environ will retrieve the token for the specified key and store it to the token variable.
To create a connection to the Discord API you need to create a client, this is what is doing the communicating. You can name "client" anything you want, but for now keep it as client as it will easier to follow along with the rest of the sushi card. Client will now be how you reference the connection, either to start it or to get information from it.
In between the parenthesis you can set specific settings for your client, such as the prefix for the command and if there is case sensitivity.
This is an example of a variable.
When the bot has finished setting up and connecting to the Discord API, it will fire an event. When using the @client.event handler, whenever an event happens, it will check the code following the event handler. If the event is defined as onready the code after that will fire, in this case, printing "The Discord bot is up!" to the console. There a bunch of different events that can happen, such as on_message, on_message_delete, etc. You will be using events like these in the future.
Now we need to actually start the Discord bot. At the current moment it's not doing anything. Using the client variable we established before, we can start the bot by giving it the bot token, so Discord knows which bot to start up and what bot we are controlling. You can do this by adding the following code to the bottom of your Repl.
Now press the green run button on the top of your Repl. You should see "The Discord bot is up!" be printed into your console. Now if you look at your Discord server, the bot account should be online and on the right hand side of the your screen you should see something like this:
Your code should look something like the following at this point in the sushi card:
If your code is not like this or is not working, please read through the sushi card again OR ask a mentor for guidance.