Created
July 25, 2017 15:42
-
-
Save jacoby/74dd305b0d91a47ab3d928562655d033 to your computer and use it in GitHub Desktop.
Tool I'm creating that uses sentiment analysis to only send positive tweets, because it only sends the tweet if SA >= 0.5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use feature qw{ postderef say signatures } ; | |
use strict ; | |
use warnings ; | |
use utf8 ; | |
no warnings qw{ experimental::postderef experimental::signatures } ; | |
use Carp ; | |
use Data::Dumper ; | |
use Getopt::Long ; | |
use IO::Interactive qw{ interactive } ; | |
use LWP::UserAgent ; | |
use JSON ; | |
use YAML qw{ LoadFile } ; | |
my $options = options() ; | |
my $config = config() ; | |
if ( check_status( $options->{ status }, $config ) >= 0.5 ) { | |
send_tweet( $options, $config ) ; | |
} | |
exit ; | |
sub send_tweet ( $options, $config ) { | |
say '' ; | |
} | |
sub check_status ( $status, $config ) { | |
my $j = JSON->new->canonical->pretty ; | |
my $key = $config->{ microsoft }{ text_analytics }{ key } ; | |
my $id = 'tweet_' . time ; | |
my $object ; | |
push @{ $object->{ documents } }, | |
{ | |
language => 'EN', | |
text => $status, | |
id => $id, | |
} ; | |
my $json = $j->encode( $object ) ; | |
my $api = 'https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment' ; | |
my $agent = LWP::UserAgent->new ; | |
my $request = HTTP::Request->new( POST => $api ) ; | |
$request->header( 'Ocp-Apim-Subscription-Key' => $key ) ; | |
$request->content( $json ) ; | |
my $response = $agent->request( $request ) ; | |
if ( $response->is_success ) { | |
my $out = decode_json $response->content ; | |
my $doc = $out->{ documents }[ 0 ] ; | |
return $doc->{ score } ; | |
} | |
else { | |
croak( $response->status_line ) ; | |
} | |
return 1 ; | |
} | |
sub config () { | |
my $config ; | |
$config->{ twitter } = LoadFile( join '/', $ENV{ HOME }, '.twitter.cnf' ) ; | |
$config->{ microsoft } = LoadFile( join '/', $ENV{ HOME }, '.microsoft.yml' ) ; | |
return $config ; | |
} | |
sub options () { | |
my $options ; | |
GetOptions( | |
'help' => \$options->{ help }, | |
'username=s' => \$options->{ username }, | |
'status=s' => \$options->{ status }, | |
) ; | |
show_usage( $options ) ; | |
return $options ; | |
} | |
sub show_usage ($options) { | |
if ( $options->{ help } | |
|| !$options->{ username } | |
|| !$options->{ status } ) { | |
say { interactive } <<'HELP'; | |
Only Positive Tweets -- Does text analysis of content before tweeting | |
-u user Twitter screen name (required) | |
-s status Status to be tweeted (required) | |
-h help This screen | |
HELP | |
exit ; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment