A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://github.com/pme123/scala-telegrambot4s below:

pme123/scala-telegrambot4s: Demo Bot for Workshop with Scala and Telegrambot4s

Telegram Bot Demo with Scala

This page was originally created for a JUGs workshop.

The workshop is about the first steps on implementing a chat bot with:

The following chapters document the workshop step by step.

A basic understanding of SBT and Scala will help;).

Preparation for the Workshop Create an account for Telegram

To get an account for Telegram you need a mobile number.

So the easiest way is to install the mobile app in your app store:

To make sure that every one is on the same page, we start with the same Project.

This part we do together step by step.

We want to write a Bot that does something for us:

Each Messaging Provider (e.g. Telegram) provides an API to interact with the Messaging infrastructur. That's what your Bot needs to communicate with the world. These APIs are usually stateless web services that return data structure as JSON. As this is messaging everything is asynchronous (I get back to that)!

Now to simplify that, you find Wrappers in some programming languages. As for Scala they are a bit rare - so thankfully for Telegram there is a great one: telegrambot4s

And on top of that comes your Bot!

First we want to provide the token in a safe way to avoid leaking it.

lazy val botToken: String = scala.util.Properties
  .envOrNone("BOT_TOKEN")
  .getOrElse(Source.fromResource("bot.token").getLines().mkString)

Before we start let's explain shortly the difference between Webhooks and Polling. This is the quote from the Scala API:

Both methods are fully supported. Polling is the easiest method; it can be used locally without any additional requirements. It has been radically improved, doesn't flood the server (like other libraries do) and it's pretty fast.

Using webhooks requires a server (it won't work on your laptop). For a comprehensive reference check Marvin's Patent Pending Guide to All Things Webhook.

So for this workshop, or examples in general Polling is the way to go.

(Here the Solution Branch if you have problems)

Let's greet the Bot and it should return that with a personalized greeting.

object HelloBot
  extends TelegramBot // the general bot behavior
    with Polling // we use Polling
    with Commands { // and we want to listen to Commands

  lazy val token: String = botToken // the token is required by the Bot behavior

  onCommand('hello) { implicit msg => // listen for the command hello and
    reply(s"Hello ${msg.from.map(_.firstName).getOrElse("")}!") // and reply with the personalized greeting
  }
}
object BotApp extends App {
  HelloBot.run()
}
hello - Simple Hello World.

(Here the Solution Branch if you have problems)

The first step to implement a conversation with a user is to understand the concept of callbacks. To guide the user through a conversation you can provide a keyboard. These keys (buttons) are identified with a callback identifier.

Create a Scala class CounterBot in the bots package (you can copy the HelloBot:

  onCommand("/counter") { implicit msg =>
    reply("Press to increment!", replyMarkup = Some(markupCounter(0)))
  }
  private def markupCounter(n: Int): InlineKeyboardMarkup = {
    requestCount += 1
    InlineKeyboardMarkup.singleButton( // set a layout for the Button
      InlineKeyboardButton.callbackData( // create the button into the layout
        s"Press me!!!\n$n - $requestCount", // text to show on the button (count of the times hitting the button and total request count)
        tag(n.toString))) // create a callback identifier
  }
  private val TAG = "COUNTER_TAG"
  private def tag: String => String = prefixTag(TAG)
  onCallbackWithTag(TAG) { implicit cbq => // listens on all callbacks that START with TAG
    // Notification only shown to the user who pressed the button.
    ackCallback(Some(cbq.from.firstName + " pressed the button!"))
    // Or just ackCallback() - this is needed by Telegram!

    for {
      data <- cbq.data //the data is the callback identifier without the TAG (the count in our case)
      Extractors.Int(n) = data // extract the optional String to an Int
      msg <- cbq.message
    } /* do */ {
      request(
        EditMessageReplyMarkup( // to update the existing button - (not creating a new button)
          Some(ChatId(msg.source)), // msg.chat.id
          Some(msg.messageId),
          replyMarkup = Some(markupCounter(n + 1))))
    }
  }
object CounterBotApp extends App {
  CounterBot.run()
}
  hello - Simple Hello World.
  counter - Counts the time a User hits the button.
Next steps (Next workshop;)

This was the basic workshop.

As mentioned above the wrapper hides the actual API. If you want to check that out, check out the first version of this Workshop:

Now we want to do complexer conversations. To get to this next level we need quite some ingredients:

I created a small library for that, check out: play-akka-telegrambot4s

Here is an example where I created a step-by-step guide you can follow: scala-adapters-images


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4