source: lib/BarnOwl/Module/Twitter.pm @ cdb546f

release-1.10release-1.7release-1.8release-1.9
Last change on this file since cdb546f was 706ff88, checked in by Nelson Elhage <nelhage@mit.edu>, 15 years ago
Make Twitter.pm deal better if you've never received a tweet. If you had never received a tweet (or, more likely, a direct message), we were spew "unitialized" warnings every second until you got one.
  • Property mode set to 100644
File size: 8.3 KB
Line 
1use warnings;
2use strict;
3
4=head1 NAME
5
6BarnOwl::Module::Twitter
7
8=head1 DESCRIPTION
9
10Post outgoing zephyrs from -c $USER -i status -O TWITTER to Twitter
11
12=cut
13
14package BarnOwl::Module::Twitter;
15
16use Net::Twitter;
17use JSON;
18
19use BarnOwl;
20use BarnOwl::Hooks;
21use BarnOwl::Message::Twitter;
22use HTML::Entities;
23
24my $twitter;
25my $user     = BarnOwl::zephyr_getsender();
26my ($class)  = ($user =~ /(^[^@]+)/);
27my $instance = "status";
28my $opcode   = "twitter";
29
30sub fail {
31    my $msg = shift;
32    undef $twitter;
33    BarnOwl::admin_message('Twitter Error', $msg);
34    die("Twitter Error: $msg\n");
35}
36
37my $desc = <<'END_DESC';
38BarnOwl::Module::Twitter will watch for authentic zephyrs to
39-c $twitter:class -i $twitter:instance -O $twitter:opcode
40from your sender and mirror them to Twitter.
41
42A value of '*' in any of these fields acts a wildcard, accepting
43messages with any value of that field.
44END_DESC
45BarnOwl::new_variable_string(
46    'twitter:class',
47    {
48        default     => $class,
49        summary     => 'Class to watch for Twitter messages',
50        description => $desc
51    }
52);
53BarnOwl::new_variable_string(
54    'twitter:instance',
55    {
56        default => $instance,
57        summary => 'Instance on twitter:class to watch for Twitter messages.',
58        description => $desc
59    }
60);
61BarnOwl::new_variable_string(
62    'twitter:opcode',
63    {
64        default => $opcode,
65        summary => 'Opcode for zephyrs that will be sent as twitter updates',
66        description => $desc
67    }
68);
69
70BarnOwl::new_variable_bool(
71    'twitter:poll',
72    {
73        default => 1,
74        summary => 'Poll Twitter for incoming messages',
75        description => "If set, will poll Twitter every minute for normal updates,\n"
76        . 'and every two minutes for direct message'
77     }
78 );
79
80my $conffile = BarnOwl::get_config_dir() . "/twitter";
81open(my $fh, "<", "$conffile") || fail("Unable to read $conffile");
82my $cfg = do {local $/; <$fh>};
83close($fh);
84eval {
85    $cfg = from_json($cfg);
86};
87if($@) {
88    fail("Unable to parse ~/.owl/twitter: $@");
89}
90
91$twitter  = Net::Twitter->new(username   => $cfg->{user} || $user,
92                              password   => $cfg->{password},
93                              source => 'barnowl');
94
95eval {
96    $twitter->{ua}->timeout(1);
97};
98
99if(!defined($twitter->verify_credentials())) {
100    fail("Invalid twitter credentials");
101}
102
103sub match {
104    my $val = shift;
105    my $pat = shift;
106    return $pat eq "*" || ($val eq $pat);
107}
108
109sub handle_message {
110    my $m = shift;
111    ($class, $instance, $opcode) = map{BarnOwl::getvar("twitter:$_")} qw(class instance opcode);
112    if($m->sender eq $user
113       && match($m->class, $class)
114       && match($m->instance, $instance)
115       && match($m->opcode, $opcode)
116       && $m->auth eq 'YES') {
117        twitter($m->body);
118    }
119}
120
121our $last_poll        = 0;
122our $last_direct_poll = 0;
123our $last_id          = undef;
124our $last_direct      = undef;
125
126unless(defined($last_id)) {
127    eval {
128        $last_id = $twitter->friends_timeline({count => 1})->[0]{id};
129    };
130    $last_id = 0 unless defined($last_id);
131}
132
133unless(defined($last_direct)) {
134    eval {
135        $last_direct = $twitter->direct_messages()->[0]{id};
136    };
137    $last_direct = 0 unless defined($last_direct);
138}
139
140sub poll_messages {
141    poll_twitter();
142    poll_direct();
143}
144
145sub twitter_error {
146    my $ratelimit = $twitter->rate_limit_status;
147    unless(defined($ratelimit)) {
148        # Twitter's just sucking, sleep for 5 minutes
149        $last_direct_poll = $last_poll = time + 60*5;
150        die("Twitter seems to be having problems.\n");
151    }
152    if($ratelimit->{remaining_hits} <= 0) {
153        $last_direct_poll = $last_poll = $ratelimit->{reset_time_in_seconds};
154        die("Twitter: ratelimited until " . $ratelimit->{reset_time} . "\n");
155    }
156}
157
158sub poll_twitter {
159    return unless ( time - $last_poll ) >= 60;
160    $last_poll = time;
161    return unless BarnOwl::getvar('twitter:poll') eq 'on';
162
163    my $timeline = $twitter->friends_timeline( { since_id => $last_id } );
164    unless(defined($timeline)) {
165        twitter_error();
166        return;
167    };
168    if ( scalar @$timeline ) {
169        for my $tweet ( reverse @$timeline ) {
170            if ( $tweet->{id} <= $last_id ) {
171                next;
172            }
173            my $msg = BarnOwl::Message->new(
174                type      => 'Twitter',
175                sender    => $tweet->{user}{screen_name},
176                recipient => $cfg->{user} || $user,
177                direction => 'in',
178                source    => decode_entities($tweet->{source}),
179                location  => decode_entities($tweet->{user}{location}||""),
180                body      => decode_entities($tweet->{text})
181               );
182            BarnOwl::queue_message($msg);
183        }
184        $last_id = $timeline->[0]{id};
185    } else {
186        # BarnOwl::message("No new tweets...");
187    }
188}
189
190sub poll_direct {
191    return unless ( time - $last_direct_poll) >= 120;
192    $last_direct_poll = time;
193    return unless BarnOwl::getvar('twitter:poll') eq 'on';
194
195    my $direct = $twitter->direct_messages( { since_id => $last_direct } );
196    unless(defined($direct)) {
197        twitter_error();
198        return;
199    };
200    if ( scalar @$direct ) {
201        for my $tweet ( reverse @$direct ) {
202            if ( $tweet->{id} <= $last_direct ) {
203                next;
204            }
205            my $msg = BarnOwl::Message->new(
206                type      => 'Twitter',
207                sender    => $tweet->{sender}{screen_name},
208                recipient => $cfg->{user} || $user,
209                direction => 'in',
210                location  => decode_entities($tweet->{sender}{location}||""),
211                body      => decode_entities($tweet->{text}),
212                isprivate => 'true'
213               );
214            BarnOwl::queue_message($msg);
215        }
216        $last_direct = $direct->[0]{id};
217    } else {
218        # BarnOwl::message("No new tweets...");
219    }
220}
221
222sub twitter {
223    my $msg = shift;
224    if($msg =~ m{\Ad\s+([^\s])+(.*)}sm) {
225        twitter_direct($1, $2);
226    } elsif(defined $twitter) {
227        $twitter->update($msg);
228    }
229}
230
231sub twitter_direct {
232    my $who = shift;
233    my $msg = shift;
234    if(defined $twitter) {
235        $twitter->new_direct_message({
236            user => $who,
237            text => $msg
238           });
239        if(BarnOwl::getvar("displayoutgoing") eq 'on') {
240            my $tweet = BarnOwl::Message->new(
241                type      => 'Twitter',
242                sender    => $cfg->{user} || $user,
243                recipient => $who, 
244                direction => 'out',
245                body      => $msg,
246                isprivate => 'true'
247               );
248            BarnOwl::queue_message($tweet);
249        }
250    }
251}
252
253sub twitter_atreply {
254    my $to  = shift;
255    my $msg = shift;
256    twitter("@".$to." ".$msg);
257}
258
259BarnOwl::new_command(twitter => \&cmd_twitter, {
260    summary     => 'Update Twitter from BarnOwl',
261    usage       => 'twitter [message]',
262    description => 'Update Twitter. If MESSAGE is provided, use it as your status.'
263    . "\nOtherwise, prompt for a status message to use."
264   });
265
266BarnOwl::new_command('twitter-direct' => \&cmd_twitter_direct, {
267    summary     => 'Send a Twitter direct message',
268    usage       => 'twitter-direct USER',
269    description => 'Send a Twitter Direct Message to USER'
270   });
271
272BarnOwl::new_command( 'twitter-atreply' => sub { cmd_twitter_atreply(@_); },
273    {
274    summary     => 'Send a Twitter @ message',
275    usage       => 'twitter-atreply USER',
276    description => 'Send a Twitter @reply Message to USER'
277    }
278);
279
280
281sub cmd_twitter {
282    my $cmd = shift;
283    if(@_) {
284        my $status = join(" ", @_);
285        twitter($status);
286    } else {
287      BarnOwl::start_edit_win('What are you doing?', \&twitter);
288    }
289}
290
291sub cmd_twitter_direct {
292    my $cmd = shift;
293    my $user = shift;
294    die("Usage: $cmd USER\n") unless $user;
295    BarnOwl::start_edit_win("$cmd $user", sub{twitter_direct($user, shift)});
296}
297
298sub cmd_twitter_atreply {
299    my $cmd  = shift;
300    my $user = shift;
301    BarnOwl::start_edit_win("Reply to \@" . $user, sub { twitter_atreply($user, shift) });
302}
303
304eval {
305    $BarnOwl::Hooks::receiveMessage->add("BarnOwl::Module::Twitter::handle_message");
306    $BarnOwl::Hooks::mainLoop->add("BarnOwl::Module::Twitter::poll_messages");
307};
308if($@) {
309    $BarnOwl::Hooks::receiveMessage->add(\&handle_message);
310    $BarnOwl::Hooks::mainLoop->add(\&poll_messages);
311}
312
313BarnOwl::filter('twitter type ^twitter$');
314
3151;
Note: See TracBrowser for help on using the repository browser.