首页 > 解决方案 > 字典中的“IndexError:无法将'int'放入索引大小的整数”

问题描述

我正在尝试在python中创建一个不和谐的机器人,并做一个像MEE6之类的xp模拟器。但是,当我尝试使用我目前拥有的东西时,我得到了一个错误。我目前的代码是:

#A ton of imports
def unload_cache(file: str):
    return open("cache/" + file, "r").read()

def reload_cache(file: str, new):
    cache = open("cache/" + file, "w")
    cache.write(str(new))
    cache.close()

def add_xp(server_id, user_id, xp: int):
    dicts = unload_cache("server_xp.txt")
    try:
        data = dicts[server_id]
        try:
            data[user_id] = data[user_id] + xp
            dicts[server_id] = data
        except KeyError:
            data[user_id] = xp
            dicts[server_id] = data
    except:
        dicts[server_id] = {user_id:xp}
    reload_cache("server_xp.txt", dicts)

@bot.event
async def on_message(message):
    server_id = int(message.server.id)
    add_xp(server_id, message.author.id, 1)
    print(message.author.name + " gaind 1 xp at " + message.server.id)

为了总结这一点,它基本上打开一个包含字典的文件,并在{ServerID:{Player1ID:xp, Player2ID:xp, etc}, etc}每次有人说话时添加 1 xp。我有用于多服务器支持的多个服务器 ID。出于某种原因,我得到了这个确切的错误:

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\client.py", line 307, in _run_event
    yield from getattr(self, event)(*args, **kwargs)
  File "C:\Users\User\Python\Confusion Bot\bot.py", line 83, in on_message
    add_xp(server_id, message.author.id, 1)
  File "C:\Users\User\Python\Confusion Bot\bot.py", line 43, in add_xp
    dicts[server_id] = {user_id:xp}
IndexError: cannot fit 'int' into an index-sized integer
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\User\Python\Confusion Bot\bot.py", line 35, in add_xp
    data = dicts[server_id]
IndexError: cannot fit 'int' into an index-sized integer

标签: python-3.xdiscord.pyindex-error

解决方案


推荐阅读