Twitter (OAuth2.0)
Stay organized with collections
Save and categorize content based on your preferences.
Retrieve trends for a given location
/**
* Example of using Twitter Application-only authentication from Google Ads Scripts
* Application-only authentication is used where the aspects of the API being
* used do not require impersonating a given Twitter user.
*
* Example usage:
* initializeOAuthClient();
* // Get trends using a woeId to specify location. See:
* // https://developer.yahoo.com/geo/geoplanet/guide/concepts.html
* const results = getTrendsForLocation(44418);
*
* See https://developers.google.com/google-ads/scripts/docs/features/third-party-apis#client_credentials_grant
* for details on configuring this script.
*
* NOTE: This script also requires the OAuth2 library to be pasted at the end,
* as obtained from https://developers.google.com/google-ads/scripts/docs/examples/oauth20-library
*/
// Consumer Key for your application set up at https://apps.twitter.com. See
// 'Keys and Access Tokens' for generating your consumer key.
const
TWITTER_CONSUMER_KEY
=
'
INSERT_CONSUMER_KEY_HERE
'
;
const
TWITTER_CONSUMER_SECRET
=
'
INSERT_CONSUMER_SECRET_HERE
'
;
let
authUrlFetch
;
// Call this function just once, to initialize the OAuth client.
function
initializeOAuthClient
()
{
if
(
typeof
OAuth2
==
=
'
undefined
'
)
{
const
libUrl
=
'
https
:
//developers.google.com/google-ads/scripts/docs/examples/oauth20-library';
throw
Error
(
'
OAuth2
library
not
found
.
Please
take
a
copy
of
the
OAuth2
'
+
'
library
from
'
+
libUrl
+
'
and
append
to
the
bottom
of
this
script
.
'
);
}
const
tokenUrl
=
'
https
:
//api.twitter.com/oauth2/token';
authUrlFetch
=
OAuth2
.
withClientCredentials
(
tokenUrl
,
TWITTER_CONSUMER_KEY
,
TWITTER_CONSUMER_SECRET
);
}
/**
* Retrieves a list of trending topics for a given geographic area of interest.
* @param {string} woeId Geographic location specified in Yahoo! Where On Earth
* format. See https://developer.yahoo.com/geo/geoplanet/guide/concepts.html
* @return {Object} The Trends results object, see:
* https://dev.twitter.com/rest/reference/get/trends/place for details.
*/
function
getTrendsForLocation
(
woeId
)
{
const
url
=
`
https
:
//api.twitter.com/1.1/trends/place.json?id=${woeId}`;
const
response
=
authUrlFetch
.
fetch
(
url
);
return
JSON
.
parse
(
response
.
getContentText
());
}
// Paste in OAuth2 library here, from:
// https://developers.google.com/google-ads/scripts/docs/examples/oauth20-library
/**
* Example of using Twitter Application-only authentication from Google Ads Scripts
* Application-only authentication is used where the aspects of the API being
* used do not require impersonating a given Twitter user.
*
* Example usage:
* initializeOAuthClient();
* const results = getTweetsForSearch('Olympics 2016');
* const localResults = getTweetsForSearch('Euro 2016', '51.5085300,-0.1257400,10mi');
*
* See https://developers.google.com/google-ads/scripts/docs/features/third-party-apis#client_credentials_grant
* for details on configuring this script.
*
* NOTE: This script also requires the OAuth2 library to be pasted at the end,
* as obtained from https://developers.google.com/google-ads/scripts/docs/examples/oauth20-library
*/
// Consumer Key for your application set up at https://apps.twitter.com. See
// 'Keys and Access Tokens' for generating your consumer key.
const
TWITTER_CONSUMER_KEY
=
'
INSERT_CONSUMER_KEY_HERE
'
;
const
TWITTER_CONSUMER_SECRET
=
'
INSERT_CONSUMER_SECRET_HERE
'
;
let
authUrlFetch
;
// Call this function just once, to initialize the OAuth client.
function
initializeOAuthClient
()
{
if
(
typeof
OAuth2
==
=
'
undefined
'
)
{
const
libUrl
=
'
https
:
//developers.google.com/google-ads/scripts/docs/examples/oauth20-library';
throw
Error
(
'
OAuth2
library
not
found
.
Please
take
a
copy
of
the
OAuth2
'
+
'
library
from
'
+
libUrl
+
'
and
append
to
the
bottom
of
this
script
.
'
);
}
const
tokenUrl
=
'
https
:
//api.twitter.com/oauth2/token';
authUrlFetch
=
OAuth2
.
withClientCredentials
(
tokenUrl
,
TWITTER_CONSUMER_KEY
,
TWITTER_CONSUMER_SECRET
);
}
/**
* Retrieves Tweets for a specific search term.
* @param {string} searchTerm The search term to look for.
* @param {string=} opt_geocode Limit returned Tweets to those from users in a
* location. Specified in the form "latitude,longitude,radius", where radius
* is in either "km" or "mi". e.g. 37.781157,-122.398720,1mi
* @param {string=} opt_mode Optional preference for recent, popular or mixed
* results. Defaults to 'mixed', other options are 'recent' and 'popular'.
* @return {Object} The statuses results object, see:
* https://dev.twitter.com/rest/reference/get/search/tweets for details.
*/
function
getTweetsForSearch
(
searchTerm
,
opt_geocode
,
opt_mode
)
{
const
mode
=
opt_mode
||
'
mixed
'
;
const
url
=
'
https
:
//api.twitter.com/1.1/search/tweets.json?q=' +
encodeURIComponent
(
searchTerm
)
+
'
& result_type
=
'
+
mode
;
if
(
opt_geocode
)
{
url
+=
'
geocode
=
'
+
opt_geocode
;
}
const
response
=
authUrlFetch
.
fetch
(
url
);
return
JSON
.
parse
(
response
.
getContentText
());
}
// Paste in OAuth2 library here, from:
// https://developers.google.com/google-ads/scripts/docs/examples/oauth20-library
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License
, and code samples are licensed under the Apache 2.0 License
. For details, see the Google Developers Site Policies
. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-08-20 UTC.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-20 UTC."],[[["\u003cp\u003eThese Google Ads scripts demonstrate how to use Twitter's Application-only authentication to retrieve data without impersonating a specific user.\u003c/p\u003e\n"],["\u003cp\u003eThe provided examples show how to retrieve trending topics for a given location using a WOEID and search for tweets based on a search term, optionally filtering by location and result type.\u003c/p\u003e\n"],["\u003cp\u003eBefore using these scripts, you need to set up a Twitter application and insert your consumer key and secret into the script, as well as include the OAuth2 library.\u003c/p\u003e\n"]]],[],null,["# Twitter (OAuth2.0)\n\nRetrieve trends for a given location\n------------------------------------\n\n```carbon\n/**\n * Example of using Twitter Application-only authentication from Google Ads Scripts\n * Application-only authentication is used where the aspects of the API being\n * used do not require impersonating a given Twitter user.\n *\n * Example usage:\n * initializeOAuthClient();\n * // Get trends using a woeId to specify location. See:\n * // https://developer.yahoo.com/geo/geoplanet/guide/concepts.html\n * const results = getTrendsForLocation(44418);\n *\n * See https://developers.google.com/google-ads/scripts/docs/features/third-party-apis#client_credentials_grant\n * for details on configuring this script.\n *\n * NOTE: This script also requires the OAuth2 library to be pasted at the end,\n * as obtained from https://developers.google.com/google-ads/scripts/docs/examples/oauth20-library\n */\n// Consumer Key for your application set up at https://apps.twitter.com. See\n// 'Keys and Access Tokens' for generating your consumer key.\nconst TWITTER_CONSUMER_KEY = 'INSERT_CONSUMER_KEY_HERE';\nconst TWITTER_CONSUMER_SECRET = 'INSERT_CONSUMER_SECRET_HERE';\n\nlet authUrlFetch;\n\n// Call this function just once, to initialize the OAuth client.\nfunction initializeOAuthClient() {\n if (typeof OAuth2 === 'undefined') {\n const libUrl = 'https://developers.google.com/google-ads/scripts/docs/examples/oauth20-library';\n throw Error('OAuth2 library not found. Please take a copy of the OAuth2 ' +\n 'library from ' + libUrl + ' and append to the bottom of this script.');\n }\n const tokenUrl = 'https://api.twitter.com/oauth2/token';\n authUrlFetch = OAuth2.withClientCredentials(\n tokenUrl, TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET);\n}\n\n/**\n * Retrieves a list of trending topics for a given geographic area of interest.\n * @param {string} woeId Geographic location specified in Yahoo! Where On Earth\n * format. See https://developer.yahoo.com/geo/geoplanet/guide/concepts.html\n * @return {Object} The Trends results object, see:\n * https://dev.twitter.com/rest/reference/get/trends/place for details.\n */\nfunction getTrendsForLocation(woeId) {\n const url = `https://api.twitter.com/1.1/trends/place.json?id=${woeId}`;\n const response = authUrlFetch.fetch(url);\n return JSON.parse(response.getContentText());\n}\n\n// Paste in OAuth2 library here, from:\n// https://developers.google.com/google-ads/scripts/docs/examples/oauth20-library\n```\n\nRetrieve tweets for a given search query\n----------------------------------------\n\n```carbon\n/**\n * Example of using Twitter Application-only authentication from Google Ads Scripts\n * Application-only authentication is used where the aspects of the API being\n * used do not require impersonating a given Twitter user.\n *\n * Example usage:\n * initializeOAuthClient();\n * const results = getTweetsForSearch('Olympics 2016');\n * const localResults = getTweetsForSearch('Euro 2016', '51.5085300,-0.1257400,10mi');\n *\n * See https://developers.google.com/google-ads/scripts/docs/features/third-party-apis#client_credentials_grant\n * for details on configuring this script.\n *\n * NOTE: This script also requires the OAuth2 library to be pasted at the end,\n * as obtained from https://developers.google.com/google-ads/scripts/docs/examples/oauth20-library\n */\n// Consumer Key for your application set up at https://apps.twitter.com. See\n// 'Keys and Access Tokens' for generating your consumer key.\nconst TWITTER_CONSUMER_KEY = 'INSERT_CONSUMER_KEY_HERE';\nconst TWITTER_CONSUMER_SECRET = 'INSERT_CONSUMER_SECRET_HERE';\n\nlet authUrlFetch;\n\n// Call this function just once, to initialize the OAuth client.\nfunction initializeOAuthClient() {\n if (typeof OAuth2 === 'undefined') {\n const libUrl = 'https://developers.google.com/google-ads/scripts/docs/examples/oauth20-library';\n throw Error('OAuth2 library not found. Please take a copy of the OAuth2 ' +\n 'library from ' + libUrl + ' and append to the bottom of this script.');\n }\n const tokenUrl = 'https://api.twitter.com/oauth2/token';\n authUrlFetch = OAuth2.withClientCredentials(\n tokenUrl, TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET);\n}\n\n/**\n * Retrieves Tweets for a specific search term.\n * @param {string} searchTerm The search term to look for.\n * @param {string=} opt_geocode Limit returned Tweets to those from users in a\n * location. Specified in the form \"latitude,longitude,radius\", where radius\n * is in either \"km\" or \"mi\". e.g. 37.781157,-122.398720,1mi\n * @param {string=} opt_mode Optional preference for recent, popular or mixed\n * results. Defaults to 'mixed', other options are 'recent' and 'popular'.\n * @return {Object} The statuses results object, see:\n * https://dev.twitter.com/rest/reference/get/search/tweets for details.\n */\nfunction getTweetsForSearch(searchTerm, opt_geocode, opt_mode) {\n const mode = opt_mode || 'mixed';\n const url = 'https://api.twitter.com/1.1/search/tweets.json?q=' +\n encodeURIComponent(searchTerm) + '&result_type=' + mode;\n if (opt_geocode) {\n url += 'geocode=' + opt_geocode;\n }\n const response = authUrlFetch.fetch(url);\n return JSON.parse(response.getContentText());\n}\n\n// Paste in OAuth2 library here, from:\n// https://developers.google.com/google-ads/scripts/docs/examples/oauth20-library\n```"]]