/lib/Jabbot/Core.pm

https://github.com/gugod/jabbot · Perl · 66 lines · 53 code · 13 blank · 0 comment · 9 complexity · 87f958fe5fb0aa50a84c8f1988c6c6fd MD5 · raw file

  1. package Jabbot::Core;
  2. use v5.18;
  3. use utf8;
  4. use Jabbot;
  5. use Jabbot::Types qw(JabbotMessage);
  6. use JSON qw(to_json);
  7. use UNIVERSAL::require;
  8. sub new {
  9. state $core;
  10. return $core if $core;
  11. my $class = shift;
  12. my $self = bless {}, $class;
  13. $self->{plugins} = [];
  14. for my $plugin (map { "Jabbot::Plugin::$_"} @{Jabbot->config->{plugins}}) {
  15. unless ($plugin->require) {
  16. warn "* $plugin failed to be loaded.\n";
  17. next;
  18. }
  19. unless ($plugin->can('can_answer') && $plugin->can('answer') &&
  20. $plugin->can('can_answer') != \&Jabbot::Plugin::can_answer &&
  21. $plugin->can('answer') != \&Jabbot::Plugin::answer) {
  22. warn "* $plugin not loaded due to the lack of 'can_answer' or 'answer' method\n";
  23. next;
  24. }
  25. push @{ $self->{plugins} }, $plugin->new( core => $self );
  26. }
  27. $core = $self;
  28. return $self;
  29. }
  30. sub answers {
  31. my ($self, $message) = @_;
  32. JabbotMessage->assert_valid($message);
  33. my @answers;
  34. for my $plugin (@{$self->{plugins}}) {
  35. next unless $plugin->can_answer($message);
  36. my $plugin_name = ref($plugin) =~ s/^Jabbot::Plugin:://r;
  37. eval {
  38. my $a = $plugin->answer($message);
  39. if (ref($a) eq 'HASH') {
  40. $a->{plugin} = $plugin_name;
  41. push @answers, $a;
  42. } else {
  43. say STDERR "No answer from $plugin_name";
  44. }
  45. 1;
  46. } or do {
  47. my $err = $@ || "(zombie error)";
  48. warn "[Jabbot::Core][ERROR][plugin=${plugin_name}] $err";
  49. }
  50. }
  51. return \@answers;
  52. }
  53. 1;