![最终产品图片](https://i-blog.csdnimg.cn/blog_migrate/4bd0a96994b1825487567580a7019746.png)
欢迎! 我知道自从我添加到我们的Twitter API系列以来已经有一段时间了。 我一直很忙。 首先是脑肿瘤 ,然后是机器人放射外科手术 ,然后是正在进行的Yii编程系列及其相关的启动系列 ,最后是Meeting Planner的发布 。
我决定使用Twitter API编写今天的教程,以创建朋友(Twitter称呼您所关注的人)。
为什么? 好吧,2016年美国离奇的大选凸显了Twitter上每天都在发生的一些虐待和骚扰,这对于公司来说几乎没有做过过滤。作为程序员,我们知道这并不难。 它只是担心失去吸引可恶的可悲者的听众,这些可恶者吸引了可观的广告收入。
许多妇女因其骚扰而离开了该服务-Twitter有时对此表示歉意,称其试图允许言论自由。 坦白说,当无限期出现骚扰时,没有言论自由。
也有文章强调了多少人的追随者主要是男性 。 尽管Twitter不会询问用户性别,但它会统计分析其广告客户的帐户性别。
您可以在其分析页面上窥视Twitter广告自身的人口统计估计。 如下所示,Twitter估计我的追随者中有69%是男性。
![使用Twitter API构建-Twitter Analytics性别估算](https://i-blog.csdnimg.cn/blog_migrate/393f9e276f8f05279d08e4df73809539.png)
喧的是,在Twitter上很难找到女人的声音。 但是他们在那里。 皮尤(Pew) 报告说,有21%的女性互联网用户使用Twitter,而25%的男性互联网用户使用Twitter。
![使用Twitter API通过Pew Research进行Twitter人口统计](https://i-blog.csdnimg.cn/blog_migrate/a4855091a234bad65b9deccf92c4e86f.png)
因此,今天我将指导您使用PHP的Yii2框架来访问Twitter API并自动将好友添加到人们的Twitter帐户中。 (如果您想了解更多关于Yii2,看看我们的一系列平行 编程使用Yii2 。)
而且,我已经创建了一个网站Twixxr.com ,通过在Twitter上添加杰出女性作为您的帐户,您可以展示该功能。
如果您有任何问题或反馈,请在下面的评论中发布,或通过Twitter @reifman与我联系 。
回顾:Twitter API教程
过去,我虽然编写了一些Twitter API教程,但它们都是基于Yii 1.x代码的。 Yii2已经存在很长时间了,尽管我已经撰写了有关OAuth登录的文章,但我没有针对您自己的帐户和/或代表已升级框架的经过身份验证的帐户撰写有关API方面的文章。 这并不容易-Twitter还没有很棒的Yii2插件。
今天的教程不仅会指导您使用OAuth验证站点访问者的帐户,而且还将向您展示如何使用他们授予的访问权限将朋友添加到他们的帐户中。
使用TwitterOAuth PHP库
不幸的是,我找不到针对Yii2的可靠的Twitter API扩展,因此我利用通用的Twitter OAuth PHP库创建了自己的Twitter模型。
许多复杂的API都没有提供好的文档,我感谢TwitterOAuth提供的分步实时演练。 这非常有用:
![从TwitterOAuth演练中使用Twitter API步骤构建](https://i-blog.csdnimg.cn/blog_migrate/b64e7bc5e6903494e72cf36d3a7babf6.png)
产品服务目标
Twixxr服务将对站点访问者进行身份验证,然后自动将新朋友添加到他们的帐户中。 朋友将从我在Twitter上确定的600多位有影响力的女性中选出:
![构建Twitter API Twixxr服务主页](https://i-blog.csdnimg.cn/blog_migrate/ee2cdd51ba5ac15c71ba9e8fa57ae69d.png)
让我们开始遍历代码。
验证用户
我的TwitterController.php有两个基本方法,即请求和返回。 这是Request方法:
public function actionRequest()
{
if (Yii::$app->user->isGuest) {
// user has not logged in to yii site
$t = new Twitter();
$url = $t->getAuthorizeUrl();
$this->redirect($url);
} else {
// already verified with us, look up their access keys
$t = new Twitter();
$t->refreshConnection(Yii::$app->user->getId());
$this->goHome();
}
}
在new Twitter();
调用的Twitter.php模型new Twitter();
获得一个唯一的getAuthorizeURL()
以便您将站点访问者重定向到Twitter身份验证页面,例如https://api.twitter.com/oauth/authorize?oauth_token=q-7ChxxxxxxxxxxxnpXAAABzzzzzzz6E :
![使用Twitter API进行OAuth授权重定向](https://i-blog.csdnimg.cn/blog_migrate/13495feb6cfa0601d237996ba50d81b0.png)
一旦用户在Twitter上授权了您的应用程序,它们就会被重定向回我们的Return方法:
public function actionReturn()
{
// returning from authentication
/* If the oauth_token is old redirect to the connect page. */
if (isset($_REQUEST['oauth_token']) && Yii::$app->session['oauth_token'] !== $_REQUEST['oauth_token']) {
Yii::$app->session['oauth_status'] = 'oldtoken';
return $this->goHome();
}
$t = new Twitter();
$user_id = $t->getConnection($_REQUEST['oauth_verifier']);
$person = new \common\models\User;
$identity = $person->findIdentity($user_id);
$u = User::findOne($user_id);
if ($identity->validateAuthKey($u->auth_key)) {
Yii::$app->user->login($identity);
}
$this->redirect(['twixxr/amplify']);
}
Twitter模型使用您的应用程序使用者密钥和使用者密钥,这些密钥是在向服务注册时收到的 :
<?php
namespace frontend\models;
use Yii;
use yii\base\Model;
use common\models\User;
use frontend\models\Auth;
use Abraham\TwitterOAuth\TwitterOAuth;
/**
* This is the model class for table "payment".
*
* @property integer $id
* @property integer $user_id
* @property string $amount
* @property integer $created_at
* @property integer $updated_at
*
* @property User $user
*/
class Twitter extends Model {
public $consumerKey;
public $consumerSecret;
public $connection;
public function init() {
$this->consumerKey = Yii::$app->components['authClientCollection']['clients']['twitter']['consumerKey'];
$this->consumerSecret = Yii::$app->components['authClientCollection']['clients']['twitter']['consumerSecret'];
}
然后,上面显示的Return方法将注册用户并存储该帐户的长期访问密钥-这使您可以无限期地代表他们进行API调用:
public function getConnection($oauth_verifier='') {
$connection = new TwitterOAuth($this->consumerKey, $this->consumerSecret,Yii::$app->session['oauth_token'],Yii::$app->session['oauth_token_secret']);
/* Create TwitteroAuth object with app key/secret and token key/secret from default phase */
$access_token = $connection->oauth("oauth/access_token", ["oauth_verifier" => $oauth_verifier]);
/* Save the access tokens. Normally these would be saved in a database for future use. */
$user_id=$this->register($access_token);
//Yii::$app->session['access_token'] = $access_token;
/* Remove no longer needed request tokens */
unset(Yii::$app->session['oauth_token']);
unset(Yii::$app->session['oauth_token_secret']);
$this->connection = new TwitterOAuth($this->consumerKey, $this->consumerSecret, $access_token['oauth_token'], $access_token['oauth_token_secret']);
return $user_id;
}
public function register($access_token) {
$screen_name = $access_token['screen_name'];
$source_id = $access_token['user_id'];
$user = User::find()->where(['username'=>$screen_name])->one();
if (is_null($user)) {
// sign them up
$user = new User();
$user->username = $screen_name;
$user->email = $screen_name.'@twixxr.com';
$user->setPassword(Yii::$app->security->generateRandomString(12));
$user->generateAuthKey();
$user->save();
}
$auth = Auth::find()->where(['source_id'=>$source_id])->one();
if (is_null($auth)) {
// add an auth entry
$auth = new Auth();
$auth->user_id = $user->id;
$auth->source = 'twitter';
$auth->source_id = $source_id;
$auth->screen_name = $user->username;
$auth->oauth_token = $access_token['oauth_token'];
$auth->oauth_token_secret = $access_token['oauth_token_secret'];
$auth->x_auth_expires =0;
$auth->save();
} else {
$auth->oauth_token = $access_token['oauth_token'];
$auth->oauth_token_secret = $access_token['oauth_token_secret'];
$auth->update();
}
return $user->id;
}
为了对他们的帐户进行读写访问,我从“ 启动系列”的“使用OAuth简化Onramp”中描述的简单身份验证访问扩展了Auth表,以包括这些额外的验证密钥。
我也鼓励您逐步通过TwitterOAuth进行现场直播。 这是一个很好的示例,展示了您自己的Twitter帐户的所有运行情况。
导入名称,个人档案和照片
接下来,我创建了一个Twixxr.php模型,该模型将提供该服务特定的各种重要功能。 首先,我创建了Twixxr::loadProfiles()
来同步在我的静态“商品”数据库中标识的每个女性的姓名,个人简介和Twitter相关计数,例如个人资料照片,状态信息,关注者,关注者。
public function loadProfiles() {
// clean Item table
$this->cleanup();
$t = new Twitter();
$t->refreshConnection(1); // for admin user = 1
$time_stale = time()-(24*3600);
$people = Item::find()
->where('updated_at<'.$time_stale)
->orWhere('updated_at=created_at')
->orderBy('rand()')->all();
$cnt=0;
foreach ($people as $i) {
// to do - or if updated at is stale
if ($i->detail=='') {
$result = $t->getUsersShow($i->path);
echo $i->path.', ';
if (isset($result->errors)) {
var_dump($result);
continue;
}
if (isset($result->name)) {
$i->title = Html::encode($this->removeEmoji($result->name));
if ($i->title=='') {
$i->title='n/a';
}
}
if (isset($result->screen_name)) {
$i->path = $result->screen_name;
}
if (isset($result->description)) {
$i->detail=Html::encode($this->removeEmoji($result->description));
}
if (isset($result->profile_image_url_https)) {
$i->image_url = $result->profile_image_url_https;
}
$i->validate();
var_dump($i->getErrors());
$i->update();
SocialProfile::fill($i->id,$result);
$cnt+=1;
if ($cnt>25) exit;
}
}
}
这由控制台cron作业调用,我将在后面的Yii2系列文章中进行介绍 。 因此,这些配置文件在几天内以特定间隔逐渐重复地同步。
跟随:建立友谊
我不会在这里详细说明,但是基本上我创建了一个针对每个用户和女性帐户的单个请求的日志表。 换句话说,塞缪尔将有500个条目,要求数据库中的每个女人增加友谊。
不过,首先,我要确保Samuel(以及Twixxr的每个用户)都遵循Twixxr_com帐户 。
$result = $t->createFriend('twixxr_com');
$total_request+=1;
if ($result !== false) {
$action->status = Log::STATUS_COMPLETE;
$action->save();
}
在cron作业处理这些命令之前,它将在适当的阶段刷新Samuel和每个用户的Twitter授权和连接:
$t->refreshConnection($action->user_id);
然后,这是Twitter::createFriend($screen_name)
方法:
public function createFriend($username) {
$add = $this->connection
->post("friendships/create", ["screen_name" => $username]);
if ($this->connection->getLastHttpCode() == 200) {
// successful
return $add;
} else {
// Handle error case
return false;
}
}
然后,对Log表格中详细说明的Samuel要求的所有女性执行此操作-当然,下面发生了很多事情,我将对其进行描述:
echo 'add '.$person->path.' to '.$action->user_id.'<br />';
if ($x>7) {
$mode ='limited';
echo 'Limited to max requests per user<br />';
// skip this user and go to next one...
continue; // on to next user
}
$followed_by = $t->getFriendshipsShow($u->username,$person->path);
if ($followed_by == -10) {
echo 'rate limit error<br />';
$mode ='limited';
// skip this user and go to next one...
continue; // on to next user
} else if ($followed_by==0) {
$x+=1;
echo 'request follow<br />';
$result = $t->createFriend($person->path);
$total_request+=1;
if ($result !== false) {
$action->status = Log::STATUS_COMPLETE;
$action->completion_at = time();
$action->save();
} else {
echo 'skip due to error';
$action->status = Log::STATUS_SKIP_ERROR;
$action->completion_at = time();
$action->save();
}
} else {
echo 'already followed<br /><br />';
$action->status = Log::STATUS_SKIPPED;
$action->save();
}
}
Twitter的API具有严格的速率限制,因此有时很难使用它们的API。 上面的cron作业一次创建了七个目标帐户的友谊,然后切换到另一个用户的请求,直到稍后再次调用。
这是Twitter::getFriendshipsShow()
,它检查该帐户是否已经在遵循所需的帐户。 在上面的代码中,它跳过了多余的请求,以节省速率限制。
public function getFriendshipsShow($source_name,$target_name) {
$result = $this->connection->get("friendships/show", ["source_screen_name" => $source_name,"target_screen_name" => $target_name]);
if (isset($result->errors)) {
if ($result->errors[0]->message=='Rate limit exceeded') {
return -10;
}
} else {
if (isset($result->relationship->target->followed_by)) {
if ($result->relationship->target->followed_by) {
return 1;
} else {
return 0;
}
}
}
return -1;
}
在不久的将来,我将为此实现Twitter的批量API ,使用get / friendships / lookup仅进行一次调用,而不是每个用户进行数百次调用。 请注意,您将需要一个开发人员帐户才能访问此页面。
取消关注:破坏友谊
您还可以通过API撤消这些友谊:
$statuses = $connection->post("friendships/destroy", ["screen_name" => $u]);
我正在记录Twixxr建立的每个连接,如果Twitter的API速率限制不那么繁琐和耗时,我将允许访问者使用Twixxr的撤消功能,如果他们不喜欢所有新产品,则取消关注所有女性帐户。
性能
我在Twixxr中做了很多工作来管理性能。 基本上,我构建了Log表来快速记录用户请求的所有友谊。 但是所有这些都是在后台处理的。
不幸的是,Twitter API不允许发布要批量跟踪的帐户列表。 当用户在您的站点上时,根本无法实时做到这一点。
因此,用户对Twixxr请求的响应是立即的,但是要遵循所有帐户可能要花费几个小时或更长时间。
这是TwixxrController.php follow All方法:
public function actionAll()
{
// make request for authenticated user to follow all twitter profiles
$x = new Twixxr();
$x->followTwixxr(Yii::$app->user->getId());
$x->followAll(Yii::$app->user->getId());
Yii::$app->getSession()->setFlash('success', Yii::t('frontend','Your request has been added to our queue.'));
$this->redirect(['twixxr/complete',['task'=>'all']]);
// redir home
}
这是Twixxr::followAll
和followCount
方法,上面的编号按钮也使用followCount
方法,用于跟踪100、200、300位女性,等等。
public function followAll($user_id) {
$allWomen = Item::find()->count();
$this->followCount($user_id,$allWomen);
}
public function followCount($user_id,$cnt=100) {
$women = Item::find()->orderBy('rand()')->limit($cnt)->all();
foreach ($women as $w) {
$l = Log::find()
->where(['user_id'=>$user_id,'item_id'=>$w->id])
->one();
if (!is_null($l)) {
$l->status = Log::STATUS_PENDING;
$l->update();
} else {
$l = new Log();
$l->user_id = $user_id;
$l->item_id = $w->id;
$l->event_id = Twixxr::EVENT_ADD;
$l->status = Log::STATUS_PENDING;
$l->save();
}
}
}
他们只是为每个友谊请求创建日志条目,以使cron作业在后台处理。
下一步是什么?
希望您喜欢在Yii2中使用TwitterOAuth.php,以及如何代表您的站点用户授权和应用Twitter API。
接下来,我想使用Twitter API分析自己的关注者。 我怀疑绝大多数Twitter关注者都是垃圾机器人,并且我想使用API来证明这一点。 敬请关注。
如果您有任何问题或建议,请在评论中发布。 如果您想了解我将来的Envato Tuts +教程和其他系列,请访问我的讲师页面或关注@reifman 。 一定要检查一下我的启动系列和Meeting Planner 。
相关链接
- 特威克斯
- 如何使用Yii2系列进行编程(Envato Tuts +)
- Yii2开发者交流 ,我的Yii2资源网站
- 如何使用yii2-authclient使用单访问令牌与Twitter通信(Yii文档)
- Twitter开发人员文档
- Twitter OAuth PHP库