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

release-1.10release-1.7release-1.8release-1.9
Last change on this file since b56f2c3 was b56f2c3, checked in by Nelson Elhage <nelhage@mit.edu>, 15 years ago
Get the last message before setting the timeout.
  • Property mode set to 100644
File size: 8.9 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
24our $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
95if(!defined($twitter->verify_credentials())) {
96    fail("Invalid twitter credentials");
97}
98
99our $last_poll        = 0;
100our $last_direct_poll = 0;
101our $last_id          = undef;
102our $last_direct      = undef;
103
104unless(defined($last_id)) {
105    eval {
106        $last_id = $twitter->friends_timeline({count => 1})->[0]{id};
107    };
108    $last_id = 0 unless defined($last_id);
109}
110
111unless(defined($last_direct)) {
112    eval {
113        $last_direct = $twitter->direct_messages()->[0]{id};
114    };
115    $last_direct = 0 unless defined($last_direct);
116}
117
118eval {
119    $twitter->{ua}->timeout(1);
120};
121
122sub match {
123    my $val = shift;
124    my $pat = shift;
125    return $pat eq "*" || ($val eq $pat);
126}
127
128sub handle_message {
129    my $m = shift;
130    ($class, $instance, $opcode) = map{BarnOwl::getvar("twitter:$_")} qw(class instance opcode);
131    if($m->sender eq $user
132       && match($m->class, $class)
133       && match($m->instance, $instance)
134       && match($m->opcode, $opcode)
135       && $m->auth eq 'YES') {
136        twitter($m->body);
137    }
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) && ref($ratelimit) eq 'HASH') {
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        return;
152    }
153    if(exists($ratelimit->{remaining_hits})
154       && $ratelimit->{remaining_hits} <= 0) {
155        $last_direct_poll = $last_poll = $ratelimit->{reset_time_in_seconds};
156        die("Twitter: ratelimited until " . $ratelimit->{reset_time} . "\n");
157    } elsif(exists($ratelimit->{error})) {
158        die("Twitter: ". $ratelimit->{error} . "\n");
159        $last_direct_poll = $last_poll = time + 60*20;
160    }
161}
162
163sub poll_twitter {
164    return unless ( time - $last_poll ) >= 60;
165    $last_poll = time;
166    return unless BarnOwl::getvar('twitter:poll') eq 'on';
167
168    my $timeline = $twitter->friends_timeline( { since_id => $last_id } );
169    unless(defined($timeline) && ref($timeline) eq 'ARRAY') {
170        twitter_error();
171        return;
172    };
173    if ( scalar @$timeline ) {
174        for my $tweet ( reverse @$timeline ) {
175            if ( $tweet->{id} <= $last_id ) {
176                next;
177            }
178            my $msg = BarnOwl::Message->new(
179                type      => 'Twitter',
180                sender    => $tweet->{user}{screen_name},
181                recipient => $cfg->{user} || $user,
182                direction => 'in',
183                source    => decode_entities($tweet->{source}),
184                location  => decode_entities($tweet->{user}{location}||""),
185                body      => decode_entities($tweet->{text}),
186                status_id => $tweet->{id}
187               );
188            BarnOwl::queue_message($msg);
189        }
190        $last_id = $timeline->[0]{id};
191    } else {
192        # BarnOwl::message("No new tweets...");
193    }
194}
195
196sub poll_direct {
197    return unless ( time - $last_direct_poll) >= 120;
198    $last_direct_poll = time;
199    return unless BarnOwl::getvar('twitter:poll') eq 'on';
200
201    my $direct = $twitter->direct_messages( { since_id => $last_direct } );
202    unless(defined($direct) && ref($direct) eq 'ARRAY') {
203        twitter_error();
204        return;
205    };
206    if ( scalar @$direct ) {
207        for my $tweet ( reverse @$direct ) {
208            if ( $tweet->{id} <= $last_direct ) {
209                next;
210            }
211            my $msg = BarnOwl::Message->new(
212                type      => 'Twitter',
213                sender    => $tweet->{sender}{screen_name},
214                recipient => $cfg->{user} || $user,
215                direction => 'in',
216                location  => decode_entities($tweet->{sender}{location}||""),
217                body      => decode_entities($tweet->{text}),
218                isprivate => 'true'
219               );
220            BarnOwl::queue_message($msg);
221        }
222        $last_direct = $direct->[0]{id};
223    } else {
224        # BarnOwl::message("No new tweets...");
225    }
226}
227
228sub twitter {
229    my $msg = shift;
230    my $reply_to = shift;
231
232    if($msg =~ m{\Ad\s+([^\s])+(.*)}sm) {
233        twitter_direct($1, $2);
234    } elsif(defined $twitter) {
235        $twitter->update({
236            status => $msg,
237            defined($reply_to) ? (in_reply_to_status_id => $reply_to) : ()
238           });
239    }
240}
241
242sub twitter_direct {
243    my $who = shift;
244    my $msg = shift;
245    if(defined $twitter) {
246        $twitter->new_direct_message({
247            user => $who,
248            text => $msg
249           });
250        if(BarnOwl::getvar("displayoutgoing") eq 'on') {
251            my $tweet = BarnOwl::Message->new(
252                type      => 'Twitter',
253                sender    => $cfg->{user} || $user,
254                recipient => $who, 
255                direction => 'out',
256                body      => $msg,
257                isprivate => 'true'
258               );
259            BarnOwl::queue_message($tweet);
260        }
261    }
262}
263
264sub twitter_atreply {
265    my $to  = shift;
266    my $id  = shift;
267    my $msg = shift;
268    if(defined($id)) {
269        twitter("@".$to." ".$msg, $id);
270    } else {
271        twitter("@".$to." ".$msg);
272    }
273}
274
275BarnOwl::new_command(twitter => \&cmd_twitter, {
276    summary     => 'Update Twitter from BarnOwl',
277    usage       => 'twitter [message]',
278    description => 'Update Twitter. If MESSAGE is provided, use it as your status.'
279    . "\nOtherwise, prompt for a status message to use."
280   });
281
282BarnOwl::new_command('twitter-direct' => \&cmd_twitter_direct, {
283    summary     => 'Send a Twitter direct message',
284    usage       => 'twitter-direct USER',
285    description => 'Send a Twitter Direct Message to USER'
286   });
287
288BarnOwl::new_command( 'twitter-atreply' => sub { cmd_twitter_atreply(@_); },
289    {
290    summary     => 'Send a Twitter @ message',
291    usage       => 'twitter-atreply USER',
292    description => 'Send a Twitter @reply Message to USER'
293    }
294);
295
296
297sub cmd_twitter {
298    my $cmd = shift;
299    if(@_) {
300        my $status = join(" ", @_);
301        twitter($status);
302    } else {
303      BarnOwl::start_edit_win('What are you doing?', \&twitter);
304    }
305}
306
307sub cmd_twitter_direct {
308    my $cmd = shift;
309    my $user = shift;
310    die("Usage: $cmd USER\n") unless $user;
311    BarnOwl::start_edit_win("$cmd $user", sub{twitter_direct($user, shift)});
312}
313
314sub cmd_twitter_atreply {
315    my $cmd  = shift;
316    my $user = shift || die("Usage: $cmd USER [In-Reply-To ID]\n");
317    my $id   = shift;
318    BarnOwl::start_edit_win("Reply to \@" . $user, sub { twitter_atreply($user, $id, shift) });
319}
320
321eval {
322    $BarnOwl::Hooks::receiveMessage->add("BarnOwl::Module::Twitter::handle_message");
323    $BarnOwl::Hooks::mainLoop->add("BarnOwl::Module::Twitter::poll_messages");
324};
325if($@) {
326    $BarnOwl::Hooks::receiveMessage->add(\&handle_message);
327    $BarnOwl::Hooks::mainLoop->add(\&poll_messages);
328}
329
330BarnOwl::filter('twitter type ^twitter$');
331
3321;
Note: See TracBrowser for help on using the repository browser.