У меня есть такой код для тг бота:

import os
import logging
from dotenv import load_dotenv
import requests
import sqlite3
from telegram import (
    ReplyKeyboardMarkup,
    Update,
    ReplyKeyboardRemove,
    KeyboardButton,
    InlineKeyboardMarkup,
    InlineKeyboardButton
)
from telegram.ext import (
    Application,
    CommandHandler,
    MessageHandler,
    filters,
    ContextTypes,
    ConversationHandler,
    CallbackContext,
    CallbackQueryHandler
)
from datetime import datetime, timedelta, time
import pytz
import uuid

# Настройка логгирования
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO
)
logger = logging.getLogger(__name__)

# Загружаем переменные из .env
load_dotenv()
BOT_TOKEN = os.getenv('BOT_TOKEN')
WEATHER_API_KEY = os.getenv('WEATHER_API_KEY')

# Константы
DEMBEL_DATE = datetime(2025, 12, 6)
MOSCOW_TZ = pytz.timezone('Europe/Moscow')

# Инициализация базы данных
def init_db():
    conn = sqlite3.connect('bot.db')
    cursor = conn.cursor()
    
    # Таблица пользователей
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS users (
        user_id INTEGER PRIMARY KEY,
        username TEXT,
        first_name TEXT,
        last_name TEXT,
        balance REAL DEFAULT 0,
        referral_code TEXT UNIQUE,
        referred_by TEXT,
        favorite_city TEXT
    )
    ''')
    
    # Таблица рефералов
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS referrals (
        referral_id INTEGER PRIMARY KEY AUTOINCREMENT,
        referrer_id INTEGER,
        referred_id INTEGER,
        date TEXT,
        FOREIGN KEY(referrer_id) REFERENCES users(user_id),
        FOREIGN KEY(referred_id) REFERENCES users(user_id)
    )
    ''')
    
    # Таблица заметок
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS notes (
        note_id INTEGER PRIMARY KEY AUTOINCREMENT,
        user_id INTEGER,
        text TEXT,
        date TEXT,
        FOREIGN KEY(user_id) REFERENCES users(user_id)
    ''')
    
    conn.commit()
    conn.close()

init_db()

# Клавиатуры
def get_main_menu():
    keyboard = [
        [KeyboardButton("👤 Профиль")],
        [KeyboardButton("🌤 Погода")],
        [KeyboardButton("📝 Заметки")]
    ]
    return ReplyKeyboardMarkup(keyboard, resize_keyboard=True)

def get_profile_menu():
    keyboard = [
        [KeyboardButton("⏳ До дембеля")],
        [KeyboardButton("💰 Баланс")],
        [KeyboardButton("💳 Пополнить баланс")],
        [KeyboardButton("👥 Рефералы")],
        [KeyboardButton("🔙 Назад")]
    ]
    return ReplyKeyboardMarkup(keyboard, resize_keyboard=True)

def get_weather_menu():
    keyboard = [
        [KeyboardButton("🏠 Родной город")],
        [KeyboardButton("🏙 Москва")],
        [KeyboardButton("🔍 Поиск города")],
        [KeyboardButton("⭐ Избранные города")],
        [KeyboardButton("🔙 Назад")]
    ]
    return ReplyKeyboardMarkup(keyboard, resize_keyboard=True)

def get_notes_menu():
    keyboard = [
        [KeyboardButton("✏️ Новая заметка")],
        [KeyboardButton("📖 Мои заметки")],
        [KeyboardButton("🔙 Назад")]
    ]
    return ReplyKeyboardMarkup(keyboard, resize_keyboard=True)

# Функции работы с БД
def get_user(user_id):
    conn = sqlite3.connect('bot.db')
    cursor = conn.cursor()
    cursor.execute('SELECT * FROM users WHERE user_id = ?', (user_id,))
    user = cursor.fetchone()
    conn.close()
    return user

def create_user(user_id, username, first_name, last_name):
    conn = sqlite3.connect('bot.db')
    cursor = conn.cursor()
    referral_code = str(uuid.uuid4())[:8]
    cursor.execute('''
    INSERT OR IGNORE INTO users (user_id, username, first_name, last_name, referral_code)
    VALUES (?, ?, ?, ?, ?)
    ''', (user_id, username, first_name, last_name, referral_code))
    conn.commit()
    conn.close()

def update_balance(user_id, amount):
    conn = sqlite3.connect('bot.db')
    cursor = conn.cursor()
    cursor.execute('UPDATE users SET balance = balance + ? WHERE user_id = ?', (amount, user_id))
    conn.commit()
    conn.close()

def add_referral(referrer_id, referred_id):
    conn = sqlite3.connect('bot.db')
    cursor = conn.cursor()
    cursor.execute('INSERT INTO referrals (referrer_id, referred_id, date) VALUES (?, ?, ?)', 
                  (referrer_id, referred_id, datetime.now().strftime('%Y-%m-%d')))
    conn.commit()
    conn.close()

def get_referrals_count(user_id):
    conn = sqlite3.connect('bot.db')
    cursor = conn.cursor()
    cursor.execute('SELECT COUNT(*) FROM referrals WHERE referrer_id = ?', (user_id,))
    count = cursor.fetchone()[0]
    conn.close()
    return count

def add_note(user_id, text):
    conn = sqlite3.connect('bot.db')
    cursor = conn.cursor()
    cursor.execute('INSERT INTO notes (user_id, text, date) VALUES (?, ?, ?)', 
                  (user_id, text, datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
    conn.commit()
    conn.close()

def get_notes(user_id):
    conn = sqlite3.connect('bot.db')
    cursor = conn.cursor()
    cursor.execute('SELECT note_id, text, date FROM notes WHERE user_id = ? ORDER BY date DESC', (user_id,))
    notes = cursor.fetchall()
    conn.close()
    return notes

def set_favorite_city(user_id, city):
    conn = sqlite3.connect('bot.db')
    cursor = conn.cursor()
    cursor.execute('UPDATE users SET favorite_city = ? WHERE user_id = ?', (city, user_id))
    conn.commit()
    conn.close()

def get_favorite_city(user_id):
    conn = sqlite3.connect('bot.db')
    cursor = conn.cursor()
    cursor.execute('SELECT favorite_city FROM users WHERE user_id = ?', (user_id,))
    city = cursor.fetchone()
    conn.close()
    return city[0] if city else None

# Обработчики команд
async def start(update: Update, context: CallbackContext):
    user = update.effective_user
    create_user(user.id, user.username, user.first_name, user.last_name)
    
    # Проверка реферала
    if context.args:
        referrer_code = context.args[0]
        conn = sqlite3.connect('bot.db')
        cursor = conn.cursor()
        cursor.execute('SELECT user_id FROM users WHERE referral_code = ?', (referrer_code,))
        referrer = cursor.fetchone()
        if referrer and referrer[0] != user.id:
            add_referral(referrer[0], user.id)
            update_balance(referrer[0], 100)  # Награда за реферала
            await context.bot.send_message(
                chat_id=referrer[0],
                text=f"🎉 Новый реферал! Вам начислено 100 рублей!"
            )
        conn.close()
    
    await update.message.reply_text(
        f"Привет, {user.first_name}! 👋\nВыберите раздел:",
        reply_markup=get_main_menu()
    )

async def profile(update: Update, context: CallbackContext):
    await update.message.reply_text(
        "👤 Профиль:",
        reply_markup=get_profile_menu()
    )

async def weather(update: Update, context: CallbackContext):
    await update.message.reply_text(
        "🌤 Погода:",
        reply_markup=get_weather_menu()
    )

async def notes(update: Update, context: CallbackContext):
    await update.message.reply_text(
        "📝 Заметки:",
        reply_markup=get_notes_menu()
    )

async def back_to_main(update: Update, context: CallbackContext):
    await update.message.reply_text(
        "Главное меню:",
        reply_markup=get_main_menu()
    )

async def dembel_count(update: Update, context: CallbackContext):
    now = datetime.now(MOSCOW_TZ)
    delta = DEMBEL_DATE - now
    days = delta.days
    
    await update.message.reply_text(
        f"⏳ До дембеля осталось {days} дней!\n"
        f"🗓 Дата дембеля: {DEMBEL_DATE.strftime('%d.%m.%Y')}",
        reply_markup=get_profile_menu()
    )

async def show_balance(update: Update, context: CallbackContext):
    user = get_user(update.effective_user.id)
    await update.message.reply_text(
        f"💰 Ваш баланс: {user[4]} рублей",
        reply_markup=get_profile_menu()
    )

async def show_referrals(update: Update, context: CallbackContext):
    user = get_user(update.effective_user.id)
    count = get_referrals_count(user[0])
    await update.message.reply_text(
        f"👥 Ваша реферальная ссылка:\n"
        f"https://t.me/{context.bot.username}?start={user[5]}\n\n"
        f"🔢 Количество рефералов: {count}",
        reply_markup=get_profile_menu()
    )

async def add_money(update: Update, context: CallbackContext):
    keyboard = [
        [InlineKeyboardButton("100 рублей", callback_data="add_100")],
        [InlineKeyboardButton("500 рублей", callback_data="add_500")],
        [InlineKeyboardButton("1000 рублей", callback_data="add_1000")]
    ]
    await update.message.reply_text(
        "💳 Выберите сумму для пополнения:",
        reply_markup=InlineKeyboardMarkup(keyboard)
    )

async def button_callback(update: Update, context: CallbackContext):
    query = update.callback_query
    user_id = query.from_user.id
    
    if query.data.startswith('add_'):
        amount = int(query.data.split('_')[1])
        update_balance(user_id, amount)
        await query.edit_message_text(
            f"✅ Ваш баланс пополнен на {amount} рублей!\n"
            f"💰 Новый баланс: {get_user(user_id)[4]} рублей"
        )
    
    await query.answer()

async def weather_in_city(update: Update, context: CallbackContext, city):
    # Здесь реализация получения погоды
    await update.message.reply_text(
        f"Погода в {city}: ...",
        reply_markup=get_weather_menu()
    )

async def favorite_city(update: Update, context: CallbackContext):
    city = get_favorite_city(update.effective_user.id)
    if city:
        await weather_in_city(update, context, city)
    else:
        await update.message.reply_text(
            "У вас нет избранного города. Используйте поиск, чтобы добавить город.",
            reply_markup=get_weather_menu()
        )

async def search_city(update: Update, context: CallbackContext):
    await update.message.reply_text(
        "🔍 Введите название города:",
        reply_markup=ReplyKeyboardRemove()
    )
    return 'WAITING_CITY'

async def process_city(update: Update, context: CallbackContext):
    city = update.message.text
    user_id = update.effective_user.id
    
    # Проверяем, есть ли город в базе
    set_favorite_city(user_id, city)
    
    await update.message.reply_text(
        f"✅ Город {city} добавлен в избранное!",
        reply_markup=get_weather_menu()
    )
    return ConversationHandler.END

async def show_notes(update: Update, context: CallbackContext):
    notes = get_notes(update.effective_user.id)
    if notes:
        text = "📖 Ваши заметки:\n\n" + "\n\n".join(
            f"{note[2]}: {note[1]}" for note in notes
        )
    else:
        text = "У вас пока нет заметок."
    
    await update.message.reply_text(
        text,
        reply_markup=get_notes_menu()
    )

async def new_note(update: Update, context: CallbackContext):
    await update.message.reply_text(
        "✏️ Введите текст заметки:",
        reply_markup=ReplyKeyboardRemove()
    )
    return 'WAITING_NOTE'

async def process_note(update: Update, context: CallbackContext):
    text = update.message.text
    add_note(update.effective_user.id, text)
    
    await update.message.reply_text(
        "✅ Заметка сохранена!",
        reply_markup=get_notes_menu()
    )
    return ConversationHandler.END

def main():
    application = Application.builder().token(BOT_TOKEN).build()
    
    # Обработчики
    application.add_handler(CommandHandler('start', start))
    
    application.add_handler(MessageHandler(filters.Text(['👤 Профиль']), profile))
    application.add_handler(MessageHandler(filters.Text(['🌤 Погода']), weather))
    application.add_handler(MessageHandler(filters.Text(['📝 Заметки']), notes))
    application.add_handler(MessageHandler(filters.Text(['🔙 Назад']), back_to_main))
    
    application.add_handler(MessageHandler(filters.Text(['⏳ До дембеля']), dembel_count))
    application.add_handler(MessageHandler(filters.Text(['💰 Баланс']), show_balance))
    application.add_handler(MessageHandler(filters.Text(['💳 Пополнить баланс']), add_money))
    application.add_handler(MessageHandler(filters.Text(['👥 Рефералы']), show_referrals))
    
    application.add_handler(MessageHandler(filters.Text(['🏠 Родной город']), lambda u, c: weather_in_city(u, c, "Родной город")))
    application.add_handler(MessageHandler(filters.Text(['🏙 Москва']), lambda u, c: weather_in_city(u, c, "Москва")))
    application.add_handler(MessageHandler(filters.Text(['⭐ Избранные города']), favorite_city))
    
    application.add_handler(MessageHandler(filters.Text(['✏️ Новая заметка']), new_note))
    application.add_handler(MessageHandler(filters.Text(['📖 Мои заметки']), show_notes))
    
    # Обработчики с состояниями
    conv_handler_weather = ConversationHandler(
        entry_points=[MessageHandler(filters.Text(['🔍 Поиск города']), search_city)],
        states={
            'WAITING_CITY': [MessageHandler(filters.TEXT & ~filters.COMMAND, process_city)],
        },
        fallbacks=[]
    )
    
    conv_handler_notes = ConversationHandler(
        entry_points=[MessageHandler(filters.Text(['✏️ Новая заметка']), new_note)],
        states={
            'WAITING_NOTE': [MessageHandler(filters.TEXT & ~filters.COMMAND, process_note)],
        },
        fallbacks=[]
    )
    
    application.add_handler(conv_handler_weather)
    application.add_handler(conv_handler_notes)
    application.add_handler(CallbackQueryHandler(button_callback))
    
    application.run_polling()

if __name__ == '__main__':
    main()


Выдаёт ошибку в терминале:

PS C:\Users\Rota-4\Desktop\WeatherBot> python weather_bot.py
Traceback (most recent call last):
  File "C:\Users\Rota-4\Desktop\WeatherBot\weather_bot.py", line 88, in <module>
    init_db()
  File "C:\Users\Rota-4\Desktop\WeatherBot\weather_bot.py", line 50, in init_db
    cursor.execute('''
sqlite3.DatabaseError: file is not a database
PS C:\Users\Rota-4\Desktop\WeatherBot> 

База данных у меня такая:

def init_db():
    conn = sqlite3.connect('bot.db')
    cursor = conn.cursor()
    
    # Таблица пользователей
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS users (
        user_id INTEGER PRIMARY KEY,
        username TEXT,
        first_name TEXT,
        last_name TEXT,
        balance REAL DEFAULT 0,
        referral_code TEXT UNIQUE,
        referred_by TEXT,
        favorite_city TEXT
    )
    ''')
    
    # Таблица рефералов
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS referrals (
        referral_id INTEGER PRIMARY KEY AUTOINCREMENT,
        referrer_id INTEGER,
        referred_id INTEGER,
        date TEXT,
        FOREIGN KEY(referrer_id) REFERENCES users(user_id),
        FOREIGN KEY(referred_id) REFERENCES users(user_id)
    )
    ''')
    
    # Таблица заметок (ИСПРАВЛЕНО)
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS notes (
        note_id INTEGER PRIMARY KEY AUTOINCREMENT,
        user_id INTEGER,
        text TEXT,
        date TEXT,
        FOREIGN KEY(user_id) REFERENCES users(user_id)
    )  # Добавлена закрывающая скобка
    ''')
    
    conn.commit()
    conn.close()