Thomas Unkles1
Giga Contributor

In the age of social media it's important to access Twitter from ServiceNow. Here is a handy library to help you.

var socialTracker = Class.create();
socialTracker.prototype = {
	
	initialize: function() {
	},

	searchTwitter: function (searchFor){
		var searchResults = this.queryTwitter('https://api.twitter.com/2/tweets/search/recent?','query=entity:'+searchFor+'&tweet.fields=author_id');
		
		for (var eachTweet in searchResults.data) {	
			var searchNames = this.queryTwitter('https://api.twitter.com/2/users/', searchResults.data[eachTweet].author_id);
			
			gs.log("Name: " + searchNames.data.name);
			gs.log("Username: " + searchNames.data.username);
			gs.log("Tweeted: " + searchResults.data[eachTweet].text);
		}
	},

	queryTwitter: function (endPoint,Parameters) {
		
		var token = 'GET YOUR OWN TOKEN';
		var request = new sn_ws.RESTMessageV2();
		request.setHttpMethod('GET');
		request.setRequestHeader("authorization",'Bearer '+ token);
		request.setEndpoint(endPoint + Parameters);
		var response = request.execute();
		var responseBody = JSON.parse(response.getBody());
		return responseBody;
	},
	type: 'socialTracker'
};

To get this to work, you'll have to activate an account with Twitter developer and insert a valid authentication token into the code above.

This code will search for a term and list the most recent tweets relating to the term.

To run enter the following code into a background script.

var getTwitter = new socialTracker().searchTwitter("Mars");

find_real_file.png

Version history
Last update:
‎02-18-2021 11:01 PM
Updated by: