powershell - 如何使用 Powershell 连接到 Twitter API 并遵循参数

标签 powershell azure twitter azure-hdinsight

我使用 Microsoft Azure Powershell 连接到 Twitter API 时收到以下错误:

使用“0”个参数调用“GetResponse”时出现异常:远程服务器返回错误:<401> 未经授权。” 行:1 字符:1 + $response = $request.GetResponse() ; + 类别信息:未指定:(:) [],MethodInitationException + FullQualifiedErrorId:WebException

背景是我从 HDInsight 开始,并按照 http://azure.microsoft.com/en-gb/documentation/articles/hdinsight-analyze-twitter-data/ 中的示例进行操作。这有效。

我现在正在重做第一步(连接到 Twitter API)并尝试使用 api 的不同字段(我使用的是“follow”而不是“track”),但脚本出错了。

我在 Powershell 中运行的脚本如下:

Write-Host "Set variables ..." -ForegroundColor Green
$storageAccountName = "mystorageaccountname"
$containerName = "containername"

$destBlobName = "tutorials/twitter/data/tweets.txt"

$followString = "1920771606"
$follow = [System.Uri]::EscapeDataString($followString);
$lineMax = 10  #about 3 minutes every 100 lines

$oauth_consumer_key = "mykey";
$oauth_consumer_secret = "mysecret";
$oauth_token = "myoauthtoken";
$oauth_token_secret = "my_oauth_secret";

Write-Host "Define the Azure storage connection string ..." -ForegroundColor Green
$storageAccountKey = get-azurestoragekey $storageAccountName | %{$_.Primary}
$storageConnectionString = "DefaultEndpointsProtocol=https;AccountName=$storageAccountName;AccountKey=$storageAccountKey"

Write-Host "Create block blob object ..." -ForegroundColor Green
$storageAccount = [Microsoft.WindowsAzure.Storage.CloudStorageAccount]::Parse($storageConnectionString)
$storageClient = $storageAccount.CreateCloudBlobClient();
$storageContainer = $storageClient.GetContainerReference($containerName)
$destBlob = $storageContainer.GetBlockBlobReference($destBlobName)

Write-Host "Define a MemoryStream and a StreamWriter for writing ..." -ForegroundColor Green
$memStream = New-Object System.IO.MemoryStream
$writeStream = New-Object System.IO.StreamWriter $memStream

Write-Host "Format oauth strings ..." -ForegroundColor Green
$oauth_nonce =     [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes([System.DateTime]::Now.Ticks.ToString()));
$ts = [System.DateTime]::UtcNow - [System.DateTime]::ParseExact("01/01/1970", "dd/MM/yyyy", $null)
$oauth_timestamp = [System.Convert]::ToInt64($ts.TotalSeconds).ToString();

$signature = "POST&";
$signature += [System.Uri]::EscapeDataString("https://stream.twitter.com/1.1/statuses/filter.json") + "&";
$signature += [System.Uri]::EscapeDataString("oauth_consumer_key=" + $oauth_consumer_key + "&");
$signature += [System.Uri]::EscapeDataString("oauth_nonce=" + $oauth_nonce + "&"); 
$signature += [System.Uri]::EscapeDataString("oauth_signature_method=HMAC-SHA1&");
$signature += [System.Uri]::EscapeDataString("oauth_timestamp=" + $oauth_timestamp + "&");
$signature += [System.Uri]::EscapeDataString("oauth_token=" + $oauth_token + "&");
$signature += [System.Uri]::EscapeDataString("oauth_version=1.0&");
$signature += [System.Uri]::EscapeDataString("follow=" + $follow);

$signature_key = [System.Uri]::EscapeDataString($oauth_consumer_secret) + "&" + [System.Uri]::EscapeDataString($oauth_token_secret);

$hmacsha1 = new-object System.Security.Cryptography.HMACSHA1;
$hmacsha1.Key = [System.Text.Encoding]::ASCII.GetBytes($signature_key);
$oauth_signature = [System.Convert]::ToBase64String($hmacsha1.ComputeHash([System.Text.Encoding]::ASCII.GetBytes($signature)));

$oauth_authorization = 'OAuth ';
$oauth_authorization += 'oauth_consumer_key="' + [System.Uri]::EscapeDataString($oauth_consumer_key) + '",';
$oauth_authorization += 'oauth_nonce="' + [System.Uri]::EscapeDataString($oauth_nonce) + '",';
$oauth_authorization += 'oauth_signature="' + [System.Uri]::EscapeDataString($oauth_signature) + '",';
$oauth_authorization += 'oauth_signature_method="HMAC-SHA1",'
$oauth_authorization += 'oauth_timestamp="' + [System.Uri]::EscapeDataString($oauth_timestamp) + '",'
$oauth_authorization += 'oauth_token="' + [System.Uri]::EscapeDataString($oauth_token) + '",';
$oauth_authorization += 'oauth_version="1.0"';

$post_body = [System.Text.Encoding]::ASCII.GetBytes("follow=" + $follow);

Write-Host "Create HTTP web request ..." -ForegroundColor Green
[System.Net.HttpWebRequest] $request = [System.Net.WebRequest]::Create("https://stream.twitter.com/1.1/statuses/filter.json");
$request.Method = "POST";
$request.Headers.Add("Authorization", $oauth_authorization);
$request.ContentType = "application/x-www-form-urlencoded";
$body = $request.GetRequestStream();

$body.write($post_body, 0, $post_body.length);
$body.flush();
$body.close();
$response = $request.GetResponse() ;

Write-Host "Start stream reading ..." -ForegroundColor Green

$sReader = New-Object System.IO.StreamReader($response.GetResponseStream())

$inrec = $sReader.ReadLine()
$count = 0
while (($inrec -ne $null) -and ($count -le $lineMax))
{
if ($inrec -ne "")
{
    Write-Host $count.ToString() ", " -NoNewline -ForegroundColor Green
    if ($count%10 -eq 0){
        write-host " --- " -NoNewline
        Get-Date -Format hh:mm:sstt
    }

    $writeStream.WriteLine($inrec)
    $count ++
}

$inrec=$sReader.ReadLine()
}

Write-Host "Write to the destination blob ..." -ForegroundColor Green
$writeStream.Flush()
$memStream.Seek(0, "Begin")
$destBlob.UploadFromStream($memStream) 

$sReader.close()
Write-Host "Complete!" -ForegroundColor Green

最佳答案

使用我的 PSTwitter 模块:

TechNet Gallery 上的 Powershell Twitter REST API 1.1 模块...

现在在 github 上:

https://github.com/mkellerman/PSTwitterAPI

关于powershell - 如何使用 Powershell 连接到 Twitter API 并遵循参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27667408/

相关文章:

visual-studio - VS 2017 - USQL - 解析管道分隔文件

android - 将 JAR 文件添加到 Android 应用程序

hadoop - 如何使用水槽获取实时推文?

java - Twitter 数据的图形可视化

powershell - WMI - 使用非管理员帐户查询服务器

azure - 如何使用 PowerShell 在 Azure 中创建新的警报规则?

powershell - 如何在 PowerShell 中格式化 Sitecore 中的字符串时使用下划线

azure - ADF 和存储帐户的 Terraform 身份访问

.net - 为什么Vista会报告我的Windows帐户没有管理员角色?

regex - Powershell RegEx - 捕获 "too much"(不遵守非贪婪指标?)