private void CallData(TwitAuthenticateResponse twitAuthResponse, string authHeader, string cursor) { try { JObject j = GetJSonObject(twitAuthResponse, authHeader, cursor); JArray data = (JArray)j["users"]; if (data != null) { foreach (var item in data) { TwiterFollowers objTwiterFollowers = new TwiterFollowers(); objTwiterFollowers.ScreenName = item["screen_name"].ToString().Replace("\"", ""); objTwiterFollowers.ProfileImage = item["profile_image_url"].ToString().Replace("\"", ""); objTwiterFollowers.UserId = item["id"].ToString().Replace("\"", ""); listFollowers.Add(objTwiterFollowers); } JValue next_cursor = (JValue)j["next_cursor"]; if (long.Parse(next_cursor.Value.ToString()) > 0) { CallData(twitAuthResponse, authHeader, next_cursor.Value.ToString()); } } } catch (Exception ex) { //do nothing } }
private IEnumerable<Tweet> GetNewTweet() { IEnumerable<Tweet> empty = Enumerable.Empty<Tweet>(); if (_bearerToken == null) { _bearerToken = GetBearerToken(); if (_bearerToken == null) { return empty; } } IEnumerable<Tweet> history = LoadHistory(); if (history == null) { return empty; } IEnumerable<Tweet> timeline = GetTimeLine(); if (timeline == null) { return empty; } List<Tweet> newitems = timeline.Where(x => history.All(y => y.ID != x.ID)).ToList(); if (!SaveHistory(newitems, history)) { Console.WriteLine("*** ERROR SAVING TWEETS ***"); } return newitems.Count >= _maxitems ? newitems.Take(_maxitems) : newitems; }
public TwitAuthenticateResponse GetAccessTokenTwitter() { //Busca o token de acesso para a API do Twitter, vai ser utilizado dentro do chatterbot. Nota-se que não é necessário login // You need to set your own keys var oAuthConsumerKey = "qWh8ir2uy6jgMILcgFxRitq6R"; var oAuthConsumerSecret = "cF71OBRKJTNhrncTrH9Ei1HKIoFwOWKodd7AbflDhCRzBKDozh"; var oAuthUrl = "https://api.twitter.com/oauth2/token"; // Do the Authenticate var authHeaderFormat = "Basic {0}"; var authHeader = string.Format(authHeaderFormat, Convert.ToBase64String(Encoding.UTF8.GetBytes(Uri.EscapeDataString(oAuthConsumerKey) + ":" + Uri.EscapeDataString((oAuthConsumerSecret))) )); var postBody = "grant_type=client_credentials"; HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(oAuthUrl); authRequest.Headers.Add("Authorization", authHeader); authRequest.Method = "POST"; authRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8"; authRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; using (Stream stream = authRequest.GetRequestStream()) { byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody); stream.Write(content, 0, content.Length); } authRequest.Headers.Add("Accept-Encoding", "gzip"); WebResponse authResponse = authRequest.GetResponse(); // deserialize into an object TwitAuthenticateResponse twitAuthResponse = new TwitAuthenticateResponse(); using (authResponse) { using (var reader = new StreamReader(authResponse.GetResponseStream())) { JavaScriptSerializer js = new JavaScriptSerializer(); var objectText = reader.ReadToEnd(); twitAuthResponse = JsonConvert.DeserializeObject <TwitAuthenticateResponse>(objectText); } } return(twitAuthResponse); }
private JObject GetJSonObject(TwitAuthenticateResponse twitAuthResponse, string authHeader, string cursor) { string resource_url = string.Format(resource_urlFormat, screen_name, cursor); if (string.IsNullOrEmpty(cursor)) { resource_url = resource_url.Substring(0, resource_url.IndexOf("&cursor")); } HttpWebRequest fRequest = (HttpWebRequest)WebRequest.Create(resource_url); var timelineHeaderFormat = "{0} {1}"; fRequest.Headers.Add("Authorization", string.Format(timelineHeaderFormat, twitAuthResponse.token_type, twitAuthResponse.access_token)); fRequest.Method = "Get"; WebResponse response = fRequest.GetResponse(); string result = new StreamReader(response.GetResponseStream()).ReadToEnd(); return(JObject.Parse(result)); }
public JsonResult ValidaUserTwitter(string screenName) { TwitAuthenticateResponse accessToken = GetAccessTokenTwitter(); //Retira o '@' caso o usuário tenha inserido no campo if (screenName[0].Equals('@')) { screenName = screenName.Substring(1); } // Verifica se o usuário informado realmente existe var userFormat = "https://api.twitter.com/1.1/users/show.json?screen_name={0}"; var userUrl = string.Format(userFormat, screenName); HttpWebRequest userRequest = (HttpWebRequest)WebRequest.Create(userUrl); var userHeaderFormat = "{0} {1}"; userRequest.Headers.Add("Authorization", string.Format(userHeaderFormat, accessToken.TokenType, accessToken.AccessToken)); userRequest.Method = "Get"; try { WebResponse userResponse = userRequest.GetResponse(); var userJson = string.Empty; using (userResponse) { using (var reader = new StreamReader(userResponse.GetResponseStream())) { userJson = reader.ReadToEnd(); } dynamic user = new JavaScriptSerializer().DeserializeObject(userJson); if (user["id"] > 0 && !user["protected"]) { return(Json(true, JsonRequestBehavior.AllowGet)); } } } catch (Exception ex) { } return(Json(false, JsonRequestBehavior.AllowGet)); }
public string Authentificate() { //string access_token = "909380327956676609-kdNj948SFAGv0uI6YVTB0ldnuccX5yH"; //string access_token_secret = "2Mmn5ud70jGQVyN4h3Puew1yzGYqskuzQo3MGAqpkdnLA"; //string cons_key = "9eTJLyDqpUdY78Lu9QKzn03bs"; //string cons_secret = "ZgjxeVbB8ApBxEuUamrUO4LGSlYcI6Qg4ttGGnKNEEIL5L70Gm"; //// Auth.SetUserCredentials(cons_key, cons_secret, access_token, access_token_secret); //ITwitterCredentials creds = new TwitterCredentials(cons_key, cons_secret, access_token, access_token_secret); //Auth.SetUserCredentials(cons_key, cons_secret, access_token, access_token_secret); // TwitterCredentials.SetCredentials(access_token, access_token_secret, cons_key, cons_secret); var oAuthConsumerKey = "9eTJLyDqpUdY78Lu9QKzn03bs"; var oAuthConsumerSecret = "ZgjxeVbB8ApBxEuUamrUO4LGSlYcI6Qg4ttGGnKNEEIL5L70Gm"; var oAuthUrl = "https://api.twitter.com/oauth2/token"; var screenname = "iamlaba1"; var authHeaderFormat = "Basic {0}"; var authHeader = string.Format(authHeaderFormat, Convert.ToBase64String(Encoding.UTF8.GetBytes(Uri.EscapeDataString(oAuthConsumerKey) + ":" + Uri.EscapeDataString((oAuthConsumerSecret))) )); var postBody = "grant_type=client_credentials"; HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(oAuthUrl); authRequest.Headers.Add("Authorization", authHeader); authRequest.Method = "POST"; authRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8"; authRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; using (Stream stream = authRequest.GetRequestStream()) { byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody); stream.Write(content, 0, content.Length); } authRequest.Headers.Add("Accept-Encoding", "gzip"); WebResponse authResponse = authRequest.GetResponse(); TwitAuthenticateResponse twitAuthResponse; using (authResponse) { using (var reader = new StreamReader(authResponse.GetResponseStream())) { var objectText = reader.ReadToEnd(); dynamic x = Newtonsoft.Json.JsonConvert.DeserializeObject(objectText); twitAuthResponse = new TwitAuthenticateResponse() { access_token = x.access_token, token_type = x.token_type }; } } var timelineFormat = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={0}&include_rts=1&exclude_replies=1&count=5"; var timelineUrl = string.Format(timelineFormat, screenname); HttpWebRequest timeLineRequest = (HttpWebRequest)WebRequest.Create(timelineUrl); var timelineHeaderFormat = "{0} {1}"; timeLineRequest.Headers.Add("Authorization", string.Format(timelineHeaderFormat, twitAuthResponse.token_type, twitAuthResponse.access_token)); timeLineRequest.Method = "Get"; WebResponse timeLineResponse = timeLineRequest.GetResponse(); var timeLineJson = string.Empty; using (timeLineResponse) { using (var reader = new StreamReader(timeLineResponse.GetResponseStream())) { timeLineJson = reader.ReadToEnd(); } } return(timeLineJson.ToString()); }
public Twitter(TwitterType tp) { ConsumerCredentials = new MyConsumerCredentials(); tType = tp; // Do the Authenticate var oAuthUrl = Constants.OAUTHURL; // You need to set your own keys and screen name switch (tType) { case TwitterType.Unfollow: authHeader = string.Concat(Constants.BASIC, Constants.SPACE, Convert.ToBase64String(Encoding.UTF8.GetBytes(Uri.EscapeDataString(ConsumerCredentials.oauth_consumer_key) + Constants.COLON + Uri.EscapeDataString((ConsumerCredentials.oauth_consumer_secret))) )); break; case TwitterType.Friends: authHeader = string.Concat(Constants.BASIC, Constants.SPACE, Convert.ToBase64String(Encoding.UTF8.GetBytes(Uri.EscapeDataString(ConsumerCredentials.oauth_consumer_key) + Constants.COLON + Uri.EscapeDataString((ConsumerCredentials.oauth_consumer_secret))) )); break; case TwitterType.TimeLine: authHeader = string.Concat(Constants.BASIC, Constants.SPACE, Convert.ToBase64String(Encoding.UTF8.GetBytes(Uri.EscapeDataString(ConsumerCredentials.oauth_consumer_key) + Constants.COLON + Uri.EscapeDataString((ConsumerCredentials.oauth_consumer_secret))) )); break; case TwitterType.ByTweetId: authHeader = string.Concat(Constants.BASIC, Constants.SPACE, Convert.ToBase64String(Encoding.UTF8.GetBytes(Uri.EscapeDataString(ConsumerCredentials.oauth_consumer_key) + Constants.COLON + Uri.EscapeDataString((ConsumerCredentials.oauth_consumer_secret))) )); break; } var postBody = Constants.POSTBODY; HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(oAuthUrl); authRequest.Headers.Add(Constants.AUTHORIZATION, authHeader); authRequest.Method = Constants.POST; authRequest.ContentType = Constants.CONTENTTYPE; authRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; using (Stream stream = authRequest.GetRequestStream()) { byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody); stream.Write(content, 0, content.Length); } authRequest.Headers.Add(Constants.ACCEPTENCODING, Constants.GZIP); WebResponse authResponse = authRequest.GetResponse(); // deserialize into an object using (authResponse) { using (var reader = new StreamReader(authResponse.GetResponseStream())) { JavaScriptSerializer js = new JavaScriptSerializer(); var objectText = reader.ReadToEnd(); twitAuthResponse = JsonConvert.DeserializeObject <TwitAuthenticateResponse>(objectText); } } }
public async Task SetDiscoverSomethingTwitterAsync(TwitAuthenticateResponse twitAuthResponse, string screenName, long idMax, string idLogin) { var item = await DocumentDBRepository <Login> .GetItemAsync(idLogin); // Busca uma lista de tweets do usuário, neste caso os 100 primeiros. Após isso, é feito por thread, pegando os 100 tweets mais antigos que estes, e assim sucessivamente var timelineFormat = ""; var timelineUrl = ""; if (idMax > 0) { timelineFormat = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={0}&max_id={1}&include_rts=0&exclude_replies=1&count=100"; timelineUrl = string.Format(timelineFormat, screenName, idMax); } else { timelineFormat = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={0}&include_rts=0&exclude_replies=1&count=100"; timelineUrl = string.Format(timelineFormat, screenName); } HttpWebRequest timeLineRequest = (HttpWebRequest)WebRequest.Create(timelineUrl); var timelineHeaderFormat = "{0} {1}"; timeLineRequest.Headers.Add("Authorization", string.Format(timelineHeaderFormat, twitAuthResponse.TokenType, twitAuthResponse.AccessToken)); timeLineRequest.Method = "Get"; WebResponse timeLineResponse = timeLineRequest.GetResponse(); var timeLineJson = string.Empty; using (timeLineResponse) { using (var reader = new StreamReader(timeLineResponse.GetResponseStream())) { timeLineJson = reader.ReadToEnd(); } } dynamic tweets = new JavaScriptSerializer().DeserializeObject(timeLineJson); int count = 0; List <string> textTweets = new List <string>(); List <string> idTweets = new List <string>(); foreach (dynamic tweet in tweets) { //Joga todos os textos dos tweets dentro de uma lista, e os ids em outra textTweets.Add(tweet["text"]); long id = tweet["id"]; idTweets.Add(id.ToString()); count++; } //Busca token de acesso para API de Translate string authToken = await GetAccessTokenTranslateAsync(); //Chama API de Tradução, traduzindo o tweet de pt para en string[] translates = TranslateArray(authToken, "pt", "en", textTweets.ToArray()); string[] ids = idTweets.ToArray(); //Monta objeto para fazer a chamada da API de análise do texto do tweet KeyPhrases KeyPhrases = new KeyPhrases(); for (int i = 0; i < translates.Length; i++) { Document document = new Document(); document.Id = ids[i]; document.Language = "en"; document.Text = translates[i]; KeyPhrases.Documents.Add(document); } //Chama API de Análise de Texto, para buscar as palavras chave da frase tweetada dynamic keyPhrasesObj = GetKeyPhrases(KeyPhrases); List <string> keyPhrases = new List <string>(); foreach (var doc in keyPhrasesObj["documents"]) { //Coloca num stringão todas as palavras chaves separadas por ", " keyPhrases.Add(string.Join(", ", doc["keyPhrases"])); } //Busca token de acesso para API de Translate authToken = await GetAccessTokenTranslateAsync(); //Chama API de Tradução, agora traduzindo as palavras chave em en para pt para mostrar corretamente pro usuário string[] translateskeyPhrases = TranslateArray(authToken, "en", "pt", keyPhrases.ToArray()); for (int i = 0; i < translateskeyPhrases.Length; i++) { References reference = new References(); reference.IdTweet = ids[i]; //tweet.TextTweet = foreach (string keyPhraseTranslate in translateskeyPhrases[i].Split(new[] { ", " }, StringSplitOptions.None)) { //Verifica se já tem no objeto uma palavra chave com o mesmo texto if (item.KeyPhrases.Count(k => k.Text == keyPhraseTranslate) > 0) { //Se já existe, somente inclui uma nova referência item.KeyPhrases.FirstOrDefault(k => k.Text == keyPhraseTranslate).References.Add(reference); } else { //Caso não exista, cria uma nova KeyPhrase keyPhrase = new KeyPhrase(); keyPhrase.Text = keyPhraseTranslate; keyPhrase.References.Add(reference); item.KeyPhrases.Add(keyPhrase); } } } await DocumentDBRepository <Login> .UpdateItemAsync(idLogin, item); //ID do último tweet retornado, para consultar os mais antigos a partir desse, na próxima vez var lastTweet = tweets[count - 1]; long id_max = lastTweet["id"]; //Inicia thread para ir enchendo a base do usuário com mais tweets /*new Thread(async () => * { * await SetDiscoverSomethingTwitterAsync(twitAuthResponse, screenName, id_max - 1, idLogin); * }).Start();*/ }