1

For example, if the user sends the bot /text @USER how do I get @USER's id and message them?

Question different from this since the answer to that question requires said user (@USER) to already message the bot/the owner to already know the user's id.

Community
  • 1
  • 1
Noam Barnea
  • 23
  • 1
  • 7
  • Possible duplicate of [How to obtain Telegram chat\_id for a specific user?](http://stackoverflow.com/questions/31078710/how-to-obtain-telegram-chat-id-for-a-specific-user) – Ali Mottaghi Pour Aug 14 '16 at 12:04
  • Not duplicate since the answer for "[How to obtain Telegram chat_id for a specific user?](http://stackoverflow.com/questions/31078710/how-to-obtain-telegram-chat-id-for-a-specific-user)" requires said user to already message the bot/the owner to already know the user's id. – Noam Barnea Aug 14 '16 at 12:11

1 Answers1

2

There are 3 conditions:

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)

This is a sample JSON response from Telegram when user send /1 command, as you see telegram always attaches sender chat_id,firs_name,last_name and username(if exists) to each message that bot receives:

This is a sample JSON response from Telegram when user send <code>/1</code> command

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.

Seyfi
  • 1,832
  • 1
  • 20
  • 35
  • Using this and the `pickle` library I managed to store a users dictionary `{'@USER': 999999999}` as a file and load it whenever the bot starts up (if a new user sends it /start it'll add them to the dictionary) – Noam Barnea Aug 15 '16 at 08:03
  • I'll try to implement that. Do you know any way to update a dictionary in such a way that the key changes but the value does not? – Noam Barnea Aug 15 '16 at 20:12
  • @NoamBarnea ,I recommend you to use databases like MySQL and so on instead of handling a file . – Seyfi Aug 15 '16 at 21:33