我正在开发用于管理企业用途任务的电报机器人。团队负责人注册他的公司并获得唯一的ID,然后可以分配任务。问题是,当团队负责人分配任务时,他可以使用 /viewtasks 访问它们。但是,当员工尝试查看任务时,它会打印出“错误。您尚未注册”。
似乎无法检索与用户关联的 company_id,即使它已使用此 ID 注册。我的代码如下。请注意,我正在使用 aiogram 库
感谢您的帮助!
这是我的代码:
@dp.message(Command("viewtasks")) 异步 def view_tasks(消息: 消息): user_id = 消息.from_user.id logging.debug(f"用户 ID: {user_id}")
# Fetch user details
cursor.execute("SELECT company_id, role FROM users WHERE id = ?", (user_id,))
result = cursor.fetchone()
logging.debug(f"User details fetched for user ID {user_id}: {result}")
if not result:
await message.answer("Error. You are not registered")
return
company_id, role = result
# Fetch tasks associated with the user
if role == 'team_lead':
cursor.execute("SELECT task FROM tasks WHERE company_id = ?", (company_id,))
else:
cursor.execute("SELECT task FROM tasks WHERE user_id = ?", (user_id,))
tasks = cursor.fetchall()
# Debugging: Log the fetched tasks
logging.debug(f"Fetched tasks for user {user_id} role: {role}: {tasks}")
if not tasks:
await message.answer("No tasks")
else:
response = "\n".join([task[0] for task in tasks])
await message.answer(response)
这是我的数据库 (sqlite):
cursor.execute(''' 如果不存在则创建表用户( id 整数主键自动增量, 用户名文本, 电子邮件文本, 公司 ID 整数, 角色文本, 外键(company_id)参考公司(company_id)) ''')
cursor.execute(''' 如果不存在则创建表任务( id 整数主键自动增量, 用户 ID 整数, 任务文本, due_date 文本, 公司 ID 整数, 外键(user_id)引用用户(id), 外键(company_id)参考公司(company_id)) ''')
conn.commit()
代码的问题在于,你正在使用
user_id
作为
users
表中的主键,但在 Telegram 中,它不是唯一的。你需要使用 Telegram 的
user_id
(即
message.from_user.id
) 来查找用户的唯一 ID,然后使用该 ID 从数据库中检索信息。
以下是修改后的代码:
@dp.message(Command("viewtasks"))
async def view_tasks(message: Message):
telegram_user_id = message.from_user.id
logging.debug(f"Telegram User ID: {telegram_user_id}")
# Fetch user details using Telegram user ID
cursor.execute("SELECT id, company_id, role FROM users WHERE telegram_id = ?", (telegram_user_id,))
result = cursor.fetchone()
logging.debug(f"User details fetched for Telegram user ID {telegram_user_id}: {result}")
if not result:
await message.answer("Error. You are not registered.")
return
user_id, company_id, role = result
# Fetch tasks associated with the user
if role == 'team_lead':
cursor.execute("SELECT task FROM tasks WHERE company_id = ?", (company_id,))
else:
cursor.execute("SELECT task FROM tasks WHERE user_id = ?", (user_id,))
tasks = cursor.fetchall()
# Debugging: Log the fetched tasks
logging.debug(f"Fetched tasks for user {user_id} role: {role}: {tasks}")
if not tasks:
await message.answer("No tasks.")
else:
response = "\n".join([task[0] for task in tasks])
await message.answer(response)
你需要对数据库进行以下更改:
-
添加
telegram_id
列到users
表:
sql
ALTER TABLE users ADD COLUMN telegram_id INTEGER;
-
在用户注册时存储
telegram_id
:
在用户注册过程中,你需要将
message.from_user.id
存储到
users
表的
telegram_id
列中。
通过这些修改,你的机器人应该能够正确地识别用户并检索他们的任务。
标签:python,sqlite,telegram-bot,aiogram From: 78831964