@Vova124

Почему мой код вызывает ошибку?

Вот код:
import discord
from discord.ext import commands
from discord.utils import get
from config import settings
import json
import sys
import random
import asyncio
import sqlite3
import random
from random import randint

client = commands.Bot(command_prefix=settings['PREFIX'], intents=discord.Intents.all())
client.remove_command('help')

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


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

    cursor.execute("""CREATE TABLE IF NOT EXISTS shop (
        role_id INT,
        id INT,
        cost BIGINT
    )""")

    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, {guild.id})")
            else:
                pass

    connection.commit()
    print('client 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, 1, {member.guild.id})")
        connection.commit()
    else:
        pass

@client.command(aliases =['balance','cash'])
async def __balance(ctx, member: discord.Member = None):
    if member is None:
        member = ctx.author

    amount = cursor.execute("SELECT cash FROM users WHERE id = {}".format(member.id)).fetchone()[0]

    await ctx.send(embed=discord.Embed(
        description=f""" Баланс **{member}** составляет **{amount}**"""
    ))

@client.command(aliases = ['award'])
@commands.has_permissions(administrator=True)
async def __award(ctx, member: discord.Member = None, amount: int=None):
    if member is None:
        await ctx.send(f"**{ctx.author}**, укажите рабочего, которому желаете выдать определённую сумму")
    else:
        if amount is None:
            await ctx.send(f"**{ctx.author}**, укажите сумму, которую желаете начислить на счёт рабочего")
        else:
            cursor.execute("UPDATE users SET cash = cash + {} WHERE id = {}".format(amount, member.id))
            connection.commit()

            await ctx.message.add_reaction('✔️')

@client.command(aliases = ['add-shop'])
@commands.has_permissions(administrator=True)
async def __add_shop(ctx, role: discord.Role = None, cost: int = None):
    if role is None:
        await ctx.send(f"**{ctx.author}**, укажите роль, которую желаете внести в магазин")
    else:
        if cost is None:
            await ctx.send(f"**{ctx.author}**, укажите стоимость для данной роли")
        elif cost < 0:
            await ctx.send(f"**{ctx.author}**, стоимость роли не может быть такой маленькой")
        else:
            cursor.execute("INSERT INTO shop VALUES ({}, {}, {})".format(role.id, ctx.guild.id, cost))
            connection.commit()

            await ctx.message.add_reaction('✔️')

@client.command(aliases = ['remove-shop'])
@commands.has_permissions(administrator=True)
async def __remove_shop(ctx, role: discord.Role = None):
    if role is None:
        await ctx.send(f"**{ctx.author}**, укажите роль, которую желаете удалить из магазина")
    else:
        cursor.execute("DELETE FROM shop WHERE role_id = {}".format(role.id))
        connection.commit()

        await ctx.message.add_reaction('✔️')

@client.command(aliases = ['shop'])
async def __shop(ctx):
    embed = discord.Embed(title = "Магазин ролей")

    for row in cursor.execute("SELECT role_id, cost FROM shop WHERE id = {}".format(ctx.guild.id)):
        if ctx.guild.get_role(row[0]) != None:
            embed.add_field(
                name = f"Стоимость **{row[1]}**",
                value = f"Вы приобретаете роль {ctx.guild.get_role(row[0]).mention}",
                inline = False
            )
        else:
            pass

    await ctx.send(embed = embed)

@client.command(aliases = ['buy', 'buy-role'])
async def __buy(ctx, role: discord.Role = None):
    if role is None:
        await ctx.send(f"**{ctx.author}**, укажите роль, которую желаете купить")
    else:
        if role in ctx.author.roles:
            await ctx.send(f"**{ctx.author}**, у вас уже приобретена данная роль")
        elif cursor.execute("SELECT cost FROM shop WHERE role_id = {}".format(role.id)).fetchone()[0] > cursor.execute("SELECT cash FROM users WHERE id ={}".format(ctx.author.id)).fetchone()[0]:
            await ctx.send(f"**{ctx.author}**,у вас недостаточно средств для покупки данной роли")
        else:
            await ctx.author.add_roles(role)
            cursor.execute("UPDATE users SET cash = cash - {0} WHERE id = {1}".format(cursor.execute("SELECT cost FROM shop WHERE role_id = {}".format(role.id)).fetchone()[0], ctx.author.id))
            connection.commit()

            await ctx.message.add_reaction('✔️')

@client.command(aliases = ['rep', '+rep'])
async def __rep(ctx,member: discord.Member = None):
    if member is None:
        await ctx.send(f"**{ctx.author}, укажите рабочего фабрики")
    else:
        if member.id == ctx.author.id:
            await ctx.send(f"**{ctx.author}**, вы не можете указать самого себя")
        else:
            cursor.execute("UPDATE users SET rep = rep + {} WHERE id = {}".format(1,member.id))
            connection.commit()

            await ctx.message.add_reaction('✔️')
@client.command()
async def work(ctx):
    global last_work_time
    if last_work_time == 0:
        stoimost = randint(20,100)
        await ctx.send(f'Ваш топтаний оценили в {stoimost}')
        cursor.execute("UPDATE users SET cash = cash + {} WHERE id = {}".format(stoimost, ctx.author.id))
        connection.commit()
        last_work_time = 60
        for i in range(60):
            await asyncio.sleep(1)
            last_work_time-=1
    else:
        await ctx.send(f'Вы уже выполняли работу в эту минуту! Ждите {last_work_time} секунд')


@client.command(aliases=['leaderboard', 'lb'])
async def __leaderboard(ctx):
    embed = discord.Embed(title='Топ 10 сервера')
    counter = 0

    for row in cursor.execute(
            "SELECT name, cash FROM users WHERE server_id = {} ORDER BY cash DESC LIMIT 10".format(ctx.guild.id)):
        counter += 1
        embed.add_field(
            name=f'# {counter} | `{row[0]}`',
            value=f'Баланс: {row[1]}',
            inline=False
        )

    await ctx.send(embed=embed)


client.run(settings['TOKEN'])


Вот ошибка:

Traceback (most recent call last):
  File "C:\Users\dubey\PycharmProjects\pythonProject2\venv\lib\site-packages\discord\ext\commands\core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\dubey\PycharmProjects\pythonProject2\main.py", line 174, in __leaderboard
    for row in cursor.execute(
sqlite3.OperationalError: no such column: server_id

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

Traceback (most recent call last):
  File "C:\Users\dubey\PycharmProjects\pythonProject2\venv\lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\dubey\PycharmProjects\pythonProject2\venv\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\dubey\PycharmProjects\pythonProject2\venv\lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OperationalError: no such column: server_id
  • Вопрос задан
  • 107 просмотров
Решения вопроса 1
SoreMix
@SoreMix
yellow
бд удалить с диска и запустить код.
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
menma_uzumakie
@menma_uzumakie
Рекомендую питон поучить сначала
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы