So, I was writing a script which allows my discord bot to return lyrics after being issued command, using the lyricgenius API. However, whenever I deliberately typed in gibberish so that the bot wouldn't find the lyrics and execute the code in the AttributeError exception block, the console said the exception was ignored. I am using discord.py ver 1.01. Any ideas? Thanks in advance
def fetch_lyrics(array):
song = genius.search_song(title=array[0],artist=array[1])
return song.lyrics
@client.event
async def on_message(message):
if message.content.startswith("hello"):
await message.channel.send("hello")
if message.content.startswith("$lyrics"):
global lyrics
global searchstring
pre_search_array = message.content.split()
del pre_search_array[0]
for z in pre_search_array:
searchstring += z+" "
search_array = searchstring.split(",")
if len(fetch_lyrics(search_array)) > 2000:
pass
else :
try:
await message.channel.send(fetch_lyrics(search_array))
except AttributeError:
await message.channel.send("Could not find the song")
#resets the list
searchstring = ""
pre_search_array.clear()
search_array.clear()
Error Message:
Ignoring exception in on_message
Traceback (most recent call last):
File "/Users/kevinhadinata/Desktop/pythonProject2/venv/lib/python3.7/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "/Users/kevinhadinata/Desktop/pythonProject2/main.py", line 38, in on_message
if len(fetch_lyrics(search_array)) > 2000:
File "/Users/kevinhadinata/Desktop/pythonProject2/main.py", line 16, in fetch_lyrics
return song.lyrics
AttributeError: 'NoneType' object has no attribute 'lyrics'
Fatal read error on socket transport
protocol: <asyncio.sslproto.SSLProtocol object at 0x102ae0908>
transport: <_SelectorSocketTransport fd=11 read=polling write=<idle, bufsize=0>>
Traceback (most recent call last):
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/asyncio/selector_events.py", line 801, in _read_ready__data_received
data = self._sock.recv(self.max_size)
TimeoutError: [Errno 60] Operation timed out
You are using fetch_lyrics
(which causes the error) in len(fetch_lyrics(search_array)) > 2000:
, you have to catch that error. The direct method would be moving that to the try and except.
try:
if len(fetch_lyrics(search_array)) > 2000:
pass
except AttributeError:
print('not a valid song')
You could also raise a Custom Error in the fetch_lyrics
and catch it.