LoginSignup
6
7

More than 5 years have passed since last update.

PHPからMastodon APIを使って投稿する

Last updated at Posted at 2017-05-05

PHPでMastodonのAPI Client(あるいはSDK)を書いてみたので、紹介をします ヾ(〃><)ノ゙

この記事を書いたのは高橋会長(@takahashim)のMastodon API gemを使って投稿するにインスパイヤされて。

インストール

BaguettePHP/mastodon-api: Mastodon API Client for PHPは開発中で全部のAPIが網羅されてるわけじゃないけど、投稿APIはあるので投稿はできます。

対応してるPHPのバージョンは5.5以上です。残念ながら5.4系では動きません。

最近のモダンなPHPを意識して書いてるので、インストールにはComposerが必要です。Composerがなければ、Download Composerの通りに手元に持ってきてくださいね。

ここではサンプルコードなので、特定のPHPプロジェクトではなくグローバルインストールしてみることにします。

php composer.phar global require
Changed current directory to /Users/megurine/.composer
Using version ^0.0.1 for zonuexe/mastodon-api
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 3 installs, 0 updates, 0 removals
  - Installing respect/validation (1.1.12): Loading from cache
  - Installing zonuexe/objectsystem (0.6.0): Loading from cache
  - Installing zonuexe/mastodon-api (0.0.1): Loading from cache
respect/validation suggests installing egulias/email-validator (Strict (RFC compliant) email validation)
respect/validation suggests installing malkusch/bav (German bank account validation)
respect/validation suggests installing symfony/validator (Use Symfony validator through Respect\Validation)
respect/validation suggests installing zendframework/zend-validator (Use Zend Framework validator through Respect\Validation)
respect/validation suggests installing fabpot/php-cs-fixer (Fix PSR2 and other coding style issues)
Writing lock file
Generating autoload files

はい、自分のホームディレクトリにインストールできましたね。

設定

.envってファイルに情報を書き込みます。適当にぐぐってアプリケーションを作成してください。ぐぐれ。

.env
APP_NAME="PhpMastodon Test"
USERNAME="mail@example.com"
PASSWORD="password"
CLIENT_ID="xxxxxxxxxxxxxxxxxxxxx"
CLIENT_SECRET="yyyyyyyyyyyyyyyyyyyy"

注意

ここで紹介する.envファイルを使った設定は検証用のカンタンな仕組みだから、Webアプリとかで利用するときは十分に注意してね。

書き込んでみる

<?php
require_once getenv('HOME') . '/.composer/vendor/autoload.php';
use Baguette\Mastodon as m;
error_reporting(E_ALL);

$config = new m\Config\DotEnvStorage(__DIR__ . '/.env', ['read_only' => false]);
$client = $config->getClientIdAndSecret();
$service = m\session(
    'pawoo.net', $client['client_id'], $client['client_secret'],
    [
        'scope' => 'read write follow',
        'grant' => $config->getUsernameAndPassword(),
        'authorization' => $config->getAuthorization(),
    ]
);

// .env ファイルにアクセストークンがなかったときに勝手に書き込んでくれるよ
$config->setAuthorizationFromObject($service->session->authorize());
$config->save();

// やっほーって書き込むよ
$service->postStatus(m\toot('やっほー'));

簡単でしょ?

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7