Javarevisited

A humble place to learn Java and Programming better.

Follow publication

Member-only story

Sending a message to a Telegram channel the easy way

Today we’ll see by practical examples how to send a message to a Telegram channel.

The BotFather

In order to be able to do so, you will have first to:

  • Create a Telegram public channel
  • Create a Telegram BOT via BotFather
  • Set the bot as administrator in your channel

Provided that you did the above, now you can send a message to your channel by issuing an HTTP GET request to the Telegram BOT API at the following URL:

https://api.telegram.org/bot[BOT_API_KEY]/sendMessage?chat_id=[MY_CHANNEL_NAME]&text=[MY_MESSAGE_TEXT]

where:

  • BOT_API_KEY is the API Key generated by BotFather when you created your bot
  • MY_CHANNEL_NAME is the handle of your channel (e.g. @my_channel_name)
  • MY_MESSAGE_TEXT is the message you want to send (URL-encoded)

Now let’s se how to do this in different languages the easy way.

JAVA

String urlString = "https://api.telegram.org/bot%s/sendMessage?chat_id=%s&text=%s";String apiToken = "my_bot_api_token";
String chatId = "@my_channel_name";
String text = "Hello world!";
urlString = String.format(urlString, apiToken, chatId, text);URL url = new URL(urlString);
URLConnection conn = url.openConnection();
StringBuilder sb = new StringBuilder();
InputStream is = new BufferedInputStream(conn.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String inputLine = "";
while ((inputLine = br.readLine()) != null) {
sb.append(inputLine);
}
String response = sb.toString();
// Do what you want with response

Kotlin

var urlString = "https://api.telegram.org/bot%s/sendMessage?chat_id=%s&text=%s"val apiToken = "my_bot_api_token"
val chatId = "@my_channel_name"
val text = "Hello world!"
urlString = String.format(urlString, apiToken, chatId, text)val url = URL(urlString)
val conn = url.openConnection()
val inputStream = BufferedInputStream(conn.getInputStream())…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Javarevisited
Javarevisited

Published in Javarevisited

A humble place to learn Java and Programming better.

Paolo Montalto
Paolo Montalto

Written by Paolo Montalto

Android Engineer, freelance, mobile developer, software craftsman, guitar strummer, husband, father, humble.

Responses (29)

Write a response