@cryptone

Скрипт бота в телеграм запускается и сразу завершает работу без ошибки, почему?

import logging
import os
import telegram
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler
import sqlite3

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)

# Connect to the database
conn = sqlite3.connect('addresses.db')
cursor = conn.cursor()

# Create the table to store addresses and number of places
cursor.execute('''
CREATE TABLE IF NOT EXISTS addresses (address text, places integer)
''')
conn.commit()

# Store an address and number of places in the database
def add_address(update, context):
    address = update.message.text.split()[1:]
    address = ', '.join(address)
    places = update.message.text.split()[-1]
    cursor.execute("INSERT INTO addresses VALUES (?,?)", (address, places))
    conn.commit()
    update.message.reply_text("Address and number of places added successfully!")

# Return a list of addresses and number of places from the database
def list_addresses(update, context):
    cursor.execute("SELECT * FROM addresses")
    addresses = cursor.fetchall()
    keyboard = []
    for address in addresses:
        button = [InlineKeyboardButton(f"{address[0]}: {address[1]} places", callback_data=address[0])]
        keyboard.append(button)
    reply_markup = InlineKeyboardMarkup(keyboard)
    update.message.reply_text("List of addresses and number of places:", reply_markup=reply_markup)

# Handle button presses in the inline keyboard
def button(update, context):
    query = update.callback_query
    query.answer()
    query.edit_message_text(text=f"Selected address: {query.data}")

def main():
    try:
        # Create the Updater and pass it the bot's token.
        bot = telegram.Bot(token=os.environ['TOKEN'])
        updater = Updater(bot.token, use_context=True)

        # Get the dispatcher to register handlers
        dp = updater.dispatcher

    # Add command handlers
        dp.add_handler(CommandHandler("add", add_address))
        dp.add_handler(CommandHandler("list", list_addresses))

    # Add callback handler
        dp.add_handler(CallbackQueryHandler(button))

    # Start the Bot
        updater.start_polling()

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
        updater.idle()
    except Exception as e:
        logger.error(f"{e}")


Скрипт запускается и сразу завершает работу без ошибки, в чём дело?
  • Вопрос задан
  • 249 просмотров
Решения вопроса 1
TOA
@TOA
Негр c агрессивным характером.
Скрипт, скорее всего, завершается немедленно, потому что вы пропустили вызов функции main() в конце скрипта. Функция main() содержит всю логику для бота, но если ее не вызвать, скрипт запустится без выполнения этой логики и немедленно завершится. Чтобы решить эту проблему, добавьте следующую строку в конец скрипта:
if __name__ == '__main__':
    main()
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

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

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