Twitter Developer C++Builderでツイートするアプリ作成方法[JAPAN]

Posted by on in Programming

毛利です。

 

C++Builder(VCL)でTwitterアプリを作る方法をご紹介致します。

Twitter Developersにアクセスする。

https://dev.twitter.com/ ここにアクセスする

サイトの下の方に「Tools」「Manage my apps」があるのでクリック

Create New Appでアプリを作成


登録画面の「Application Details」を入力と「Developer Agreement」チェックし、
「Create your Twitter application」をクリックします。

Twitter App完成

C++Builderでプロジェクトを作成

C++Builderを起動し [新規作成 | VCL フォーム アプリケーション - C++Builder]でプロジェクトを作成します。
TRESTRequestTRESTResponseTRESTClientTOAuth1Authenticatorと各コンポーネントを配置します。

OAuth1_Twitter->AccessTokenEndpoint   = "https://api.twitter.com/oauth/access_token";
OAuth1_Twitter->AuthenticationEndpoint  = "https://api.twitter.com/oauth/authenticate";
//Desktop applications only support the oauth_callback value 'oob'
OAuth1_Twitter->CallbackEndpoint        = "oob";
OAuth1_Twitter->RequestTokenEndpoint    = "https://api.twitter.com/oauth/request_token";

OAuth1_Twitter->CallbackEndpointにはoob(out-of-band) PINコードを入力する方法です。

PINを取得するまでのコード

void __fastcall TForm1::btn_Twitter_RequestAuthPINClick(TObject *Sender)
{
    RESTRequest->ResetToDefaults;
    RESTClient->ResetToDefaults;
    RESTResponse->ResetToDefaults;

    //Consumer Key (API Key) Developer Twitter.
    OAuth1_Twitter->ConsumerKey      = customer_key;
    //Consumer Secret (API Secret) Developer Twitter.
    OAuth1_Twitter->ConsumerSecret   = customer_secret;


    OAuth1_Twitter->AccessToken      = "";
    OAuth1_Twitter->AccessTokenSecret    = "";
    OAuth1_Twitter->RequestToken        = "";
    OAuth1_Twitter->RequestTokenSecret   = "";
    OAuth1_Twitter->VerifierPIN         = "";

    if (OAuth1_Twitter->ConsumerKey == "")
    {
        TaskMessageDlg("Error", "A Consumer-ID (\"client-id\" or \"app-id\") is required.", TMsgDlgType::mtError, TMsgDlgButtons() << mbOK, 0);
        return;
    };

    RESTClient->BaseURL              = OAuth1_Twitter->RequestTokenEndpoint;
    RESTClient->Authenticator        = OAuth1_Twitter;

    RESTRequest->Method              = TRESTRequestMethod::rmPOST;
    RESTRequest->Execute();

    UnicodeString LToken;
    if (RESTResponse->GetSimpleValue("oauth_token", LToken) )
        OAuth1_Twitter->RequestToken     = LToken;

    if (RESTResponse->GetSimpleValue("oauth_token_secret", LToken))
        OAuth1_Twitter->RequestTokenSecret   = LToken;


    f_RequestToken_         = OAuth1_Twitter->RequestToken;
    f_RequestTokenSecret_   = OAuth1_Twitter->RequestTokenSecret;

    UnicodeString LURL      = OAuth1_Twitter->AuthenticationEndpoint;
    LURL                    = LURL + "?oauth_token=" + OAuth1_Twitter->RequestToken;

    std::unique_ptr<Tfrm_OAuthWebForm> wv_{ std::make_unique<Tfrm_OAuthWebForm>(this) };
    wv_->ShowModalWithURL(LURL);

}

PIN に値を入れて AccessTokenを取得するまでのコード

void __fastcall TForm1::btn_Twitter_RequestAccessTokenClick(TObject *Sender)
{
    RESTRequest->ResetToDefaults;
    RESTClient->ResetToDefaults;
    RESTResponse->ResetToDefaults;
    /// grab the verifier from the edit-field
    OAuth1_Twitter->VerifierPIN      = "先ほど↑取得したPIN;

    /// here, we want to change the request-token and the verifier into an access-token
    if ((OAuth1_Twitter->RequestToken == "") || (OAuth1_Twitter->VerifierPIN == "") )
    {
        TaskMessageDlg("Error", "Request-token and verifier are both required.", TMsgDlgType::mtError, TMsgDlgButtons() << mbOK, 0);
        return;
    };

    /// we want to request an access-token
    OAuth1_Twitter->AccessToken          = "";
    OAuth1_Twitter->AccessTokenSecret    = "";

    RESTClient->BaseURL                  = OAuth1_Twitter->AccessTokenEndpoint;
    RESTClient->Authenticator            = OAuth1_Twitter;

    RESTRequest->Method              = TRESTRequestMethod::rmPOST;
    RESTRequest->Params->AddItem("oauth_verifier", OAuth1_Twitter->VerifierPIN,
        TRESTRequestParameterKind::pkGETorPOST,
        TRESTRequestParameterOptions()<<TRESTRequestParameterOption::poDoNotEncode);

    RESTRequest->Execute();

    UnicodeString LToken_;
    if (RESTResponse->GetSimpleValue("oauth_token", LToken_) )
        OAuth1_Twitter->AccessToken          = LToken_;
    Memo1->Lines->Append("OAuth1_Twitter->AccessToken " + LToken_ );

    if (RESTResponse->GetSimpleValue("oauth_token_secret", LToken_) )
        OAuth1_Twitter->AccessTokenSecret    = LToken_;
    Memo1->Lines->Append("OAuth1_Twitter->AccessTokenSecret " + LToken_ );

    /// now we should remove the request-token
    OAuth1_Twitter->RequestToken         = "";
    OAuth1_Twitter->RequestTokenSecret      = "";
    OAuth1_Twitter->VerifierPIN              = "";

    f_AccessToken_          = OAuth1_Twitter->AccessToken;
    f_AccessTokenSecret_    = OAuth1_Twitter->AccessTokenSecret;
    f_RequestToken_         = OAuth1_Twitter->RequestToken;
    f_RequestTokenSecret_   = OAuth1_Twitter->RequestTokenSecret;

}

ツイートを送信する

void __fastcall TForm1::btn_TwitterClick(TObject *Sender)
{
    if (Memo2->Lines->Text.Length() == 0)
    {

        TaskMessageDlg("Error", "Status-Field (the \"tweet\") must not be empty.", TMsgDlgType::mtError, TMsgDlgButtons() << mbOK, 0);
        return;
    }
    RESTRequest->ResetToDefaults;
    RESTClient->ResetToDefaults;
    RESTResponse->ResetToDefaults;

    RESTClient->BaseURL          = api_twitter;
    RESTClient->Authenticator    = OAuth1_Twitter;


    RESTRequest->Resource        = resource_uri;

    RESTRequest->Method          = TRESTRequestMethod::rmPOST;

    std::unique_ptr<TURLEncoding> URLEncoding_{std::make_unique<TURLEncoding>()};
    UnicodeString tweet_    = URLEncoding_->Encode("ツイートしたい文字列");

    RESTRequest->Params->AddItem("status", tweet_,
        TRESTRequestParameterKind::pkGETorPOST,
        TRESTRequestParameterOptions()<<TRESTRequestParameterOption::poDoNotEncode);

    //RESTRequest->URLAlreadyEncoded    = true;
    RESTRequest->Execute();

}


About
Gold User, No rank,
Delphi / C++Builder blogger

Comments

Check out more tips and tricks in this development video: