我该如何解决此错误? TypeError:列表索引必须是整数或切片,而不是str:discord.py

时间:2018-08-16 05:32:17

标签: python typeerror discord.py

嘿,我正在编码一个不和谐的机器人,因此我决定向其中添加一个调平系统。因为如果服务器成员足够活跃并且可以聊天,那么他们就可以升级。这就是我的atm(“用于水准仪”)

    import discord
    from discord.ext.commands import Bot
    from discord.ext import commands
    from random import randint
    import random
    import asyncio
    import pickle
    import os
    import json
    from itertools import cycle
    import time
    os.chdir('C:\Users\Desktop\MyBot')



@bot.event
async def on_member_join(member):
    with open('users.json', 'r') as f:
        users = json.load(f)

    await update_data(users, member)


    with open('users.json', 'w') as f:
        json.dump(users, f)

@bot.event
async def on_message(message):
    with open('users.json', 'r') as f:
        users = json.load(f)

    await update_data(users, message.author)
    await add_experience(users, message.authors, 5)
    await level_up(users, message.author, message.channel)


    with open('users.json', 'w') as f:
        json.dump(users, f)
async def update_data(users, user):
    if not user.id in users:
        users[user.id] = []
        users[user.id]['experience'] = 1
        users[user.id]['level'] = 1

async def add_experience(users, user, exp):
    users[user.id]['experience'] += exp

async def level_up(users, user, channel):
    experience = users[user.id]['experience']
    lvl_start = users[user.id]['level']
    lvl_end = int(experience ** (1/4))

    if lvl_start < lvl_end:
        await bot.send_messgae(channel, '{} have leveled up to level {}'.format(user.mention, lvl_end))
        user[user.id]['level'] = lvl_end

这是我得到的确切错误。

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\MYNAME\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\client.py", line 307, in _run_event
    yield from getattr(self, event)(*args, **kwargs)
  File "C:\Users\MYNAME\Desktop\MyBot\CrestBot.py", line 36, in on_message
    await update_data(users, message.author)
  File "C:\Users\MYNAME\Desktop\MyBot\CrestBot.py", line 46, in update_data
    users[user.id]['experience'] = 0
TypeError: list indices must be integers or slices, not str

2 个答案:

答案 0 :(得分:0)

基本上,users[user.id]似乎是一个列表,您正尝试像字典一样对其进行索引(例如users[user.id]['experience'])。如果没有有关用户模型以及users是什么的更多信息,很难提出确切的解决方案。

答案 1 :(得分:0)

然后答案是

    the code users[user.id] = [] #This line needs to be changed to this users[user.id] = {}
    users[user.id]['experience'] = 1;users
    [user.id]['level'] = 1.