如何从方法中获取消息

时间:2019-04-20 06:07:15

标签: scala recursion scala-cats for-comprehension

我想将控制台IO应用程序(总计数)重写为messenger-bot。 StdIn.readLine()让我递归获得下一个输入数字。

object HelloCountBot extends TelegramBot with Polling with Commands {
  def go(number: Long, chatId: Long): IO[Long] =
    for {
      input <- ??? /*here I need get the next number*/
      acc <- input.toLong match {
        case 0L => sendMessageMethodIO(chatId, "The sum is:") *> IO(0L)
        case _ => go(number + 1, chatId)
      }
      acc <- IO(acc + input.toLong)
    } yield acc

  /*input point for every new message*/
  override def onMessage(message: Message) = message.text match {
    case Some(text) if text == "start" => go(1, message.chat.id)
      .unsafeRunSync
  }

  def main(args: Array[String]): Unit = HelloCountBot.run()
}

如何组织代码以使用单元返回从onMessage方法获取递归内的下一条消息。

1 个答案:

答案 0 :(得分:0)

我没有在https://github.com/bot4s/telegram中找到任何以您想要的方式接收消息的方法。因此,我认为最好的选择是创建有状态的bot,如以下示例所示:https://github.com/bot4s/telegram/blob/master/examples/src/StatefulBot.scala

因此,如果我正确理解您的代码,则可以按以下方式进行重组(特征PerChatState来自上面的链接):

object HelloCountBot
  extends TelegramBot
    with Polling
    with Commands
    with PerChatState[Long] {

  override def onMessage(message: Message): Future[Unit] = {

    implicit val msg = message

    message.text match {
      case Some(text) if text == "start" =>
        Future {
          setChatState(0L)
        }
      case Some(value) if value == "0" =>
        withChatState {
          sum =>
            reply(s"The sum is ${sum.getOrElse(0L)}")
              .map(_ => clearChatState)
        }

      case Some(value) =>
        withChatState {
          mayBeSum =>
            Future {
              mayBeSum.foreach(
                sum => setChatState(sum + value.toLong)
              )
            }
        }
    }
  }

  def main(args: Array[String]): Unit = HelloCountBot.run()
}

它使用Futures,但您可以根据需要将其重写为IO。