avatar

Andres Jaimes

Sending a message using telegram and scala

By Andres Jaimes

- 2 minutes read - 419 words

In this article we are going to use scala to send a message via Telegram. The process is very simple and pretty much involves setting up a bot and making a GET request to Telegram’s api.

The Telegram app on the phone has more features than its desktop counterpart. I recommend you to use the phone version to make sure you have access to all the required features.

On Telegram

1. Create a Telegram public channel

Telegram requires you to have a public channel to be able to publish messages using a bot.

Go ahead and create a public channel using the app.

2. Create a Bot using the BotFather

The BotFather is a special Bot created by Telegram that allows you to create and maintain your bots. Search for @BotFather on the app and follow the instructions to create a new bot. You’ll be asked to create a name and a username for it.

3. Add your new bot as administrator to your channel

Add your new bot as administrator to the public channel you created on step 1.

On Scala

1. Add a REST library to your project

Add to your project a library that allows you to send remote requests. If you’re using the PlayFramework you can use ws. In my case, I’m going to go with scalaj, so I have to add it to my build.sbt file:

libraryDependencies += "org.scalaj" %% "scalaj-http" % "2.4.1"

2. Create a function

Sending a message to telegram requires you to send a GET request to Telegram’s send-message endpoint:

https://api.telegram.org/bot$botApiKey/sendMessage

I’m going to create a function that sends a request to this endpoint and returns the api’s response to its caller:

import java.net.URLEncoder
import scalaj.http.{Http, HttpOptions}

val botApiKey = "1234567890:your-bot-api-key"
val chatId = "@your-public-chat-id"

val connectionTimeout = 1000 * 10 // in milliseconds
val readTimeout = 1000 * 10 // in milliseconds

def sendMessage(message: String): Option[String] = {
  val url = s"https://api.telegram.org/bot$botApiKey/sendMessage" +
              s"?chat_id=${URLEncoder.encode(chatId, "UTF-8")}" +
              s"&parse_mode=MarkdownV2" +
              s"&text=${URLEncoder.encode(message, "UTF-8")}"
  val response = Http(url)
    .options(HttpOptions.followRedirects(true))
    .timeout(connectionTimeout, readTimeout)
    .asString

  if (response.is2xx) Some(response.body)
  else None
}

The endpoint takes the following parameters:

  • chat_id: your public channel id.
  • parse_mode: MarkdownV2 or HTML. Yes, Telegram can parse your markdown and html messages.
  • text: your message.

The last step is to use your function:

val response: Option[String] = sendMessage("This is *beautiful*")

Making an API request is a blocking operation, so I recommend you to evaluate your use-cases and implement this function using futures.

Happy texting.

References