Script to integrate Platform.sh with Telegram

Well, for those Telegram fans, out there here’s a simple script to post activities to Telegram.

See the docs for general information about activity scripts

Usage:

Add the required configuration variables:

platform variable:create --level project --name env:TELEGRAM_TOKEN --value foo
platform variable:create --level project --name env:TELEGRAM_CHAT_ID --value bar

Replacing foo and bar with appropriate values (you’d probably want to create a bot user with a token).

Save the script below as telegram.js and using the CLI: platform integration:add --type script --file ./telegram.js

var storage = require("storage");
/**
 * Sends a  message to Telegram.
 *
 * You must first configure  Platform.sh variables named "TELEGRAM_TOKEN".
 * and "TELEGRAM_CHAT_ID"
 * That is the API token and chat to which the message will be sent.
 *
 * To control what events it will run on, use the --events switch in
 * the Platform.sh CLI.
 *
 * @param {string} message
 *   The message body to send.
 */
function sendTelegramMessage(message) {

    console.log((new Date).getDay());

    if ((new Date).getDay() === 5) {
        message += "\r\nOn a Friday! :calendar:";
    }
    var token = storage.get('env:TELEGRAM_TOKEN') || variables()['env:TELEGRAM_TOKEN'];
    var chat_id = storage.get('env:TELEGRAM_CHAT_ID') || variables()['env:TELEGRAM_CHAT_ID'];
    
    storage.set('env:TELEGRAM_TOKEN', token);
    storage.set('env:TELEGRAM_CHAT_ID', chat_id);
    
    if (!token) {
        throw new Error('You must define a TELEGRAM_TOKEN project variable.');
    }

    var url = "https://api.telegram.org/bot" + token + "/sendMessage";

    var body = {
        chat_id: chat_id,
        text: message,
        
    }

    var resp = fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(body),
    });

    if (!resp.ok) {
        console.log("Sending telegram message failed: " + resp.body.text());
    }
}

function variables() {
    var vars = {};
    activity.payload.deployment.variables.forEach(function(variable) {
        vars[variable.name] = variable.value;
    });

    return vars;
}

sendTelegramMessage(activity.text);
1 Like