Jump to content

[Tutorial] Push Notifications using Telegram (Example Code and MORE!)


agentcallooh

Recommended Posts

Hey all, this tutorial will teach you how to enable push notifications in your script using the Telegram platform.

What is Telegram?

Telegram (Wikipedia) is a massively popular, fast, secure and private messenger with 200 million monthly active users (as of March 2018). It provides a straightforward yet powerful chat bot API that rivals Discord and WhatsApp. (I'd argue it's way better than both -wink-)

Oh, and it's free.

Step 1: Telegram Client and Account

Obviously, you'll need a Telegram to account to use it. Sign up for Telegram using your phone number (you cannot use email/password) via the Telegram Web client, or via the Android/iOS app (use the links on telegram.org). This should be a no-brainer.

Concerned about privacy, or don't want to give out your actual phone number? That's good - you can use a Google Voice phone number instead of your own. They never call, text or sell your phone number - except once to verify ownership of the number. Other alternatives include freephonenum.com, but beware: if you lose a disposable number and get logged out it's game over. Here's a guide from TechJunkie on Telegram privacy and recommended settings you should use.

Step 2: Getting a Telegram Bot Token and Your Chat ID

The first thing you'll require is a Telegram chat bot. Every bot a single bot token used to control it. Start a conversation with the BotFather (@BotFather), who will guide you through the creation of your bot and provide you its token. First, type /start, then /newbot. The BotFather should guide you through the rest of the process of choosing a name and username. He'll end with providing the bot token. Optional: You can choose to upload a profile picture for your bot, or set the about text and description. Once you have this, you're ready to continue! Your bot token should look something like this:

1020719143:AAFy_Qq45y5bLmsZllUrsZ5yLkCvY6obNkk (FYI, this and all other tokens in this post have already been revoked, so they will not work)

image.png.6508d888302101bc3498ff87353e9bc0.png  -->  image.png.fe03ba2307d473facafeb38d590872d4.png

Open a chat with your bot the same way you did with BotFather - enter its username in the search bar. Type or tap /start to send your first message to your bot - don't miss this step! Nothing happens because there's no software listening on the other end. That's OK, we won't need any in order to send a message!

image.png.7ce8cfb2c3500b9dd4e3d3014f25b2ed.png  -->  image.png.61b4f93a6573f5930e5e5af9702509fa.png

Next, we're going to retrieve the chat ID between your Telegram account and the bot. By sending /start to your bot, you queue an update that contains the chat ID. To fetch this update, we'll use the getUpdates method of the bot API. Use your browser to visit the following URL and replace TOKEN with the entire bot token:

The result should be a JSON object with an array of updates. One update should describe your /start message - and the chat it came from. I've highlighted mine below: 91741518. (Since this is a one-on-one chat between me and my bot, it's the same as my Telegram user ID. This similarity isn't guaranteed, though!)

image.png.487c1fdd3cedc04bf06096204bb89d7c.png

Don't see any updates? That means you need to send a message to your bot to produce one - see above. Once you have your Telegram bot token and the chat ID between you and your bot, continue on!

Step 3: Sending a Message

When you send a message on Telegram, you send it to a chat (not a user). The chat ID you got in the previous section is for a one-on-one chat between you and your bot. So how do we send a message to this chat? Good news: It's as easy as sending an HTTP request! (Baeldung has an OK-ish article on this topic) To keep the Java code simple, we send a POST to the sendMessage endpoint. Don't worry - I built a small Java class for you to use in your projects. No extra work necessary! Here it is:

TelegramBot.java

Quote

 


// Author: agentcallooh
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class TelegramBot {
    private final String API_HOST = "api.telegram.org";
    private String token;

    public TelegramBot(String token) { this.token = token; }
    public String getBaseUrl() { return "https://" + API_HOST + "/bot" + token; }

    // https://core.telegram.org/bots/api#making-requests
    public boolean sendRequest(String endpoint, Map<String, String> parameters) {
        // Build the URL
        URL url = null;
        try { url = new URL(getBaseUrl() + endpoint);
        } catch (MalformedURLException e) { e.printStackTrace(); return false; }
        try {
            // Build connection
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.setConnectTimeout(5000);
            con.setReadTimeout(5000);
            con.setDoOutput(true);
            // Write our data
            DataOutputStream out = new DataOutputStream(con.getOutputStream());
            out.writeBytes(ParameterStringBuilder.getParamsString(parameters));
            out.flush();
            out.close();
            // Send the request
            con.connect();
            // Process the response
            return con.getResponseCode() == 200;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    // https://core.telegram.org/bots/api#sendmessage
    public boolean sendMessage(long chatId, String text) {
        Map<String, String> params = new HashMap<>();
        params.put("chat_id", String.valueOf(chatId));
        params.put("text", text);
        return sendRequest("/sendMessage", params);
    }
}

class ParameterStringBuilder {
    // Turn a Map<String, String> into something like foo=bar&spam=eggs
    public static String getParamsString(Map<String, String> params) {
        StringBuilder result = new StringBuilder();
        for (String key: params.keySet()) {
            try {
                String k = URLEncoder.encode(key, "UTF-8");
                String v = URLEncoder.encode(params.get(key), "UTF-8");
                result.append(k).append("=").append(v).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        String resultStr = result.toString();
        // There is a trailing &, shave it off.
        if (!resultStr.equals("")) resultStr = resultStr.substring(0, resultStr.length() - 1);
        return resultStr;
    }
}

 

Below is an example script showing how to use the TelegramBot class. Be sure to open OSBot's Data directory (C:\Users\YOU\OSBot\Data or ~\OSBot\Data) and add two files - TelegramBotToken.txt and TelegramChatId.txt. Put your values from the previous section in these files. You could also paste your token and chat ID directly into your code, but this is highly discouraged.

TelegramExample.java

Quote

// Author: agentcallooh
import org.osbot.rs07.script.Script;
import org.osbot.rs07.script.ScriptManifest;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

@ScriptManifest(name = "Telegram Example", author = "agentcallooh", version = 1.0, info = "", logo = "")
public class TelegramExample extends Script {
    private final String TELEGRAM_BOT_TOKEN_FILENAME = "TelegramBotToken.txt";
    private final String TELEGRAM_CHAT_ID_FILENAME = "TelegramChatId.txt";
    private long telegramChatId;
    private TelegramBot telegramBot;

    public void onStart() {
        telegramBot = new TelegramBot(loadTextFromFile(TELEGRAM_BOT_TOKEN_FILENAME));
        telegramChatId = Long.parseLong(loadTextFromFile(TELEGRAM_CHAT_ID_FILENAME));
    }

    private String loadTextFromFile(String filename){
        try {
            return new String(Files.readAllBytes(Paths.get(
                    getDirectoryData() + File.separator + filename
            )));
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private void notify(String message) {
        if (telegramBot == null) return;
        telegramBot.sendMessage(telegramChatId, message);
    }

    @Override
    public int onLoop() {
        // This script just does one thing: send notification then exit
        notify("Hello, world from OSBot!");
        stop(false);
        return 1000;
    }
}

 

Run the script using OSBot. You should see... DING! A notification, and the message that triggered it in your Telegram client:

image.png.db4a8f671589559fa8b9b542be59a8a9.png --> image.png.d96965a079702478263cf16a1d602654.png

Attention: NEVER put your bot token within your source code! EVER!

This is a big security risk! Instead, you should load config info like this from a file located within OSBot's data directory (getDirectoryData). You can learn more at this other tutorial I wrote. The example bot script gives you a nice easy way of doing this - please use this.

Bonus: Using a Telegram Channel or Group Chat

If you're collaborating and would like your bot to post to a place where its messages are visible to more than just you, you can use the chat ID of a group chat or channel instead of a one-on-one conversation with the bot. In order to do this, first create a channel or group chat. Then add your bot to it via its username (Note: Make sure to add the bot as an admin if using a group chat)

image.png.f2749ce0859b05f4b064fb8838cf795c.png --> image.png.ebe04c303eb72cdb8c5b4d61afa38771.png  --> image.png.1ad6656c93a8319efb5be5f8eb0f6d00.png

Using the same process as before: send a message to your group/channel. Then load /getUpdates and find the new "channel_post" or group chat message, then "chat": {"id": ... }. You might see the message from before (ignore it). This is the chat ID you want to use!
image.png.2ccf577c62406236f6455cd6b624e851.png

Coming Soon: Uploading Screenshots

If there is interest, I'll write about uploading OSBot screenshots to Telegram to view anywhere. This is more involved, so I'll only do it if there's significant interest!

Conclusion

Telegram is a great platform to use for messaging, even for automated scripts like OSBot's. If a bot gets a rare drop, gets PK'd or otherwise needs to get a hold of a human, this is a fantastic way to do it.

Thanks for reading my guide!! 😁 

 

 

Edited by agentcallooh
Remove extra screenshots and add script credit
  • Like 7
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...