summaryrefslogtreecommitdiff
path: root/smsbot
blob: 60fb8f6562fbd64c4a5ba94670e0b9e552cb4a53 (plain)
  1. #!/usr/bin/perl
  2. use strict;
  3. use utf8;
  4. use AnyEvent;
  5. use AnyEvent::XMPP::Client;
  6. use AnyEvent::XMPP::Ext::Disco;
  7. use AnyEvent::XMPP::Ext::Version;
  8. use AnyEvent::XMPP::Ext::MUC;
  9. use AnyEvent::XMPP::Namespaces qw/xmpp_ns/;
  10. use AnyEvent::XMPP::Util qw/node_jid res_jid/;
  11. my @msgs;
  12. sub read_messages {
  13. my ($msgs_file) = @_;
  14. open my $f, $msgs_file
  15. or die "Couldn't open messages file: '$msgs_file'\n";
  16. (@msgs) = map { chomp; $_ } <$f>;
  17. close $f;
  18. }
  19. sub answer_to {
  20. my ($msg) = @_;
  21. my $talkmsg = $msgs[int (rand (@msgs))];
  22. "You said '$msg' but... " . $talkmsg;
  23. }
  24. binmode STDOUT, ":utf8";
  25. my ($jid, $pw, $inputfile, $room) = @ARGV;
  26. unless (@ARGV >= 3) {
  27. warn "usage: talkbot <jid> <password> <talkfile> [<conference room jid>]\n";
  28. exit;
  29. }
  30. read_messages ($inputfile);
  31. my $j = AnyEvent->condvar;
  32. my $cl = AnyEvent::XMPP::Client->new (debug => 1);
  33. my $disco = AnyEvent::XMPP::Ext::Disco->new;
  34. my $version = AnyEvent::XMPP::Ext::Version->new;
  35. my $muc = AnyEvent::XMPP::Ext::MUC->new (disco => $disco);
  36. $cl->add_extension ($disco);
  37. $cl->add_extension ($version);
  38. $cl->add_extension ($muc);
  39. $cl->set_presence (undef, 'I\'m a talking bot.', 1);
  40. $cl->add_account ($jid, $pw);
  41. warn "connecting to $jid...\n";
  42. $cl->reg_cb (
  43. session_ready => sub {
  44. my ($cl, $acc) = @_;
  45. $muc->join_room ($acc->connection, $room, node_jid ($acc->jid));
  46. $muc->reg_cb (
  47. message => sub {
  48. my ($cl, $room, $msg, $is_echo) = @_;
  49. return if $is_echo;
  50. return if $msg->is_delayed;
  51. my $mynick = res_jid ($room->nick_jid);
  52. if ($msg->any_body =~ /^\s*\Q$mynick\E:\s+(.*?)\s*$/) {
  53. my $ans = answer_to ($1);
  54. my $repl = $msg->make_reply;
  55. $repl->add_body ($ans);
  56. $repl->send;
  57. }
  58. }
  59. );
  60. },
  61. message => sub {
  62. my ($cl, $acc, $msg) = @_;
  63. my $talkmsg = $msgs[int (rand (@msgs))];
  64. my $repl = $msg->make_reply;
  65. $repl->add_body (answer_to ($msg->any_body));
  66. warn "Got message: '".$msg->any_body."' from ".$msg->from."\n";
  67. warn "Answered: $talkmsg\n";
  68. $repl->send;
  69. },
  70. contact_request_subscribe => sub {
  71. my ($cl, $acc, $roster, $contact) = @_;
  72. $contact->send_subscribed;
  73. warn "Subscribed to ".$contact->jid."\n";
  74. },
  75. error => sub {
  76. my ($cl, $acc, $error) = @_;
  77. warn "Error encountered: ".$error->string."\n";
  78. $j->broadcast;
  79. },
  80. disconnect => sub {
  81. warn "Got disconnected: [@_]\n";
  82. $j->broadcast;
  83. },
  84. );
  85. $cl->start;
  86. $j->wait;