Bot.scala 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. /*
  2. This file is part of karl-marx.
  3. karl-marx is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. karl-marx is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with karl-marx. If not, see <https://www.gnu.org/licenses/>.
  13. */
  14. package org.congressodeiradicali.karlmarx
  15. import java.io.File
  16. import com.bot4s.telegram.api.RequestHandler
  17. import com.bot4s.telegram.api.declarative.{Command, Commands}
  18. import com.bot4s.telegram.clients.ScalajHttpClient
  19. import com.bot4s.telegram.future.{Polling, TelegramBot}
  20. import com.bot4s.telegram.methods.{GetChatMember, GetMe}
  21. import com.bot4s.telegram.models.{Chat, ChatId, User}
  22. import org.congressodeiradicali.karlmarx.coreplugins.{BanPlugin, EchoPlugin, PluginManagerPlugin, SetPlugin}
  23. import slogging.{LogLevel, LoggerConfig, PrintLoggerFactory}
  24. import scala.concurrent.{ExecutionContext, Future}
  25. class Bot(val token: String) extends TelegramBot
  26. with Polling
  27. with Commands[Future] {
  28. LoggerConfig.factory = PrintLoggerFactory()
  29. // set log level, e.g. to TRACE
  30. LoggerConfig.level = LogLevel.TRACE
  31. val localizer = new Localizer("it_IT")
  32. def localize(s: LocalizableString.Value) = localizer.getString(s)
  33. override val client: RequestHandler[Future] = new ScalajHttpClient(token)
  34. val redis = new RedisAsyncClient(sys.env("REDIS_HOST"), 6379)
  35. private def plugin(plugin: Plugin) = plugin.identifier -> plugin
  36. var plugins: Map[String, Plugin] = Map(
  37. plugin(new PluginManagerPlugin(this)),
  38. plugin(new BanPlugin(this)),
  39. plugin(new EchoPlugin(this)),
  40. plugin(new SetPlugin(this))
  41. )
  42. // Load external plugins
  43. val pluginLoader: PluginLoader = new JARPluginLoader()
  44. private def loadExternalPlugins = {
  45. val d = new File("plugins")
  46. if (d.exists && d.isDirectory) {
  47. d.listFiles().filter(_.isFile).map(pluginLoader.loadFromFile)
  48. }
  49. }
  50. loadExternalPlugins
  51. ////////////////////////
  52. // Future[Option[T]] is just two wrappers; remove the inner, useless one
  53. def collapseFutureOption[T](arg: Future[Option[T]]): Future[T] = arg.flatMap {
  54. case Some(x) => Future(x)
  55. case None => Future.failed(new RuntimeException("Future contains null option"))
  56. }
  57. def runAgainst(handlerPair: Plugin#CommandHandlerPair, botUser: Option[User], cmd: Command): Boolean = {
  58. handlerPair._1
  59. .to(botUser.flatMap(_.username)) // Apply filter to bot username
  60. .accept(cmd)
  61. }
  62. onExtMessage { case (message, botUser) =>
  63. val argv: Array[String] = message.text match {
  64. case Some(text) => text.split(" ")
  65. case None => Array()
  66. }
  67. val enabledPlugins = plugins.values filter(_.enabled)
  68. val messagesFuture = Future.sequence(enabledPlugins
  69. .flatMap(_.messageHandlers)
  70. .map(handler => handler(message))
  71. .map(collapseFutureOption)
  72. .map(maybeResponse => maybeResponse.flatMap { response => reply(response)(message) })
  73. )
  74. val commandsFuture = using(command) { cmd =>
  75. Future.sequence(enabledPlugins
  76. .flatMap(_.commandHandlers)
  77. .filter(pair => runAgainst(pair, botUser, cmd))
  78. .map(pair => pair._2(message, argv))
  79. .map(collapseFutureOption)
  80. .map(maybeResponse => maybeResponse.flatMap { response => reply(response)(message) })
  81. ).flatMap(_ => Future{unit})
  82. }(message)
  83. Future.sequence(List(messagesFuture, commandsFuture)).flatMap(_ => Future{unit}) // Discard the content
  84. }
  85. def requestBotUser(user: User, chat: Chat) =
  86. request(GetChatMember(ChatId.fromChat(chat.id), user.id)).map {
  87. chatMember => new BotUser(user, chat, this, chatMember)
  88. }(ExecutionContext.global)
  89. }