#Load installed packages
library(twitteR)
library(tm) 
## Loading required package: NLP
library(ggplot2) 
## 
## Attaching package: 'ggplot2'
## The following object is masked from 'package:NLP':
## 
##     annotate
library(stringr)
library(RColorBrewer)
library(syuzhet)
library(twitteR)
CONSUMER_SECRET <-"LtZOaw4W6wbaB6grqlmcaeZzBUX0GRLih3YGHskZoRHzvWSxdh"
CONSUMER_KEY <- "wuZ6OITxlU99FjjE2USFa4Zf8"
ACCESS_SECRET <- "09qXsDWA3AiFELPO2OXJGpCvsrdEiCgfxL47MijugXmu5"
ACCESS_TOKEN <- "1390086794901737474-H5hAlP06rhqyolbSQV1lhUEA0hZMXR"

setup_twitter_oauth(consumer_key = CONSUMER_KEY,
                    consumer_secret = CONSUMER_SECRET,
                    access_token = ACCESS_TOKEN,
                    access_secret = ACCESS_SECRET)
## [1] "Using direct authentication"
twitterUser <- getUser("vicegandako")
tweets <- searchTwitter("vicegandako", n = 5000, 
                        since = "2021-05-01", 
                        until ="2021-05-07", 
                        lang ="en",
                        retryOnRateLimit = 120)
## Warning in doRppAPICall("search/tweets", n, params = params, retryOnRateLimit =
## retryOnRateLimit, : 5000 tweets were requested but the API can only return 669
tweets.df = twListToDF(tweets) 
#extract timeline tweets 
extractTimelineTweets <- function(username,tweetCount){ 
  # timeline tweets 
  twitterUser <- getUser(username) 
  tweets = userTimeline(twitterUser,n=tweetCount) 
  tweets.df = twListToDF(tweets) 
issue.df$text <- sapply(tweets.df$text,function(x) iconv(enc2utf8(x), sub="byte")) 
  
  return(tweeets.df) 
}   
encodeSentiment <- function(x) { 
  if(x <= -0.5){ 
    "1) very negative" 
  }else if(x > -0.5 & x < 0){ 
    "2) negative" 
  }else if(x > 0 & x < 0.5){ 
    "4) positive" 
  }else if(x >= 0.5){ 
    "5) very positive" 
  }else { 
    "3) neutral" 
  } 
}  
#sentiment analysis 
tweetSentiments <- get_sentiment (tweets.df$text,method = "syuzhet") 
tweets <- cbind(tweets.df, tweetSentiments)  
#positive and negative sentiments 
tweets$sentiment <- sapply(tweets$tweetSentiments,encodeSentiment) 
head(tweets, n = 1)  
##                                                                                                                                               text
## 1 RT @CHIMANDATrends: We trended today! Thank you for joining us, Team CM, Team A &amp; Team C! Hopefully, maging guest rin sa It's Showtime Tago…
##   favorited favoriteCount replyToSN             created truncated replyToSID
## 1     FALSE             0      <NA> 2021-05-06 23:59:58     FALSE       <NA>
##                    id replyToUID
## 1 1390456334865166341       <NA>
##                                                                           statusSource
## 1 <a href="http://twitter.com/download/android" rel="nofollow">Twitter for Android</a>
##       screenName retweetCount isRetweet retweeted longitude latitude
## 1 VelascoJoannah           13      TRUE     FALSE        NA       NA
##   tweetSentiments        sentiment
## 1             1.1 5) very positive
qplot(tweets$tweetSentiments) + theme(legend.position="none")+ 
  xlab("Sentiment Score") + 
  ylab("Number of tweets") +  
  ggtitle("Tweets by Sentiment Score")   
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

# NRC Sample (various emotions such as anger, fear, joy, ...) 
tweetSentiments <- get_nrc_sentiment(tweets.df$text) 
head(tweetSentiments) 
##   anger anticipation disgust fear joy sadness surprise trust negative positive
## 1     0            0       0    0   0       0        0     1        0        0
## 2     0            0       0    0   0       0        0     2        0        3
## 3     0            0       0    0   0       0        0     2        0        3
## 4     0            0       0    0   0       0        0     0        0        0
## 5     0            0       0    0   0       0        0     0        0        0
## 6     1            1       0    0   0       0        1     1        0        0
tweets <- cbind(tweets.df, tweetSentiments) 
tweets[c(1:5),c(1, 17:26)]  
##                                                                                                                                               text
## 1 RT @CHIMANDATrends: We trended today! Thank you for joining us, Team CM, Team A &amp; Team C! Hopefully, maging guest rin sa It's Showtime Tago…
## 2     @vicegandako Hello hoomans! Looking for academic helper? Need to rest? Tinatamad? Check my service for a student-fr… https://t.co/LTg86sJlVN
## 3     @vicegandako Hello hoomans! Looking for academic helper? Need to rest? Tinatamad? Check my service for a student-fr… https://t.co/njV9u0RI6j
## 4                              RT @AprilJi79102256: ILoveYou Both \U0001f970💋😍\n@vicegandako / Ion Perez\n\n#MrAndMrsPerez https://t.co/JH3ithyHe1
## 5       😂😂😂🤣🤣🤣 \n@vicegandako @VhongX44 @anakarylle @prinsesachinita @ryanbang @jugsjugsjugs @teddspotting @itsShowtimeNa… https://t.co/331wk0ZgOP
##   anger anticipation disgust fear joy sadness surprise trust negative positive
## 1     0            0       0    0   0       0        0     1        0        0
## 2     0            0       0    0   0       0        0     2        0        3
## 3     0            0       0    0   0       0        0     2        0        3
## 4     0            0       0    0   0       0        0     0        0        0
## 5     0            0       0    0   0       0        0     0        0        0
sentimentTotals <- data.frame(colSums(tweets[,c(17:26)]))  
names(sentimentTotals) <- "count" 
sentimentTotals <- cbind("sentiment" = rownames(sentimentTotals), sentimentTotals) 
rownames(sentimentTotals) <- NULL 
sentimentTotals  
##       sentiment count
## 1         anger    77
## 2  anticipation   159
## 3       disgust    43
## 4          fear    74
## 5           joy   392
## 6       sadness    53
## 7      surprise    58
## 8         trust   233
## 9      negative   174
## 10     positive   483
ggplot(data = sentimentTotals, aes(x = sentiment, y = count)) + 
  geom_bar(aes(fill = sentiment), stat = "identity") + 
  theme(legend.position = "none") + 
  xlab("Sentiment") + ylab("Total Count") + ggtitle("Total Sentiment Score for All Tweets")