如何通过提及 (@User) 获取用户 ID

How to get a user's id from mentioning (@User)

例如,如果用户发送机器人 /text @USER 我如何获取@USER 的 ID 并向他们发送消息?

问题与 不同,因为该问题的答案要求所述用户 (@USER) 已经向 bot/the 所有者发送消息,让其知道用户的 ID。

有3个条件:

1-@user is not subscribed to your bot before(not initiated chat with your bot before or it does block your bot after some chat with your bot: In this condition you can NEVER send any type of message to that @user.

2-@user doesn't exist or is incorrect . As you know, a telegram user subscribe with phone and first name (at least) and he/she could not have any @user id: In this condition there is no user name to send.

3-@user exists and already is your bot subscriber. In this condition you should save all subscribers chat_id and their related user_name as they sends some messages to your bot in a database because these data are part of each message you receive from users. So for send to that @user you should find related chat_id from your DB.(Non of Telegram Bot API methods use @username but they use chat_id)

这是用户发送 /1 命令时电报的 JSON 响应示例,如您所见,电报始终附加发件人 chat_idfirs_namelast_nameusername(如果存在)到机器人收到的每条消息:

UPDATED:

As users may change they @username during the time, it is better to update your chat_id<-->@username database with each message you receive.