带有 postgresql 和 asyncpg 的 Telegram 机器人。数据库查询执行期间出错:“NoneType”对象没有属性“send

问题描述 投票:0回答:1

我在 postgresql 上有电报机器人和数据库。 数据库 有一张图片。 我的数据库工作正常,如果我需要在其中添加一些东西,它就会工作。 我需要可以为某人添加订阅并获得订阅的功能。

添加订阅功能

async def add_subscription(user_id: BigInteger, start_date: DateTime, end_date: DateTime):
    async with async_session() as session:
        async with session.begin():
            new_subscription = UserSubscription(
                user_id=user_id,
                subscription_start=start_date,
                subscription_end=end_date
            )
            session.add(new_subscription)
            await session.commit()

获取订阅功能

async def get_subscription(user_id: BigInteger):
    async with async_session() as session:
        print(f"Running DB query for user_id: {user_id}")
        async with session.begin():
            print("session begins")
            try:
                query = text("SELECT subscription_start, subscription_end FROM users WHERE user_id = :user_id")
                result = await session.scalars(query, {"user_id": user_id})
                subscription = result._fetchone_impl()
                return subscription
            except Exception as e:
                print(f"Error during DB query execution: {e}")
                return None

我添加了很多打印来尝试了解错误在哪里。第二个函数(我的意思是 get_subscription)我面临打印(“会话开始”),然后我面临错误。它说:

session begins
2024-09-04 01:08:52,132 INFO sqlalchemy.engine.Engine BEGIN (implicit)
INFO:sqlalchemy.engine.Engine:BEGIN (implicit)
2024-09-04 01:08:52,133 INFO sqlalchemy.engine.Engine SELECT subscription_start, subscription_end FROM users WHERE user_id = $1
INFO:sqlalchemy.engine.Engine:SELECT subscription_start, subscription_end FROM users WHERE user_id = $1
2024-09-04 01:08:52,134 INFO sqlalchemy.engine.Engine [cached since 21.7s ago] (1867377574,)
INFO:sqlalchemy.engine.Engine:[cached since 21.7s ago] (1867377574,)
Error during DB query execution: 'NoneType' object has no attribute 'send'
2024-09-04 01:08:52,135 INFO sqlalchemy.engine.Engine COMMIT
INFO:sqlalchemy.engine.Engine:COMMIT
Subscription: None

1867377574 : MY TG ID.

我在我的机器人中创建了一个名为“/subscription”的命令。我的代码是:

@dp.message(Command("subscription"))
async def cmd_subscription(message: types.Message):
    print("Command /subscription received") 
    user_id = message.from_user.id
    print(f"User ID: {user_id}")
    try:
        subscription = await db.get_subscription(user_id)
        print(f"Subscription: {subscription}")  # Выводим полученные данные
    except Exception as e:
        print(f"Error retrieving subscription: {e}")  # Выводим ошибку, если что-то пошло не так
        return  # Прерываем выполнение, если есть ошибка
    
    if subscription:
        start_date, end_date = subscription
        response = f"Subscription Start: {start_date}\nSubscription End: {end_date}"
    else:
        response = "No subscription found for your user ID."
    
    try:
        await message.answer(response)
    except Exception as e:
        print(f"Error sending message: {e}")  # Выводим ошибку, если не удаётся отправить сообщение

因此,当我到达机器人并写入命令 /subscription 时,它显示“未找到您的用户 ID 的订阅”并给出错误数据库查询执行期间出现错误:“NoneType”对象没有属性“send”。 我没有得到比 subscription = wait db.get_subscription(user_id) 更进一步的信息,所以问题出在第二个函数 (get_subscription) 或数据库连接 idk 中。

我在代码末尾有这个,它可能有用

async def main():
    
    # Получение подписки
    subscription = await get_subscription(user_id=1867377574)
    print(subscription)

# Запуск основного асинхронного цикла
asyncio.run(main())
database postgresql python-asyncio telegram-bot
1个回答
0
投票

好吧,我找到了解决方案。我没有添加 if name == "main": asyncio.run(main())。我认为它必须在 Bot.py 文件中,但不能在database.py 文件中。

© www.soinside.com 2019 - 2024. All rights reserved.