Python Forum
Answer for newbie, Sqlite3
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Answer for newbie, Sqlite3
#1
Question 
I made a discord bot on a task using plugins Sqlite3,Json,Disnake. But I got such an error as no such column: Speed. I searched for the problem on the internet, but all the ways did not help. Here is my code:
import disnake
from disnake.ext import commands
import sqlite3
import json

# Создайте подключение к базе данных (файл "bot_database.db")conn = sqlite3.connect('bot_database.db')
cursor = conn.cursor()


cursor.execute('''
    CREATE TABLE IF NOT EXISTS user_scores (
        user_id INTEGER PRIMARY KEY,
        score INTEGER DEFAULT 0,
        Speed INTEGER DEFAULT 0,
        Strength INTEGER DEFAULT 0,
        Magic INTEGER DEFAULT 0,
        Toughness INTEGER DEFAULT 0
    )
''')

conn.commit()

cursor.execute('''
    CREATE TABLE IF NOT EXISTS variables (
        name TEXT PRIMARY KEY,
        value TEXT
    )
''')
conn.commit()


def load_variables():
    global Your_ochki, Attributes
    try:
        with open('config.json', 'r') as config_file:
            config_data = json.load(config_file)
            Your_ochki = config_data.get('Your_ochki', {})
            Attributes = config_data.get('Attributes', [0, 0, 0, 0])
    except FileNotFoundError:
        pass

def save_variables():
    config_data = {
        'Your_ochki': Your_ochki,
        'Attributes': Attributes
    }
    with open('config.json', 'w') as config_file:
        json.dump(config_data, config_file)


intents = disnake.Intents.default()
intents.message_content = True


bot = commands.Bot(command_prefix="-", intents=intents)

Your_ochki = {}
Attributes = [0, 0, 0, 0]  # Список значений для Speed, Sila, Magic, Prochka


@bot.event
async def on_ready():
    print(f"Бот подключен как {bot.user.name}")
    cursor.execute('SELECT (user_id, score, Speed, Strength, Magic, Toughness) FROM user_scores')
    data = cursor.fetchall()
    for user_id, score, Speed, Strength, Magic, Toughness in data:
        Your_ochki[user_id] = score
        Attributes = [Speed, Strength, Magic, Toughness]

    
    load_variables()

@bot.command()
async def ping(ctx):
    await ctx.send("Pong!")


@bot.command()
async def stats(ctx, member: disnake.Member = None):
    if member is None:
        member = ctx.author  # Если не указан участник, используем вызывающего пользователя

    member_name = member.display_name if member.nick else member.name  # Получаем отображаемое имя, учитывая nickname

    embed = disnake.Embed(title=f"Статистика персонажа {member_name}", color=0x000000)  # Черный цвет
    embed.add_field(name="Очки улучшений", value=f"💎 {Your_ochki.get(ctx.author.id, 0)}", inline=False)  # Эмодзи для очков
    embed.add_field(name="Скорость", value=f"⚡ {Attributes[0]}", inline=False)  # Эмодзи для скорости
    embed.add_field(name="Сила", value=f"💪 {Attributes[1]}", inline=False)  # Эмодзи для силы
    embed.add_field(name="Владение магией", value=f"✨ {Attributes[2]}", inline=False)  # Эмодзи для магии
    embed.add_field(name="Прочка", value=f"🛡️ {Attributes[3]}", inline=False)  # Эмодзи для прочности

    await ctx.send(embed=embed)


@bot.command()
@commands.has_permissions(manage_guild=True)
async def add_ochki(ctx, member: disnake.Member, amount: int):
    if not isinstance(member, disnake.Member):
        await ctx.send("Вы должны упомянуть участника сервера.")
        return

    if amount == 0:
        await ctx.send("Вы не можете добавить 0 очков.")
        return


    member_id = member.id
    cursor.execute('SELECT score FROM user_scores WHERE user_id = ?', (member_id,))
    current_score = cursor.fetchone()

    if current_score is None:
        current_score = 0
    else:
        current_score = current_score[0]

    new_score = current_score + amount

   
    cursor.execute('INSERT OR REPLACE INTO user_scores (user_id, score) VALUES (?, ?)', (member_id, new_score))
    conn.commit()


    Your_ochki[member_id] = new_score

   
    success_embed = disnake.Embed(title="Успешное добавление очков",
                                  description=f"Добавлено {amount} очков {member.mention}. "
                                              f"Текущее количество очков: {new_score}",
                                  color=0x00FF00)

    await ctx.send(embed=success_embed)


@bot.command()
async def upgrade(ctx, attribute: str, amount: int):
    global Your_ochki, Attributes

    
    error_embed = disnake.Embed(title="Ошибка", description=f"У вас не хватает очков для улучшения '{attribute}'.",
                                color=0xFF0000)

   
    user_score = Your_ochki.get(ctx.author.id, 0)

   
    if user_score >= amount:
        if attribute.lower() == "скорость":
            Attributes[0] += amount
        elif attribute.lower() == "сила":
            Attributes[1] += amount
        elif attribute.lower() == "владение магией":
            Attributes[2] += amount
        elif attribute.lower() == "прочка":
            Attributes[3] += amount

        Your_ochki[ctx.author.id] -= amount

       
        cursor.execute('UPDATE user_scores SET score = ?, Speed = ?, Strength = ?, Magic = ?, Toughness = ? WHERE user_id = ?',
                       (Your_ochki[ctx.author.id], Attributes[0], Attributes[1], Attributes[2], Attributes[3], ctx.author.id))

        conn.commit()

      
        upgrade_embed = disnake.Embed(title="Улучшение характеристики",
                                      description=f"Характеристика '{attribute}' улучшена на {amount} очков. "
                                                  f"Текущие характеристики:\n"
                                                  f"Скорость: {Attributes[0]}\n"
                                                  f"Сила: {Attributes[1]}\n"
                                                  f"Владение магией: {Attributes[2]}\n"
                                                  f"Прочка: {Attributes[3]}\n"
                                                  f"Осталось очков: {Your_ochki[ctx.author.id]}",
                                      color=0x00FF00)

        save_variables()  

        await ctx.send(embed=upgrade_embed)
    else:
        await ctx.send(embed=error_embed)
This code must store 5 variables in it. Also output embed where it is written with the command. Please help if you can
Reply
#2
Check the db file, maybe the table was created initially without Speed column?
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Hello,

please post the full stack trace of the error you get so we can see where the error occurs.

Regards, noisefloor
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Coding answer for newbie cg3 2 1,167 Aug-05-2023, 12:17 PM
Last Post: jefsummers
  What am I doing wrong to not get the answer pav1983 7 3,727 Jun-25-2020, 08:53 PM
Last Post: ndc85430
  Need help with an assignment, not an answer. celtickodiak 4 2,955 Oct-01-2019, 02:04 PM
Last Post: jefsummers

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020