Skip to main content

How to send a contact form to Telegram (bot token and chat ID)

Updated 7 min readMarkdown

A Telegram bot can post every contact form message to your phone, a group or a channel. You need two things from Telegram, a bot token and a chat ID, and something on a server that holds the token, because anyone who has it can send messages as your bot. It can't go in your page's JavaScript.

This guide gets the token and chat ID first, since you need them either way. Then there are two ways to send the messages:

  1. A PHP script next to your site, if you're on shared hosting (cPanel, Hostinger, Bluehost and the like). It's one file and needs no build step.
  2. A form backend, if you'd rather not run anything and want spam filtering and storage too.

Get the bot token and chat ID

The token

In Telegram, message @BotFather, send /newbot, and pick a name and a username. BotFather replies with a token like 123456789:AAH.... Copy all of it, including the numbers before the colon.

The chat ID

First put the bot where the messages should go:

  • Just you: open your bot and press Start. A bot can't message someone who never started it.
  • A group: add the bot to the group, then send /start@your_bot_username there. Bots in groups only see commands and replies meant for them by default, so a plain message won't show up in the next step.
  • A channel: add the bot as an administrator that can post messages, then post anything in the channel.

Then open this in your browser, with your token in place of <token>:

https://api.telegram.org/bot<token>/getUpdates

Find "chat":{"id": in the response and copy the number. Private chats have a positive ID. Groups and channels start with a minus sign, like -1001234567890, and the minus is part of the ID. For a public channel you can also use its username, like @yourchannel.

If you see "result":[], Telegram has nothing new for the bot yet (it keeps updates for 24 hours). Send the message or command again and reload.

1. A PHP script on shared hosting

The form

<form action="/contact.php" method="POST">
  <input name="name" placeholder="Name" required>
  <input name="email" type="email" placeholder="Email" required>
  <textarea name="message" placeholder="Message" required></textarea>
  <!-- Honeypot: hidden from people, bots fill it in -->
  <div aria-hidden="true" style="position:absolute; left:-9999px">
    <input type="text" name="_gotcha" tabindex="-1" autocomplete="off">
  </div>
  <button type="submit">Send</button>
</form>

Keep the token out of the web root

Save the token in a file one folder above public_html, so it can't be downloaded even if PHP stops running for some reason. Call it telegram-config.php:

<?php
return [
    'token' => '123456789:AAH...',
    'chat_id' => '-1001234567890',
    'thanks_url' => '/thanks.html',
];

The script

Save this as public_html/contact.php:

<?php
$config = require dirname(__DIR__) . '/telegram-config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit;
}

// Honeypot filled in: pretend it worked and send nothing.
if (!empty($_POST['_gotcha'])) {
    header('Location: ' . $config['thanks_url'], true, 303);
    exit;
}

function field(string $name, int $max): string {
    return mb_substr(trim((string) ($_POST[$name] ?? '')), 0, $max);
}

// The message uses Telegram's HTML mode, so <, > and & in what visitors
// type have to be escaped, or Telegram refuses the whole message.
function h(string $text): string {
    return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

$name = field('name', 200);
$email = field('email', 200);
$message = field('message', 3500);

if ($email === '' || $message === '') {
    http_response_code(400);
    exit('Email and message are required');
}

$text = "<b>New contact form message</b>\n\n"
    . '<b>Name:</b> ' . h($name) . "\n"
    . '<b>Email:</b> ' . h($email) . "\n\n"
    . h($message);

$ch = curl_init('https://api.telegram.org/bot' . $config['token'] . '/sendMessage');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => http_build_query([
        'chat_id' => $config['chat_id'],
        'text' => $text,
        'parse_mode' => 'HTML',
        'link_preview_options' => json_encode(['is_disabled' => true]),
    ]),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 10,
]);
$response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($status !== 200) {
    // Telegram's error says what's wrong, like "chat not found".
    error_log('Telegram sendMessage failed: ' . $status . ' ' . $response);
    http_response_code(502);
    exit("Couldn't send your message. Please try again.");
}

header('Location: ' . $config['thanks_url'], true, 303);

Submit the form once. If nothing arrives, the reason is in your host's PHP error log (in cPanel, Metrics → Errors, or an error_log file next to the script).

Why messages go missing

  • 400 Bad Request: can't parse entities. Someone typed <3 or a < b and it wasn't escaped. In HTML mode Telegram rejects the whole message rather than showing it as text, which is why the script runs everything through h().
  • 400 Bad Request: chat not found. The chat ID is wrong (often the minus sign got lost), or the bot isn't in that chat.
  • 403 Forbidden: bot can't initiate conversation with a user. You never pressed Start in the private chat. After that it works.
  • 403 Forbidden: bot was kicked or bot was blocked by the user. Someone removed the bot. Add it back.
  • 400 Bad Request: group chat was upgraded to a supergroup chat. When a group gets bigger or changes some settings, Telegram turns it into a supergroup with a new ID. The response includes migrate_to_chat_id; put that number in your config.
  • 4,096 characters per message. Telegram rejects anything longer. The script cuts each field so a long message still fits.
  • Rate limits. Telegram asks bots to stay under about one message a second per chat and 20 a minute in a group. Past that you get 429 Too Many Requests and the script doesn't retry.
  • Your host blocks outgoing requests. Some free hosting plans don't let PHP call other servers, so curl_exec times out and $status is 0. Ask your host or move to a paid plan.

The honeypot stops simple bots. Anything that fills in the form like a person, or posts straight to contact.php, still lands in your chat, and with nothing stored, a failed send means the message is gone. How to stop contact form spam goes through the other layers.

2. A form backend

With Formkove, the form posts to a Formkove URL and there's no script to host:

<form action="https://app.formkove.com/api/forms/YOUR_FORM_ID/submissions" method="POST">

In the form's Integrations → Telegram, paste the bot token and chat ID from the first section and click Send test. The token is stored encrypted and never shown again. Each submission arrives as one message with the form name, every field, a download link for each uploaded file and, when AI is on, its sentiment and tags. Field values are escaped, and long submissions are trimmed to fit 4,096 characters, with the full one in your dashboard.

You can add one Telegram connection per chat, and a routing rule decides what goes where. For example, a sales group that only gets submissions tagged sales-lead, or your private chat for anything with negative sentiment. Rules can test the AI's tags and sentiment, the spam score, or any form field.

Spam is held back before it reaches Telegram and kept in your dashboard for 30 days in case one was a real message. Every submission is saved and emailed to you even if the bot gets kicked from the chat. Rate limits and Telegram outages are retried, and every failed delivery is listed in Delivery history with Telegram's error.

Telegram, tags and routing are on the Pro and Agency plans, and Free accounts get them on their first 50 submissions (pricing). Setup and troubleshooting are in the Telegram docs.


Originally published on formkove.com.

No comments yet. Be the first to comment.