8
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

HangoutsChatにPHPから投稿してみる

Last updated at Posted at 2018-03-09

HangoutsChatが使えるようになっていたので、Webhookをサクッと試してみました。

前提条件

terminal
% sw_vers
ProductName:	Mac OS X
ProductVersion:	10.14.2
BuildVersion:	18C54

% brew --version
Homebrew 1.8.6
Homebrew/homebrew-core (git revision 91f9; last commit 2019-01-08)
Homebrew/homebrew-cask (git revision 366f9; last commit 2019-01-07)

% php -v
PHP 7.3.0 (cli) (built: Jan  3 2019 10:08:00) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.0-dev, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.3.0, Copyright (c) 1999-2018, by Zend Technologies

Webhookの準備

[チャットルームの名前] → [Webhookを設定]

[Webhookを追加]をクリックして、名前とアイコン画像を適当に設定して[保存]をクリック
出来上がったWebhookのURLをとっておく

ソースの準備

chat.php
<?php
// WebhookのURL
$url = 'https://chat.googleapis.com/v1/spaces/...';
// 送りたいメッセージ
$message = 'めっせーじ';

$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => json_encode(['text' => $message], JSON_UNESCAPED_UNICODE),
    CURLOPT_HTTPHEADER => ['Content-Type: application/json']
]);

$response = curl_exec($curl);
var_dump($response);
curl_close($curl);

実行

コマンドラインから実行します。

terminal
% php chat.php

参考文献

8
4
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
8
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?