blib/lib/Net/Jabber/Bot.pm

filter: Statementstmt 77.1% 340 / 441 Branchbran 58.9% 79 / 134 Conditioncond 43.4% 23 / 53 MC/DCmcdc 13.7% 4 / 29 Subroutinesub 90.3% 47 / 52 Podpod 95.2% 20 / 21 totaltotal 70.2% 513 / 730 CC 94 SCAR 24.8
CC
94
Cov
70%
_jabber_presence_message
56.0
BUILD
26.6
_process_jabber_message
22.9
CRAP 12.0
↑ Summary
1 package Net::Jabber::Bot;
2  
3 12 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 12 ▶use Types::Standard qw(Int HashRef Str Maybe ArrayRef Bool CodeRef InstanceOf Num);
Subroutine BEGIN: called CC=1 SCAR=0.0
5 12 ▶use Type::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 12 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 12 ▶use Net::Jabber;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 12 ▶use Time::HiRes;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 12 ▶use Sys::Hostname;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 12 ▶use Log::Log4perl qw(:easy);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 12 ▶use Mozilla::CA;
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 138 ▶my $PosInt = Type::Tiny->new( name => 'PosInt', parent => Int, constraint => sub { $_ > 0 } );
Subroutine __ANON__: called CC=1 SCAR=0.0
15 135 ▶my $PosNum = Type::Tiny->new( name => 'PosNum', parent => Num, constraint => sub { $_ > 0 } );
Subroutine __ANON__: called CC=1 SCAR=0.0
16 27 ▶my $NonNegNum = Type::Tiny->new( name => 'NonNegNum', parent => Num, constraint => sub { $_ >= 0 } );
Subroutine __ANON__: called CC=1 SCAR=0.0
17 37 ▶my $HundredInt = Type::Tiny->new( name => 'HundredInt', parent => Num, constraint => sub { $_ > 100 } );
Subroutine __ANON__: called CC=1 SCAR=0.0
18  
19 0 ▶my $CoercedBool = Bool->plus_coercions( Str, sub { ( $_ =~ m/(^on$)|(^true$)/i ) + 0 } );
Subroutine __ANON__: not called CC=1 SCAR=1.2
20  
21 has jabber_client => (
22 isa => Maybe [ InstanceOf ['Net::Jabber::Client'] ],
23 is => 'rw',
24 27 ▶ default => sub { Net::Jabber::Client->new }
Subroutine __ANON__: called CC=1 SCAR=0.0
25 12 );
26  
27 12 has 'client_session_id' => ( isa => Str, is => 'rw' );
28 12 has 'connect_time' => ( isa => $PosInt, is => 'rw', default => 9_999_999_999 );
29 12 has 'forum_join_grace' => ( isa => $NonNegNum, is => 'rw', default => 10 );
30 22 ▶has 'server_host' => ( isa => Str, is => 'rw', lazy => 1, default => sub { shift->server } );
Subroutine __ANON__: called CC=1 SCAR=0.0
31 12 has 'server' => ( isa => Str, is => 'rw' );
32 12 has 'port' => ( isa => $PosInt, is => 'rw', default => 5222 );
33 12 has 'gtalk' => ( isa => Bool, is => 'rw', default => '0' );
34 12 has 'tls' => ( isa => Bool, is => 'rw', default => '0' );
35 12 has 'ssl_ca_path' => ( isa => Str, is => 'rw', default => Mozilla::CA::SSL_ca_file() );
36 12 has 'ssl_verify' => ( isa => Bool, is => 'rw', default => '1' );
37 12 has 'connection_type' => ( isa => Str, is => 'rw', default => 'tcpip' );
38 12 has 'conference_server' => ( isa => Str, is => 'rw' );
39 12 has 'username' => ( isa => Str, is => 'rw' );
40 12 has 'password' => ( isa => Str, is => 'rw' );
41 12 has 'alias' => ( isa => Str, lazy => 1, is => 'rw', default => 'net_jabber_bot' );
42  
43 # Resource defaults to alias_hostname_pid
44 27 ▶has 'resource' => ( isa => Str, lazy => 1, is => 'rw', default => sub { shift->alias . "_" . hostname . "_" . $$ } );
Subroutine __ANON__: called CC=1 SCAR=0.0
45 10 ▶has 'message_function' => ( isa => Maybe [CodeRef], is => 'rw', default => sub { undef } );
Subroutine __ANON__: called CC=1 SCAR=0.0
46 10 ▶has 'background_function' => ( isa => Maybe [CodeRef], is => 'rw', default => sub { undef } );
Subroutine __ANON__: called CC=1 SCAR=0.0
47 12 has 'loop_sleep_time' => ( isa => $PosNum, is => 'rw', default => 5 );
48 12 has 'process_timeout' => ( isa => $PosNum, is => 'rw', default => 5 );
49 has 'from_full' => (
50 isa => Str,
51 lazy => 1,
52 is => 'rw',
53 default => sub {
54 2 ▶ my $self = shift;
Subroutine __ANON__: called CC=4 SCAR=15.8
55 2 ▶ ($self->username || '') . '@' . ($self->server || '') . '/' . ($self->alias || '');
Condition50%3/6
$self->username || ''
l!l
20
$self->server || ''
l!l
20
$self->alias || ''
l!l
20
MC/DC0%0/1
$self->username || ''
$self->username
MC/DC0%0/1
$self->server || ''
$self->server
MC/DC0%0/1
$self->alias || ''
$self->alias
Truth table50%1/2
A
A= $self->username
Aresult
11
00
Truth table50%1/2
A
A= $self->server
Aresult
11
00
Truth table50%1/2
A
A= $self->alias
Aresult
11
00
56 }
57 12 );
58  
59 12 has 'safety_mode' => ( isa => $CoercedBool, is => 'rw', default => 1, coerce => 1 );
60 12 has 'ignore_server_messages' => ( isa => $CoercedBool, is => 'rw', default => 1, coerce => 1 );
61 12 has 'ignore_self_messages' => ( isa => $CoercedBool, is => 'rw', default => 1, coerce => 1 );
62 12 has 'auto_subscribe' => ( isa => $CoercedBool, is => 'rw', default => 1, coerce => 1 );
63 12 has 'forums_and_responses' => ( isa => HashRef [ ArrayRef [Str] ], is => 'rw' ); # List of forums we're in and the strings we monitor for.
64 27 ▶has 'forum_join_time' => ( isa => HashRef [Int], is => 'rw', default => sub { {} } ); # List of when we joined each forum
Subroutine __ANON__: called CC=1 SCAR=0.0
65 10 ▶has 'out_messages_per_second' => ( isa => $PosNum, is => 'rw', default => sub { 5 } );
Subroutine __ANON__: called CC=1 SCAR=0.0
66 27 ▶has 'message_delay' => ( isa => $PosNum, is => 'rw', default => sub { 1 / 5 } );
Subroutine __ANON__: called CC=1 SCAR=0.0
67  
68 12 has 'max_message_size' => ( isa => $HundredInt, is => 'rw', default => 1000000 );
69 12 has 'max_messages_per_hour' => ( isa => $PosInt, is => 'rw', default => 1000000 );
70  
71 # Initialize this hour's message count.
72 has 'messages_sent_today' => (
73 isa => HashRef,
74 is => 'ro',
75 default => sub {
76 27 ▶ { (localtime)[7] => { (localtime)[2] => 0 } }
Subroutine __ANON__: called CC=1 SCAR=0.0
77 }
78 12 );
79  
80 12 has '_running' => ( isa => Bool, is => 'rw', default => 0 );
81  
82  
83 =head1 NAME
84  
85 Net::Jabber::Bot - Automated Bot creation with safeties
86  
87 =head1 VERSION
88  
89 Version 2.1.8
90  
91 =cut
92  
93 12 our $VERSION = '2.1.9';
94  
95 =head1 SYNOPSIS
96  
97 Program design:
98 This is a Moo based Class.
99  
100 The idea behind the module is that someone creating a bot should not really have to know a whole lot about how the Jabber protocol works in order to use it. It also allows us to abstract away all the things that can get a bot maker into trouble. Essentially the object helps protect the coders from their own mistakes.
101  
102 All someone should have to know and define in the program away from the object is:
103  
104 =over
105  
106 =item 1. Config - Where to connect, how often to do things, timers, etc
107  
108 =item 2. A subroutine to be called by the bot object when a new message comes in.
109  
110 =item 3. A subroutine to be called by the bot object every so often that lets the user do background activities (check logs, monitor web pages, etc.),
111  
112 =back
113  
114 The object at present has the following enforced safeties as long as you do not override safety mode:
115  
116 =over
117  
118 =item 1. Limits messages per second, configurable at start up, (Max is 5 per second) by requiring a sleep timer in the message sending subroutine each time one is sent.
119  
120 =item 2. Endless loops of responding to self prevented by now allowing the bot message processing subroutine to know about messages from self
121  
122 =item 3. Forum join grace period to prevent bot from reacting to historical messages
123  
124 =item 4. Configurable aliases the bot will respond to per forum
125  
126 =item 5. Limits maximum message size, preventing messages that are too large from being sent (largest configurable message size limit is 1000).
127  
128 =item 6. Automatic chunking of messages to split up large messages in message sending subroutine
129  
130 =item 7. Limit on messages per hour. (max configurable limit of 125) Messages are visible via log4perl, but not ever be sent once the message limit is reached for that hour.
131  
132 =back
133  
134 =head1 FUNCTIONS
135  
136 =over 4
137  
138 =item B<new>
139  
140 Minimal:
141  
142 my $bot = Net::Jabber::Bot->new(
143 server => 'host.domain.com', # Name of server when sending messages internally.
144 conference_server => 'conference.host.domain.com',
145 port => 522,
146 username => 'username',
147 password => 'pasword',
148 safety_mode => 1,
149 message_function => \&new_bot_message,
150 background_function => \&background_checks,
151 forums_and_responses => \%forum_list
152 );
153  
154 All options:
155  
156 my $bot = Net::Jabber::Bot->new(
157 server => 'host.domain.com', # Name of server when sending messages internally.
158 conference_server => 'conference.host.domain.com',
159 server_host => 'talk.domain.com', # used to specify what jabber server to connect to on connect?
160 tls => 0, # set to 1 for google
161 ssl_ca_path => '', # path to your CA cert bundle
162 ssl_verify => 0, # for testing and for self-signed certificates
163 connection_type => 'tcpip',
164 port => 522,
165 username => 'username',
166 password => 'pasword',
167 alias => 'cpan_bot',
168 message_function => \&new_bot_message,
169 background_function => \&background_checks,
170 loop_sleep_time => 15,
171 process_timeout => 5,
172 forums_and_responses => \%forum_list,
173 ignore_server_messages => 1,
174 ignore_self_messages => 1,
175 out_messages_per_second => 4,
176 max_message_size => 1000,
177 max_messages_per_hour => 100
178 );
179  
180  
181 Set up the object and connect to the server. Hash values are passed to new as a hash.
182  
183 The following initialization variables can be passed. Only marked variables are required (TODO)
184  
185 =over 5
186  
187 =item B<safety_mode>
188  
189 safety_mode = (1,0)
190  
191 Determines if the bot safety features are turned on and enforced. This mode is on by default. Many of the safety features are here to assure you do not crash your favorite jabber server with floods, etc. DO NOT turn it off unless you're sure you know what you're doing (not just Sledge Hammer certain)
192  
193 =item B<server>
194  
195 Jabber server name
196  
197 =item B<server_host>
198  
199 Defaults to the same value set for 'server' above.
200 This is where the bot initially connects. For google for instance, you should set this to 'gmail.com'
201  
202 =item B<conference_server>
203  
204 Conference server (usually conference.$server_name)
205  
206 =item B<port>
207  
208 Defaults to 5222
209  
210 =item B<gtalk>
211  
212 Boolean value. defaults to 0. Set to 1 for Google Talk connections. This automatically enables TLS and sets server_host to 'gmail.com' (unless you provide your own server_host).
213  
214 =item B<tls>
215  
216 Boolean value. defaults to 0. for google, it is know that this value must be 1 to work.
217  
218 =item B<ssl_ca_path>
219  
220 The path to your CA cert bundle. This is passed on to XML::Stream eventually.
221  
222 =item B<ssl_verify>
223  
224 Enable or disable server certificate validity check when connecting to server. This is passed on to XML::Stream eventually.
225  
226 =item B<connection_type>
227  
228 defaults to 'tcpip' also takes 'http'
229  
230 =item B<username>
231  
232 The user you authenticate with to access the server. Not full name, just the stuff to the left of the @...
233  
234 =item B<password>
235  
236 password to get into the server
237  
238 =item B<alias>
239  
240 This will be your nickname in rooms, as well as the login resource (which can't have duplicates). I couldn't come up with any reason these should not be the same so hardcoded them to be the same.
241  
242 =item B<forums_and_responses>
243  
244 A hash ref which lists the forum names to join as the keys and the values are an array reference to a list of strings they are supposed to be responsive to.
245 The array is order sensitive and an empty string means it is going to respond to all messages in this forum. Make sure you list this last.
246  
247 The found 'response string' is assumed to be at the beginning of the message. The message_funtion function will be called with the modified string.
248  
249 alias = jbot:, attention:
250  
251 example1:
252  
253 message: 'jbot: help'
254  
255 passed to callback: 'help'
256  
257 =item B<message_function>
258  
259 The subroutine the bot will call when a new message is received by the bot. Only called if the bot's logic decides it's something you need to know about.
260  
261 =item B<background_function>
262  
263 The subroutine the bot will call when every so often (loop_sleep_time) to allow you to do background activities outside jabber stuff (check logs, web pages, etc.)
264  
265 =item B<loop_sleep_time>
266  
267 Frequency background function is called.
268  
269 =item B<process_timeout>
270  
271 Time Process() will wait if no new activity is received from the server
272  
273 =item B<ignore_server_messages>
274  
275 Boolean value as to whether we should ignore messages sent to us from the jabber server (addresses can be a little cryptic and hard to process)
276  
277 =item B<ignore_self_messages>
278  
279 Boolean value as to whether we should ignore messages sent by us.
280  
281 BE CAREFUL if you turn this on!!! Turning this on risks potentially endless loops. If you're going to do this, please be sure safety is turned on at least initially.
282  
283 =item B<auto_subscribe>
284  
285 Boolean value controlling whether the bot automatically accepts presence subscription requests from any JID. Defaults to 1 (enabled) for backward compatibility. Set to 0 to ignore subscription requests, which prevents unknown users from tracking the bot's online status.
286  
287 =item B<out_messages_per_second>
288  
289 Limits the number of messages per second. Number must be E<gt> 0
290  
291 default: 5
292  
293 safety: 5
294  
295 =item B<max_message_size>
296  
297 Specify maximimum size a message can be before it's split and sent in pieces.
298  
299 default: 1,000,000
300  
301 safety: 1,000
302  
303 =item B<max_messages_per_hour>
304  
305 Limits the number of messages per hour before we refuse to send them
306  
307 default: 125
308  
309 safety: 166
310  
311 =back
312  
313 =cut
314  
315 # Handle initialization of objects of this class...
316 sub BUILD {
317 27 ▶ my ( $self, $params ) = @_;
Subroutine BUILD: called CC=13 SCAR=32.8
Pod undocumented
318  
319 # Deal with legacy bug
320 27 ▶ if ( $params->{background_activity} || $params->{message_callback} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{"background_activity"} or $params->{"message_callback"}) 0 27 27
Condition33%1/3
$params->{"background_activity"} or $params->{"message_callback"}
l!l&&r!l&&!r
0027
MC/DC0%0/2
$params->{"background_activity"} or $params->{"message_callback"}
$params->{"background_activity"} $params->{"message_callback"}
Truth table33%1/3
A or B
A= $params->{"background_activity"}B= $params->{"message_callback"}
ABresult
1X1
011
000
321 0 my $warn_message = "\n\n" . "*" x 70 . "\n" . "WARNING!!! You're using old parameters for your bot initialization\n" . "'message_callback' should be changed to 'message_function'\n" . "'background_activity' should be changed to 'background_function'\n" . "I'm correcting this, but you should fix your code\n" . "*" x 70 . "\n" . "\n\n";
322 0 warn($warn_message);
323 0 WARN($warn_message);
324  
325 $self->background_function( $params->{background_activity} )
326 0 ▶ if ( !$self->background_function && $params->{background_activity} );
Branch: 1 branch
BranchTrueFalseTotal
if not $self->background_function and $params->{"background_activity"} 0 0 0
Condition0%0/3
not $self->background_function and $params->{"background_activity"}
!ll&&!rl&&r
000
MC/DC0%0/2
not $self->background_function and $params->{"background_activity"}
not $self->background_function $params->{"background_activity"}
Truth table0%0/3
not(A) and B
A= not $self->background_functionB= $params->{"background_activity"}
ABresult
0X0
100
111
327 $self->message_function( $params->{message_callback} )
328 0 ▶ if ( !$self->message_function && $params->{message_callback} );
Branch: 1 branch
BranchTrueFalseTotal
if not $self->message_function and $params->{"message_callback"} 0 0 0
Condition0%0/3
not $self->message_function and $params->{"message_callback"}
!ll&&!rl&&r
000
MC/DC0%0/2
not $self->message_function and $params->{"message_callback"}
not $self->message_function $params->{"message_callback"}
Truth table0%0/3
not(A) and B
A= not $self->message_functionB= $params->{"message_callback"}
ABresult
0X0
100
111
329 # sleep removed — the warning above is sufficient to alert developers
330 }
331  
332 # GTalk convenience: auto-configure TLS and server_host for Google Talk
333 27 ▶ if ( $self->gtalk ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->gtalk) 5 22 27
334 5 $self->tls(1);
335 5 ▶ $self->server_host('gmail.com') if ( !$params->{server_host} );
Branch: 1 branch
BranchTrueFalseTotal
unless $params->{"server_host"} 4 1 5
336 }
337  
338 # Message delay is inverse of out_messages_per_second
339 27 $self->message_delay( 1 / $self->out_messages_per_second );
340  
341 # Enforce all our safety restrictions here.
342 27 ▶ if ( $self->safety_mode ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->safety_mode) 26 1 27
343  
344 # more than 5 messages per second risks server flooding.
345 26 ▶ $self->message_delay( 1 / 5 ) if ( $self->message_delay < 1 / 5 );
Branch: 1 branch
BranchTrueFalseTotal
if $self->message_delay < "0.2" 0 26 26
346  
347 # Messages should be small to not overwhelm rooms/people/server
348 26 ▶ $self->max_message_size(1000) if ( $self->max_message_size > 1000 );
Branch: 1 branch
BranchTrueFalseTotal
if $self->max_message_size > 1000 10 16 26
349  
350 # More than 4,000 messages a day is a little excessive.
351 26 ▶ $self->max_messages_per_hour(125) if ( $self->max_messages_per_hour > 166 );
Branch: 1 branch
BranchTrueFalseTotal
if $self->max_messages_per_hour > 166 10 16 26
352  
353 # Should not be responding to self messages to prevent loops.
354 26 $self->ignore_self_messages(1);
355 }
356  
357 #Initialize the connection.
358 27 $self->_init_jabber;
359 }
360  
361 # Return a code reference that will pass self in addition to arguements passed to callback code ref.
362 sub _callback_maker {
363 126 ▶ my $self = shift;
Subroutine _callback_maker: called CC=1 SCAR=0.0
364 126 my $Function = shift;
365  
366 # return sub {return $code_ref->($self, @_);};
367 126 ▶ return sub { return $Function->( $self, @_ ); };
Subroutine __ANON__: called CC=1 SCAR=0.0
368 }
369  
370 # Creates client object and manages connection. Called on new but also called by re-connect
371 sub _init_jabber {
372 42 ▶ my $self = shift;
Subroutine _init_jabber: called CC=7 SCAR=19.7
373  
374 # Create a new client if we don't have one (e.g., after disconnect/reconnect)
375 42 ▶ $self->jabber_client( Net::Jabber::Client->new ) if !defined $self->jabber_client;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->jabber_client 15 27 42
376  
377 42 my $connection = $self->jabber_client;
378  
379 42 DEBUG("Set the call backs.");
380 42 $connection->PresenceDB(); # Init presence DB.
381 42 $connection->RosterDB(); # Init Roster DB.
382 42 $connection->SetCallBacks(
383 'message' => $self->_callback_maker( \&_process_jabber_message ), 'presence' => $self->_callback_maker( \&_jabber_presence_message )
384 , 'iq' => $self->_callback_maker( \&_jabber_in_iq_message )
385 );
386  
387 42 DEBUG( "Connect. hostname => " . $self->server . ", port => " . $self->port );
388 42 my %client_connect_hash = (
389 hostname => $self->server,
390 port => $self->port,
391 tls => $self->tls,
392 ssl_ca_path => $self->ssl_ca_path,
393 ssl_verify => $self->ssl_verify,
394 connectiontype => $self->connection_type,
395 componentname => $self->server_host,
396 );
397  
398 42 my $status = $connection->Connect(%client_connect_hash);
399  
400 42 ▶ if ( !defined $status ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $status) 9 33 42
401 9 ERROR("ERROR: Jabber server is down or connection was not allowed: $!");
402 9 die("Jabber server is down or connection was not allowed: $!");
403 }
404  
405 33 DEBUG( "Logging in... as user " . $self->username . " / " . $self->resource );
406 33 DEBUG( "PW: ********" );
407  
408 # Moved into connect hash via 'componentname'
409 # my $sid = $connection->{SESSION}->{id};
410 # $connection->{STREAM}->{SIDS}->{$sid}->{hostname} = $self->server_host;
411  
412 33 my @auth_result = $connection->AuthSend(
413 username => $self->username,
414 password => $self->password,
415 resource => $self->resource,
416 );
417  
418 33 ▶ if ( !defined $auth_result[0] || $auth_result[0] ne "ok" ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $auth_result[0] or $auth_result[0] ne "ok") 0 33 33
Condition33%1/3
not defined $auth_result[0] or $auth_result[0] ne "ok"
l!l&&r!l&&!r
0033
MC/DC0%0/2
not defined $auth_result[0] or $auth_result[0] ne "ok"
not defined $auth_result[0] $auth_result[0] ne "ok"
Truth table33%1/3
not(A) or B
A= not defined $auth_result[0]B= $auth_result[0] ne "ok"
ABresult
1X1
011
000
419 0 ERROR( "Authorization failed: for " . $self->username . " / " . $self->resource );
420 0 foreach my $result (@auth_result) {
421 0 ERROR("$result");
422 }
423 0 die( "Failed to re-connect: " . join( "\n", @auth_result ) );
424 }
425  
426 33 $connection->RosterRequest();
427  
428 33 $self->client_session_id( $connection->{SESSION}->{id} );
429  
430 33 DEBUG("Sending presence to tell world that we are logged in");
431 33 $connection->PresenceSend();
432 33 $self->Process(5);
433  
434 33 DEBUG("Getting Roster to tell server to send presence info");
435 33 $connection->RosterGet();
436 33 $self->Process(5);
437  
438 33 foreach my $forum ( keys %{ $self->forums_and_responses } ) {
439 35 $self->JoinForum($forum);
440 }
441  
442 33 INFO( "Connected to server '" . $self->server . "' successfully" );
443 33 $self->connect_time(time); # Track when we came online.
444 33 return 1;
445 }
446  
447 =item B<JoinForum>
448  
449 Joins a jabber forum and sleeps safety time. Also prevents the object
450 from responding to messages for a grace period in efforts to get it to
451 not respond to historical messages. This has failed sometimes.
452  
453 NOTE: No error detection for join failure is present at the moment. (TODO)
454  
455 =cut
456  
457 sub JoinForum {
458 35 ▶ my $self = shift;
Subroutine JoinForum: called CC=2 SCAR=7.2
Pod documented
459 35 my $forum_name = shift;
460  
461 35 ▶ if ( !$self->IsConnected ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->IsConnected) 0 35 35
462 0 WARN("Cannot join forum '$forum_name': not connected");
463 0 return;
464 }
465  
466 35 DEBUG( "Joining $forum_name on " . $self->conference_server . " as " . $self->alias );
467  
468 35 $self->jabber_client->MUCJoin(
469 room => $forum_name,
470 server => $self->conference_server,
471 nick => $self->alias,
472 );
473  
474 35 $self->forum_join_time->{$forum_name} = time;
475 35 DEBUG( "Sleeping " . $self->message_delay . " seconds" );
476 35 Time::HiRes::sleep $self->message_delay;
477 }
478  
479 =item B<Process>
480  
481 Mostly calls it's client connection's "Process" call.
482 Also assures a timeout is enforced if not fed to the subroutine
483 You really should not have to call this very often.
484 You should mostly be calling Start() and just let the Bot kernel handle all this.
485  
486 =cut
487  
488 sub Process { # Call connection process.
489 105 ▶ my $self = shift;
Subroutine Process: called CC=3 SCAR=11.0
Pod documented
490 105 my $timeout_seconds = shift;
491  
492 105 ▶ return if !$self->IsConnected;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->IsConnected 1 104 105
493  
494 #If not passed explicitly
495 104 ▶ $timeout_seconds = $self->process_timeout if ( !defined $timeout_seconds );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $timeout_seconds 0 104 104
496  
497 104 my $process_return = $self->jabber_client->Process($timeout_seconds);
498 104 return $process_return;
499 }
500  
501 =item B<Start>
502  
503 Primary subroutine save new called by the program. Runs a loop of:
504  
505 =over
506  
507 =item 1. Process
508  
509 =item 2. If Process failed, Reconnect to server over larger and larger timeout
510  
511 =item 3. run background process fed from new, telling it who I am and how many loops we have been through.
512  
513 =item 4. Enforce a sleep to prevent server floods.
514  
515 =back
516  
517 The loop runs until Stop() is called. Returns the loop iteration count.
518  
519 =cut
520  
521 sub Start {
522 6 ▶ my $self = shift;
Subroutine Start: called CC=5 SCAR=16.7
Pod documented
523  
524 6 my $time_between_background_routines = $self->loop_sleep_time;
525 6 my $process_timeout = $self->process_timeout;
526 6 my $background_subroutine = $self->background_function;
527 6 my $message_delay = $self->message_delay;
528  
529 6 my $last_background = time - $time_between_background_routines - 1; # Call background process every so often...
530 6 my $counter = 0; # Keep track of how many times we've looped.
531  
532 6 $self->_running(1);
533  
534 6 ▶ while ( $self->_running ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_running) 20 6 26
535 # Process and re-connect if you have to.
536 20 eval { $self->Process($process_timeout) };
537  
538 20 ▶ if ($@) { #Assume the connection is down...
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 20 20
539 0 ERROR("Server error: $@");
540 0 my $message = "Disconnected from " . $self->server . ":" . $self->port . " as " . $self->username;
541  
542 0 ERROR("$message Reconnecting...");
543 0 sleep 5; # TODO: Make re-connect time flexible somehow
544 0 $self->ReconnectToServer();
545 }
546  
547 # Call background function
548 20 ▶ if ( defined $background_subroutine && $last_background + $time_between_background_routines < time ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $background_subroutine and $last_background + $time_between_background_routines < time) 10 10 20
Condition66%2/3
defined $background_subroutine and $last_background + $time_between_background_routines < time
!ll&&!rl&&r
01010
MC/DC50%1/2
defined $background_subroutine and $last_background + $time_between_background_routines < time
defined $background_subroutine $last_background + $time_between_background_routines < time
Truth table66%2/3
A and B
A= defined $background_subroutineB= $last_background + $time_between_background_routines < time
ABresult
0X0
100
111
549 10 &$background_subroutine( $self, ++$counter );
550 10 $last_background = time;
551 }
552 20 Time::HiRes::sleep $message_delay;
553 }
554  
555 6 return $counter;
556 }
557  
558 =item B<Stop>
559  
560 $bot->Stop();
561  
562 Signals the Start() loop to exit after the current iteration completes.
563 Typically called from within the background_function or message_function callback.
564  
565 =cut
566  
567 sub Stop {
568 8 ▶ my $self = shift;
Subroutine Stop: called CC=1 SCAR=0.0
Pod documented
569  
570 8 INFO("Stop requested, will exit Start() loop after current iteration");
571 8 $self->_running(0);
572 8 return 1;
573 }
574  
575 =item B<ReconnectToServer>
576  
577 You should not ever need to use this. the Start() kernel usually figures this out and calls it.
578  
579 Internal process:
580  
581 1. Disconnects
582 3. Re-initializes
583  
584 =cut
585  
586 sub ReconnectToServer {
587 6 ▶ my $self = shift;
Subroutine ReconnectToServer: called CC=5 SCAR=16.1
Pod documented
588  
589 6 my $background_subroutine = $self->background_function;
590  
591 6 $self->Disconnect();
592  
593 6 my $sleep_time = 5;
594 6 ▶ while ( !$self->IsConnected() ) { # jabber_client variable defines if we're connected.
Branch: 1 branch
BranchTrueFalseTotal
if (not $self->IsConnected) 14 6 20
595 14 INFO("Sleeping $sleep_time before attempting re-connect");
596 14 sleep $sleep_time;
597 14 ▶ $sleep_time *= 2 if ( $sleep_time < 300 );
Branch: 1 branch
BranchTrueFalseTotal
if $sleep_time < 300 14 0 14
598 14 eval { $self->_init_jabber() };
599 14 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 8 6 14
600 8 WARN("Reconnection attempt failed: $@");
601 # Clean up partial client state so IsConnected() stays false
602 # and next _init_jabber() creates a fresh client
603 8 $self->jabber_client(undef);
604 8 next;
605 }
606 6 ▶ if ( defined $background_subroutine ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $background_subroutine) 6 0 6
607 6 INFO("Running background routine.");
608 6 &$background_subroutine( $self, 0 ); # call background proc so we can check for errors while down.
609 }
610 }
611 }
612  
613 =item B<Disconnect>
614  
615 Disconnects from server if client object is defined. Assures the client object is deleted.
616  
617 =cut
618  
619 sub Disconnect {
620 14 ▶ my $self = shift;
Subroutine Disconnect: called CC=2 SCAR=6.9
Pod documented
621  
622 14 $self->connect_time( '9' x 10 ); # Way in the future
623  
624 14 INFO("Disconnecting from server");
625 14 ▶ return if ( !defined $self->jabber_client ); # do not proceed, no object.
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->jabber_client 6 8 14
626  
627 8 $self->jabber_client->Disconnect();
628 8 my $old_client = $self->jabber_client;
629 8 $self->jabber_client(undef);
630  
631 8 DEBUG("Disconnected.");
632 8 return 1;
633 }
634  
635 =item B<IsConnected>
636  
637 Reports connect state (true/false) based on the status of client_start_time.
638  
639 =cut
640  
641 sub IsConnected {
642 374 ▶ my $self = shift;
Subroutine IsConnected: called CC=1 SCAR=0.0
Pod documented
643  
644 374 return defined $self->jabber_client;
645 }
646  
647 # TODO: ***NEED VERY GOOD DOCUMENTATION HERE*****
648  
649 =item B<_process_jabber_message> - DO NOT CALL
650  
651 Handles incoming messages.
652  
653 =cut
654  
655 sub _process_jabber_message {
656 182 ▶ my $self = shift;
Subroutine _process_jabber_message: called CC=18 SCAR=31.3
657 182 DEBUG("_process_jabber_message called");
658  
659 182 my $session_id = shift;
660 182 my $message = shift;
661  
662 182 my $type = $message->GetType();
663 182 my $fromJID = $message->GetFrom("jid");
664 182 my $from_full = $message->GetFrom();
665  
666 182 my $from = $fromJID->GetUserID();
667 182 my $resource = $fromJID->GetResource();
668 182 my $subject = $message->GetSubject();
669 182 my $body = $message->GetBody();
670  
671 182 my $reply_to = $from_full;
672 182 ▶ $reply_to =~ s/\/.*$// if ( $type eq 'groupchat' );
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "groupchat" 92 90 182
673  
674 # TODO:
675 # Don't know exactly why but when a message comes from gtalk-web-interface, it works well, but if the message comes from Gtalk client, bot dies
676 # my $message_date_text; eval { $message_date_text = $message->GetTimeStamp(); } ; # Eval is a really bad idea. we need to understand why this is failing.
677  
678 # my $message_date_text = $message->GetTimeStamp(); # Since we're not using the data, we'll turn this off since it crashes gtalk clients aparently?
679 # my $message_date = UnixDate($message_date_text, "%s") - 1*60*60; # Convert to EST from CST;
680  
681 # Ignore any messages within 'forum_join_grace' seconds of start or join of that forum
682 182 my $grace_period = $self->forum_join_grace;
683 182 my $time_now = time;
684 182 ▶ if ( $self->connect_time > $time_now - $grace_period
Branch: 1 branch
BranchTrueFalseTotal
if ($self->connect_time > $time_now - $grace_period or defined $self->forum_join_time->{$from} and $self->forum_join_time->{$from} > $time_now - $grace_period) 1 181 182
Condition66%4/6
$self->connect_time > $time_now - $grace_period or defined $self->forum_join_time->{$from} and $self->forum_join_time->{$from} > $time_now - $grace_period
l!l&&r!l&&!r
10181
defined $self->forum_join_time->{$from} and $self->forum_join_time->{$from} > $time_now - $grace_period
!ll&&!rl&&r
89920
MC/DC33%1/3
$self->connect_time > $time_now - $grace_period or defined $self->forum_join_time->{$from} and $self->forum_join_time->{$from} > $time_now - $grace_period
$self->connect_time > $time_now - $grace_period defined $self->forum_join_time->{$from} $self->forum_join_time->{$from} > $time_now - $grace_period
Truth table50%2/4
A or B and C
A= $self->connect_time > $time_now - $grace_periodB= defined $self->forum_join_time->{$from}C= $self->forum_join_time->{$from} > $time_now - $grace_period
ABCresult
1XX1
0111
00X0
0100
685 || ( defined $self->forum_join_time->{$from} && $self->forum_join_time->{$from} > $time_now - $grace_period ) ) {
686 1 my $cond1 = $self->connect_time . " > $time_now - $grace_period";
687 1 ▶ my $cond2 = ($self->forum_join_time->{$from} || 'undef') . " > $time_now - $grace_period";
Condition50%1/2
$self->forum_join_time->{$from} || 'undef'
l!l
01
MC/DC0%0/1
$self->forum_join_time->{$from} || 'undef'
$self->forum_join_time->{$from}
Truth table50%1/2
A
A= $self->forum_join_time->{$from}
Aresult
11
00
688 1 DEBUG("Ignoring messages cause I'm in startup for forum $from\n$cond1\n$cond2");
689 1 return; # Ignore messages the first few seconds.
690 }
691  
692 # Ignore Group messages with no resource on them. (Server Messages?)
693 181 ▶ if ( $self->ignore_server_messages ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->ignore_server_messages) 181 0 181
694 181 ▶ if ( $from_full !~ m/^([^\@]+)\@([^\/]+)\/(.+)$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($from_full =~ m[^([^\@]+)\@([^/]+)/(.+)$]) 0 181 181
695 0 DEBUG("Server message? ($from_full) - $message");
696 0 ▶ return if ( $from_full !~ m/^([^\@]+)\@([^\/]+)\// );
Branch: 1 branch
BranchTrueFalseTotal
unless $from_full =~ m[^([^\@]+)\@([^/]+)/] 0 0 0
697 0 ERROR("Couldn't recognize from_full ($from_full). Ignoring message: $body");
698 0 return;
699 }
700 }
701  
702 # Are these my own messages?
703 181 ▶ if ( $self->ignore_self_messages ) { # TODO: || $self->safety_mode (this breaks tests in 06?)
Branch: 1 branch
BranchTrueFalseTotal
if ($self->ignore_self_messages) 160 21 181
704  
705 160 ▶ if ( defined $resource && $resource eq $self->resource ) { # Ignore my own messages.
Branch: 1 branch
BranchTrueFalseTotal
if (defined $resource and $resource eq $self->resource) 160 0 160
Condition33%1/3
defined $resource and $resource eq $self->resource
!ll&&!rl&&r
00160
MC/DC0%0/2
defined $resource and $resource eq $self->resource
defined $resource $resource eq $self->resource
Truth table33%1/3
A and B
A= defined $resourceB= $resource eq $self->resource
ABresult
0X0
100
111
706 160 DEBUG("Ignoring message from self...\n");
707 160 return;
708 }
709 }
710  
711 # Determine if this message was addressed to me. (groupchat only)
712 21 my $bot_address_from;
713 21 my @aliases_to_respond_to = $self->get_responses($from);
714  
715 21 ▶ if ( $#aliases_to_respond_to >= 0 and $type eq 'groupchat' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($#aliases_to_respond_to >= 0 and $type eq "groupchat") 12 9 21
Condition66%2/3
$#aliases_to_respond_to >= 0 and $type eq "groupchat"
!ll&&!rl&&r
9012
MC/DC50%1/2
$#aliases_to_respond_to >= 0 and $type eq "groupchat"
$#aliases_to_respond_to >= 0 $type eq "groupchat"
Truth table66%2/3
A and B
A= $#aliases_to_respond_to >= 0B= $type eq "groupchat"
ABresult
0X0
100
111
716 12 my $request;
717 12 foreach my $address_type (@aliases_to_respond_to) {
718 24 my $qm_address_type = quotemeta($address_type);
719 24 ▶ next if ( $body !~ m/^\s*$qm_address_type\s*(\S.*)$/ms );
Branch: 1 branch
BranchTrueFalseTotal
unless $body =~ /^\s*$qm_address_type\s*(\S.*)$/ms 12 12 24
720 12 $request = $1;
721 12 $bot_address_from = $address_type;
722 12 last; # do not need to loop any more.
723 }
724 12 ▶ if ( !defined $request ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $request) 0 12 12
725 0 DEBUG("Message not relevant to bot");
726 0 return;
727 }
728 12 $body = $request;
729 }
730  
731 # Call the message callback if it's defined.
732 21 ▶ if ( defined $self->message_function ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->message_function) { } 21 0 21
733 21 $self->message_function->(
734 bot_object => $self,
735 from_full => $from_full,
736 body => $body,
737 type => $type,
738 reply_to => $reply_to,
739 bot_address_from => $bot_address_from,
740 message => $message
741 );
742 21 return;
743 }
744 else {
745 0 WARN("No handler for messages!");
746 0 INFO("New Message: $type from $from ($resource). sub=$subject -- $body");
747 }
748 }
749  
750 =item B<get_responses>
751  
752 $bot->get_responses($forum_name);
753  
754 Returns the array of messages we are monitoring for in supplied forum or replies with undef.
755  
756 =cut
757  
758 sub get_responses {
759 21 ▶ my $self = shift;
Subroutine get_responses: called CC=3 SCAR=11.3
Pod documented
760  
761 21 my $forum = shift;
762  
763 21 ▶ if ( !defined $forum ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $forum) 0 21 21
764 0 WARN("No forum supplied for get_responses()");
765 0 return;
766 }
767  
768 21 my @aliases_to_respond_to;
769 21 ▶ if ( defined $self->forums_and_responses->{$forum} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->forums_and_responses->{$forum}) 12 9 21
770 12 @aliases_to_respond_to = @{ $self->forums_and_responses->{$forum} };
771 }
772  
773 21 return @aliases_to_respond_to;
774 }
775  
776 =item B<_jabber_in_iq_message> - DO NOT CALL
777  
778 Called when the client receives new messages during Process of this type.
779  
780 =cut
781  
782 sub _jabber_in_iq_message {
783 0 ▶ my $self = shift;
Subroutine _jabber_in_iq_message: not called CC=3 SCAR=24.8
784  
785 0 my $session_id = shift;
786 0 my $iq = shift;
787  
788 0 DEBUG( "IQ Message:" . $iq->GetXML() );
789 0 my $from = $iq->GetFrom();
790  
791 # my $type = $iq->GetType();DEBUG("Type=$type");
792 0 my $query = $iq->GetQuery(); #DEBUG("query=" . Dumper($query));
793  
794 0 ▶ if ( !$query ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($query) 0 0 0
795 0 DEBUG("iq->GetQuery() returned undef.");
796 0 return;
797 }
798  
799 0 my $xmlns = $query->GetXMLNS();
800 0 DEBUG("xmlns=$xmlns");
801  
802 # Respond to version requests with information about myself.
803 0 ▶ if ( $xmlns eq "jabber:iq:version" ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($xmlns eq "jabber:iq:version") 0 0 0
804  
805 # convert 5.010000 to 5.10.0
806 0 my $perl_version = $];
807 0 $perl_version =~ s/(\d{3})(?=\d)/$1./g;
808 0 $perl_version =~ s/\.0+(\d)/.$1/g;
809  
810 0 $self->jabber_client->VersionSend(
811 to => $from,
812 name => __PACKAGE__,
813 ver => $VERSION,
814 os => "Perl v$perl_version"
815 );
816 }
817 }
818  
819 =item B<_jabber_presence_message> - DO NOT CALL
820  
821 Called when the client receives new presence messages during Process.
822 Mostly we are just pushing the data down into the client DB for later processing.
823  
824 =cut
825  
826 sub _jabber_presence_message {
827 0 ▶ my $self = shift;
Subroutine _jabber_presence_message: not called CC=7 SCAR=40.3
828  
829 0 my $session_id = shift;
830 0 my $presence = shift;
831  
832 0 my $type = $presence->GetType();
833 0 ▶ if ( $type eq 'subscribe' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'subscribe') { } 0 0 0
elsif ($type eq 'unsubscribe') { } 0 0 0
834 0 my $from = $presence->GetFrom();
835 0 ▶ if ( $self->auto_subscribe ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->auto_subscribe) { } 0 0 0
836 0 $self->jabber_client->Subscription(
837 type => "subscribe",
838 to => $from
839 );
840 0 $self->jabber_client->Subscription( type => "subscribed", to => $from );
841 0 INFO("Processed subscription request from $from");
842 }
843 else {
844 0 INFO("Ignored subscription request from $from (auto_subscribe disabled)");
845 }
846 0 return;
847 }
848 elsif ( $type eq 'unsubscribe' ) {
849 0 my $from = $presence->GetFrom();
850 0 $self->jabber_client->Subscription(
851 type => "unsubscribed",
852 to => $from
853 );
854 0 INFO("Processed unsubscribe request from $from");
855 0 return;
856 }
857  
858 # Without explicitly setting a priority, XMPP::Protocol will store all JIDs with an empty
859 # priority under the same key rather than in an array.
860 0 ▶ $presence->SetPriority(0) unless $presence->GetPriority();
Branch: 1 branch
BranchTrueFalseTotal
unless $presence->GetPriority 0 0 0
861  
862 0 $self->jabber_client->PresenceDBParse($presence); # Since we are always an object just throw it into the db.
863  
864 0 my $from = $presence->GetFrom();
865 0 ▶ $from = "." if ( !defined $from );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $from 0 0 0
866  
867 0 my $status = $presence->GetStatus();
868 0 ▶ $status = "." if ( !defined $status );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $status 0 0 0
869  
870 0 DEBUG("Presence From $from t=$type s=$status");
871 0 DEBUG( "Presence XML: " . $presence->GetXML() );
872 }
873  
874 =item B<respond_to_self_messages>
875  
876 $bot->respond_to_self_messages($value = 1);
877  
878  
879 Tells the bot to start reacting to it\'s own messages if non-zero is passed. Default is 1.
880  
881 =cut
882  
883 sub respond_to_self_messages {
884 10 ▶ my $self = shift;
Subroutine respond_to_self_messages: called CC=2 SCAR=6.9
Pod documented
885  
886 10 my $setting = shift;
887 10 ▶ $setting = 1 if ( !defined $setting );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $setting 4 6 10
888  
889 10 $self->ignore_self_messages( !$setting );
890 10 return !!$setting;
891 }
892  
893 =item B<get_messages_this_hour>
894  
895 $bot->get_messages_this_hour();
896  
897 Returns the number of messages sent so far this hour.
898  
899 =cut
900  
901 sub get_messages_this_hour {
902 28 ▶ my $self = shift;
Subroutine get_messages_this_hour: called CC=2 SCAR=6.9
Pod documented
903  
904 28 my $yday = (localtime)[7];
905 28 my $hour = (localtime)[2];
906 28 my $messages_this_hour = $self->messages_sent_today->{$yday}->{$hour};
907 28 ▶ return $messages_this_hour || 0; # Assure it's not undef to avoid math warnings
Condition100%2/2
$messages_this_hour || 0
l!l
253
MC/DC100%1/1
$messages_this_hour || 0
$messages_this_hour
Truth table100%2/2
A
A= $messages_this_hour
Aresult
11
00
908 }
909  
910 =item B<get_safety_mode>
911  
912 Validates that we are in safety mode. Returns a bool as long as we are an object, otherwise returns undef
913  
914 =cut
915  
916 sub get_safety_mode {
917 1 ▶ my $self = shift;
Subroutine get_safety_mode: called CC=6 SCAR=24.3
Pod documented
918  
919 # Must be in safety mode and all thresholds met.
920 1 ▶ my $mode =
Condition33%4/12
$self->safety_mode && $self->message_delay >= 0.2 && $self->max_message_size <= 1000 && $self->max_messages_per_hour <= 166 && $self->ignore_self_messages
!ll&&!rl&&r
001
$self->safety_mode and $self->message_delay >= "0.2" and $self->max_message_size <= 1000 and $self->max_messages_per_hour <= 166
!ll&&!rl&&r
001
$self->safety_mode and $self->message_delay >= "0.2" and $self->max_message_size <= 1000
!ll&&!rl&&r
001
$self->safety_mode and $self->message_delay >= "0.2"
!ll&&!rl&&r
001
MC/DC0%0/5
$self->safety_mode && $self->message_delay >= 0.2 && $self->max_message_size <= 1000 && $self->max_messages_per_hour <= 166 && $self->ignore_self_messages
$self->safety_mode $self->message_delay >= "0.2" $self->max_message_size <= 1000 $self->max_messages_per_hour <= 166 $self->ignore_self_messages
Truth table16%1/6
A and B and C and D && E
A= $self->safety_modeB= $self->message_delay >= "0.2"C= $self->max_message_size <= 1000D= $self->max_messages_per_hour <= 166E= $self->ignore_self_messages
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
921 $self->safety_mode
922 && $self->message_delay >= 1 / 5
923 && $self->max_message_size <= 1000
924 && $self->max_messages_per_hour <= 166
925 && $self->ignore_self_messages;
926  
927 1 ▶ return $mode || 0;
Condition50%1/2
$mode || 0
l!l
10
MC/DC0%0/1
$mode || 0
$mode
Truth table50%1/2
A
A= $mode
Aresult
11
00
928 }
929  
930 =item B<SendGroupMessage>
931  
932 $bot->SendGroupMessage($name, $message);
933 $bot->SendGroupMessage($name, $message, $from);
934  
935 Tells the bot to send a message to the recipient room name.
936  
937 $from is an optional JID to set as the sender of the message.
938 Note that most XMPP servers will not allow spoofing the from field
939 and may reject the message or disconnect the client.
940  
941 =cut
942  
943 sub SendGroupMessage {
944 84 ▶ my $self = shift;
Subroutine SendGroupMessage: called CC=2 SCAR=7.0
Pod documented
945 84 my $recipient = shift;
946 84 my $message = shift;
947 84 my $from = shift;
948  
949 84 ▶ $recipient .= '@' . $self->conference_server if ( $recipient !~ m{\@} );
Branch: 1 branch
BranchTrueFalseTotal
unless $recipient =~ /\@/ 84 0 84
950  
951 84 return $self->SendJabberMessage( $recipient, $message, 'groupchat', undef, $from );
952 }
953  
954 =item B<SendPersonalMessage>
955  
956 $bot->SendPersonalMessage($recipient, $message);
957 $bot->SendPersonalMessage($recipient, $message, $from);
958  
959 How to send an individual message to someone.
960  
961 $recipient must read as user@server/Resource or it will not send.
962  
963 $from is an optional JID to set as the sender of the message.
964 Note that most XMPP servers will not allow spoofing the from field
965 and may reject the message or disconnect the client.
966  
967 =cut
968  
969 sub SendPersonalMessage {
970 102 ▶ my $self = shift;
Subroutine SendPersonalMessage: called CC=1 SCAR=0.0
Pod documented
971 102 my $recipient = shift;
972 102 my $message = shift;
973 102 my $from = shift;
974  
975 102 return $self->SendJabberMessage( $recipient, $message, 'chat', undef, $from );
976 }
977  
978 =item B<SendJabberMessage>
979  
980 $bot->SendJabberMessage($recipient, $message, $message_type, $subject, $from);
981  
982 The master subroutine to send a message. Called either by the user, SendPersonalMessage, or SendGroupMessage. Sometimes there
983 is call to call it directly when you do not feel like figuring you messaged you.
984 Assures message size does not exceed a limit and chops it into pieces if need be.
985  
986 NOTE: non-printable characters (unicode included) will be replaced with a dot before sending to the server.
987 Newlines (LF and CR) are preserved so that multiline messages work correctly.
988  
989 s/[^\r\n[:print:]]+/./xmsg
990  
991 =cut
992  
993 sub SendJabberMessage {
994 186 ▶ my $self = shift;
Subroutine SendJabberMessage: called CC=5 SCAR=16.1
Pod documented
995  
996 186 my $recipient = shift;
997 186 my $message = shift;
998 186 my $message_type = shift;
999 186 my $subject = shift;
1000 186 my $from = shift;
1001  
1002 186 my $max_size = $self->max_message_size;
1003  
1004 # Split the message into no more than max_message_size so that we do not piss off jabber.
1005 # Split on new line. Space if you have to or just chop at max size.
1006 186 my @message_chunks = ( $message =~ /.{1,$max_size}$|.{1,$max_size}\n|.{1,$max_size}\s|.{1,$max_size}/gs );
1007  
1008 186 ▶ DEBUG("Max message = $max_size. Splitting...") if ( $#message_chunks > 0 );
Branch: 1 branch
BranchTrueFalseTotal
if $#message_chunks > 0 2 184 186
1009 186 my $return_value;
1010 186 foreach my $message_chunk (@message_chunks) {
1011 196 my $msg_return = $self->_send_individual_message( $recipient, $message_chunk, $message_type, $subject, $from );
1012 196 ▶ if ( defined $msg_return ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $msg_return) 6 190 196
1013 6 ▶ $return_value = ( $return_value // '' ) . $msg_return;
Condition50%1/2
$return_value // ""
l!l
06
MC/DC0%0/1
$return_value // ""
$return_value
Truth table50%1/2
A
A= $return_value
Aresult
11
00
1014 }
1015 }
1016 186 return $return_value;
1017 }
1018  
1019 # $self->_send_individual_message($recipient, $message_chunk, $message_type, $subject);
1020 # Private subroutine only called directly by SetForumSubject and SendJabberMessage.
1021 # There are a bunch of fancy things this does, but the important things are:
1022 # 1. sleep a minimum of .2 seconds every message
1023 # 2. Make sure we have not sent too many messages this hour and block sends if they are attempted over a certain limit (max limit is 125)
1024 # 3. Strip out special characters that will get us booted from the server.
1025  
1026 sub _send_individual_message {
1027 196 ▶ my $self = shift;
Subroutine _send_individual_message: called CC=13 SCAR=26.2
1028  
1029 196 my $recipient = shift;
1030 196 my $message_chunk = shift;
1031 196 my $message_type = shift;
1032 196 my $subject = shift;
1033 196 my $from = shift;
1034  
1035 196 ▶ if ( !defined $message_type ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $message_type) 0 196 196
1036 0 ERROR("Undefined \$message_type");
1037 0 return "No message type!\n";
1038 }
1039  
1040 196 ▶ if ( !defined $recipient ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $recipient) 0 196 196
1041 0 ERROR('$recipient not defined!');
1042 0 return "No recipient!\n";
1043 }
1044  
1045 # Check connection first — don't count messages that can't actually be sent.
1046 # Otherwise, messages attempted during disconnection inflate the hourly
1047 # counter and can exhaust the limit before real messages are sent.
1048 196 ▶ if ( !$self->IsConnected ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->IsConnected) 5 191 196
1049 5 ▶ $subject = "" if ( !defined $subject ); # Keep warning messages quiet.
Branch: 1 branch
BranchTrueFalseTotal
unless defined $subject 5 0 5
1050 5 ▶ $message_chunk = "" if ( !defined $message_chunk ); # Keep warning messages quiet.
Branch: 1 branch
BranchTrueFalseTotal
unless defined $message_chunk 0 5 5
1051  
1052 5 ERROR( "Can't send: Jabber server is down. Tried to send: \n" . "To: $recipient\n" . "Subject: $subject\n" . "Type: $message_type\n" . "Message sent:\n" . "$message_chunk" );
1053  
1054 5 return "Server is down.\n";
1055 }
1056  
1057 191 my $yday = (localtime)[7];
1058 191 my $hour = (localtime)[2];
1059  
1060 # Clean up entries from previous days to prevent unbounded memory growth
1061 191 for my $old_day ( keys %{ $self->messages_sent_today } ) {
1062 195 ▶ delete $self->messages_sent_today->{$old_day} if $old_day != $yday;
Branch: 1 branch
BranchTrueFalseTotal
if $old_day != $yday 10 185 195
1063 }
1064  
1065 191 my $messages_this_hour = $self->messages_sent_today->{$yday}->{$hour} += 1;
1066  
1067 191 ▶ if ( $messages_this_hour > $self->max_messages_per_hour ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($messages_this_hour > $self->max_messages_per_hour) 1 190 191
1068 1 ▶ $subject = "" if ( !defined $subject ); # Keep warning messages quiet.
Branch: 1 branch
BranchTrueFalseTotal
unless defined $subject 1 0 1
1069 1 ▶ $message_chunk = "" if ( !defined $message_chunk ); # Keep warning messages quiet.
Branch: 1 branch
BranchTrueFalseTotal
unless defined $message_chunk 0 1 1
1070  
1071 1 my $max_per_hour = $self->max_messages_per_hour;
1072 1 ERROR( "Can't send message because we've already tried to send $messages_this_hour of $max_per_hour messages this hour.\n" . "To: $recipient\n" . "Subject: $subject\n" . "Type: $message_type\n" . "Message sent:\n" . "$message_chunk" );
1073  
1074 # Send 1 panic message out to jabber if this is our last message before quieting down.
1075 1 return "Too many messages ($messages_this_hour)\n";
1076 }
1077  
1078 # Strip out anything that's not a printable character except new line, we want to be able to send multiline message, aren't we?
1079 # Now with unicode support?
1080 190 $message_chunk =~ s/[^\r\n[:print:]]+/./xmsg;
1081  
1082 190 my $message_length = length($message_chunk);
1083 190 DEBUG("Sending message $yday-$hour-$messages_this_hour $message_length bytes to $recipient");
1084 190 my %message_args = (
1085 to => $recipient,
1086 body => $message_chunk,
1087 type => $message_type,
1088 subject => $subject,
1089 );
1090 190 ▶ $message_args{from} = $from if defined $from;
Branch: 1 branch
BranchTrueFalseTotal
if defined $from 2 188 190
1091 190 $self->jabber_client->MessageSend(%message_args);
1092  
1093 190 DEBUG( "Sleeping " . $self->message_delay . " after sending message." );
1094 190 Time::HiRes::sleep $self->message_delay; #Throttle messages.
1095  
1096 190 ▶ if ( $messages_this_hour == $self->max_messages_per_hour ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($messages_this_hour == $self->max_messages_per_hour) 1 189 190
1097 1 $self->jabber_client->MessageSend(
1098 to => $recipient, body => "Cannot send more messages this hour. "
1099 . "$messages_this_hour of "
1100 . $self->max_messages_per_hour
1101 . " already sent."
1102 , type => $message_type
1103 );
1104 }
1105 190 return; # Means we succeeded!
1106 }
1107  
1108 =item B<SetForumSubject>
1109  
1110 $bot->SetForumSubject($recipient, $subject);
1111  
1112 Sets the subject of a forum
1113  
1114 =cut
1115  
1116 sub SetForumSubject {
1117 2 ▶ my $self = shift;
Subroutine SetForumSubject: called CC=2 SCAR=7.2
Pod documented
1118  
1119 2 my $recipient = shift;
1120 2 my $subject = shift;
1121  
1122 2 ▶ if ( length $subject > $self->max_message_size ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $subject > $self->max_message_size) 2 0 2
1123 2 my $subject_len = length($subject);
1124 2 ERROR("Someone tried to send a subject message $subject_len bytes long!");
1125 2 $subject = substr( $subject, 0, $self->max_message_size );
1126 2 DEBUG("Truncated subject: $subject");
1127 2 return "Subject is too long!";
1128 }
1129 0 $self->_send_individual_message( $recipient, "Setting subject to $subject", 'groupchat', $subject );
1130  
1131 0 return;
1132 }
1133  
1134 =item B<ChangeStatus>
1135  
1136 $bot->ChangeStatus($presence_mode, $status_string);
1137  
1138 Sets the Bot's presence status.
1139 $presence mode could be something like: (Chat, Available, Away, Ext. Away, Do Not Disturb).
1140 $status_string is an optional comment to go with your presence mode. It is not required.
1141  
1142 =cut
1143  
1144 sub ChangeStatus {
1145 1 ▶ my $self = shift;
Subroutine ChangeStatus: called CC=2 SCAR=7.5
Pod documented
1146 1 my $presence_mode = shift;
1147 1 my $status_string = shift; # (optional)
1148  
1149 1 ▶ if ( !$self->IsConnected ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->IsConnected) 1 0 1
1150 1 WARN("Cannot change status: not connected");
1151 1 return 0;
1152 }
1153  
1154 0 $self->jabber_client->PresenceSend( show => $presence_mode, status => $status_string );
1155  
1156 0 return 1;
1157 }
1158  
1159 =item B<GetRoster>
1160  
1161 $bot->GetRoster();
1162  
1163 Returns a list of the people logged into the server.
1164 I suspect we really want to know who is in a particular forum right?
1165 In which case we need another sub for this.
1166 =cut
1167  
1168 sub GetRoster {
1169 1 ▶ my $self = shift;
Subroutine GetRoster: called CC=3 SCAR=15.0
Pod documented
1170  
1171 1 ▶ if ( !$self->IsConnected ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->IsConnected) 1 0 1
1172 1 WARN("Cannot get roster: not connected");
1173 1 return ();
1174 }
1175  
1176 0 my @rosterlist;
1177 0 foreach my $jid ( $self->jabber_client->RosterDBJIDs() ) {
1178 0 my $username = $jid->GetJID();
1179 0 push( @rosterlist, $username );
1180 }
1181 0 return @rosterlist;
1182 }
1183  
1184 =item B<GetStatus>
1185  
1186 my $status = $bot->GetStatus($jid);
1187  
1188 Returns the presence status of the given JID. Possible return values are
1189 "unavailable" (if not connected or JID not found in the presence database),
1190 "available" (if present with no specific show value), or the XMPP show value
1191 (e.g. "away", "xa", "dnd", "chat").
1192  
1193 =cut
1194  
1195 sub GetStatus {
1196  
1197 1 ▶ my $self = shift;
Subroutine GetStatus: called CC=4 SCAR=23.7
Pod documented
1198 1 my ($jid) = shift;
1199  
1200 1 ▶ return "unavailable" if !$self->IsConnected;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->IsConnected 1 0 1
1201  
1202 0 my $Pres = $self->jabber_client->PresenceDBQuery($jid);
1203  
1204 0 ▶ if ( !( defined($Pres) ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $Pres) 0 0 0
1205  
1206 0 return "unavailable";
1207 }
1208  
1209 0 my $show = $Pres->GetShow();
1210 0 ▶ if ($show) {
Branch: 1 branch
BranchTrueFalseTotal
if ($show) 0 0 0
1211  
1212 0 return $show;
1213 }
1214  
1215 0 return "available";
1216  
1217 }
1218  
1219 =item B<AddUser>
1220  
1221 $bot->AddUser($jid);
1222  
1223 Sends a subscription request to the given JID and auto-approves their
1224 reciprocal subscription. This adds the user to the bot's roster and allows
1225 mutual presence visibility.
1226  
1227 =cut
1228  
1229 sub AddUser {
1230 0 ▶ my $self = shift;
Subroutine AddUser: not called CC=2 SCAR=17.9
Pod documented
1231 0 my $user = shift;
1232  
1233 0 ▶ if ( !$self->IsConnected ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->IsConnected) 0 0 0
1234 0 WARN("Cannot add user '$user': not connected");
1235 0 return;
1236 }
1237  
1238 0 $self->jabber_client->Subscription( type => "subscribe", to => $user );
1239 0 $self->jabber_client->Subscription( type => "subscribed", to => $user );
1240 }
1241  
1242 =item B<RmUser>
1243  
1244 $bot->RmUser($jid);
1245  
1246 Sends an unsubscribe request for the given JID and revokes their subscription
1247 to the bot's presence. This effectively removes the user from the bot's roster.
1248  
1249 =cut
1250  
1251 sub RmUser {
1252 0 ▶ my $self = shift;
Subroutine RmUser: not called CC=2 SCAR=17.9
Pod documented
1253 0 my $user = shift;
1254  
1255 0 ▶ if ( !$self->IsConnected ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->IsConnected) 0 0 0
1256 0 WARN("Cannot remove user '$user': not connected");
1257 0 return;
1258 }
1259  
1260 0 $self->jabber_client->Subscription( type => "unsubscribe", to => $user );
1261 0 $self->jabber_client->Subscription( type => "unsubscribed", to => $user );
1262 }
1263  
1264 =back
1265  
1266 =head1 AUTHOR
1267  
1268 Todd Rinaldo C<< <toddr@cpan.org> >>
1269  
1270 =head1 BUGS
1271  
1272 Please report any bugs or feature requests through the GitHub issue tracker at
1273 L<https://github.com/cpan-authors/perl-net-jabber-bot/issues>.
1274  
1275 =head1 SUPPORT
1276  
1277 You can find documentation for this module with the perldoc command.
1278  
1279 perldoc Net::Jabber::Bot
1280  
1281 You can also look for information at:
1282  
1283 =over 4
1284  
1285 =item * Metacpan
1286  
1287 L<https://metacpan.org/pod/Net::Jabber::Bot>
1288  
1289 =item * GitHub
1290  
1291 L<https://github.com/cpan-authors/perl-net-jabber-bot>
1292  
1293 =back
1294  
1295 =head1 ACKNOWLEDGEMENTS
1296  
1297 =head1 COPYRIGHT & LICENSE
1298  
1299 Copyright 2007 Todd E Rinaldo, all rights reserved.
1300  
1301 This program is free software; you can redistribute it and/or modify it
1302 under the same terms as Perl itself.
1303  
1304 =cut
1305  
1306 12 1; # End of Net::Jabber::Bot
↑ Summary