redwebcreation/twitter-stream-api
Composer 安装命令:
composer require redwebcreation/twitter-stream-api
包简介
Consume the Twitter Stream API in real-time.
关键字:
README 文档
README
Consume the Twitter Stream API v2 in real-time.
This package is the spiritual successor of fennb/phirehose. It also uses some of salsify/jsonstreamingparser and maxakawizard/json-collection-parser.
Getting started
You need an approved developer account. If you don't have one, apply here. Once you are in, create an "Application" in the Developer Portal and generate a new bearer token.
Requires PHP 8.1+
You can install the package via composer:
composer require redwebcreation/twitter-stream-api
Then, create a connection:
$connection = new \Felix\TwitterStream\TwitterConnection( bearerToken: '...' # the one you got from the Developer Portal );
Usage
Streams
Creating a stream
$stream = new \Felix\TwitterStream\Streams\VolumeStream(); // or $stream = new \Felix\TwitterStream\Streams\FilteredStream();
Configuring a stream
withTweetLimit(int)- Limit the number of tweets a connection should process$stream->withTweetLimit(100_000);
fields(string[])- See Fieldsexpansions(...string)- See Expansions
For advanced use
withBufferSize(int = 85)- How many bytes should the parser store before trying to parse the JSON, on very high-volume streams, using a larger buffer size is recommended (2500, 10000, depending on the volume). Setting to a big value > 2000 on a low-volume stream would result in 0 tweets being processed until there are enough tweets in the buffer.
Interacting with a stream
stopListening()- Stops listening to the stream.createdAt(): int- The UNIX timestamp at which you started listeningtimeElapsedInSeconds(): int- How much time passed since you started listeningtweetsReceived(): int- How much the stream sent
For advanced use
response(): Psr\Http\Message\ResponseInterface- The response sent by Twitter
Listening to a stream
$stream->listen($connection, function (object $tweet) { echo $tweet->data->text . PHP_EOL; });
Filtering the stream
This part only applies if you're interested in the filtered stream.
Building a rule
Note, If you change your rules while connected to the stream, Twitter will use the new rules immediately.
Save, read and delete rules
You can not update rules.
use Felix\TwitterStream\Rule\RuleManager; $rule = new RuleManager($connection);
Let's create a rule:
$rule->save( # tweets must contain the word cat and have at least one image "cat has:images", "images of cats" );
You may now retrieve your newly saved rule:
$rule->all();
Which returns an array of Felix\TwitterStream\Rule\Rule:
[ 0 => Felix\TwitterStream\Rule\Rule{ +value: "cat has:images", +tag: "images of cats", +id: "4567654567654567654" } ]
Note, the
Felix\TwitterStream\Rule\Ruleis merely a Data Object, it does not contain any method.
To delete the rule pass its ID to the delete method:
$rule->delete('4567654567654567654');
Batch Processing
To save many rules at once:
use Felix\TwitterStream\Rule\Rule; $rule->saveMany([ new Rule("cats has:images", "cat pictures"), new Rule("dogs has:images", "dog pictures"), new Rule("horses has:images", "horse picture"), ]);
To delete these new rules,
$rule->delete([ '[RULE ID]', '[RULE ID]', '[RULE ID]', ]);
Validating your rules
You can either use the validate() method:
# returns a list of errors $errors = $rule->validate('cats ha:images');
Or, the save and saveMany method both have a dryRun parameter:
$rule->save('...', '...', dryRun: true); $rule->saveMany([...], dryRun: true);
Rule Builder
Every operator is available, here's an example:
$rule->new('listening to music') ->raw('#nowplaying') ->isNotRetweet() ->lang('en') ->save();
You may also use and[Operator], or[Operator], for example orNotFrom('ID') or andBioLocation('location').
Compiling this would produce the following:
#nowplaying -is:retweet lang:en sample:10
Tips
- To directly add a string to the rule, use
raw(string) - You may call
dump()ordd()to quickly debug your rule. andis the default operator, you may omit it. For example,andIsNotRetweet()is the same asisNotRetweet().
Fields
Fields allow for more customization regarding the payload returned per tweet. Let's see that in an example below:
$stream ->fields([ 'tweet' => 'author_id' // or, // 'tweet' => ['author_id', '...'] ]) ->listen(...);
Which could return:
{
"data": {
"id": "1234321234321234321",
"text": "Hello world!",
"author_id": "5678765678765678765"
}
}
Here's the list of all the available field types and their respective object model (last updated: Aug. 2022):
- Tweet
- User
- Media
- Poll
- Place
You can also check out Twitter’s documentation for more details.
Expansions
Expansions let you expand ids to their complete object, for example, if you request an extra author_id field, you may expand it using the author_id expansion:
$stream ->fields(['tweet' => 'author_id']) ->expansions('author_id') ->listen(...);
Which could return:
{
"data": {
"id": "1234321234321234321",
"text": "Hello world!",
"author_id": "5678765678765678765"
},
"includes": {
"users": [
{
"id": "5678765678765678765",
"name": "John Doe",
"username": "johndoe"
}
]
}
}
The list of expansions is quite extensive and not all expansions work the same, please check out Twitter's documentation. on the subject.
Testing
composer test
Twitter Stream API was created by Félix Dorn under the MIT License.
redwebcreation/twitter-stream-api 适用场景与选型建议
redwebcreation/twitter-stream-api 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 20.77k 次下载、GitHub Stars 达 32, 最近一次更新时间为 2021 年 05 月 07 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「php」 「api」 「twitter」 「phirehose」 「streaming」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 redwebcreation/twitter-stream-api 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 redwebcreation/twitter-stream-api 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 redwebcreation/twitter-stream-api 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Handles basic OAuth/OAuth2 authentication along with classes for common services
Simple Twitter API wrapper
Simple Sharing generates social media share links within CP entry pages, allowing you to quickly & easily share entries.
A PSR-7 compatible library for making CRUD API endpoints
A helper module for pdf-print, print and social share functionality based on bootstrap to custom modules.
Laravel package for the simplification and integration of many of your users most wanted login providers. Installation is a breeze. Never worry about OAuth again.
统计信息
- 总下载量: 20.77k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 32
- 点击次数: 6
- 依赖项目数: 1
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2021-05-07