telegram icon indicating copy to clipboard operation
telegram copied to clipboard

Declarative SuccessfulPayment handler

Open aaabramov opened this issue 5 years ago • 2 comments

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.

aaabramov avatar Jan 04 '20 20:01 aaabramov

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.

mukel avatar Jan 05 '20 01:01 mukel

@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?

aaabramov avatar Jan 05 '20 13:01 aaabramov