Jump to content
EyeDentify

How to post Tweets to Twitter API with TwitterOauth

Recommended Posts

Hello There Fellow PW lovers.

I wanted to share this code that i created to post tweets to the Twitter API in an upcomming project i am working on.

And i Thought that everyone could have some use for it.

I am using Composer to load the TwitterOAuth PHP library for working with the Twitter API in this code example.

Also you need to create an App and have your own API keys ready, you can do that here:
https://developer.twitter.com/en/apps

The code posts a string and uploads media to be used with the tweet.
For the TwitterOAuth methods information see the link above.

Note: The paths to the media needs to be local for TwitterOAuth to pick them up and upload them.
See this link for filesize limits and other info on media attachements.

https://developer.twitter.com/en/docs/media/upload-media/overview

<?PHP
/*
    TwitterOAuth API via Composer
    https://twitteroauth.com/
*/
include('vendor/autoload.php');

/* define the classes */
use Abraham\TwitterOAuth\TwitterOAuth;

function postTweetUpdate($str = '', $mediaArray = null) {

    /*
        Twitter OAuth keys
        Create your App and find your API keys here:
        https://developer.twitter.com/en/apps
    */
    $consumer_key = '';
    $consumer_secret = '';
    $access_token = '';
    $access_token_secret = '';
    
    /* init API */
    $connection = new TwitterOAuth($consumer_key, $consumer_secret, $access_token, $access_token_secret);
    
    if(is_array($mediaArray)) {
        
        $mediaIDS = array();
        
        /*
            Up to 4 media objects can be uploaded.
            https://developer.twitter.com/en/docs/media/upload-media/overview
        */
        
        foreach($mediaArray AS $key => $media_path) {
            
            /* Upload media to twitter API and get media ID back */
            $mediaOBJ = $connection->upload('media/upload', ['media' => $media_path]);
            
            /* push uploaded media ID to array */
            array_push($mediaIDS, $mediaOBJ->media_id_string);
        }
        
        /* create comma delimited list of media ID:s */
        $mediaIDstr = implode(',', $mediaIDS);
    }
        
    /* API params */
    $arrayCfg['status'] = $str;
    $arrayCfg['media_ids'] = $mediaIDstr;
    
    /*
        Make POST request to Twitter API
        https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
    */
    $statuses = $connection->post("statuses/update", $arrayCfg);
    
    /* return payload */
    return $statuses;
}

?>
<?PHP
    /* string to Post */
    $str = 'Test Tweet... ' . PHP_EOL;
    $str .= '#mytweet' . PHP_EOL;
    $str .= 'http://www.mywebsite.com' . PHP_EOL;
    $str .= '' . hash('sha1', mt_rand(0, 1000000));
    
    /* media to upload */
    $mediaToUpload[] = 'images/my_image.jpg';

    /* make request to Twitter API */
    $payLoad = postTweetUpdate($str, $mediaToUpload);
?>

<h3>Debug</h3>
<pre><?PHP print_r($payLoad); ?></pre>

I have the Debug part because its handy to see what is returned from the Twitter API.

  • Like 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By joe_g
      Hello,
      Has anyone worked with the twitter oEmbed to get a single tweet embed-code?
      I was hoping there was a plugin for this, but it doesn't seem to be one. Ideally I'd like to fill in the tweet id or address, and the rest is filled in. I'm trying to avoid having the client pasting the embed code themselves (can go wrong easier).
      To write a plugin for this is a bit over my head at the moment. I would need to do caching and things like that not to affect the page load too much. But maybe someone has already done this one way or another?
      thanks!
       
       
    • By KG60
      I'm not sure if I'm posting this in the correct area so apologies if I'm not. I'm trying to get a selection of tweets appearing on a website in a similar style to the WordPress Juiz-Last-Tweet Widget.
      I'm managed to get the actual design correct now but I'm not sure how to actually pull the tweets in. The idea is for a selection of about 10 tweets appearing on a 10 second rotation as per the attached file example.
      I've got a version running on a test site at http://owltreeweb.solutions/bni-bolton
      My php & javascript coding knowledge isn't great so any help on getting this completed would be greatly appreciated.
      I do have a latest tweets script running at the right of the screen, so I have the Twitter data widget ID,  but I think the Juiz-Last-Tweet option which is currently in the footer of the site looks a lot smarter and I would like to replace the current one. 
      I do have the .js files if they are any help.
      Thanks in advance.

    • By a-ok
      Hi folks,
      Bit of an odd one... I'm adding some meta tags for Facebook and Twitter to the head.inc file and I'm trying to make the output per tag as global as possible. These are the tags I have so far:
      <meta property="og:title" content="<?php echo $page->title; ?>" /> <meta property="og:image" content="" /> <meta property="og:url" content="<?php echo $page->url; ?>" /> <meta property="og:description" content="" /> <meta name="twitter:url" content="<?php echo $page->url; ?>"> <meta name="twitter:title" content="<?php echo $page->title; ?>"> <meta name="twitter:description" content=""> <meta name="twitter:image" content=""> As you can see I have a few obvious ones set up, but I'm curious to know how you all might think about outputting the image and description meta information? I'm thinking finding the first image on the page and the first text output on the page but that's a little tricky, isn't it? Do you think these should be set up as separate fields for pages within the CMS for the client to fill out as they fill out the pages... as part of the process for SEO? And if there's any tips to why using these tags are bad please do say so.
      Many thanks,
      R
    • By tibs
      I don't always want to bother registering users, I just want them to be able to log in. I'm not alone because there are a number of other threads about OAuth, none of which mentions Opauth.
      Opauth is a lean, non-opinionated, modular PHP thingy. It has 18 providers listed on their page, some of which are built-in, some are 3rd-party. Their website itself is an example, and it's on github as well.
      It's lean: it doesn't need the provider SDKs, it implements only what it needs in the auth modules.
      It's non-opinionated: you give your user a link to /auth/facebook, and then you are waiting for the results on /auth/callback; what you do with the returned array is your choice (the urls are of course customizable).
      I could put together Twitter / Google / Facebook auth for a (non-processwire) site really quick. I stored the API auth params for the modules in a table as json-encoded hashes (just 2 keys and  2 values, but the keys vary by API, so that was the easiest), and I did the same with the returned credentials. Besides provider, uid, and credentials (what we really need), Opauth also returns a somewhat variable set of details about the profiles in the info key, stuff like name, gender, urls, and the like; the Processwire module could opt to mine and store in fields whatever it deems useful, then store the rest as json, or just throw it away. An example for what you get in your callback:
      Array ( [auth] => Array ( [provider] => Facebook [uid] => 1480000000008166 [info] => Array ( [name] => Tibs [image] => https://graph.facebook.com/1480000000008166/picture?type=square [first_name] => Tibs [urls] => Array ( [facebook] => https://www.facebook.com/app_scoped_user_id/1480000000008166/ ) ) [credentials] => Array ( [token] => CAAEajKBojCkBAHj6cy0mM4EZBPvs082t5Vkm3PGa44jsfrfzCS1SwV09qOaZBQYnfxLnCacb7Wkr536wDzusIh4mkMmvwoC5VdZBKFRAGyLpqcVJYdWCIFv0iwfkjpiLpDsGVBChj1ac1Lq6ZBFjuCdrtfpcQtgWbonDVCzwGwZB0A37vLaQbCuh8OnbdRY1U1dPE2ZBU2PmgNGNP1ghzNo [expires] => 2016-01-06T10:29:53+00:00 ) [raw] => Array ( [id] => 1480000000008166 [first_name] => Tibs [gender] => male [link] => https://www.facebook.com/app_scoped_user_id/148000000000166/ [locale] => en_US [name] => Tibs [timezone] => 1 [updated_time] => 2015-01-25T19:54:12+0000 [verified] => 1 ) ) [timestamp] => 2015-11-07T11:20:56+00:00 [signature] => hmcuwumqat4w84g1gkw0cgokloogg4w ) To be honest, I'm not even working on anything in Processwire at the moment, but I wanted to post about Opauth since I discovered it. If someone decides to implement OAuth before I get around it myself, Opauth is the perfect candidate to do the heavy lifting
    • By Marty Walker
      Hello,
      I have a client that needs to be able to embed tweets into a ckeditor body field. I've turned ACF and HTML purifying to off. All I get is the embed code block wrapped in a <p>:
      <blockquote class="twitter-tweet" lang="en"><p>You can pursue photography for the pure enjoyment of it. No fine art photography ambitions necessary. You'll be ok.</p>— Bryan Formhals (@bryanformhals) <a href=" ">January 4, 2014</a></blockquote> <script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script> I've tried throwing jQuery to unwrap the blockquote from the <p> but no go either? How do I do it?
×
×
  • Create New...