Skip to content Skip to sidebar Skip to footer

Sending Message To Telegram Bot

i need some help, am trying to send message to telegram bot but things are not working out for me, am just trying to archive what i want to do. am new to jquery and javascript belo

Solution 1:

There are several issues in you script:

  • Your <body> tag is misplaced
  • AFAIK, your payload must be form encoded (not as GET params)
  • Use ` for format strings instead of "
  • read the input values in the execute method, not outside (otherwise you read them only once on page load).
  • You cannot use <br> or <html> in the message, see the docs
<!DOCTYPE html><htmllang="en"><head><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script></head><body><inputtype="text"id="fname"name="fname"placeholder="fullname"><inputtype="text"id="country"name="country"placeholder="country"><inputtype="button"id="add_button"value="Submit"><divid="response"></div><script>const token = '<token>';
    const chatId = '<chat_id>';

    $(document).ready(function () {
        $("#add_button").on('click', function (event) {
            execute();
        });

        functionexecute() {
            const fname = document.querySelector('#fname').value;
            const country = document.querySelector('#country').value;
            const message = `Fullname: ${fname}\nCountry: ${country}`;

            $.ajax({
                type: 'POST',
                url: `https://api.telegram.org/bot${token}/sendMessage`,
                data: {
                    chat_id: chatId,
                    text: message,
                    parse_mode: 'html',
                },
                success: function (res) {
                    console.debug(res);
                    $('#response').text('Message sent');
                },
                error: function (error) {
                    console.error(error);
                    alert("error failed");
                }
            });
        }
    });
</script></body></html>

And a security note:

Do NOT use this script in any production! NEVER EVER! Everyone would be able to read and abuse your bot token. Use a backend for this.

Post a Comment for "Sending Message To Telegram Bot"