#python-3.x #discord #discord.py
#python-3.x #Discord #discord.py
Вопрос:
Я столкнулся с проблемой, когда каждый раз, когда кто-то отправляет сообщение, код переходит в IndexError: list index out of range
.
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = '')
bot = commands.Bot('.')
@client.event
async def on_ready():
print('Bot Online')
@client.event
async def on_message(message):
if message.author == client.user:
return
name = message.mentions[0].id
if name == usersid:
await message.channel.send('Currently missing in action')
else:
pass
client.run('012345678901234567890123456789')
Ignoring exception in on_message
Traceback (most recent call last):
File "C:UsersJackAppDataRoamingPythonPython38site-packagesdiscordclient.py", line 312, in _run_event
await coro(*args, **kwargs)
File "c:UsersJackDesktopDiscordBotbot.py", line 17, in on_message
name = message.mentions[0].id
IndexError: list index out of range
Ответ №1:
Это происходит потому, что каждый раз, когда кто-то отправляет сообщение, он пытается извлечь первое упоминание о сообщении. Но если в сообщении нет упоминания, то возникает ошибка. Вы можете просто исправить это с помощью
if message.mentions:
name = message.mentions[0].id
этот код.
Ответ №2:
Я думаю, что проблема с вашим кодом заключается в том, что он будет искать упоминания каждый раз при получении сообщения. Попробуйте этот код:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = '.')
@client.event
async def on_ready():
print('Bot Online')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.mentions:
name = message.mentions[0].id
if name == usersid:
await message.channel.send('Currently missing in action')
else:
pass
client.run('012345678901234567890123456789')