Z
Z
zxcigan2021-01-02 01:56:48
Python
zxcigan, 2021-01-02 01:56:48

I can't figure out what's the problem?

This is the bot code I am trying to make:

import discord
from discord.ext import commands
import sqlite3
import config
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 TNT,
    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, 1)")
      else:
        pass
  connection.commit()
  print('BOT LOX')


@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, 1)")
    connection.commit()
  else:
    pass


@client.command()
async def cash(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]} :polegar_para_cima:**"""
    ))
  else:
    await ctx.send(embed = discord.Embed(
      description = f"""У него, **{member}** вот столько балов!**{cursor.execute("SELECT cash FROM users WHERE id = {}".format(member.id)).fetchone()[0]} :polegar_para_cima:**"""
    ))


client.run(settings['TOKEN'])

It starts, but when I write the cash command, it gives me an error:

Ignoring exception in command cash:
Traceback (most recent call last):
  File "C:\Users\black\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Python\bot.py", line 47, in cash
    description = f"""У тебя , **{ctx.author}**  вот столько балов!**{cursor.execute("SELECT cash FROM users WHERE id = {}".format(ctx.author.id)).fetchone()[0]} :polegar_para_cima:**"""
TypeError: 'NoneType' object is not subscriptable

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

Traceback (most recent call last):
  File "C:\Users\black\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\black\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\black\AppData\Local\Programs\Python\Python310\lib\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

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vindicar, 2021-01-02
@zxcigan

description = f"""У тебя , **{ctx.author}** вот столько балов!**{cursor.execute("SELECT cash FROM users WHERE id = {}".format(ctx.author.id)).fetchone()[0]} :polegar_para_cima:**"""

Here is this - three times govnokod.
1. Do not put anything more complicated than one arithmetic operation into template strings - the result is absolutely unreadable and uncontrollable (as you have seen).
Not right:
description = f"""У тебя , **{ctx.author}** вот столько балов!**{cursor.execute("SELECT cash FROM users WHERE id = {}".format(ctx.author.id)).fetchone()[0]} :polegar_para_cima:**"""

Correctly:
score = cursor.execute("SELECT cash FROM users WHERE id = {}".format(ctx.author.id)).fetchone()[0]
description = f"""У тебя , **{ctx.author}** вот столько балов!**{score} :polegar_para_cima:**"""

2. Never form queries through string formatting. It's too easy to catch a mistake, explicit or implicit.
Not right:
score = cursor.execute("SELECT cash FROM users WHERE id = {}".format(ctx.author.id))

Correctly:
score = cursor.execute("SELECT cash FROM users WHERE id = ?", (ctx.author.id,) )

3. Always check what you get from the database! There is no guarantee that the entry with the specified id really exists.
Not right:
score = cursor.execute("SELECT cash FROM users WHERE id = ?", (ctx.author.id,) ).fetchone()[0]
description = f"""У тебя , **{ctx.author}** вот столько балов!**{score} :polegar_para_cima:**"""

Correctly:
score_row = cursor.execute("SELECT cash FROM users WHERE id = ?", (ctx.author.id,) ).fetchone()
if score_row is not None:
    description = f"""У тебя , **{ctx.author}** вот столько балов!**{score_row[0]} :polegar_para_cima:**"""
else:
    # что делать, если такого юзера еще нет в базе?
    cursor.execute("INSERT INTO users (id, cash) VALUES (?, 0)", (ctx.author.id,) ) # можно его добавить
    description = f"""У тебя , **{ctx.author}** пока нет ничего! Но скоро будет!"""

4. Points, damn it.

E
Ekaterina, 2021-01-02
@neredko1703

this is off topic, but purely advice, if heroku hosting, then choose the mongodb database.
(if you have any questions, write to ds neredko # 3131 I will try to help)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question