дублируется ответ бота, и при добавлении машины с помощью команды появляется ошибка " database is locked"

import discord
from discord.ext import commands
from discord.ui import Button, View, Modal, TextInput
import sqlite3

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

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

# Инициализация базы данных и таблицы
def init_db():
    conn = sqlite3.connect('cars.db')
    c = conn.cursor()
    c.execute('''
        CREATE TABLE IF NOT EXISTS cars (
            id INTEGER PRIMARY KEY,
            name TEXT NOT NULL,
            status TEXT NOT NULL,
            number TEXT,
            user TEXT,
            guild_id INTEGER NOT NULL,
            channel_id INTEGER NOT NULL
        )
    ''')
    conn.commit()
    conn.close()

init_db()

# Функция для получения списка машин для конкретного сервера и канала
def get_cars(guild_id, channel_id):
    conn = sqlite3.connect('cars.db')
    c = conn.cursor()
    c.execute('SELECT * FROM cars WHERE guild_id = ? AND channel_id = ?', (guild_id, channel_id))
    cars = c.fetchall()
    conn.close()
    return cars

class TakeCarModal(Modal):
    def __init__(self, user, guild_id, channel_id):
        super().__init__(title="Взять машину")
        self.user = user
        self.guild_id = guild_id
        self.channel_id = channel_id
        self.car_name = TextInput(label="Название или номер машины", style=discord.TextStyle.short)
        self.fuel_input = TextInput(label="Количество бензина (литры)")
        self.add_item(self.car_name)
        self.add_item(self.fuel_input)

    async def on_submit(self, interaction: discord.Interaction):
        fuel = self.fuel_input.value
        car_name = self.car_name.value

        try:
            fuel = float(fuel)
        except ValueError:
            await interaction.response.send_message("Количество бензина должно быть числом.", ephemeral=True)
            return

        conn = sqlite3.connect('cars.db')
        c = conn.cursor()
        c.execute('SELECT * FROM cars WHERE (name = ? OR id = ?) AND guild_id = ? AND channel_id = ?', (car_name, car_name, self.guild_id, self.channel_id))
        car = c.fetchone()

        if car and car[2] == "Свободно":
            c.execute('UPDATE cars SET status = ?, user = ? WHERE id = ?', ("Занято", self.user.mention, car[0]))
            conn.commit()
            await interaction.response.send_message(f"Вы взяли машину {car[1]}", ephemeral=True)
            await update_car_list(interaction.channel)

            # Отправляем сообщение в канал уведомлений
            channel = bot.get_channel(self.channel_id)
            if channel:
                embed = discord.Embed(
                    title="Машина взята",
                    description=f"Взял:\n {self.user.mention}\n\nМашина:\n {car[1]}\n\nБензин:\n {fuel} литров",
                    color=discord.Color.green()
                )
                await channel.send(embed=embed)
        else:
            await interaction.response.send_message(f"Машина {car_name} не найдена или уже занята", ephemeral=True)
        conn.close()

class ReturnCarModal(Modal):
    def __init__(self, user, guild_id, channel_id):
        super().__init__(title="Вернуть машину")
        self.user = user
        self.guild_id = guild_id
        self.channel_id = channel_id
        self.car_name = TextInput(label="Название или номер машины")
        self.fuel_left = TextInput(label="Оставшееся количество бензина (литры)", style=discord.TextStyle.short)
        self.add_item(self.car_name)
        self.add_item(self.fuel_left)

    async def on_submit(self, interaction: discord.Interaction):
        car_name = self.car_name.value
        fuel_left = self.fuel_left.value

        try:
            fuel_left = float(fuel_left)
        except ValueError:
            await interaction.response.send_message("Количество бензина должно быть числом.", ephemeral=True)
            return

        conn = sqlite3.connect('cars.db')
        c = conn.cursor()
        c.execute('SELECT * FROM cars WHERE (name = ? OR id = ?) AND guild_id = ? AND channel_id = ?', (car_name, car_name, self.guild_id, self.channel_id))
        car = c.fetchone()

        if car and car[2] == "Занято":
            c.execute('UPDATE cars SET status = ?, user = ? WHERE id = ?', ("Свободно", "", car[0]))
            conn.commit()
            await interaction.response.send_message(f"Вы вернули машину {car[1]}", ephemeral=True)
            await update_car_list(interaction.channel)

            # Отправляем сообщение в канал уведомлений
            channel = bot.get_channel(self.channel_id)
            if channel:
                embed = discord.Embed(
                    title="Машина возвращена",
                    description=f"Вернул:\n {self.user.mention}\n\nМашина:\n {car[1]}\n\nБензин:\н {fuel_left} литров",
                    color=discord.Color.red()
                )
                await channel.send(embed=embed)
        else:
            await interaction.response.send_message(f"Машина {car_name} не найдена или уже свободна", ephemeral=True)
        conn.close()

class CarListView(View):
    def __init__(self, user, guild_id, channel_id):
        super().__init__(timeout=None)
        self.user = user
        self.guild_id = guild_id
        self.channel_id = channel_id

    @discord.ui.button(label="Взять машину", style=discord.ButtonStyle.green)
    async def take_car_button(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_modal(TakeCarModal(interaction.user, self.guild_id, self.channel_id))

    @discord.ui.button(label="Вернуть машину", style=discord.ButtonStyle.red)
    async def return_car_button(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_modal(ReturnCarModal(interaction.user, self.guild_id, self.channel_id))

async def update_car_list(channel):
    cars = get_cars(channel.guild.id, channel.id)

    if not cars:
        await channel.send("Список машин пуст.")
        return

    car_list_message = ""
    for car in cars:
        car_status = "**Свободно**" if car[2] == "Свободно" else f"**Занято ({car[4]})**"
        car_list_message += f"{car[0]}. {car[1]}\n{car_status}\n\n"

    embed = discord.Embed(
        title="Список машин",
        description=car_list_message,
        color=discord.Color.blue()
    )

    view = CarListView(channel.guild.me, channel.guild.id, channel.id)
    await channel.send(embed=embed, view=view)

@bot.command()
async def auto(ctx):
    await update_car_list(ctx.channel)

@bot.command()
async def delete(ctx, car_id: int):
    conn = sqlite3.connect('cars.db')
    c = conn.cursor()
    c.execute('DELETE FROM cars WHERE id = ? AND guild_id = ? AND channel_id = ?', (car_id, ctx.guild.id, ctx.channel.id))
    conn.commit()
    conn.close()
    await ctx.send(f"Машина с ID {car_id} была удалена из базы данных.")
    await update_car_list(ctx.channel)

@bot.command()
async def clear(ctx, amount: int):
    if amount <= 0:
        await ctx.send("Количество сообщений должно быть больше 0.")
        return
    await ctx.channel.purge(limit=amount + 1)
    await ctx.send(f"Удалено {amount} сообщений.", delete_after=5)

@bot.command()
async def delete_all(ctx):
    conn = sqlite3.connect('cars.db')
    c = conn.cursor()
    c.execute('DELETE FROM cars WHERE guild_id = ? AND channel_id = ?', (ctx.guild.id, ctx.channel.id))
    conn.commit()
    conn.close()
    await ctx.send("Все машины были удалены из базы данных.")
    await update_car_list(ctx.channel)

@bot.command()
async def add_car(ctx, *, name: str):
    conn = sqlite3.connect('cars.db')
    c = conn.cursor()
    c.execute('INSERT INTO cars (name, status, guild_id, channel_id) VALUES (?, ?, ?, ?)', (name, "Свободно", ctx.guild.id, ctx.channel.id))
    conn.commit()
    conn.close()
    await ctx.send(f"Машина {name} была успешно добавлена.")
    await update_car_list(ctx.channel)
    

 

Ответы (0 шт):