简体   繁体   中英

TypeError: 'NoneType' object is not subscriptable ERROR

This is the Code i write for a levelling System for a Discord Server and now i got this error. But the Bot is starting, but have some problem to execute the commands. The Code create the DB and set everyone a start EXP to 100, but something went wrong with the level system itselfs.

level = ["Gamer", "Pro gamer", "Epic gamer", "Legendary gamer", "Godly gamer"]
levelnum = [10,20,30,40,50]

cluster = MongoClient("")

levelling = cluster[""][""]

class levelsys(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_ready(self):
        print("Levelsystem is ready")

    @commands.Cog.listener()
    async def on_message(self,message):
        if message.channel.id in talk_channels:
            stats = levelling.find_one({"id" : message.author.id})
        if not message.author.bot:
            newuser = {"id" : message.author.id, "xp" : 100}
            levelling.insert_one(newuser)
        else:
            xp = stats["xp"] + 5
            levelling.update_one ({"id":message.author.id}, {"$set":{"xp":xp}})
            lvl = 0
            while True:
                if xp < ((50*(lvl**2))+(50*(lvl-1))):
                    break
                lvl += 1
            xp -= ((50*((lvl-1)**2))+(50*(lvl-1)))
            if xp == 0:
                await message.channel.send(f"well done {message.author.mention}! You leveld up to **level: {lvl}**")
                for i in range(len(level)):
                    if lvl == levelnum[i]:
                        await message.author.add_roles(discord.utils.get(message.author.guild.roles, name=level[i]))
                        embed = discord.Embed(description=f"{message.author.mention} you have gotten role **{level[i]}**!!!")
                        embed.set_thumbnail(url=message.author.avatar_url)
                        await message.channel.send(embed=embed)

@commands.command()
async def rank(self, ctx):
    if ctx.channel.id == bot_channel:
        stats = levelling.find_one({"id" : ctx.author.id})
        if stats is None:
            embed = discord.Embed(description="You haven't sent any message, no rank!!!")
            await ctx.channel.send(emebed=embed)
        else:
                xp = stats["xp"]
                lvl = 0
                rank = 0
                while True:
                        if xp < ((50*(lvl**2))+(50*(lvl-1))):
                            break
                        lvl += 1
                xp -= ((50*((lvl-1)**2))+(50*(lvl-1)))
                boxes = int((xp/(200*((1/2)* lvl)))*20)
                rankings = levelling.find().sort("xp",-1)
                for x in rankings:
                     rank += 1
                     if stats ["id"] == x["id"]:
                         break
                embed = discord.Embed(title="{}'s level stats".format(ctx.author))
                embed.add_field(name="Name", value=ctx.author.mention, inline=True)
                embed.add_field(name="XP", value=f"{xp}/{int(200*((1/2)*lvl))}", inline=True)
                embed.add_field(name="Rank", value=f"{rank}/{ctx.guild.member_count}", inline=True)
                embed.add_field(name="Progress Bar [lvl", value=boxes * ":blue_square:" + (20-boxes) * "white_large_square:", inline=False)
                embed.set_thumbnail(url=ctx.author.avatar_url)
                await ctx.channel.send(embed=embed)

@commands.command()
async def leaderboard(self, ctx):
    if (ctx.channel.id == bot_channel):
        rankings = levelling.find().sort("xp",-1)
        i = 1
        embed = discord.Embed(title="Rankings:")
        for x in rankings:
            try:
                temp = ctx.guild.get_member(x["id"])
                tempxp = x["xp"]
                embed.add_field(name=f"{i}: {temp.name}", value=f"Total XP: {tempxp}", inline=False)
                i += 1
            except:
                pass
            if i == 11:
                break
        await ctx.channel.send(embed=embed)

def setup(client):
    client.add_cog(levelsys(client))
    

And i got this error

04.05 18:38:00 [Bot] Ignoring exception in on_message
04.05 18:38:00 [Bot] Traceback (most recent call last):
04.05 18:38:00 [Bot] File "/.local/lib/python3.9/site-packages/discord/client.py", line 343, in _run_event
04.05 18:38:00 [Bot] await coro(*args, **kwargs)
04.05 18:38:00 [Bot] File "/cogs/levelsys.py", line 32, in on_message
04.05 18:38:00 [Bot] xp = stats["xp"] + 5
04.05 18:38:00 [Bot] TypeError: 'NoneType' object is not subscriptable

Hopefully someone can help me

The problem might be with this part of your code:

async def on_message(self,message):
    if message.channel.id in talk_channels:
        stats = levelling.find_one({"id" : message.author.id})
    if not message.author.bot:
        newuser = {"id" : message.author.id, "xp" : 100}
        levelling.insert_one(newuser)
    else:
        xp = stats["xp"] + 5
    .
    .
    .

When the first if condition is true then you will have the stats variable set, otherwise you will have no such variable.

The second if statement is independent and on the else branch of it you try to use the stats variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM