Last active
December 27, 2022 14:15
-
-
Save TylerLeonhardt/96bba0c9647ba4b934f1904916ead7d2 to your computer and use it in GitHub Desktop.
Search Twitter
This file contains hidden or 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
<# | |
.SYNOPSIS | |
Creates access token for Twitter API calls. To get keys go to: https://apps.twitter.com/ | |
.DESCRIPTION | |
Creates access token for Twitter API calls. To get keys go to: https://apps.twitter.com/ | |
.PARAMETER ConsumerKey | |
The ConsumerKey. You get this from https://apps.twitter.com/ | |
.PARAMETER ConsumerSecret | |
The ConsumerSecret. You get this from https://apps.twitter.com/ | |
.EXAMPLE | |
Set-TweetScriptKeys -ConsumerKey <your key> -ConsumerSecret <your key> | |
#> | |
function Set-TwitterKeys { | |
[CmdletBinding()] | |
param( | |
[Parameter(Mandatory=$true)] | |
[string] | |
$ConsumerKey, | |
[Parameter(Mandatory=$true)] | |
[string] | |
$ConsumerSecret | |
) | |
$Bytes = [System.Text.Encoding]::Default.GetBytes("$($ConsumerKey):$($ConsumerSecret)") | |
$EncodedText =[Convert]::ToBase64String($Bytes) | |
$EncodedText | |
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" | |
$headers.Add("Authorization", "Basic $EncodedText") | |
$global:AccessToken = (Invoke-RestMethod https://api.twitter.com/oauth2/token?grant_type=client_credentials -Method POST -Headers $headers).access_token | |
} | |
<# | |
.SYNOPSIS | |
Gets the last 15 tweets that contain the given query. | |
.DESCRIPTION | |
Gets the last 15 tweets that contain the given query. | |
.PARAMETER Query | |
The query you'd like to search for. | |
.EXAMPLE | |
Get-TwitterTweet -Query '#powershell' | |
#> | |
function Get-TwitterTweet { | |
[CmdletBinding()] | |
param( | |
[Parameter(Mandatory = $true)] | |
[string] | |
$Query | |
) | |
$Query = [System.Web.HttpUtility]::UrlEncode($Query) | |
if ($AccessToken -eq $null -or $AccessToken -eq "") { | |
Write-Host "Missing Access token. Please use Set-TweetScriptKeys. To get keys go to: https://apps.twitter.com/" | |
return | |
} | |
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" | |
$headers.Add("Authorization", "Bearer $AccessToken") | |
return (Invoke-RestMethod "https://api.twitter.com/1.1/search/tweets.json?q=$Query" -Headers $headers).statuses | |
} | |
# Usage | |
# Set your keys | |
Set-TwitterKeys -ConsumerKey <consumer key> -ConsumerSecret <consumer secret> | |
# Get the last 15 tweets for a given query | |
$tweets = Get-TwitterTweet -Query '#powershell' | |
# Get a single tweet object | |
$tweets[0] | |
# Get the text of all the tweets | |
$tweets.text |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment