redis hashtag
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.
在本系列的第一部分中,我们在Twitter上研究了各种类型的竞赛,并选择开发一个主题标签竞赛,因为它是最受欢迎的竞赛类型之一,并且不依赖运气。 到目前为止,我们已经使用Twitter应用程序对用户进行了身份验证。 今天,我们将继续为用户实现推文功能。
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.
我们的首要任务是将用户的详细信息分配到浏览器会话中,从而允许用户多次鸣叫,而无需为每条鸣叫授权应用程序。 以下代码将详细信息添加到会话中,并初始化tweet屏幕。
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.
让我们看一下使用HTML表单的tweet屏幕的实现。
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.
现在,用户可以使用简单HTML表单提交推文。
(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:
用户提交表单后,我们需要使用此提交的内容在其Twitter个人资料上自动创建推文。 我们需要使用以下内容更新控制器代码:
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.
这将拦截POST请求并添加推文内容。 我们将使用一个名为createTweet
的函数来访问Twitter API,如下所示。
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.
正如我们在计划部分讨论的那样,每个推文都将使用两个名为#SPC
和#twcontesttutorial
主题标签。 接下来,我们将检查推文内容中的错误。 成功验证之后,我们将使用initializeTwitterObject
函数创建Twitter库对象,如以下代码所示。
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
.
在这种情况下,将使用user_token
和user_secret
初始化该对象,而不仅仅是使用consumer_key
和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.
接下来,我们使用1.1/statuses/update
API URL执行tweet请求。 我们使用status参数将用户提交的文本与#标签一起传递。 请求成功后,我们会向用户显示消息以完成该过程。
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.
比赛结果将根据转发次数进行计算。 我们必须使用Twitter搜索API函数来获得所需的结果。 让我们看一下更新后的代码。
if(isset($_GET['action']) && $_GET['action'] == 'results'){
$contest->getContestResults();
}
Now we are going to look at the getContestResults
function.
现在我们来看一下getContestResults
函数。
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.
首先,我们定义搜索所需的参数。 搜索查询将是两个标签的组合。 我们还使用-RT
来防止对转发进行计数,因为不应将转发计为从应用程序生成的推文。
count
parameter defines the number of records per page.
count
参数定义每页的记录数。
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.
result_type
参数定义结果集中的推文类型。 它可以具有“混合”,“最近”或“受欢迎”的值。 我们使用'recent'作为result_type
来获取最新的推文。
Next, we call the retrieveTweets
function for generating the results. The following code previews the retrieveTweets
function implementation.
接下来,我们调用retrieveTweets
函数来生成结果。 下面的代码预览了retrieveTweets
函数的实现。
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.
这是用于对推文进行分页搜索的递归函数。 我们使用默认参数调用1.1/search/tweets
API URL,并将所有产生的tweets分配到一个数组中。 我们必须递归调用此函数以生成剩余页面的结果。 因此,我们检查响应中next_results
的可用性,以及我们的结果集是否超过给定的限制。
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.
然后,我们提取max_id
参数并将其分配给搜索参数以生成下一个结果集。 最后,我们递归调用该函数,直到达到结果结尾或500条推文并将其分配给result_tweets
数组。 现在,我们可以返回到getContestResults
函数的其余部分。
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.
接下来,我们遍历result_tweets
数组,并通过计算每个用户名的总tweets来创建一个新数组。 最后,我们用用户名显示结果的转发数。 我们可以通过对该数组进行排序来自动选择获奖者。
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.
我们将结果集限制为500条推文。 限制结果集中的推文数量也将对我们的应用程序有利。 因为它只会使用比赛的最新500条推文。 因此,用户不能只创建推文并坐下来。 他们必须连续进行鸣叫,才能在比赛结束前进入最新的500条鸣叫。
We have completed the implementation of the Twitter hashtag contest and now it’s time for you to check it out.
我们已经完成了Twitter标签竞赛的实施,现在是时候让您查看一下。
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:
开发该应用程序是为了向您介绍使用Twitter API进行比赛的方法,但是它确实有一些局限性。 要进行现场比赛,您需要仔细考虑并解决这些限制。 限制包括:
- 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
PHP不应输出太多HTML代码-除非竞赛应用是一次性应用,否则您应该使用框架并依靠视图和模板来保持代码的结构化
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.
解决以上限制后,即可使用此应用程序创建真实的Twitter竞赛。 您还可以考虑其他Twitter API功能来更改规则和获胜标准。
(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.
一旦您习惯了Twitter竞赛开发,便可以使用多种Twitter API函数轻松生成独特类型的竞赛。 我建议尝试以下竞赛以精通该主题,并开始产生更高的访问量并推广您的应用程序。
- 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.
举办追随竞赛-首先,用户需要按照给定的Twitter个人资料进入竞赛。 然后,您可以创建一条推文,要求其他人关注。 可以根据用户关注者列表中的关注者最多来选择获胜者。 - 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.
建立清单竞赛–首先要求用户进行身份验证并创建有关给定主题的清单。 然后,让用户通过推特推广他们的名单。 可以根据列表中最大的订户数量来选择获奖者。