I've been doing a lot of work creating discord bots with the discord api through javascript with discord.js.
I am trying to create my first discord bot with python using the discord api through discord.py and with requests through requests.py.
My goal is to check status code on a site, and when a message is sent that contains "status code," it will reply with the site's status code in an embed.
Here is my code to do so:
import discord
import requests
r = requests.get('redactedurl')
test = r.status_code
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as {0}!'.format(self.user))
async def on_message(self, message):
if (message.channel.id == redacted):
if "status code" in message.content:
print('Message from {0.author}: {0.content}'.format(message))
embed = discord.Embed(color=0x00ff00)
embed.title = "test"
embed.description = '**Status Code:** {r.status_code}'
await message.channel.send(embed=embed)
client = MyClient()
client.run('redacted')
The following is a list of questions I hope anybody can answer to help me out :)
As you see here: https://gyazo.com/f6ae7082486cade72389534a05655fec, this just sends "{r.status_code}" in the embed, instead of the actual status code, what am I doing wrong?
What does it mean when i see 0 in the curly brackets. For example, can somebody explain "('Logged on as {0}!'.format(self.user))" to me? Since I'm new to python and discord.py, I am confused about this whole line. I know what the outcome is, but forgive my ignorance, is it all necessary?
In "send(embed=embed)", why can't i just put send(embed)?
Finally, is there anything else that i can do to improve the code?
Thank you so much if you're able to help!
In the line you set the embed description, outputting r.status_code
as a string instead of the value it contains. Try embed.description = '**Status Code:** {0}'.format(r.status_code)
The 0 resembles the index of the value that is supposed to be there. For example, '{1}'.format(10, 20)
would print out the value at index 1 which in this case is 20.
When you use send(embed)
then the bot will end up sending the embed in string form which will look very off, if you try sending it you will see what I mean. In this case, we have to specify which argument we are assigning the value to. This function accepts kwargs
which are Keyworded arguments, in this case, embed is one of the kwargs
in this send()
function. This function accepts other kwargs
as well such as content, tts, delete_after, etc.
It is all documented.
You can simplify creating the embed by passing in the kwargs
, for example: discord.Embed(title='whatever title', color='whatever color')
The discord.Embed()
can support more arguments if you look at the documentation.
Here is a link to the documentation: https://discordpy.readthedocs.io/en/latest/index.html
If you search for TextChannel
, and look for the send()
function, you can find more arguments supported, as well as for discord.Embed()
.