Building a Twitter Hashtag Contest – Creating and Counting Tweets

Share this article

In the first part of the series, we looked at the various types of contests on Twitter and chose to develop a hashtag contest, as it was one of the most popular types of contest and did not rely on luck. So far we have authenticated our users using the Twitter application. Today we are going to continue by implementing the tweet capabilities for our users.

Let’s get started.

Initializing The Tweet Screen

Our first task is to assign the user’s details into a browser session, allowing users to tweet multiple times without needing to authorize the app for every tweet. The following code adds the details to the session and initializes the tweet screen.

public function createUserSession($credentials){

  $_SESSION['user_id'] = $credentials["user_id"];
  $_SESSION['user_token'] = $credentials["oauth_token"];
  $_SESSION['user_secret'] = $credentials["oauth_token_secret"];

  $this->initializeTweetScreen();
}

Let’s take a look at the implementation of the tweet screen with an HTML form.

public function initializeTweetScreen($message = ''){

  $html = "<div>".$message."</div>
           <form action='' method='POST' >
             <textarea name='post_tweet' id='post_tweet'></textarea>
             <input name='submit_tweet' type='submit' value='Tweet' />
            </form>";

  echo $html;
}

Now the user can submit tweets using a simple HTML form.

Creating Tweets

Once the user submits the form, we need to use this submitted content to automatically create tweets on their Twitter profile. We need to update our controller code with the following:

if (isset($_SESSION['user_id'])) {
    if (isset($_POST['submit_tweet'])) {
        $tweet_text = isset($_POST['post_tweet']) ? $_POST['post_tweet'] : '';
        $message = $contest->createTweet($tweet_text);
        $contest->initializeTweetScreen($message);
    } else {
        $contest->initializeTweetScreen();
    }
}

This intercepts the POST request and adds the tweet content. We will be using a function called createTweet for accessing the Twitter API as shown below.

public function createTweet($tweet_text) {
    $error = "";
    $hash_tags = " #SPC #twcontesttutorial ";
    if (empty($tweet_text) || strlen($tweet_text . $hash_tags) > 140) {
        $error .= "Tweet text should contain 1-140 characters.";
    }
    if (empty($error)) {

        $twitter_auth = $this->initializeTwitterObject();
        $code = $twitter_auth->request('POST', $twitter_auth->url('1.1/statuses/update'), array('status' => $tweet_text . $hash_tags));
        if ($code == 200) {
            $response = json_decode($twitter_auth->response["response"]);
            return "Tweet Created Successfully";
        }
    } else {
        return $error;
    }
}

As we discussed in the planning section, two hashtags called #SPC and #twcontesttutorial will be used with each tweet. Next, we will check for errors in tweet content. Once it’s successfully validated, we use initializeTwitterObject function to create the Twitter library object as shown in the following code.

public function initializeTwitterObject() {

    $this->app_details = array(
        'consumer_key' => $this->config['consumer_key'],
        'consumer_secret' => $this->config['consumer_secret'],
        'user_token' => $_SESSION['user_token'],
        'user_secret' => $_SESSION['user_secret']
    );


    $twitter_auth = new tmhOAuth($this->app_details);
    return $twitter_auth;
}

In this scenario, the object will be initialized with user_token and user_secret instead of just using consumer_key and consumer_secret.

Next, we execute the tweet request using the 1.1/statuses/update API URL. We pass the user submitted text in combination with our hashtags using the status parameter. Once the request is successful, we display the message to the user to complete the process.

Now users can authorize the app and create as many tweets as they want. All tweets will have the predefined hashtags.

Displaying the Contest Results

Results of the contest will be calculated based on the number of retweets. We have to use Twitter search API functions to get the desired results. Let’s take a look at the updated code.

if(isset($_GET['action']) && $_GET['action'] == 'results'){    
  $contest->getContestResults();
}

Now we are going to look at the getContestResults function.

public function getContestResults() {

    $twitter_auth = $this->initializeTwitterObject();
    $search_params = array('q' => '#SPC #twcontesttutorial -RT', 'count' => 100, 'result_type' => 'recent');
    $this->retrieveTweets($twitter_auth, $search_params);

    $contest_results = array();
    $html = "<table>";
    $html .= "<tr><td>Username</td><td>Retweets</td></tr>";

    foreach ($this->result_tweets as $key => $value) {
        $username = $value->user->screen_name;
        $contest_results[$username] = isset($contest_results[$username]) ? ($contest_results[$username] + $value->retweet_count) : $value->retweet_count;
    }

    foreach ($contest_results as $key => $res) {
        $html .= "<tr><td>" . $key . "</td><td>" . $res . "</td></tr>";
    }

    $html .= "</table>";
    echo $html;
}

First, we define the parameters required for searching. The search query will be the combination of two hashtags. We have also used -RT to prevent the counting of retweets, as retweets shouldn’t be counted as a tweet generated from the application.

count parameter defines the number of records per page.

result_type parameter defines the type of tweets in the resulting set. It can have the values ‘mixed’, ‘recent’ or ‘popular’. We are using ‘recent’ as the result_type to get most recent tweets.

Next, we call the retrieveTweets function for generating the results. The following code previews the retrieveTweets function implementation.

public function retrieveTweets($twitter_auth, $search_params) {

    $code = $twitter_auth->request('GET', $twitter_auth->url('1.1/search/tweets'), $search_params);
    $response = json_decode($twitter_auth->response["response"]);

    foreach ($response->statuses as $value) {
        array_push($this->result_tweets, $value);
    }

    if (isset($response->search_metadata->next_results) && count($this->result_tweets) < 500) {

        $search_meta = substr($response->search_metadata->next_results, 1);
        $search_meta = explode("&", $search_meta);
        $max_id = 0;
        foreach ($search_meta as $sm) {
            $max_id_res = explode("=", $sm);
            if ($max_id_res[0] == 'max_id') {
                $max_id = $max_id_res[1];
            }
        }

        $search_params['max_id'] = $max_id;
        $this->retrieveTweets($twitter_auth, $search_params);
    }
}

This is a recursive function used for paginated searching of tweets. We call the 1.1/search/tweets API URL with the default parameters and assign all the resulted tweets into an array. We have to call this function recursively to generate the results of remaining pages. So we check the availability of next_results in response, as well as whether our result set exceeds the given limit.

Searching for all the resulting tweets and paginating is an almost impossible task. So we have to narrow the result set to a certain limit.

Then, we extract the max_id parameter and assign it to search parameters for generating the next result set. Finally, we call the function recursively until we reach the end of results or 500 tweets and assign it to the result_tweets array. Now we can move back to the remaining sections of getContestResults function.

Next, we loop through the result_tweets array and create a new array by counting the total tweets for each username. Finally, we display the resulting retweet counts with usernames. We can pick the winners automatically by sorting this array.

We are limiting the result set to 500 tweets. Limiting the number of tweets in result set will also be an advantage to our application. Because it will only use the latest 500 tweets of the contest. So the users can’t just create tweets and sit back. They have to tweet continuously to get into the latest 500 tweets before contest is completed.

We have completed the implementation of the Twitter hashtag contest and now it’s time for you to check it out.

You can access the demo here and download the source code here.

Create a few tweets and try to get as many retweets as possible. Make sure to use content related to this tutorial for tweeting. Then visit here to view the results.

Limitations

This application was developed to introduce you to the contest with Twitter API, but of course it does have some limitations. To run live contests you would need to carefully consider and solve these limitations. Limitations include:

  • Users need to be kept in database instead of just using a browser session to store values.

  • We need to implement spam filters to remove any spammy tweets using our hashtags.

  • Currently, we are considering all tweets with the given hashtags. Ideally, we should only consider those tweets created by registered users.

  • Exception handling needs to be implemented to provide error messages to users.

  • PHP shouldn’t output this much HTML code – unless the contest app is a throwaway app, you should probably use a framework and rely on views and templates to keep the code structured

Once you solve the above limitations, this application can be used to create real Twitter contests. You can also change the rules and winning criteria by considering other Twitter API features.

Conclusion

Once you get used to Twitter contest development, it becomes very easy to generate unique types of contests with a wide range of Twitter API functions. I recommend trying the following contests in order to master the subject, and begin generating higher traffic and promoting your application.

  • Build a follow and win contest – First, users need to follow a given Twitter profile to enter the contest. Then you can create a tweet asking others to follow. The winner can be selected based on the highest number of followers from the users’ followers list.

  • Build a List contest – First ask the users to authenticate themselves and create a list about a given topic. Then let users promote their list through tweets. The winner can be selected based on the largest number of subscribers in a list.

Now it’s time to use the demo and get started on Tweeting about this tutorial. All your suggestions and comments are welcome. I’m looking forward to reading your tweets!

Rakhitha NimeshRakhitha Nimesh
View Author

Rakhitha Nimesh is a software engineer and writer from Sri Lanka. He likes to develop applications and write on latest technologies. He is available for freelance writing and WordPress development. You can read his latest book on Building Impressive Presentations with Impress.js. He is a regular contributor to 1stWebDesigner, Tuts+ network and SitePoint network. Make sure to follow him on Google+.

apiauthorizationcontesthashtagoauthoauth2PHPtweettwitter
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week