Skip to content

Instantly share code, notes, and snippets.

@jacoby
Created February 27, 2012 14:27
Show Gist options
  • Save jacoby/1924186 to your computer and use it in GitHub Desktop.
Save jacoby/1924186 to your computer and use it in GitHub Desktop.
#!/usr/bin/perl
# READING DIRECT MESSAGES
use 5.010 ;
use strict ;
use Carp ;
use Data::Dumper ;
use Getopt::Long ;
use IO::Interactive qw{ interactive } ;
use Net::Twitter ;
use WWW::Shorten 'TinyURL' ;
use YAML qw{ DumpFile LoadFile } ;
# next step, add Getopt::Long into the mix
my $config_file = $ENV{ HOME } . '/.twitter_dm.cnf' ;
my $config = LoadFile( $config_file ) ;
my $param ;
GetOptions(
'user=s' => \$param->{ user } ,
) ;
if ( ! $param->{ user } ) {
say 'Need a user' ;
exit 40 ;
}
# GET key and secret from http://twitter.com/apps
my $twit = Net::Twitter->new(
traits => [ 'API::REST', 'OAuth' ],
consumer_key => $config->{ consumer_key },
consumer_secret => $config->{ consumer_secret },
) ;
# You'll save the token and secret in cookie, config file or session database
my ( $access_token, $access_token_secret ) ;
( $access_token, $access_token_secret ) = restore_tokens( $param->{ user } ) ;
if ( $access_token && $access_token_secret ) {
$twit->access_token( $access_token ) ;
$twit->access_token_secret( $access_token_secret ) ;
}
unless ( $twit->authorized ) {
# You have no auth token
# go to the auth website.
# they'll ask you if you wanna do this, then give you a PIN
# input it here and it'll register you.
# then save your token vals.
say "Authorize this app at ", $twit->get_authorization_url,
' and enter the PIN#' ;
my $pin = <STDIN> ; # wait for input
chomp $pin ;
my ( $access_token, $access_token_secret, $user_id, $screen_name ) =
$twit->request_access_token( verifier => $pin ) ;
save_tokens( $param->{ user }, $access_token, $access_token_secret ) ;
}
my $direct_messages = $twit->direct_messages( ) ;
for my $message ( @$direct_messages ) {
my $id = $message->{ id_str } ;
my $text = $message->{ text } ;
my $sender = $message->{ sender }->{ screen_name } ;
say "Sender\t" . $sender ;
say "ID\t" . $id ;
say "\t" . $text ;
say '' ;
#### 1) Check ID against DB
#### 2) if good ID, put it into DB
}
exit ;
#========= ========= ========= ========= ========= ========= =========
sub restore_tokens {
my ( $user ) = @_ ;
my ( $access_token, $access_token_secret ) ;
if ( $config->{ tokens }{ $user } ) {
$access_token = $config->{ tokens }{ $user }{ access_token } ;
$access_token_secret =
$config->{ tokens }{ $user }{ access_token_secret } ;
}
return $access_token, $access_token_secret ;
}
sub save_tokens {
my ( $user, $access_token, $access_token_secret ) = @_ ;
$config->{ tokens }{ $user }{ access_token } = $access_token ;
$config->{ tokens }{ $user }{ access_token_secret } = $access_token_secret ;
DumpFile( $config_file, $config ) ;
return 1 ;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment