使用JavaScript通过html表单发送消息到Telegram

fhity93d  于 9个月前  发布在  Java
关注(0)|答案(2)|浏览(105)

是否可以使用JavaScript将表单数据发送到电报?我读了很多答案,但几乎所有都是基于PHP的。

vwkv1x7d

vwkv1x7d1#

是的,你可以编程你的电报机器人,并使用JavaScript发送任何消息(使用AJAX,因为电报机器人API是一个基于Web请求的API)。
例如,您可以通过以下方式向特定用户发送消息:

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");

字符串
也可以使用POST请求发送数据。例如:

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` // 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));
}

// 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");


有关更多信息,请参见Telegram bot API文档:https://core.telegram.org/bots/api

7vux5j2d

7vux5j2d2#

您可以使用Telegram API发送消息。

相关问题