5
votes

I want to build a telegram bot for feed subscription, so the subscribers can get site update. But I need user to start chat with my bot. I'll using deep linking according to this url: https://core.telegram.org/bots#deep-linking (assuming there are 2 users)

  1. Show the below link to user #2 https://telegram.me/MyBot?start=$unique_code
  2. User #2 clicks on link and start chat with bot.
  3. User #2 comes back to my site and clicks on check button.
  4. Site makes a getUpdates request and find the chat_id that associated with the user's unique_code.
  5. Offset will be increased by 1.

Now there is a problem. When offset increased what about user #1 that starts chat with bot just before the user #2. If #1 clicks on check button after increasing offset by #2, the bot will not received the #1 message.

p.s. I don't want using ssl and webhook

Sorry for bad English.

1
I think you should read telegram getUpdates api again. - hamed
@hamed thanks. I read it several times but can't figured out that. - Ameer Mousavi
you don't need to show each user a unique link, each user has a unique userid and you can use it whereever you need it - hamed
Why users should come back to your site? What is the check button? - hamed
In order to send messages to users I need their chat_id and because I can't detect which user is sending /start command so I need to give them a unique_code in my site. Then user clicks on link and when clicks on /start command the unique_code passed to bot. Since I haven't webhook then user should back to my site and click on check button for updates. - Ameer Mousavi

1 Answers

3
votes

You are almost right in what you are trying to achieve. Two things:

  • Step 3 is unnecessary.
  • You should store this $unique_id somewhere, together with the user's username on your website. Then, when this person clicks on your link with your unique id, you can link the user's userId to the user's username.

So the steps become:

  1. Generate a unique code (let's call it $unique_code). Save this code together with the username of the person currently logged on on your website (let's call that $username) in a database.
  2. Show user #2 a link with this unique code (https://telegram.me/MyBot?start=$unique_code)
  3. The user clicks the link, after which your bot receives a message with the $unique_code ('/start $unique_code').
  4. The bot associates the $unique_code with $username and stores the chat_id of the user that sent the message, in the database. (message.chat.id - see https://core.telegram.org/bots/api#message)

Now, whenever you want to send a message to $username, simply look up their chat_id in the database and send a message to that chatId (https://core.telegram.org/bots/api#sendmessage).