Skip to content

Update scenario with user callback response. #326

@coren-dev

Description

@coren-dev

Suppose we have the following example:

package samples

import canoe.api._
import canoe.api.models.Keyboard
import canoe.models.{CallbackButtonSelected, InlineKeyboardButton, InlineKeyboardMarkup, Update}
import canoe.models.messages.{AnimationMessage, StickerMessage, TelegramMessage, TextMessage}
import canoe.syntax._
import cats.{Applicative, Monad}
import cats.effect.{IO, IOApp}
import cats.syntax.all._
import fs2.{Pipe, Stream}

/** Example of echos bot that will answer to you with
  * the callback data [[canoe.models.InlineKeyboardButton.callbackData]]
  * has been sent to him
  */
object CallbackHandling extends IOApp.Simple {
  val token: String = "<your telegram token>"

  def run: IO[Unit] =
    Stream
      .resource(TelegramClient.global[IO](token))
      .flatMap { implicit client =>
        Bot
          .polling[IO]
          .follow(echos)
          .through(answerCallbacks)
      }
      .compile
      .drain

  val inlineBtn = InlineKeyboardButton.callbackData(text = "Pick color", cbd = "callback data")

  val greenBtn = InlineKeyboardButton.callbackData(text = "Green", "g")
  val redBtn = InlineKeyboardButton.callbackData(text = "Red", "r")
  val inlineKeyboardMarkUp = InlineKeyboardMarkup.singleRow(Seq(greenBtn, redBtn))
  val keyboardMarkUp = Keyboard.Inline(inlineKeyboardMarkUp)

  def echos[F[_]: TelegramClient]: Scenario[F, Unit] =
    for {
      msg <- Scenario.expect(command("callback"))
      _   <- Scenario.eval(msg.chat.send(content = "pretty message", keyboard = keyboardMarkUp))
      color <- Scenario.expect(callbackResponse)
      _   <- Scenario.eval(msg.chat.send("You pick "+color+" color"))
    } yield ()

  def answerCallbacks[F[_]: Monad: TelegramClient]: Pipe[F, Update, Update] =
    _.evalTap {
      case CallbackButtonSelected(_, query) =>
        query.data match {
          case Some(cbd) =>
            for {
              _ <- query.message.traverse(_.chat.send(cbd))
              _ <- query.finish
            } yield ()
          case _ => Applicative[F].unit
        }
      case _ => Applicative[F].unit
    }
}

Would it be possible to run from some implementation that can work as expected to do "callbackResponse"?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions