Twitter API


Twitter API

It provides a standard method to call common Twitter functions. Most functions have a limit in the number of times that can be called or in the number of bytes returned in a given time period. It is also possible to pay to get a special access to Twitter.
Esta proporciona una método estándar para llamar funciones comunes de Twitter. La mayoría de las funciones tienen un límite en el número de veces que pueden llamarse o en el número de bytes que regresan en un periodo de tiempo dado. Es posible también pagar por un acceso especial en Twitter.

Twitter Application-only authentication

Instead of using a specific user, it is possible to authenticate on behalf of an application. To use this method, you need to register your application in https://apps.twitter.com.
En lugar de usar un usuario específico, es posible autenticar con la identidad de un programa. Para usar este método, usted necesita registrar su programa en https://apps.twitter.com.

Problem 1
Use your personal Twitter account to register an application called as your last name, open to the following URL: https://apps.twitter.com. To register your program, you will have your mobile phone validated and the web site of your company. If the registration is successful, Twitter Developer will provide you a Consumer Key and a Consumer Secret. Store these values in a safe place. These values are required to create a program to interact with Twitter.
Use su cuenta personal de Twitter para registrar un programa llamado como su apellido, abra el siguiente URL: https://apps.twitter.com. Para registrar su programa, usted necesitará tener su teléfono celular validado y el sitio web de su compañía. Si el registro es exitoso, Twitter Developer le proporcionará un Consumer Key y un Consumer Secret. Guarde estos valores un lugar seguro. Estos valores son requeridos para crear un programa que interactúa con Twitter.

Twitter Bearer Token

It is a text string that is used for authorization so that an application can interact with Twitter.
Es una cadena de texto que es usada para autorización del tal modo que un programa pueda interactuar con Twitter.

Problem 2
Create a Wintempla Dialog application called MyToken to obtain a Bearer Token from Twitter. A Bearer Token in a string that is required to call Twitter functions. You must temporarily store the Bearer Token. Note that the Bearer Token is valid for a specific amount of time. We will use WinHTTP to connect to Twitter, you can also use WinINet or sockets.
Cree una aplicación de Diálogo de Wintempla llamada MyToken para obtener un Bearer Token desde Twitter. Un Bearer Token es un cadena de texto que es requerida para llamar las funciones de Twitter. Usted debe temporalmente almacenar el Bearer Token. Note que el Bearer Token es válido por un cantidad específica de tiempo. Nosotros usaremos WinHTTP para conectarnos a Twitter, usted también puede usar WinINet o sockets.

GetBearerToken

MyTokenRun

Tip
To get authorization, the AUTHORIZATION KEY (in the previous figure) must be generated as follows:
  1. Use RFC 1738 (URL encode) to encode the Consumer Key and the Consumer Secret
  2. Concatenate the encoded Consumer Key, a colon character : and the encoded Consumer Secret
  3. Encode the previous string using Base64 encoding

Para conseguir autorización, la AUTHORIZATION KEY (en la figura previa) debe ser generada como sigue:
  1. Use RFC 1738 (URL encode) para codificar la Consumer Key y la Consumer Secret
  2. Concatene la Consumer Key codificada, con el símbolo de dos puntos : y la Consumer Secret codificada
  3. Codifique la cadena previa usando Base64

Step A
Edit the stdafx.h file to enable Cryptography (using Windows Cryptography) and WinHTTP.
Edite el archivo stdafx.h para habilitar Cryptography (usando Windows Cryptography) y WinHTTP.

stdafx.h
...
//_________________________________________ Cryptography
#define WIN_CRYPTOGRAPHY
//_________________________________________ WinHTTP
#define WIN_WINHTTP
...


Step B
Edit the MyToken.cpp file as shown.
Edite el archivo MyToken.cpp como se muestra.

MyToken.cpp
...
void MyToken::Window_Open(Win::Event& e)
{
     //_____________________________________________________ 1. Prepare HTTP Request
     Web::HttpTransaction transaction;
     transaction.request.serverName = L"api.twitter.com";
     transaction.request.useHTTPS = true;
     transaction.request.Method = L"POST";
     transaction.request.resource = L"/oauth2/token";
     Sys::Convert::WcharToUTF8(L"grant_type=client_credentials", transaction.request.data);
     //_______ HTTP request header
     transaction.request.header = L"Host: api.twitter.com\r\n";
     transaction.request.header += L"User-Agent: SeloTwitterApplication v1.0.0\r\n";
     transaction.request.header += L"Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n";
     transaction.request.header += L"Authorization: Basic ";
     //_____________________________________________________ 2. OAuth2: authorization
     Web::OAuth2 oauth;
     oauth.consumer_key = L"xvz1evFS4wEEPTGEFPHBog";
     oauth.consumer_secret = L"L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg";

     wstring authorization_key;
     if (oauth.GetAuthorizationKey(authorization_key) == false)
     {
          this->MessageBox(L"Error creating OAuth2 authorization key", L"MyTwitter", MB_OK | MB_ICONERROR);
     }
     transaction.request.header += authorization_key;
     //_____________________________________________________ 3. Send HTTP Request
     Web::HttpAssistant assistant;
     assistant.synchronous = true;
     Sys::Error error = assistant.SendRequest(transaction);
     if (error == true)
     {
          error.Display(hWnd, L"MyToken");
          return;
     }
     //_____________________________________________________ 4. Display HTTP Response
     tbxOutput.Text = Web::HttpResponse::GetCodeDescr(transaction.response.status_code);
     tbxOutput.Text += L"\r\n";
     tbxOutput.Text += transaction.response.content_type;
     tbxOutput.Text += L"\r\n";
     wstring wresponse_body;
     Sys::Convert::UTF8ToWstring(transaction.response.data, wresponse_body);
     tbxOutput.Text += wresponse_body;
}


Problem 3
Create a Wintempla Dialog application called MyLimit to get the rate limit context in a Twitter application. You need to obtain a Bearer Token running the previous problem. You need to use the Bearer Token in Authorization header in the HTTP Request as shown in the figure.
Cree una aplicación de Diálogo de Wintempla llamada MyLimit para obener el contexto de los límites de velocidad en una aplicación de Twitter. Usted tiene que conseguir un Bearer Token ejecutando el problema previo. Usted necesita usar el Bearer Token en un encabezado Authorization en la HTTP Request como se muestra en la figura.

RateLimitContext

MyTokenRun

Step A
Edit the stdafx.h file to enable Windows Cryptography and WinHTTP.
Edite el archivo stdafx.h para habilitar Windows Cryptography y WinHTTP.

stdafx.h
...
//_________________________________________ Cryptography
#define WIN_CRYPTOGRAPHY
//_________________________________________ WinHTTP
#define WIN_WINHTTP
...


MyLimit.cpp
...
void MyLimit::Window_Open(Win::Event& e)
{
     const char* bearerToken = "AAAAAAAAAAAAAAAAAAAAAAqE3AAWEAkYQDS1FsPiqaazBAJRqsDyc6vZ4%3D0nHFgFW6RHLUuh4hs51Z6unXNsMFvULyKwgGv68ZCrIQAYmSgS";
     wstring wbearerToken;
     Sys::Convert::StringToWstring(bearerToken, wbearerToken);
          //_____________________________________________________ 1. Prepare HTTP Request
     Web::HttpTransaction transaction;
     transaction.request.serverName = L"api.twitter.com";
     transaction.request.useHTTPS = true;
     transaction.request.Method = L"GET";
     //__________________________________________________ LIMITS
     transaction.request.resource = L"/1.1/application/rate_limit_status.json";
     transaction.request.AddQueryStringVariable(L"resources", L"help,users,search,statuses");
     //_______ HTTP request header
     transaction.request.header = L"Host: api.twitter.com\r\n";
     transaction.request.header += L"User-Agent: SeloTwitterApplication v1.0.0\r\n";
     transaction.request.header += L"Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n";
     transaction.request.header += L"Authorization: Bearer ";
     transaction.request.header += wbearerToken;
     //_____________________________________________________ 2. Send HTTP Request
     Web::HttpAssistant assistant;
     assistant.synchronous = true;
     Sys::Error error = assistant.SendRequest(transaction);
     if (error == true)
     {
          error.Display(hWnd, L"MyToken");
          return;
     }
     //_____________________________________________________ 3. Display HTTP Response
     tbxOutput.Text = Web::HttpResponse::GetCodeDescr(transaction.response.status_code);
     tbxOutput.Text += L"\r\n";
     tbxOutput.Text += transaction.response.content_type;
     tbxOutput.Text += L"\r\n";
     wstring wresponse_body;
     Sys::Convert::UTF8ToWstring(transaction.response.data, wresponse_body);
     tbxOutput.Text += wresponse_body;
}


Problem 5
Modify the previous program to list the last 10 tweets from NASA. You need to modify only the HTTP Request: resource and query string.
Modifique el programa anterior para listar los últimos 10 tweets de NASA. Usted necesita modificar solamente la HTTP Request: resource y la query string.

TimelineRun

MyLimit.cpp
...
void MyLimit::Window_Open(Win::Event& e)
{
     const char* bearerToken = "AAAAAAAAAAAAAfAAfdfdqaazBAJRqsDyc6vZ4%3D0nHFgFW6RHLfdfdvULyKwgGv68ZCrIQAYmSgS";
     wstring wbearerToken;
     Sys::Convert::StringToWstring(bearerToken, wbearerToken);
     //_____________________________________________________ 1. Prepare HTTP Request
     Web::HttpTransaction transaction;
     transaction.request.serverName = L"api.twitter.com";
     transaction.request.useHTTPS = true;
     transaction.request.Method = L"GET";
     //__________________________________________________ LAST TWEET: https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
     transaction.request.resource = L"/1.1/statuses/user_timeline.json";
     transaction.request.AddQueryStringVariable(L"count", L"10");
     transaction.request.AddQueryStringVariable(L"screen_name", L"NASA");
     ...
}


Problem 6
Modify the previous program to search about energy in Twitter. You need to modify only the HTTP Request: resource and query string.
Modifique el programa anterior para buscar sobre energía en Twitter. Usted necesita modificar solamente la HTTP Request: resource y la query string.

SearchRun

MyLimit.cpp
...
void MyLimit::Window_Open(Win::Event& e)
{
     const char* bearerToken = "AAAAAAAAAAAAAfAAfdfdqaazBAJRqsDyc6vZ4%3D0nHFgFW6RHLfdfdvULyKwgGv68ZCrIQAYmSgS";
     wstring wbearerToken;
     Sys::Convert::StringToWstring(bearerToken, wbearerToken);
     //_____________________________________________________ 1. Prepare HTTP Request
     Web::HttpTransaction transaction;
     transaction.request.serverName = L"api.twitter.com";
     transaction.request.useHTTPS = true;
     transaction.request.Method = L"GET";
     //__________________________________________________ SEARCH: https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
     transaction.request.resource = L"/1.1/search/tweets.json";
     transaction.request.AddQueryStringVariable(L"count", L"10");
     transaction.request.AddQueryStringVariable(L"q", L"energy");
     ...
}


Problem 7
Create a Wintempla Dialog application called UserLimits to get the data limits of a specific account. For this problem, we will use WinHTTP to connect to Twitter. Go to "Tweeter developer" to obtain the "Access Token" and "Access Token Secret". Do not share these tokens. If you include these tokens in your program, they MUST be encrypted.
Cree una aplicación de Diálogo de Wintempla llamada UserLimits para retraer la límites de datos de un usuario específico. Para este problema, nosotros usaremos WinHTTP para conectarnos a Twitter. Navegue a "Tweeter developer" para conseguir el "Access Token" y el "Access Token Secret". No comparte estos tokens. Si usted incluye estos token en su programa, estos deben ser encriptados.

Step A
Edit the stdafx.h file to enable Cryptography (using Windows Cryptography) and WinHTTP (using WinHTTP).
Edite el archivo stdafx.h para habilitar Cryptography (usando Windows Cryptography) y WinHTTP (usando WinHTTP).

stdafx.h
...
//_________________________________________ Cryptography
#define WIN_CRYPTOGRAPHY
//_________________________________________ WinHTTP
#define WIN_WINHTTP
...


UserLimits.cpp
...
void UserLimits::Window_Open(Win::Event& e)
{
     Web::HttpTransaction transaction;
     //_____________________________________________________ 1. Prepare HTTP Request
     transaction.request.serverName = L"api.twitter.com";
     transaction.request.useHTTPS = true;
     transaction.request.Method = L"GET";
     transaction.request.resource = L"/1.1/application/rate_limit_status.json";
     transaction.request.AddQueryStringVariable(L"resources", L"help,users,search,statuses");
     transaction.request.header = L"Host: api.twitter.com\r\n";
     transaction.request.header += L"User-Agent: SeloTwitterApplication v1.0.0\r\n";
     transaction.request.header += L"Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n";
     //_____________________________________________________ 2. OAUTH 1
     Web::OAuth1 oauth1;
     oauth1.access_token = L"92834545454542718423CAWbf5xr2A8"; // From Twitter Developer
     oauth1.access_token_secret = L"rjOhROUIRJKJKJKLFCg276"; // From Twitter Developer
     oauth1.consumer_key = L"LW8998fdKJLKJfd fdifdodfeeQQDRER"; // From Twitter Developer
     oauth1.consumer_secret = L"bdBMoOiUyUUKKJ998iereuirereV"; // From Twitter Developer
     //_____________________________________________________ 3. HTTP Authorization
     wstring oauth_key;
     oauth1.GetAuthorizationKey(transaction.request, oauth_key);
     transaction.request.header += L"Authorization: ";
     transaction.request.header += oauth_key;
     //_____________________________________________________ 4. Send HTTP Request
     Web::HttpAssistant assistant;
     assistant.synchronous = true;
     Sys::Error error = assistant.SendRequest(transaction);
     if (error == true)
     {
          error.Display(hWnd, L"UserLimits");
          return;
     }
     //_____________________________________________________ 5. Display HTTP Response
     tbxOutput.Text = Web::HttpResponse::GetCodeDescr(transaction.response.status_code);
     tbxOutput.Text += L"\r\n";
     tbxOutput.Text += transaction.response.content_type;
     tbxOutput.Text += L"\r\n";
     wstring wresponse_body;
     Sys::Convert::UTF8ToWstring(transaction.response.data, wresponse_body);
     tbxOutput.Text += wresponse_body;
}


UserLimitsRun

© Copyright 2000-2019 Wintempla selo. All Rights Reserved. Sep 05 2019. Home