2013-09-24 57 views
0

所以我想要做的就是讓用戶擁有特定的hashtag。關於使用什麼的任何想法?我正在使用Tweetsharp和C#。獲取推特具有特定#標籤的用戶

+3

你嘗試過什麼了嗎?你可以分享嗎? – meilke

+0

什麼是「具有特定主題標籤的用戶」?我沒有使用推特,但不是推文的標籤,而不是用戶?無論如何,這個如何:http://stackoverflow.com/questions/5290652/get-all-tweets-with-specific-hashtag – Corak

+0

哈哈其實我不知道如何去更進一步。我不明白Twitter上的Oauth Api,我沒有在代碼上得到任何好的例子。 我想要做的是獲得一個用戶圖片,用戶名和他們的推文,當他們有一個特定的事情的話題標籤。但我不希望用戶通過twitter來驗證信息。我知道你可以得到關於用戶沒有登錄的信息,所以不知何故我想這樣做嘿.. –

回答

0

可以用這個代碼 http://forums.asp.net/post/4761697.aspxhttp://abhi4net.blogspot.com/2013/07/twitter-api-11-integration-with-mvc-in-c.html

使用TweetSharp庫,你可以從here添加庫

Controllar代碼

public ActionResult Index() 
    { 
     List<TwitterModel> tweets = GetTweets("#twitter"); 
     return View(tweets); 
     // return View(); 
    } 
    public List<TwitterModel> GetTweets(string twitterHashTag) 
    { 

     List<TwitterModel> lstTweets = new List<TwitterModel>(); 

     // New Code added for Twitter API 1.1 
     if (!string.IsNullOrEmpty(twitterHashTag)) 
     { 
      var twitter = new TwitterHelper(ConfigurationManager.AppSettings["OauthConsumerKey"], 
                  ConfigurationManager.AppSettings["OauthConsumerKeySecret"], 
                  ConfigurationManager.AppSettings["OauthAccessToken"], 
                  ConfigurationManager.AppSettings["OauthAccessTokenSecret"]); 

      var response = twitter.GetTweets(twitterHashTag, 100); 
      dynamic timeline = System.Web.Helpers.Json.Decode(response); 
      foreach (var tweet in timeline) 
      { 
       System.Web.Helpers.DynamicJsonArray tweetJson = tweet.Value as System.Web.Helpers.DynamicJsonArray; 
       if (tweetJson != null && tweetJson.Count() > 0) 
        foreach (System.Dynamic.DynamicObject item in tweetJson) 
        { 
         TwitterModel tModel = new TwitterModel(); 
         tModel.Id = ((dynamic)item).id.ToString(); 
         tModel.AuthorName = ((dynamic)item).user.name; 
         tModel.AuthorUrl = ((dynamic)item).user.url; 
         tModel.Content = ((dynamic)item).Text; 
         string publishedDate = ((dynamic)item).created_at; 
         publishedDate = publishedDate.Substring(0, 19); 
         tModel.Published = DateTime.ParseExact(publishedDate, "ddd MMM dd HH:mm:ss", null); 

         tModel.ProfileImage = ((dynamic)item).user.profile_image_url; 
         lstTweets.Add(tModel); 
        } 
      } 
     } 
     return lstTweets; 
    } 

public class TwitterHelper 
{ 
    public const string OauthVersion = "1.0"; 
    public const string OauthSignatureMethod = "HMAC-SHA1"; 

    public TwitterHelper(string consumerKey, string consumerKeySecret, string accessToken, string accessTokenSecret) 
    { 
     this.ConsumerKey = consumerKey; 
     this.ConsumerKeySecret = consumerKeySecret; 
     this.AccessToken = accessToken; 
     this.AccessTokenSecret = accessTokenSecret; 
    } 

    public string ConsumerKey { set; get; } 
    public string ConsumerKeySecret { set; get; } 
    public string AccessToken { set; get; } 
    public string AccessTokenSecret { set; get; } 

    public string GetTweets(string twitterHashTag, int count) 
    { 
     string resourceUrl = string.Format("https://api.twitter.com/1.1/search/tweets.json"); 
     var requestParameters = new SortedDictionary<string, string>(); 
     requestParameters.Add("q", twitterHashTag); 
     requestParameters.Add("count", count.ToString()); 
     requestParameters.Add("result_type", "mixed"); 
     var response = GetResponse(resourceUrl, "GET", requestParameters); 
     return response; 
    } 

    private string GetResponse(string resourceUrl, string methodName, SortedDictionary<string, string> requestParameters) 
    { 
     ServicePointManager.Expect100Continue = false; 
     WebRequest request = null; 
     string resultString = string.Empty; 

     request = (HttpWebRequest)WebRequest.Create(resourceUrl + "?" + requestParameters.ToWebString()); 
     request.Method = methodName; 
     request.ContentType = "application/x-www-form-urlencoded"; 


     if (request != null) 
     { 
      var authHeader = CreateHeader(resourceUrl, methodName, requestParameters); 
      request.Headers.Add("Authorization", authHeader); 

      var response = (HttpWebResponse)request.GetResponse(); 
      using (var sd = new StreamReader(response.GetResponseStream())) 
      { 
       resultString = sd.ReadToEnd(); 
       response.Close(); 
      } 
     } 
     return resultString; 
    } 

    private string CreateOauthNonce() 
    { 
     return Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString())); 
    } 

    private string CreateHeader(string resourceUrl, string methodName, SortedDictionary<string, string> requestParameters) 
    { 
     var oauthNonce = CreateOauthNonce(); 
     // Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString())); 
     var oauthTimestamp = CreateOAuthTimestamp(); 
     var oauthSignature = CreateOauthSignature(resourceUrl, methodName, oauthNonce, oauthTimestamp, requestParameters); 
     //The oAuth signature is then used to generate the Authentication header. 
     const string headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " + "oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " + "oauth_token=\"{4}\", oauth_signature=\"{5}\", " + "oauth_version=\"{6}\""; 
     var authHeader = string.Format(headerFormat, Uri.EscapeDataString(oauthNonce), Uri.EscapeDataString(OauthSignatureMethod), Uri.EscapeDataString(oauthTimestamp), Uri.EscapeDataString(ConsumerKey), Uri.EscapeDataString(AccessToken), Uri.EscapeDataString(oauthSignature), Uri.EscapeDataString(OauthVersion)); 
     return authHeader; 
    } 
    private string CreateOauthSignature(string resourceUrl, string method, string oauthNonce, string oauthTimestamp, SortedDictionary<string, string> requestParameters) 
    { 
     //firstly we need to add the standard oauth parameters to the sorted list 
     requestParameters.Add("oauth_consumer_key", ConsumerKey); 
     requestParameters.Add("oauth_nonce", oauthNonce); 
     requestParameters.Add("oauth_signature_method", OauthSignatureMethod); 
     requestParameters.Add("oauth_timestamp", oauthTimestamp); 
     requestParameters.Add("oauth_token", AccessToken); 
     requestParameters.Add("oauth_version", OauthVersion); 
     var sigBaseString = requestParameters.ToWebString(); 
     var signatureBaseString = string.Concat(method, "&", Uri.EscapeDataString(resourceUrl), "&", Uri.EscapeDataString(sigBaseString.ToString())); 

     var compositeKey = string.Concat(Uri.EscapeDataString(ConsumerKeySecret), "&", Uri.EscapeDataString(AccessTokenSecret)); 
     string oauthSignature; 
     using (var hasher = new HMACSHA1(Encoding.ASCII.GetBytes(compositeKey))) 
     { 
      oauthSignature = Convert.ToBase64String(hasher.ComputeHash(Encoding.ASCII.GetBytes(signatureBaseString))); 
     } 
     return oauthSignature; 
    } 
    private static string CreateOAuthTimestamp() 
    { 
     var nowUtc = DateTime.UtcNow; 
     var timeSpan = nowUtc - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); 
     var timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString(); return timestamp; 
    } 
} 

public static class Extensions 
{ 
    public static string ToWebString(this SortedDictionary<string, string> source) 
    { 
     var body = new StringBuilder(); 
     foreach (var requestParameter in source) 
     { 
      body.Append(requestParameter.Key); 
      body.Append("="); 
      body.Append(Uri.EscapeDataString(requestParameter.Value)); 
      body.Append("&"); 
     } //remove trailing '&' 
     body.Remove(body.Length - 1, 1); return body.ToString(); 
    } 
} 

查看

@model IEnumerable<TwitterHashTag.Models.TwitterModel> 

@{ 
    Layout = null; 
} 

<!DOCTYPE html> 

<html> 
<head> 
    <meta name="viewport" content="width=device-width" /> 
    <title>Index</title> 
</head> 
<body> 
    <p> 


</p> 
<table> 
    <tr> 
     <th> 
      @Html.DisplayNameFor(model => model.Content) 
     </th> 
     <th> 
      @Html.DisplayNameFor(model => model.AuthorName) 
     </th> 
     <th> 
      @Html.DisplayNameFor(model => model.AuthorUrl) 
     </th> 
     <th> 
      @Html.DisplayNameFor(model => model.ProfileImage) 
     </th> 
     <th> 
      @Html.DisplayNameFor(model => model.Published) 
     </th> 
     <th></th> 
    </tr> 

@foreach (var item in Model) { 
    <tr> 
     <td> 
      @Html.DisplayFor(modelItem => item.Content) 
     </td> 
     <td> 
      @Html.DisplayFor(modelItem => item.AuthorName) 
     </td> 
     <td> 
      @Html.DisplayFor(modelItem => item.AuthorUrl) 
     </td> 
     <td> 
      @Html.DisplayFor(modelItem => item.ProfileImage) 
     </td> 
     <td> 
      @Html.DisplayFor(modelItem => item.Published) 
     </td> 
     <td> 

     </td> 
    </tr> 
} 

</table> 

相關問題