I’m trying to make a discord bot that would repost art submissions to the art channel after they are approved by the moderators. Every time I try to extract the attachment URL, I get this error:
JavaScript
x
8
1
Ignoring exception in on_message
2
Traceback (most recent call last):
3
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
4
await coro(*args, **kwargs)
5
File "main.py", line 32, in on_message
6
url = message.attachments[0].url
7
IndexError: list index out of range
8
I tried searching this up on the Internet, but there is nothing. The only thing I found was this post, but I did everything right. Can someone explain to me what’s happening? My code:
JavaScript
1
17
17
1
@client.event
2
async def on_message(message):
3
channel = client.get_channel(#id-here)
4
channel2 = client.get_channel(#id-here)
5
artName = message.content
6
attachment = message.attachments[0]
7
print(attachment)
8
9
embed = discord.Embed(
10
title = message.content,
11
colour = discord.Colour.red()
12
)
13
14
embed.set_author(name = message.author,
15
icon_url = message.author.avatar_url)
16
embed.set_image(url = attachment)
17
Also, I tried to use message.attachments[0].url
but got the same thing
Advertisement
Answer
This can be appear for some reasons:
- Your bot don’t check for attachments at all, so if user will send messages without image in it, bot will crash
- You don’t check who sended message and where (for example, bot can reply on it’s own message or on message which isn’t from #arts-request channel)
- You should use
url
attribute, to get image url for embed
So the final code will look like this:
JavaScript
1
27
27
1
@client.event
2
async def on_message(message):
3
arts_request = client.get_channel(some_id1)
4
arts_approve = client.get_channel(some_id2)
5
6
if message.author.bot or message.channel != arts_request:
7
# Stop command if the channel isn't #arts-request or user is bot
8
return
9
10
if not message.content or message.attachments:
11
# You can use message.channel.send() if you don't want to mention user
12
await message.reply("message should contain name and image of art!")
13
14
artName = message.content
15
attachment = message.attachments[0].url
16
17
embed = discord.Embed(
18
title = message.content,
19
colour = discord.Colour.red()
20
)
21
22
embed.set_author(name = message.author,
23
icon_url = message.author.avatar_url)
24
embed.set_image(url = attachment)
25
26
await arts_approve.send(embed)
27