Search code examples
javascripthtmltelegramform-data

Send message to Telegram through html form using Javascript


Is it possible to send Html Form Data (in a html page) to Telegram Api using JavaScript?


Solution

  • Yes you can program your telegram bot and send any message using javascript (using AJAX since the telegram bot api is a web request based api).

    For example, you send message to a specific user by this:

    let tg = {
        token: "BOT_TOKEN", // Your bot's token that got from @BotFather
        chat_id: "CHAT_ID" // The user's(that you want to send a message) telegram chat id
    }
    
    /**
     * By calling this function you can send message to a specific user
     * @param {String} the text to send
     *
    */
    function sendMessage(text)
    {
        const url = `https://api.telegram.org/bot${tg.token}/sendMessage?chat_id=${tg.chat_id}&text=${text}`; // The url to request
        const xht = new XMLHttpRequest();
        xht.open("GET", url);
        xht.send();
    }
    
    // Now you can send any text(even a form data) by calling sendMessage function.
    // For example if you want to send the 'hello', you can call that function like this:
    
    sendMessage("hello");
    

    Also you can use POST request to send data. For example:

    function sendMessage(text)
    {
        const url = `https://api.telegram.org/bot${tg.token}/sendMessage` // The url to request
    
        const obj = {
            chat_id: tg.chat_id, // Telegram chat id
            text: text // The text to send
        };
    
        const xht = new XMLHttpRequest();
        xht.open("POST", url, true);
        xht.setRequestHeader("Content-type", "application/json; charset=UTF-8");
        xht.send(JSON.stringify(obj));
    }
    

    Alternatively, you can use fetch instead of XMLHttpRequest.

    async function sendMessage(text)
    {
        const url = `https://api.telegram.org/bot${tg.token}/sendMessage` // The url to request
    
        const obj = {
            chat_id: tg.chat_id, // Telegram chat id
            text: text // The text to send
        };
    
        await fetch(url, {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(obj)
        });
    }
    

    Resources:

    Telegram Bot API documentation - https://core.telegram.org/bots/api
    Fetch API - https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
    XMLHttpRequest - https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest