@Flowmaked

Почему хостинг находит ошибку, а VS Studio нет?

Я пишу код на модер бота.
Сделал всю базу, что смог. Но sqlite3 не смог.
Задумка была какая: +rep и заносилось в таблицу репутаций, а также просмотр сообщений и лидеров по ним.
Но это вы и сами увидите в коде.

Код запустил, решил поставить на хостинг PythonAnywhere. И сразу начались проблемы.

Сейчас покажу ошибки, которые не получается обработать:

File "/home/Flowmakeed/bot/f1488.py", line 280
    @bot.message_handler(func=lambda message: message.text == '+rep')

Вот такая ошибка.
Затем была ошибка no such table users.

Вот сам код (отрывок).
Я запихал скрипт в самый конец, может в этом проблема.

bot.send_message(player_id, "Интервал 5 минут.")
        return

    players[player_id] = time.time()

    password = "FlowanTop" # set a password

    @bot.message_handler(func=lambda message: message.text == password, content_types=['text'])
    def handle_guess(message):
        player_name = message.from_user.first_name
        bot.send_message(player_id, f"✅Поздравляю, {player_name}! вы угадали код. Напишие об этом в: @FlowanaSupport_bot")

        # Notify the chat owner about the winner
        chat_owner_id = "783027478" # Put the owner's user ID here
        owner_name = bot.get_chat(chat_owner_id).first_name
        bot.send_message(chat_owner_id, f"✅Поздравляю, {owner_name}! {player_name} вы угадали пароль! Напишите об этом в : @FlowanaSupport_bot")

        # Remove the handler after the game is won
        bot.edited_message_handler(handle_guess)

    @bot.message_handler(func=lambda message: message.text != password, content_types=['text'])
    def handle_wrong_guess(message):
        if time.time() - players[player_id] < 300:
            bot.send_message(player_id, "⛔️Интервал между попытками 5 минут.")
        else:
            bot.send_message(player_id, "⛔️Неверный пароль, пробуй еще.")
            players[player_id] = time.time()

        # Remove the handler after the game is won
        bot.edited_message_handler(handle_wrong_guess)


@bot.message_handler(commands=['piar'])
def handle_piar(message):
    chat_id = message.chat.id
    markup = types.InlineKeyboardMarkup()
    btn1 = types.InlineKeyboardButton(text='О нашем боте✅', url='https://t.me/helpwithcodes')
    btn2 = types.InlineKeyboardButton(text='Наш чатик✅', url='https://t.me/Flowaneasy/1')
    markup.add(btn1, btn2)
    bot.send_message(chat_id, "Приветствую, я ваш бот модератор.\n\nПодавай заявку в наш чат.\nА также прочитай информацию о нашем боте в канале.\n\nЖми-Жми", reply_markup=markup)




@bot.message_handler(commands=['random'])
def handle_random(message):
    question = message.text.split('/random ')[-1]
    responses = ['Да', 'Нет', 'Скорее да', 'Скорее нет', 'Возможно']
    response = random.choice(responses)
    bot.reply_to(message, response)



# Словарь для хранения вариантов игры


game_options = { 'rock': 'Камень ', 'scissors': 'Ножницы ✂️', 'paper': 'Бумага '}

@bot.message_handler(commands=[ 'camen'])
def start_game(message):
    keyboard = types.InlineKeyboardMarkup()
    keyboard.row(
        types.InlineKeyboardButton(text='Камень', callback_data='rock'),
        types.InlineKeyboardButton(text='Ножницы', callback_data='scissors'),
        types.InlineKeyboardButton(text='Бумага', callback_data='paper')
    )
    bot.send_message(message.chat.id, "Выберите один из вариантов:", reply_markup=keyboard)

@bot.callback_query_handler(func=lambda call: True)
def handle_query(call):
    user_choice = call.data
    bot_choice = random.choice(list(game_options.keys()))

    result_message = "Ваш выбор: {}\nВыбор бота: {}\n\n".format(game_options[user_choice], game_options[bot_choice])

    if user_choice == bot_choice:
        result_message += "Ничья!"
    elif (user_choice == 'rock' and bot_choice == 'scissors') or (user_choice == 'scissors' and bot_choice == 'paper') or (user_choice == 'paper' and bot_choice == 'rock'):
        result_message += "Вы выиграли!"
    else:
        result_message += "Вы проиграли!"

    bot.send_message(call.message.chat.id, result_message)

    # Закончить игру
    bot.edit_message_reply_markup(call.message.chat.id, call.message.message_id) # Удалить инлайн клавиатуру









@bot.message_handler(commands=['start'])
def handle_piar(message):
    chat_id = message.chat.id
    markup = types.InlineKeyboardMarkup()
    btn1 = types.InlineKeyboardButton(text='О нашем боте✅', url='https://t.me/helpwithcodes')
    btn2 = types.InlineKeyboardButton(text='Наш чатик✅', url='https://t.me/Flowaneasy/1')
    btn3 = types.InlineKeyboardButton(text='Разработчик✅', url='https://t.me/Flowmaked')
    btn4 = types.InlineKeyboardButton(text='Поддержка 24/7', url='https://t.me/FlowanaSupport_bot')
    markup.add(btn1, btn2, btn3, btn4)
    with open('btn1.jpg' , 'rb') as photo:
            bot.send_photo(message.chat.id , photo)
   
    bot.send_message(chat_id, "Приветствую, для начала добавьте меня в чат и выдайте все права администратора\n\n/help - список всех команд\nПереходи в наш ресурсы по кнопке снизу.", reply_markup=markup)

conn = sqlite3.connect('respects.db')
cursor = conn.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS respects (chat_id INTEGER, user_id INTEGER, count INTEGER)')
cursor.execute('CREATE TABLE IF NOT EXISTS users (user_id INTEGER, username TEXT, messages_count INTEGER)')

script_dir = pathlib.Path(sys.argv[0]).parent
db_file = script_dir / 'database.db'
conn = sqlite3.connect(db_file)


@bot.message_handler(func=lambda message: message.text == '+rep')
def add_respect(message):
    chat_id = message.chat.id
    user_id = message.from_user.id

    conn = sqlite3.connect('respects.db')
    cursor = conn.cursor()

    cursor.execute('SELECT count FROM respects WHERE chat_id=? AND user_id=?', (chat_id, user_id))
    result = cursor.fetchone()

    if result:
        new_count = result[0] + 1
        cursor.execute('UPDATE respects SET count=? WHERE chat_id=? AND user_id=?', (new_count, chat_id, user_id))
    else:
        cursor.execute('INSERT INTO respects (chat_id, user_id, count) VALUES (?, ?, 1)', (chat_id, user_id))

    conn.commit()
    conn.close()

    bot.reply_to(message, 'Респект оставлен(+1)')


@bot.message_handler(commands=['tab'])
def show_respects(message):
    chat_id = message.chat.id

    conn = sqlite3.connect('respects.db')
    cursor = conn.cursor()

    cursor.execute('SELECT user_id, count FROM respects WHERE chat_id=?', (chat_id,))
    results = cursor.fetchall()

    with open('btn2.jpg', 'rb') as photo:
        if results:
            resp = 'Кол-во оставленных респектов:\n\n'
            for user_id, count in results:
                user = bot.get_chat_member(chat_id, user_id).user
                resp += f'{user.first_name}: {count}\n'
            bot.send_photo(chat_id, photo, caption=resp)
        else:
            bot.send_message(chat_id, text='Нет респектов в этом чате')

    conn.close()


@bot.message_handler(commands=['me'])
def get_messages_count(message):
    conn = sqlite3.connect('database.db')
    user_id = message.from_user.id

    with conn:
        cursor = conn.cursor()
        cursor.execute("SELECT messages_count FROM users WHERE user_id=?", (user_id,))
        result = cursor.fetchone()
        if not result:
            cursor.execute("INSERT INTO users (user_id, username, messages_count) VALUES (?, 0)", (user_id, message.from_user.username))
            conn.commit()

        cursor.execute("SELECT messages_count FROM users WHERE user_id=?", (user_id,))
        result = cursor.fetchone()
        messages_count = result[0]

        bot.send_message(message.chat.id, f"У вас {messages_count} сообщений. \nПросмотр таблицы лидеров\n/leaders")


@bot.message_handler(commands=['leaders'])
def get_leaders(message):
    conn = sqlite3.connect('database.db')

    with conn:
        cursor = conn.cursor()
        cursor.execute("SELECT username, messages_count FROM users ORDER BY messages_count DESC LIMIT 10")
        leaders = cursor.fetchall()

    table = "Лидеры по сообщениям:\n"
    for i, leader in enumerate(leaders, start=1):
        table += f"{i}. {leader[0]} - {leader[1]} сообщений\n"

    text = f"{table}\n\nВосхитительно, продолжайте!"

    markup = types.InlineKeyboardMarkup()
    btn = types.InlineKeyboardButton(text='Нашел ошибку?', url='https://t.me/FlowanaSupport_bot')
    markup.add(btn)

    bot.send_message(message.chat.id, text, reply_markup=markup)


@bot.message_handler(func=lambda message: True)
def update_messages_count(message):
    conn = sqlite3.connect('database.db')
    user_id = message.from_user.id
    username = message.from_user.username

    with conn:
        cursor = conn.cursor()
        cursor.execute("INSERT OR IGNORE INTO users (user_id, username, messages_count) VALUES (?, 0)", (user_id, username))
        cursor.execute("UPDATE users SET messages_count = messages_count + 1 WHERE user_id=?", (user_id,))
        conn.commit()
 

bot.polling()
  • Вопрос задан
  • 75 просмотров
Пригласить эксперта
Ваш ответ на вопрос

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

Войти через центр авторизации
Похожие вопросы