You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Aiogram的函数外部获取Telegram Bot用户ID?

在Aiogram中如何在消息处理函数外部获取用户ID?

你已经掌握的常规获取用户ID的方式是在消息处理函数内部直接读取:

async def start(message: types.Message):
    await bot.send_message(message.from_user.id, f'Here is your id {message.from_user.id}')

针对“能否在async def start(message: types.Message)函数外部获取该用户ID”的问题,答案是可以,但需要通过存储或上下文传递的方式实现,以下是具体方案:

方案1:使用全局存储变量

将用户ID存储到全局字典或变量中,外部函数可以直接读取该存储:

# 全局字典用于存储用户ID,键值可以用用户ID本身或其他标识
user_id_store = {}

async def start(message: types.Message):
    user_id = message.from_user.id
    user_id_store[user_id] = user_id
    await bot.send_message(user_id, f'Here is your id {user_id}')

# 外部函数获取用户ID
def get_stored_user_id(target_id):
    return user_id_store.get(target_id)

方案2:利用Aiogram的状态管理(FSM)

通过有限状态机(FSM)存储用户ID,在其他需要的地方通过状态上下文读取:

from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.dispatcher import FSMContext

# 定义状态类
class UserData(StatesGroup):
    current_user_id = State()

async def start(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    # 将用户ID存入状态
    await state.update_data(current_user_id=user_id)
    await bot.send_message(user_id, f'Here is your id {user_id}')

# 在其他异步函数中获取(需要传入state对象)
async def fetch_user_id(state: FSMContext):
    data = await state.get_data()
    return data.get('current_user_id')

方案3:写入数据库持久化存储

如果需要长期保存或跨会话获取用户ID,可以将其写入数据库(如SQLite、PostgreSQL等),外部通过数据库查询获取:

import sqlite3

# 初始化数据库连接
conn = sqlite3.connect('users.db')
cursor = conn.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS users (user_id INTEGER PRIMARY KEY)')
conn.commit()

async def start(message: types.Message):
    user_id = message.from_user.id
    # 写入数据库
    cursor.execute('INSERT OR IGNORE INTO users (user_id) VALUES (?)', (user_id,))
    conn.commit()
    await bot.send_message(user_id, f'Here is your id {user_id}')

# 外部查询用户ID
def get_user_id_from_db(target_id):
    cursor.execute('SELECT user_id FROM users WHERE user_id = ?', (target_id,))
    result = cursor.fetchone()
    return result[0] if result else None

注意事项

  • 无法在完全独立的、不依赖任何存储/上下文的外部函数中直接获取用户ID,因为用户ID只有在消息触发时才会生成并通过message对象传递,必须先将其存储到某个介质中才能在外部访问。

内容的提问来源于stack exchange,提问作者Ivan Kachula

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 12:00:54