Twitter のダイレクトメッセージ API 新仕様に TwitterOAuth で対応する方法
Twitter のダイレクトメッセージ API の仕様が変わり、従来のエンドポイントは2018年8月16日 (米国時間) で廃止されることになっています。
» Account Activity APIを全ての開発者の皆さんに公開
PHP のライブラリとしてよく使用されている TwitterOAuth は、数週間前に新仕様に対応したバージョンがリリースされていました。ここではその TwitterOAuth を使用してダイレクトメッセージを送信する方法を紹介します。なお、新仕様に対応するにはバージョン v0.9.0 以降を使用する必要があります。
ダイレクトメッセージを送信する場合
エンドポイントは従来の direct_messages/new から direct_messages/events/new に変わります。API に POST するパラメータも大きく変わっています。また、 post() メソッドの第3引数を true にすることを忘れないようにしてください。
use Abraham\TwitterOAuth\TwitterOAuth;
$connection = new TwitterOAuth('CONSUMER_KEY', 'CONSUMER_SECRET', 'ACCESS_TOKEN', 'ACCESS_TOKEN_SECRET');
$connection->post('direct_messages/events/new', [
'event' => [
'type' => 'message_create', // 固定値 (必須)
'message_create' => [
'target' => [
'recipient_id' => $userId // 送信先ユーザーID (必須)
],
'message_data' => [
'text' => '送信したいメッセージ'
] // メッセージデータ (必須)
]
]
], true); // 必ず true
写真付きのダイレクトメッセージを送信する場合
従来通り upload() メソッドを使用してからダイレクトメッセージを送信します。ダイレクトメッセージ送信時と同様のパラメータを用意し、 message_data に以下のように attachment を追加します。
$media = $connection->upload('media/upload', [
'media' => 'アップロードしたい画像ファイルのパス',
]);
$connection->post('direct_messages/events/new', [
'event' => [
'type' => 'message_create',
'message_create' => [
'target' => [
'recipient_id' => $userId,
],
'message_data' => [
'text' => '送信したいメッセージ', // attachment のみでもよい
'attachment' => [
'type' => 'media', // 必須
'media' => [
'id' => $media->media_id // 必須
]
],
],
],
],
], true);
» POST direct_messages/events/new (message_create) — Twitter Developers
» Attaching media — Twitter Developers
コメントを残す