L
L
lolSaByR2021-03-23 17:46:34
Python
lolSaByR, 2021-03-23 17:46:34

How to fix discord.py error?

Good day!
I recently started writing a bot using the discord.py library and also using the sqlite3 database.

When starting the bot, the console displays this error:

Ignoring exception in command __balance:
Traceback (most recent call last):
  File "/home/sabyr/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/sabyr/discord.py/bot.py", line 48, in __balance
    description = f"""Баланс пользователя **{ctx.author}** составляет **{cursor.execute("SELECT cash FROM users WHERE id = {}".format(ctx.author.id)).fetchone()[0]} :leaves:**"""
TypeError: 'NoneType' object is not subscriptable

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

Traceback (most recent call last):
  File "/home/sabyr/.local/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 903, in invoke
    await ctx.command.invoke(ctx)
  File "/home/sabyr/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 859, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/sabyr/.local/lib/python3.8/site-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: 'NoneType' object is not subscriptable


The code:

import discord
from discord.ext import commands

import sqlite3
from config import settings

client = commands.Bot(command_prefix = settings['PREFIX'])
client.remove_command('help')

connection = sqlite3.connect('server.db')
cursor = connection.cursor()


@client.event
async def on_ready():
    cursor.execute("""CREATE TABLE IF NOT EXISTS users (
        name TEXT,
        id INT,
        cash BIGINT,
        rep INT,
        lvl INT
    )""")

    for guild in client.guilds:
        for member in guild.members:
            if cursor.execute(f"SELECT id FROM users WHERE id = {member.id}").fetchone() is None:
                cursor.execute(f"INSERT INTO users VALUES ('{member}', {member.id}, 0, 0, 0)")
            else:
                pass

    connection.commit()
    print('BOT Connected')


@client.event
async def on_member_join(member):
    if cursor.execute(f"SELECT id FROM users WHERE id = {member.id}").fetchone() is None:
        cursor.execute(f"INSERT INTO users VALUES ('{member}', {member.id}, 0, 0, 0")
        connection.commit()
    else:
        pass


@client.command(aliases = ['balance', 'cash', 'bal'])
async def __balance(ctx, member: discord.Member = None):
    if member is None:
        await ctx.send(embed = discord.Embed(
        description = f"""Баланс пользователя **{ctx.author}** составляет **{cursor.execute("SELECT cash FROM users WHERE id = {}".format(ctx.author.id)).fetchone()[0]} :leaves:**"""
        ))
    else:
        await ctx.send(embed = discord.Embed(
        description = f"""Баланс пользователя **{member}** составляет **{cursor.execute("SELECT cash FROM users WHERE id = {}".format(member.id)).fetchone()[0]} :leaves:**"""
        ))
    

client.run(settings['TOKEN'])

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vindicar, 2021-03-24
@Vindicar

First of all, putting cursor.execute() right on the f-line is a very, very bad idea. For this they beat on the fingers.
Second, not subscriptable means that you are trying to access by index (of type x[0]) while the object (x) is None.
90% chance that this is a call to .fetchone()[0] - the query to the database does not find the desired row, then fetchone() returns None, and then an attempt to get an index from None throws an exception.
Never, NEVER write an expression in f-lines that is more complex than 2*2. Put the intermediate result into a variable, check its value for correctness, then use it.

A
AineD3V, 2021-03-23
@AineD3V

Nontype object is not subscribed to you

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question