We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 37242 ☆ A M B ☆
    • 339 Posts
    Dear MODX People,

    I'd like to share with you what I've been doing the last nights.

    I setup a site where people can enter places where they meet to go running together. It's done with FormIt and it creates resources from the frontend. As "running together" only makes sense with more people than just one, I registered a twitter account and connected it to the FormIt as a snippet to be called whenever a meeting is entered.

    Why as a snippet and not as a plugin? Because a plugin does not fire, when a resource is created via FormIt.

    You'll need a twitter dev account to do so. So go to http://dev.twitter.com and register the account you'll be tweeting from. Go to "My applications" in the menu, enter the domain you'll be tweeting from, enter some name for you application and generate an access token. You'll need four keys in total, you'll see it in the code which I took from here and edited it:

    <?php
    // OAuth Tokens
    $accesstoken = '********-***********';
    $accesssecret = '*************************';
    
    // OAuth Keys
    $consumerkey = '*****************';
    $consumerkeysecret= '******************************';
    
    // Direct message
    //$APIurl = 'https://api.twitter.com/1/direct_messages/new.xml';
    //$params="user=gallenkamp&text=".rawurlencode("This is an example for a direct message.");
    
    // Status update, known as "tweet"
    $APIurl = 'http://api.twitter.com/1/statuses/update.xml';
    $params = 'status='.rawurlencode("Ein neuer #Lauftreff mit dem Namen $title wurde für $tag in #$parentName eingetragen: $link");
    
    $reqmethod = "POST";
    
    // Build request ...
    $srequest="oauth_consumer_key=".$consumerkey;
    $srequest.="&oauth_nonce=".rand(10000001,99999999);            
    $srequest.="&oauth_signature_method=HMAC-SHA1";
    $srequest.="&oauth_timestamp=" . time();        
    $srequest.="&oauth_token=" . $accesstoken;
    $srequest.="&oauth_version=1.0";
    if ($params!="") {
        $srequest.="&".$params;
    }    
    
    // Parameters must be in the right order
    $sr=explode("&",$srequest);
    sort($sr);    
    $srequestSorted=implode("&",$sr);    
    
    // Basestring and key:
    $key=$consumerkeysecret."&".$accesssecret;      
    $basestring=strtoupper($reqmethod)."&".rawurlencode($APIurl).
        "&".rawurlencode($srequestSorted);
    
    // Create signature
    $sig=rawurlencode(base64_encode(hash_hmac('sha1', $basestring, $key, true)));    
    
    // Paste signature
    $srequest.="&oauth_signature=$sig";
    
    // send via file_get_contents
    $opts = array('http' =>
        array(
          'method'  => $reqmethod,
          'header'  => 'Content-type: application/x-www-form-urlencoded',
          'content' => $srequest
        )
    );
    // get the result
    $result = file_get_contents($APIurl, false, stream_context_create($opts));
    // echo "nResult:n" . $result;
    // echo "n... das war's!n";


    This is my code in the bottom of the formit2resource snippet which calls the tweetOnPublish snippet
    if ($hook->getValue('type')=='lauftreff') {
    
    $params['parent'] = $modx->getObject('modResource',array('id'=>$hook->getValue('parent')));
    $params['parentName'] = $params['parent']->get('pagetitle');
    $params['parentAlias'] = $params['parent']->get('alias');
     if ($tv = $modx->getObject('modTemplateVar', array ('name'=>'City')))
        {
            $tv->setValue($doc->get('id'), $params['parentName']);
            $tv->save();
        }
    
    $params['title'] = $doc->get('pagetitle');
    $params['link'] = 'http://www.lauftreff-kalender.de/lauftreffs/'.$params['parentAlias'].'.html';
    $params['tag'] = $hook->getValue('tag');
    //$params['link'] = $modx->makeUrl($params['parentId'], '', '', 'http'); // does not work, dont know why
    $modx->runSnippet('tweetOnPublish', $params);
    }


    I hope you find it useful. Let me know if you have any improvements!

    Cheers,

    Guido
      • 43230
      • 4 Posts
      Actually, thanks. You got me started. I decided to go with a Twitter API class which can be downloaded at: http://www.internoetics.com/download/php-code/twitter-oauth.zip

      You can read more about it here: http://www.internoetics.com/2011/01/12/post-to-twitter-using-oauth/

      The code author's github is here: https://github.com/abraham/twitterOAuth

      Here's my code:

      $link = 'http://gamrtag.com/'.$alias;
      $title = $doc->get('pagetitle');
      $tag = $doc->get('tags');
      
      $consumerKey = 'your_consumerKey';
      $consumerKey = 'your_consumerKey';
      $accessToken = 'your_accessToken';
      $accessTokenSecret = 'your_accessTokenSecret';
      
      // Full path to twitter.class.php (change OAuth to your own path)
      require_once MODX_CORE_PATH.'oauth/twitter.class.php';
      
      // Use bit.ly to shorten url
      $short_url = json_decode(file_get_contents("http://api.bit.ly/v3/shorten?login=your_apilogin&apiKey=your_apikey&longUrl=".urlencode("$link")."&format=json"))->data->url;
      
      // Your Message
      $message = "$title $short_url $tag";
      
      // Send tweet
      $twitter = new Twitter($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
      $twitter->send($message);


      I added a url shortner line as well. This is a lot simpler and I added it just before $modx->cacheManager->clearCache() in formit2resource.

      I still need to add an explode line to add #'s to the tags.