brutal fix for of a bug when bot is not responding. this is due to the telegram library i use doesn't support several new telegram messages and crashes during an update. updating the library to the latest version is really painful, so i'm trying to filter out this messages

This commit is contained in:
Eugene Zadyra
2021-09-20 13:56:22 +02:00
parent dc54264ccf
commit 29639d72db

View File

@@ -1,18 +1,59 @@
package com.lbs.bot.telegram
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model._
import akka.http.scaladsl.unmarshalling.Unmarshal
import com.bot4s.telegram.api.declarative.{Callbacks, Commands}
import com.bot4s.telegram.api.{AkkaTelegramBot, Polling}
import com.bot4s.telegram.api.{AkkaTelegramBot, Polling, RequestHandler}
import com.bot4s.telegram.clients.AkkaHttpClient
import com.bot4s.telegram.marshalling._
import com.bot4s.telegram.methods._
import com.bot4s.telegram.models.{InlineKeyboardMarkup, InputFile, Message}
import com.lbs.common.Logger
import io.circe.{Decoder, Encoder, Json}
import scala.concurrent.Future
class TelegramClient(onReceive: TelegramEvent => Unit, botToken: String) extends AkkaTelegramBot with Polling with Commands with Callbacks with Logger {
val client = new AkkaHttpClient(botToken)
val client: RequestHandler = new AkkaHttpClient(botToken) {
import AkkaHttpMarshalling._
private val http = Http()
private val apiBaseUrl = s"https://api.telegram.org/bot$botToken/"
override def sendRequest[R, T <: Request[_]](request: T)(implicit encT: Encoder[T], decR: Decoder[R]): Future[R] = {
Marshal(request).to[RequestEntity]
.map(re => HttpRequest(HttpMethods.POST, Uri(apiBaseUrl + request.methodName), entity = re))
.flatMap(http.singleRequest(_))
.flatMap(r => {
request match {
case _: GetUpdates =>
Unmarshal(r.entity).to[Json].flatMap { json =>
val patchedJson = json.mapObject { jsonObject =>
jsonObject.mapValues { value =>
if (value.isArray) {
value.mapArray { update =>
update.filterNot(_.findAllByKey("myChatMember").nonEmpty)
}
} else {
value
}
}
}
Unmarshal(HttpEntity(ContentTypes.`application/json`, patchedJson.noSpaces)).to[Response[R]]
}
case _ =>
Unmarshal(r.entity).to[Response[R]]
}
})
.map(processApiResponse[R])
}
}
def sendMessage(chatId: Long, text: String): Future[Message] =
loggingRequest(SendMessage(chatId, text, parseMode = Some(ParseMode.HTML)))