-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchatbot.php
More file actions
57 lines (48 loc) · 1.38 KB
/
Copy pathchatbot.php
File metadata and controls
57 lines (48 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?php
require_once "request.php";
use Amp\Websocket\Client;
class ChatBot
{
private $host;
private $token;
private $plugins = [];
private $req;
function __construct($host, $token)
{
$this->host = $host;
$this->token = $token;
$this->req = new APIRequest($host, $token);
}
function start()
{
Amp\Loop::run(function () {
$connection = yield Client\connect('ws://' . $this->host . '/ws?token=' . $this->token);
echo "websocket连接成功" . PHP_EOL;
while ($message = yield $connection->receive()) {
$payload = yield $message->buffer();
printf("Received: %s\n", $payload);
$message = json_decode($payload);
if ($message) {
//文本消息
if ($message->msgType === 1) {
foreach ($this->plugins as $plugin) {
$plugin->do($message);
}
}
}
}
});
}
function use($plguin)
{
$this->plugins[] = $plguin;
}
function sendMessage($toUser, $content)
{
try {
$this->req->sendMessage($toUser, $content);
} catch (Exception $e) {
echo "send message error:" . $e->getMessage() . PHP_EOL;
}
}
}