So I have a discord bot and I am trying to make it send a message depending on the response give from the request
@commands.command()
async def ttcheck(self, ctx, msg):
url = requests.get(f"https://www.tiktok.com/@{msg}")
print(url)
if url == "<Response [404]>":
await ctx.send("Name is not taken go get it!")
elif url == "<Response [200]>":
await ctx.send("Name is taken")
I even have the print(url) to check the console and I am getting the response 200 & 400 but for some reason it will not send the message when the correct response is given. Any clue why?
Also nothing is showing up in the console except for the response.
CodePudding user response:
A few things:
- As an advice, you shouldn't call
urlto the variable that stores the return value fromrequests.getsince that represents the response from the request, not an url. - When you execute
print(url)what you are seeing is the representation as string of the response object, but that object is not a string. If you doprint(type(url))you will see it's a requests.models.Response, and since that's the case, you can't make a comparison to a string like you are doing inurl == "<Response [404]>". - One way to accomplish what you want is to use the property
status_codefrom the response object and build the conditions likeresponse.status_code == 200andresponse.status_code == 400. This will fix the problem since the conditions you have now are not correctly checking the response status code.
CodePudding user response:
Get returns a response object, you need to access the status code, using r.status_code, you are comparing as a string and hence it doesn't pass the if conditional check.
Change like so,
if r.status_code == 200: ...
