After creating a telegram bot and gain bot token, I want to send a request to the bot API.
This link says we must send the HTTP request like this:
https://api.telegram.org/bot<token>/METHOD_NAME
and brings example for easiest method “getme” which has not any input parameters.
Imagine I want to send some messages. I should use the sendMessage
method which has two Required input parameters: chat_ID and text.
Now my Questions begins:
-
How can I write this sendMessage method in above request format with its parameters? I tried
sendMessage(param1,param2)
and received method not found message. -
What is
chat_id
? if I want to send a message to the contact, how can I know hischat_id
?
I searched a lot on the internet, there are plenty of projects on GitHub especially for this purpose, and honestly none of them makes any sense.
for god’s sake someone please help me. I am loosing way.
Regards.
2
Answers
You just send a POST request to:
For example:
In the body of the request, you URL encode the parameters:
For example, in Python using the
requests
module:When a user chats with your bot, you get a
Message
object that has a chat id (and a user id, which you can substitute for a chat id). There’s no way to initiate a chat with a user unless you already know their user id, so you have to wait for a user to talk to you. You can simplify that by using deep linking and having the user click on a link that sends a pre-made message when they hit the Start button.Edit: for those struggling to find chat_id, here’s a way:
1.- Create a bot: on Telegram’s search look for @BotFather. Click start, write /newbot, give it a name and a username. You should get a token to access the HTTP API. Save this token.
2.- Find your bot on Telegram with its username. Write something to it e.g. ‘test’. This will come in handy later.
3.- Print chat_id. Before running this function, make sure that you have at least written one message to your bot on Telegram (step 2)
Javascript code:
Try this
Example