bot4s / telegram

Telegram Bot API Wrapper for Scala
Apache License 2.0
414 stars 101 forks source link

Declarative SuccessfulPayment handler #84

Open aaabramov opened 4 years ago

aaabramov commented 4 years ago

Docs: https://core.telegram.org/bots/api#successfulpayment

Add declarative handler for successful payments to com.bot4s.telegram.api.declarative.Payments like it is done for com.bot4s.telegram.api.declarative.Payments#onPreCheckoutQuery.

mukel commented 4 years ago

You can add this extension yourself, it's not there by default since successful payments come attached to a message and not in an Update which is the common pattern for these extension methods. Here's how it would look like:

package com.bot4s.telegram.api.declarative

import cats.instances.list._
import cats.syntax.flatMap._
import cats.syntax.functor._
import cats.syntax.traverse._
import com.bot4s.telegram.api.BotBase
import com.bot4s.telegram.models.{Message, SuccessfulPayment}

import scala.collection.mutable

/**
  * Extension for processing (successful) payments.
  * See [[https://core.telegram.org/bots/payments]].
  */
trait MyPayments[F[_]] extends BotBase[F] {

  private val successfulPaymentActions = mutable.ArrayBuffer[Action[F, SuccessfulPayment]]()

  /**
    * Executes 'action' for every successful payment.
    */
  def onSuccessfulPayment(action: Action[F, SuccessfulPayment]): Unit = {
    successfulPaymentActions += action
  }

  override def receiveMessage(message: Message): F[Unit] =
    for {
      _ <- successfulPaymentActions.toList.traverse(action => message.successfulPayment.map(action).getOrElse(unit))
      _ <- super.receiveMessage(message)
    } yield ()
}

If you have any issues with payments, bugs or even feature requests (e.g. in the usability department) please file an issue; I'm glad to help.

aaabramov commented 4 years ago

@mukel Thanks a lot. I have already done that. I filed this issue to pick up it later. It seems reasonable to have such trait in core lib that having it implemented everywhere.

If we have onPreCheckoutQuery directive, what is the reason for not adding onSuccessfulPayment to core library?