Answer the question
In order to leave comments, you need to log in
How to display an error in the chat?
Hello, I am writing a music bot, I ran into the problem of finding lyrics for songs. the essence is what - a person writes a command and the name of the song, the bot gives out the text, but there are also cases when the bot cannot recognize the name of the song or just written characters from the bullshit and now I sit and think how to display an error about it. Who knows tell me please.
The code:
@commands.command()
async def lyrics(self, ctx,*, title):
url = f"https://some-random-api.ml/lyrics?title={title}"
response = requests.get(url)
json_data = json.loads(response.content)
lyrics = json_data['lyrics']
try:
if len(lyrics) > 2048:
em = discord.Embed(title=title,description = f"Я не смог отправить текст этой песни, поскольку он превышает 2000 символов. Однако вот файл с текстами песен!",color=0xa3a3ff)
await ctx.send(embed=em)
file = open("lyrics.txt", "w")
file.write(lyrics)
file.close()
return await ctx.send(file=discord.File("lyrics.txt"))
else:
em = discord.Embed(title=title,description=lyrics,color=0xa3a3ff)
await ctx.send(embed=em)
except KeyError:
em = discord.Embed(title="Вот блин!",description="Мне не удалось найти текст этой песни.",color = 0xa3a3ff)
em.set_thumbnail(url='https://cdn.discordapp.com/attachments/830818408550629407/839555682436251698/aw_snap_large.png')
await ctx.send(embed=em)
Answer the question
In order to leave comments, you need to log in
If you use someone else's API, then you should look at the doc, what is returned in case of failure (well, or just try it yourself). Most likely either 4XX/5XX statuses or conditional {"success": "false"}
. Next, you already check the status code, or something in the body of the response. It will be right.
For your code to work, delete KeyError
, it is unlikely that such a view is called at all with such an
upd code: oh, nifiga to yourself, some-random-api
not a stub, but a real site)
As it should, 500 errors.
@commands.command()
async def lyrics(self, ctx,*, title):
url = f"https://some-random-api.ml/lyrics?title={title}"
req = requests.get(url)
response = req.json()
if req.status_code == 200:
lyrics = response['lyrics']
if len(lyrics) > 2048:
em = discord.Embed(title=title,description = f"Я не смог отправить текст этой песни, поскольку он превышает 2000 символов. Однако вот файл с текстами песен!",color=0xa3a3ff)
await ctx.send(embed=em)
with open('lyrics.txt', 'w', encoding='utf-8') as f:
f.write(lyrics)
await ctx.send(file=discord.File('lyrics.txt'))
else:
em = discord.Embed(title=title,description=lyrics,color=0xa3a3ff)
await ctx.send(embed=em)
elif req.status_code == 500:
error = response.get('error', '?')
if error == 'Sorry I couldn\'t find that song\'s lyrics':
em = discord.Embed(title="Вот блин!",description="Мне не удалось найти текст этой песни.",color = 0xa3a3ff)
em.set_thumbnail(url='https://cdn.discordapp.com/attachments/830818408550629407/839555682436251698/aw_snap_large.png')
await ctx.send(embed=em)
elif error == 'Something went wrong with fetching the lyrics':
# тут что-то отвалилось, 500 код как он есть, можно попробовать запрос еще раз отправить на сайт,
# либо сказать пользователю что на сайте проблемы, пусть еще раз попробует
pass
else:
em = discord.Embed(title="Вот блин!", description=f"Неизвестная ошибка: {error}",color = 0xa3a3ff)
em.set_thumbnail(url='https://cdn.discordapp.com/attachments/830818408550629407/839555682436251698/aw_snap_large.png')
await ctx.send(embed=em)
else:
# ну тут уже бог знает что случилось, сайт ни ошибкой, ни хорошим ответом не порадовал.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question