• This repository has been archived on 21/Nov/2023
  • Stars
    star
    115
  • Rank 305,916 (Top 7 %)
  • Language
    PHP
  • License
    MIT License
  • Created almost 11 years ago
  • Updated about 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Asynchronous Twitter client compatible with mpyw/co Generator-based flows.

cowitter Build Status Code Coverage Scrutinizer Code Quality

Asynchronous Twitter client compatible with mpyw/co Generator-based flows.

PHP โ“ Feature Restriction
7.0~ ๐Ÿ˜„ Full Support
5.5~5.6 ๐Ÿ˜ง Generator is not so cool
~5.4 ๐Ÿ’ฅ Incompatible

Installing

composer require mpyw/cowitter:^1.0

Tutorial

  1. Preparation
  2. Example: Application for your own personal use
  3. Example: Sign in with Twitter
  4. Example: Commandline streaming readers
  5. Example: Account activity webhook setup and usage

Quick examples

Prepare requirements

require __DIR__ . '/vendor/autoload.php';

use mpyw\Co\Co;
use mpyw\Co\CURLException;
use mpyw\Cowitter\Client;
use mpyw\Cowitter\HttpException;

Create client

$client = new Client(['CK', 'CS', 'AT', 'ATS']);

Synchronous requests

// Search tweets
$statuses = $client->get('search/tweets', ['q' => 'cowitter'])->statuses;
var_dump($statuses);
// Update tweet
$client->post('statuses/update', ['status' => 'Cowitter is the best twitter library for PHP!']);
// Send direct message with new API
$params = [
            'event' => [
                'type' => 'message_create',
                'message_create' => [
                    'target' => [
                        'recipient_id' => 'RECIPIENT_USER_ID'
                    ],
                    'message_data' => [
                        'text' => 'Hello World!',

                    ]
                ]
            ]
        ];
// Post as json
$client->postJson('direct_messages/events/new ', $params);
// Update tweet with multiple images
$ids = [
    $client->postMultipart('media/upload', ['media' => new \CURLFile('photo01.png')])->media_id_string,
    $client->postMultipart('media/upload', ['media' => new \CURLFile('photo02.jpg')])->media_id_string,
];
$client->post('statuses/update', [
    'status' => 'My photos',
    'media_ids' => implode(',', $ids),
]);
// Listen user streaming
$client->streaming('user', function ($status) {
    if (!isset($status->text)) return;
    printf("%s(@%s) - %s\n",
        $status->user->name,
        $status->user->screen_name,
        htmlspecialchars_decode($status->text, ENT_NOQUOTES)
    );
});

Asynchronous requests

// Search tweets
Co::wait(function () use ($client) {
    $statuses = (yield $client->getAsync('search/tweets', ['q' => 'cowitter']))->statuses;
    var_dump($statuses);
});
// Rapidly update tweets for 10 times
$tasks = [];
for ($i = 0; $i < 20; ++$i) {
    $tasks[] = $client->postAsync('statuses/update', [
        'status' => str_repeat('!', $i + 1),
    ]);
}
Co::wait($tasks);
// Rapidly update tweet with multiple images
Co::wait(function () use ($client) {
    $info = yield [
        $client->postMultipartAsync('media/upload', ['media' => new \CURLFile('photo01.png')]),
        $client->postMultipartAsync('media/upload', ['media' => new \CURLFile('photo02.png')]),
    ];
    yield $client->postAsync('statuses/update', [
        'status' => 'My photos',
        'media_ids' => implode(',', array_column($info, 'media_id_string')),
    ]);
});
// Listen filtered streaming to favorite/retweet at once each tweet
Co::wait($client->streamingAsync('statuses/filter', function ($status) use ($client) {
    if (!isset($status->text)) return;
    printf("%s(@s) - %s\n",
        $status->user->name,
        $status->user->screen_name,
        htmlspecialchars_decode($status->text, ENT_NOQUOTES)
    );
    yield Co::SAFE => [ // ignore errors
        $client->postAsync('favorites/create', ['id' => $status->id_str]),
        $client->postAsync("statuses/retweet/{$status->id_str}"),
    ];
}, ['track' => 'PHP']));
// Rapidly update with MP4 video
Co::wait(function () use ($client) {
    $file = new \SplFileObject('video.mp4', 'rb');
    $on_uploading = function ($percent) {
        echo "Uploading ... ({$percent}%)\n";
    };
    $on_processing = function ($percent) {
        echo "Processing ... ({$percent}%)\n";
    };
    yield $client->postAsync('statuses/update', [
        'status' => 'My video',
        'media_ids' => (yield $client->uploadVideoAsync($file, 'tweet_video', $on_uploading, $on_processing))->media_id_string,
    ]);
    echo "Done\n";
});

Handle exceptions

try {

    // do stuff here
    $client->get(...);
    $client->post(...);

} catch (HttpException $e) {

    // cURL communication successful but something went wrong with Twitter APIs.
    $message = $e->getMessage();    // Message
    $code    = $e->getCode();       // Error code (-1 if not available)
    $status  = $e->getStatusCode(); // HTTP status code

} catch (CURLException $e) {

    // cURL communication failed.
    $message = $e->getMessage();    // Message    (equivalent to curl_error())
    $code    = $e->getCode();       // Error code (equivalent to curl_errno())

}

or

try {

    // do stuff here
    $client->get(...);
    $client->post(...);

} catch (\RuntimeException $e) {

    // Something failed.
    $message = $e->getMessage();

}

Avoiding SSL errors due to the old libcurl version

If you encountered SSL certificate problem error...

  1. Download the latest cacert.pem from official libcurl site.
    https://curl.haxx.se/docs/caextract.html
  2. Please choose either of the following solutions.

2-A: Configure globally

Specify the path as curl.cainfo in your php.ini.

curl.cainfo="C:\foo\bar\baz\cacert.pem"

DO NOT forget restarting Apache.

2-B: Configure locally

Specify the path as CURLOPT_CAINFO. Using the magic constant __DIR__ is recommended.

$client = new Client(['CK', 'CS', 'AT', 'ATS'], [CURLOPT_CAINFO => __DIR__ . '/cacert.pem']);

or

$client = new Client(['CK', 'CS', 'AT', 'ATS']);
$client = $client->withOptions([CURLOPT_CAINFO => __DIR__ . '/cacert.pem']);

Details

Read interfaces.

Todos

  • Documentation
  • Improving codes

More Repositories

1

axios-case-converter

Axios transformer/interceptor that converts snake_case/camelCase
TypeScript
160
star
2

co

Asynchronous cURL executor simply based on resource and Generator.
PHP
136
star
3

php-hyper-builtin-server

Reverse proxy for PHP built-in server which supports multiprocessing and TLS/SSL encryption
PHP
106
star
4

laravel-cached-database-stickiness

Guarantee database stickiness over the same user's consecutive requests
PHP
82
star
5

eloquent-has-by-non-dependent-subquery

Convert has() and whereHas() constraints to non-dependent subqueries.
PHP
80
star
6

comphar

Pack all composer dependencies into a single phar file.
PHP
73
star
7

hub-purge

Clear GitHub image caches on README
Shell
36
star
8

FILTER_VALIDATE_EMAIL.js

TypeScript/JavaScript Email validation compatible with PHP's filter_var($value, FILTER_VALIDATE_EMAIL)
TypeScript
26
star
9

eloquent-has-by-join

Convert has() and whereHas() constraints to join() ones for single-result relations.
PHP
24
star
10

EasyCrypt

A class that provides simple interface for decryptable encryption.
PHP
23
star
11

laravel-local-class-scope

A tiny macro that reuse a global scope class as a local scope
PHP
23
star
12

aws-lambda-billing-slack-notification

Node.js 14 ไปฅ้™ๅ‘ใ‘ใฎ AWS ๅฝ“ๆœˆๅˆฉ็”จๆ–™้‡‘ Slack ้€š็Ÿฅใ‚นใ‚ฏใƒชใƒ—ใƒˆ
TypeScript
22
star
13

laravel-database-advisory-lock

Advisory Locking Features for Postgres/MySQL/MariaDB on Laravel
PHP
22
star
14

null-auth

Null Guard for Laravel. Designed for Middleware-based authentication and testing.
PHP
19
star
15

cloudwatch-front-logger

Save your browser console logs to AWS CloudWatch (Inspired by agea/console-cloud-watch)
TypeScript
17
star
16

phpunit-patch-serializable-comparison

Fixes assertSame()/assertEquals() serialization errors running in separate processes.
PHP
14
star
17

laravel-retry-on-duplicate-key

Automatically retry non-atomic upsert operation when unique key constraints are violated.
PHP
13
star
18

compoships-eager-limit

topclaudy/compoships + staudenmeir/eloquent-eager-limit
PHP
12
star
19

scoped-auth

Apply specific scope for user authentication.
PHP
10
star
20

laravel-mysql-system-variable-manager

A tiny extension of MySqlConnection that manages session system variables
PHP
10
star
21

sqlc-restruct

Post-processor for kyleconroy/sqlc
Go
8
star
22

twhelp

Twitter OAuth CLI Helper distributed by Golang cross-compilation.
Go
8
star
23

sharable-value-objects

Share value objects that contain the same primitive value as a singleton
PHP
7
star
24

uuid-ulid-converter

UUID <=> ULID bidirectional converter
PHP
7
star
25

laravel-packages

Library packages list for Laravel
7
star
26

laravel-database-mock

[Experimental] Database Mocking Library which mocks PDO underlying Laravel Connection classes
PHP
6
star
27

sql-http-proxy

Go
5
star
28

exceper

Provides temporary error handler automatically using set_error_handler() and restore_error_handler().
PHP
5
star
29

my-bookmarklet-collection

5
star
30

BaseUTF8

BaseXX encoder/decoder which support any valid UTF-8 sequences.
PHP
4
star
31

privator

Utils for testing private methods and properties on PHP 7.0+
PHP
3
star
32

noerr

Safe property reference chaining without errors
JavaScript
3
star
33

streamable-console

Call interactive artisan command using arbitrary stream instead of STDIN.
PHP
3
star
34

zenn

Zenn ใฎ่จ˜ไบ‹ไฟ็ฎกๅ ดๆ‰€
3
star
35

docker-clean

Remove all dangling images, volumes, networks and randomly named containers
Shell
2
star
36

mockery-pdo

[Experimental] BDD-style PDO Mocking Library for Mockery
PHP
2
star
37

laravel-pdo-emulation-control

Temporarily enable/disable PDO prepared statement emulation
PHP
2
star
38

mpyw

@mpyw's profile
2
star
39

most-similar

Search most similar word from stdin.
C
1
star
40

unique-violation-detector

Detect primary/unique key or constraint violation errors from PDOException.
PHP
1
star
41

amazon-vod-preset-convert-docker

Docker for https://github.com/aws-samples/amazon-vod-preset-convert
Dockerfile
1
star
42

laravel-unique-violation-detector

Detect primary/unique key or constraint violation errors from PDOException.
PHP
1
star
43

oh-my-zsh-lukerandall-extended

oh-my-zsh lukerandall theme which supports extended features
Shell
1
star
44

suve

Interact with AWS Secrets Manager and Parameter Store
Go
1
star
45

laravel-file-errors

A tiny extension that reports validation error details about uploaded files
PHP
1
star
46

FILTER_VALIDATE_EMAIL.html

HTML Pattern Attribute Validation compatible with PHP's filter_var() and mpyw/FILTER_VALIDATE_EMAIL.js
1
star