I have been playing with the telegram API and discovered a way to send form data from a website to your phone’s telegram app. It involves creating a telegram bot with the help of botfather. I would suggest you read this article on a detailed understanding of telegram bots. So let us first create a telegram bot.
So we have created the bot and now we have the API token as well. The next thing we need to do is create a simple HTML form. So we will use the following code, it’s a very basic HTML form that submits its data to the form.php file.
<input type="text" name="name" placeholder="Your Name">
<textarea name="message" placeholder="Your Message Here" rows="6" cols="33"></textarea>
<input type="submit" value="Submit">
The form looks like this.
Now we need to write the code for the form.php file, This is a little tricky and important in terms of security as now you need to get your chat id.
The chat id will be a unique id between you and the bot you have created so that the bot only messages you. To get the chat id, search for the bot and send it a message. Once you are done with that, visit the following URL in your browser
You should see something like this
This is the update object and has many messages that have been sent to us, we are only concerned about the chat id. Currently, for my bot’s chat with me, the chat id is 316456110.
Now let’s get writing the PHP code. It is extremely functional and easy spanning just around 5 lines,
$name = $_GET['name'];
$message = $_GET['message'];
$chat_id = '316456110';
$message = urlencode("Name:".$name."\n Message : ".$message);
So from the code above, you can understand the following things.
- We defined the URL for our bot that will make requests to telegram.
- We fetched the name and message from the form and the chat id is something we already had.
- We then urlencoded the message since we did some formatting.
- We finally made the API request to telegram by supplying the message body and chat id.
- We also passed in the parse_mode parameter since our message has some HTML formatting.
That’s it for the work, Now it’s time to play. Every time someone submits the form, you will get a notification from your bot like this.
We saw a great implementation of telegram API into website forms. Telegram API is extremely flexible and you can also upload files via this method. I highly recommend that you read this article for a clear and in-depth understanding of telegram bots. If you get stuck working this out, do let me know in the comments section and I’ll be there for you.