我正在创建一个使用其API的Twitter机器人。我使用的唯一软件包是RestSharp。如果可能的话,我想要一个不包含使用帮助程序包的解决方案。
这是我的代码:
static bool tweet(string tweetstr)
{
RestClient client = new RestClient("https://api.twitter.com");
RestRequest r = new RestRequest("/1.1/statuses/update.json", Method.POST);
//tweetstr = WebUtility.UrlEncode(tweetstr);
//r.AddParameter("status", tweetstr, ParameterType.QueryStringWithoutEncode);
r.AddQueryParameter("status", tweetstr);
client.Authenticator = OAuth1Authenticator.ForProtectedResource(API_key, API_secret_key, access_token, access_token_secret);
IRestResponse res = client.Execute(r);
if (res.StatusCode == System.Net.HttpStatusCode.OK)
{
Console.WriteLine(DateTime.Now.ToString() + " Tweeted: " + tweetstr);
return true;
}
else
{
Console.WriteLine("Couldn't tweet!\nError code: " + res.StatusCode.ToString() + "\nTried to tweet: " + tweetstr + "\nResponse: " + res.Content.ToString());
return false;
}
}
现在由于某种原因,除非我在字符串中使用特殊字符(例如外语甚至是感叹号),否则它将起作用,如果我这样做,它将返回未经授权的错误,消息为“无法对您进行身份验证。”。
例如,调用tweet("testing")
可以正常工作,但是调用tweet("testing!")
将返回错误。
您可以从评论中看到,我已经尝试过自己编码,但是将返回相同的错误,或者将其发布为已编码状态的tweet。
有帮助吗?谢谢,谢谢!
如前所述,使用您的注释代码,.NET Framework库中的现有实用程序不会像Twitter API所期望的那样逃避参数值。因此,您需要手动进行操作。这是一个可解决此问题的实用程序方法Derived from the LINQ to Twitter Url.cs class:
static string EscapeUriValue(string tweetstr)
{
const string reservedChars = @"`!@#$^&*+=,:;'?/|\[] ";
var escapedString = new StringBuilder();
foreach (char symbol in tweetstr)
{
if (reservedChars.IndexOf(symbol) != -1)
{
escapedString.Append('%' + String.Format("{0:X2}", (int)symbol).ToUpper());
}
else
{
escapedString.Append(symbol);
}
}
string statusVal = escapedString.ToString();
return statusVal;
}
注意reservedChars
如何包含WebUtility.UrlEncode
不编码的字符。然后从您的代码中调用该方法(已修改):
static bool tweet(string tweetstr)
{
RestClient client = new RestClient("https://api.twitter.com");
RestRequest r = new RestRequest("/1.1/statuses/update.json", Method.POST);
//tweetstr = WebUtility.UrlEncode(tweetstr);
//r.AddParameter("status", tweetstr, ParameterType.QueryStringWithoutEncode);
string statusVal = EscapeUriValue(tweetstr);
r.AddQueryParameter("status", statusVal);
client.Authenticator = OAuth1Authenticator.ForProtectedResource(
Environment.GetEnvironmentVariable("TwitterConsumerKey"),
Environment.GetEnvironmentVariable("TwitterConsumerSecret"),
"45714308-jigHmC9CQ0mbvrKhw24DY0nRs3M5osOZAZDXhzv0O",
"eoZDg0eNTTUNzBZ4UYQugnXR7yt5xllszFdW6QiEuvepe");
IRestResponse res = client.Execute(r);
if (res.StatusCode == System.Net.HttpStatusCode.OK)
{
Console.WriteLine(DateTime.Now.ToString() + " Tweeted: " + tweetstr);
return true;
}
else
{
Console.WriteLine("Couldn't tweet!\nError code: " + res.StatusCode.ToString() + "\nTried to tweet: " + tweetstr + "\nResponse: " + res.Content.ToString());
return false;
}
}
在添加参数之前,代码将调用EscapeUriValue
方法以确保正确转义该值。