Как добавить отправителя имени команды в список в Discord.py

#python #discord.py

#питон #discord.py

Вопрос:

Я пытаюсь создать своего собственного бота Discord, используя Discord.py , и чтобы отслеживать очки отдельных игроков, я использовал список, один с именами игроков, а другой с очками игрока, и оба были одинаковыми номерами в этом списке. То, что я пытаюсь сделать, это добавить имя человека, отправившего команду, в список игроков. Код:

 
    @bot.command()
    async def pointadd(ctx, amount, points=points, players=players):
        yes = 1
        for x in players:
            if players[x] == {ctx.message.author}:
                yes = ('Yes')
                level = x
        if yes == ('Yes'):
            points[level] = (points[level]   amount)
            await ctx.send(points[level])
        else:
            players.append(ctx.message.author)
            points.append('0')

  

Ошибка:

 Ignoring exception in command pointadd:
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/pi/pipy_bot/bot.py", line 58, in pointadd
    if players[x] == {ctx.message.author}:
TypeError: list indices must be integers or slices, not str

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/discord/ext/commands/bot.py", line 903, in invoke
    await ctx.command.invoke(ctx)
  File "/usr/local/lib/python3.5/dist-packages/discord/ext/commands/core.py", line 859, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/usr/local/lib/python3.5/dist-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: list indices must be integers or slices, not str
  

Также мне могла бы понадобиться помощь, чтобы сделать это аккуратнее.

Ответ №1:

x это players элемент списка, который, я полагаю, является discord.Member объектом. Индексы списка должны быть целыми числами и ничем другим, поэтому у вас есть эта ошибка. Вам нужно будет написать:

 @bot.command()
async def pointadd(ctx, amount, points=points, players=players):
    found = False
    for x in players:
    if x == ctx.message.author:
        found = True
        level = players.index(x)
    if found:
        points[level] = (int(points[level])   amount)
        await ctx.send(points[level])
    else:
        players.append(ctx.message.author)
        points.append('0')
  

( points[level] должно быть целым числом для выполнения вычислений, поэтому я написал int(points[level]) )

Вместо использования списков вы можете использовать словари:

 #Your points definition
points = {}
  
 #Your pointadd command
@bot.command()
async def pointadd(ctx, amount: int, points=points):
    try:
        points[ctx.author.id]  = amount
    except:
        points[ctx.author.id] = 0
    await ctx.send(points[ctx.author.id])
  

В итоге ваш points словарь будет выглядеть так:

 {
    'user_id_1': xp_amount_1
    'user_id_2': xp_amount_2
    ...
}
  

Комментарии:

1. Обратная трассировка (последний последний вызов): File «/usr/local/lib/python3.5/dist-packages/discord/ext/commands/core.py «, строка 85, в обернутом файле ret = await coro(*args, **kwargs) «/home/pi/pipy_bot/bot.py «, строка 59, в точках pointadd[ctx.author.id ] = 0 Ошибка индекса: не удается вставить ‘int’ вцелое число размером с индекс

2. Приведенное выше исключение было прямой причиной следующего исключения: Трассировка (последний последний вызов): File «/usr/local/lib/python3.5/dist-packages/discord/ext/commands/bot.py «, строка 903, в invoke await ctx.command.invoke(ctx) Файл «/usr/local/lib/python3.5/dist-packages/discord/ext/commands/core.py «, строка 859, в invoke вводится ожидание (*ctx.args, **ctx.kwargs)

3. Файл «/usr/local/lib/python3.5/dist-packages/discord/ext/commands/core.py «, строка 94, в завернутом виде вызывает CommandInvokeError(exc) из exc discord.ext.commands.errors. CommandInvokeError: команда вызвала исключение: IndexError: не удается поместить ‘int’ в целое число размером с индекс — это ошибка, возникшая при использовании словарной версии.

4. cdn.discordapp.com/attachments/657259687351418880 /… это ошибка с другой, которую вы поставили.

5. Какой тип players в вашем коде? Кроме того, я исправил часть словаря