% Create Twitter object
t = twitter('ConsumerKey','ConsumerSecret','AccessToken','AccessTokenSecret');

% Search for last 100 MathWorks tweets
searchString = 'MathWorks';
s = search(t,searchString,'count',100);
statuses = s.Body.Data.statuses;
pause(2)

% Refresh latest tweets since previous request
sRefresh = search(t,searchString,'count',100,'since_id',s.Body.Data.search_metadata.max_id_str);
statuses = [statuses;sRefresh.Body.Data.statuses];

% Using max id from last request, get all available tweets
while isfield(s.Body.Data.search_metadata,'next_results')
  nextresults = string(s.Body.Data.search_metadata.next_results);
  max_id = char(extractBetween(nextresults,"max_id=","&"));
  s = search(t,searchString,'count',100,'max_id',max_id);
  statuses = [statuses;s.Body.Data.statuses];
end
  
% Parse tweets into timetable
if iscell(statuses)
  % Unstructured data
  numTweets = length(statuses);
  tweetTimes = cell(numTweets,1);
  tweetTexts = tweetTimes;
  for i = 1:numTweets
    tweetTimes{i} = statuses{i}.created_at;
    tweetTexts{i} = statuses{i}.text;
  end
else
  % Structured data
  tweetTimes = {statuses.created_at}';
  tweetTexts = {statuses.text}';
end
tweets = timetable(tweetTexts,'RowTimes',datetime(tweetTimes,'Format','eee MMM dd HH:mm:ss +SSSS yyyy'));

% Look for tweets with content defined by keywords
keywords = {'happy','great','good','fast','optimized','nice','interesting', ...
            'amazing','top','award','winner','wins','cool','thanks','useful'};

% Count number of hits
numTweets = height(tweets);

% Get number of positive tweets
numGoodTweets = 0;
for i = 1:numTweets
  dJobs = contains(tweets.tweetTexts{i},keywords,'IgnoreCase',true);
  if dJobs
    numGoodTweets = numGoodTweets + 1;
  end
end

% Retweets
numRTs = length(find(strncmp('RT @',tweets.tweetTexts,4)));

% Output table
matlabTweetTable = table(numTweets,numGoodTweets,numRTs,'VariableNames',{'Number_of_Tweets','Positive_Tweets','Retweets'});

% Post results to Twitter 
percentPosTweets = matlabTweetTable.Positive_Tweets / matlabTweetTable.Number_of_Tweets * 100;
percentReTweets = matlabTweetTable.Retweets / matlabTweetTable.Number_of_Tweets * 100;
tweetString = ['MathWorks - ' num2str(percentPosTweets) ' % positive tweets, ' num2str(percentReTweets) ' % retweets'];
d = postdata(t,'https://api.twitter.com/1.1/statuses/update.json','status',tweetString);

%   Copyright 2017 The MathWorks, Inc.