首页 > 解决方案 > Discord PY TypeError:只能将str(不是“int”)连接到str

问题描述

我正在尝试制作自己的级别机器人,但我得到:TypeError:只能将str(不是“int”)连接到str

这是我的代码:

@client.event
async def on_message(message):

            
    for badword in file:
        if badword in message.content.lower():
            await message.delete()
            await message.channel.send(f'{message.author.mention}! Your message has not passed moderation!')
        else:
            await client.process_commands(message)
        
        with open("users.json","r") as f:
            users = json.load(f)
        lvl = users[str(message.author.id)]
        
error-> sum = lvl + 1
        with open("users.json", "r") as f:
           users = json.load(f)
           users[str(message.author.id)] = sum
        with open("users.json", "w") as f:
            json.dump(users, f, indent=4)

这是我的 json :

{       "763339711988236328" : "0"
}

如何获取“0”并添加“1”以使用户升级?

喜欢:

{       "763339711988236328" : "7"
}

7 + 1 = 8

后 :

{       "763339711988236328" : "8"
}

对不起我的英语不好我来自德国

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\admin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\admin\Desktop\Marc\Bot\dcbot.py", line 71, in on_message
    sum = lvl + 1
TypeError: can only concatenate str (not "int") to str

标签: pythondiscord.py

解决方案


正如错误所暗示的那样,您试图将一个 int 添加到一个没有任何意义的字符串中。您可以尝试将字符串首先转换为 int。

sum = str(int(lvl) + 1)

推荐阅读