PluginManagerPlugin.scala 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package org.congressodeiradicali.karlmarx.coreplugins
  2. import com.bot4s.telegram.api.declarative.{CommandFilterMagnet, CommandImplicits}
  3. import com.bot4s.telegram.models.Message
  4. import org.congressodeiradicali.karlmarx.{Bot, Localizer, Plugin}
  5. import scala.concurrent.{ExecutionContext, Future}
  6. class PluginManagerPlugin(localizer: Localizer, bot: Bot) extends CorePlugin with CommandImplicits {
  7. override val name = "Plugin Manager"
  8. override val description = "Manages other plugins"
  9. override val identifier = "pluginmanager"
  10. var managedPlugins: Map[String, Plugin] = Map()
  11. var pluginStatus: Map[String, Boolean] = Map()
  12. def managePlugin(plugin: Plugin) = {
  13. managedPlugins += (plugin.identifier -> plugin)
  14. pluginStatus += (plugin.identifier -> false)
  15. }
  16. def enableByIdentifier(id: String) : Boolean = managedPlugins.get(id).fold {
  17. false
  18. } { plugin =>
  19. bot.plugins :+= plugin
  20. pluginStatus = pluginStatus.updated(plugin.identifier, true)
  21. true
  22. }
  23. def disableByIdentifier(id: String) : Boolean = managedPlugins.get(id).fold { /*checks if the plugin is managed*/
  24. false
  25. } { plugin =>
  26. bot.plugins = bot.plugins.filter { _.identifier != plugin.identifier }
  27. pluginStatus = pluginStatus.updated(plugin.identifier, false)
  28. true
  29. }
  30. override var handlers: Map[CommandFilterMagnet, Handler] = Map {
  31. stringToCommandFilter("enable") -> { (_: Message, argv: Array[String]) =>
  32. val name = argv(1)
  33. val response = if (enableByIdentifier(name)) {
  34. "Enabled!"
  35. } else {
  36. "Plugin not found"
  37. }
  38. Future { Some(response) }(ExecutionContext.global)
  39. }
  40. stringToCommandFilter("disable") -> { (_: Message, argv: Array[String]) =>
  41. val name = argv(1)
  42. val response = if (disableByIdentifier(name)) {
  43. "Disabled!"
  44. } else {
  45. "Plugin not found"
  46. }
  47. Future { Some(response) }(ExecutionContext.global)
  48. }
  49. stringToCommandFilter("status") -> { (_, _) =>
  50. val response = pluginStatus.map { pair =>
  51. managedPlugins.get(pair._1).fold {
  52. // ignore and do the rest
  53. ""
  54. } { plugin =>
  55. s"${plugin.name}. Status: ${if (pair._2) "UP" else "DOWN"}"
  56. }
  57. }.mkString("\n")
  58. Future { Some(response) }(ExecutionContext.global)
  59. }
  60. }
  61. }