Skip to content
This repository was archived by the owner on Nov 8, 2024. It is now read-only.

Commit 3a15038

Browse files
author
Muraveiko
committed
Сделал получение событий от API
1 parent 147b133 commit 3a15038

29 files changed

+613
-43
lines changed

examples/get_events.php

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
<?php
2+
require_once "../vendor/autoload.php";
3+
require_once "config.php";
4+
5+
use Antson\IcqBot\Entities\IcqEvent;
6+
use Antson\IcqBot\Entities\PayloadMessage;
7+
use Antson\IcqBot\Entities\PayloadNewChatMembers;
8+
9+
try {
10+
$icq = new Antson\IcqBot\Client(TOKEN);
11+
$events = $icq->getEvents();
12+
foreach ($events as $event){
13+
echo $event->get_eventId().') ['.$event->get_type().'] ';
14+
15+
$payload = $event->get_payload();
16+
17+
echo 'Payload instance of '.get_class($payload);
18+
echo '<br>';
19+
20+
switch ($event->get_type()){
21+
case IcqEvent::NEW_MESSAGE:
22+
/** @var PayloadMessage $payload */
23+
echo "<b>Сообщение</b> от ".$payload->get_from()->get_firstName().' '.$payload->get_from()->get_lastName().'(@'.$payload->get_from()->get_userId()."):<br>";
24+
echo "<i>".$payload->get_text()."</i><br>";
25+
break;
26+
27+
case IcqEvent::NEW_CHAT_MEMBERS:
28+
/** @var PayloadNewChatMembers $payload */
29+
echo "Пользователь ".$payload->get_addedBy()->get_firstName()." <b>добавил</b> в ".$payload->get_chat()->get_title().":<br>";
30+
$members = $payload->get_newMembers();
31+
foreach ($members as $member){
32+
echo $member->get_userId().' '.$member->get_firstName().' '.$member->get_lastName();
33+
echo "<br>";
34+
}
35+
break;
36+
37+
/**
38+
* other IcqEvent::CONST
39+
*/
40+
}
41+
}
42+
} catch (Exception $e) {
43+
echo $e->getMessage();
44+
}
45+

src/Client.php

Lines changed: 107 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace Antson\IcqBot;
44

55
use Antson\IcqBot\Entities\Entity;
6+
use Antson\IcqBot\Entities\IcqEvent;
67
use Antson\IcqBot\Entities\SendResult;
78
use Antson\IcqBot\Entities\SendFileResult;
89
use Antson\IcqBot\Entities\BotInfo;
@@ -16,6 +17,10 @@
1617
use CurlFile;
1718
use Muraveiko\PhpCurler\Curler;
1819

20+
/**
21+
* Выполнение запросов к ICQ API
22+
* @package Antson\IcqBot
23+
*/
1924
class Client
2025
{
2126
/**
@@ -34,29 +39,43 @@ class Client
3439
private $uin = '';
3540

3641
/**
37-
* @var Curler
42+
* @var int see __constructor
3843
*/
39-
private $curler;
44+
private $get_timeout;
45+
46+
/**
47+
* @var int
48+
*/
49+
private $post_timeout = 10000 ;
50+
51+
/**
52+
* Если для отправки большого файла нехватает времени
53+
* @param int $post_timeout в миллисекундах
54+
*/
55+
public function setPostTimeout($post_timeout)
56+
{
57+
$this->post_timeout = $post_timeout;
58+
}
4059

4160
/**
4261
* Client constructor.
4362
* @param string $token
4463
* @param string|null $api_url
64+
* @param int $timeout в милисекундах для гет запросов к апи
4565
* @throws Exception
4666
*/
47-
public function __construct($token, $api_url = null)
67+
public function __construct($token, $api_url = null,$timeout = 5000)
4868
{
4969
$this->token = $token;
70+
$this->get_timeout = $timeout;
71+
5072
list(, $this->uin) = explode(':', $token);
5173
if (empty($this->uin)) {
5274
throw new Exception("wrong token");
5375
}
5476
if (!is_null($api_url)) {
5577
$this->api_url = $api_url;
5678
}
57-
$this->curler = new Curler([
58-
'validMimeTypes' => 'application/json'
59-
]);
6079
}
6180

6281
/**
@@ -84,10 +103,17 @@ private function _get_default_param($chatId = null)
84103
*/
85104
private function _do_request($method, $param)
86105
{
87-
$r = $this->curler->get($this->api_url . $method . '?' . http_build_query($param));
88-
if($r === false){
89-
$curler_error = $this->curler->getError();
90-
throw new Exception($curler_error['message']);
106+
/**
107+
* @var Curler
108+
*/
109+
$curler = new Curler([
110+
'timeout' => $this->get_timeout,
111+
'validMimeTypes' => 'application/json'
112+
]);
113+
$r = $curler->get($this->api_url . $method . '?' . http_build_query($param));
114+
if ($r === false) {
115+
$curler_error = $curler->getError();
116+
throw new ExceptionLan($curler_error['message']);
91117
}
92118
return $r;
93119
}
@@ -106,7 +132,7 @@ public function myUIN()
106132
// =======================================================================================================
107133

108134
/**
109-
* Метод можно использовать для проверки валидности токена.
135+
* Метод можно использовать для проверки валидности токена. Информация об самом боте
110136
* @return BotInfo
111137
* @throws Exception
112138
*/
@@ -169,7 +195,7 @@ public function sendPresentFile($chatId, $fileId, $caption = null, $replyMsgId =
169195
{
170196
$param = $this->_get_default_param($chatId);
171197
$param['fileId'] = $fileId;
172-
if(!is_null($caption)) {
198+
if (!is_null($caption)) {
173199
$param['caption'] = $caption;
174200
}
175201
if (!is_null($replyMsgId)) {
@@ -199,11 +225,12 @@ public function sendPresentFile($chatId, $fileId, $caption = null, $replyMsgId =
199225
* @param string|null $forwardChatId
200226
* @param string|null $inlineKeyboardMarkup
201227
* @return SendFileResult
228+
* @throws ExceptionLan
202229
*/
203230
public function sendNewFile($chatId, $curlFile, $caption = null, $replyMsgId = null, $forwardMsgId = null, $forwardChatId = null, $inlineKeyboardMarkup = null)
204231
{
205232
$param = $this->_get_default_param($chatId);
206-
if(!is_null($caption)) {
233+
if (!is_null($caption)) {
207234
$param['caption'] = $caption;
208235
}
209236
if (!is_null($replyMsgId)) {
@@ -219,7 +246,20 @@ public function sendNewFile($chatId, $curlFile, $caption = null, $replyMsgId = n
219246
$param['inlineKeyboardMarkup'] = $inlineKeyboardMarkup;
220247
}
221248
$param['file'] = $curlFile;
222-
$response = $this->curler->post($this->api_url . 'messages/sendFile',$param,false) ;
249+
250+
/**
251+
* @var Curler
252+
*/
253+
$curler = new Curler([
254+
'timeout' => $this->post_timeout,
255+
'validMimeTypes' => 'application/json'
256+
]);
257+
258+
$response = $curler->post($this->api_url . 'messages/sendFile', $param, false);
259+
if ($response === false) {
260+
$curler_error = $curler->getError();
261+
throw new ExceptionLan($curler_error['message']);
262+
}
223263
return new SendFileResult($response);
224264
}
225265

@@ -264,8 +304,9 @@ public function sendPresentVoice($chatId, $fileId, $replyMsgId = null, $forwardM
264304
* @param string|null $forwardChatId
265305
* @param string|null $inlineKeyboardMarkup
266306
* @return SendFileResult
307+
* @throws ExceptionLan
267308
*/
268-
public function sendNewVoice($chatId, $curlFile, $replyMsgId = null, $forwardMsgId = null, $forwardChatId = null, $inlineKeyboardMarkup = null)
309+
public function sendNewVoice($chatId, $curlFile, $replyMsgId = null, $forwardMsgId = null, $forwardChatId = null, $inlineKeyboardMarkup = null)
269310
{
270311
$param = $this->_get_default_param($chatId);
271312
if (!is_null($replyMsgId)) {
@@ -281,7 +322,21 @@ public function sendNewVoice($chatId, $curlFile, $replyMsgId = null, $forwardMs
281322
$param['inlineKeyboardMarkup'] = $inlineKeyboardMarkup;
282323
}
283324
$param['file'] = $curlFile;
284-
$response = $this->curler->post($this->api_url . 'messages/sendVoice',$param,false) ;
325+
326+
/**
327+
* @var Curler
328+
*/
329+
$curler = new Curler([
330+
'timeout' => $this->post_timeout,
331+
'validMimeTypes' => 'application/json'
332+
]);
333+
334+
$response = $curler->post($this->api_url . 'messages/sendVoice', $param, false);
335+
if ($response === false) {
336+
$curler_error = $curler->getError();
337+
throw new ExceptionLan($curler_error['message']);
338+
}
339+
285340
return new SendFileResult($response);
286341
}
287342

@@ -340,12 +395,15 @@ public function answerCallbackQuery($queryId, $text, $showAlert = false, $url =
340395
// API: CHATS
341396
// =======================================================================================================
342397

398+
const ACTION_LOOKING = "looking";
399+
const ACTION_TYPING = "typing";
343400
/**
344401
* Отправить текущие действия в чат
345402
* @param string $chatId
346-
* @param [string] $actions - 'looking','typing' или пустой значение, если все действия завершены
403+
* @param string[] $actions - ACTION_LOOKING ,ACTION_TYPING или пустой значение, если все действия завершены
347404
* @return Entity
348405
* @throws Exception
406+
* @see Client::ACTION_TYPING, Client::ACTION_LOOKING
349407
*/
350408
public function sendActions($chatId, $actions)
351409
{
@@ -630,5 +688,36 @@ public function fileGetInfo($fileId)
630688
// API: EVENTS
631689
// =======================================================================================================
632690

633-
/* Coming soon */
691+
/**
692+
* Сообщения к боту
693+
* @param int $lastEventId
694+
* @param int $pollTime
695+
* @return IcqEvent[]
696+
* @throws Exception
697+
*/
698+
public function getEvents($lastEventId = 0, $pollTime = 25)
699+
{
700+
$events = [];
701+
702+
$timeout = $pollTime + 1; // добавляем секунду, чтобы мы не завершали соединение раньше сервера
703+
$param = $this->_get_default_param();
704+
$param['lastEventId'] = $lastEventId;
705+
$param['pollTime'] = $pollTime;
706+
$listener = new Curler([
707+
'maxFilesize' => 16777216, // 16M
708+
'validMimeTypes' => 'application/json',
709+
'timeout' => $timeout * 1000,
710+
]);
711+
$response = $listener->get($this->api_url . 'events/get?' . http_build_query($param));
712+
if ($response === false) {
713+
$curler_error = $listener->getError();
714+
throw new ExceptionLan($curler_error['message']);
715+
}
716+
717+
$data = json_decode($response);
718+
foreach ($data->events as $ev) {
719+
$events[] = new IcqEvent((array)$ev);
720+
}
721+
return $events;
722+
}
634723
}

src/Entities/Author.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<?php
2+
3+
4+
namespace Antson\IcqBot\Entities;
5+
6+
/**
7+
* Отправитель сообщения / Автор действия
8+
*/
9+
class Author extends Member
10+
{
11+
12+
}

src/Entities/BotInfo.php

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@
44
namespace Antson\IcqBot\Entities;
55

66
/**
7-
* Class BotInfo
8-
* @package Antson\IcqBot\Entities
7+
* Информация о боте
98
* @method string get_userId()
109
* @method string get_nick()
1110
* @method string get_firstName()

src/Entities/ChatInfo.php

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,29 +6,32 @@
66
use Antson\IcqBot\Exception;
77

88
/**
9-
* Class ChatInfo
10-
* @package Antson\IcqBot\Entities
9+
* Чаты бывают трех типов
1110
* @method string get_type()
1211
*/
13-
abstract class ChatInfo extends Entity
12+
abstract class ChatInfo extends Entity
1413
{
14+
const TYPE_PRIVATE = "private";
15+
const TYPE_GROUP = "group";
16+
const TYPE_CHANNEL = "channel";
17+
1518
/**
1619
* Decode response for ChatInfo query
1720
* @param $data
1821
* @return ChatInfoPrivate|ChatInfoGroup|ChatInfoChannel
1922
* @throws Exception
2023
*/
21-
public static function Fabric($data){
22-
if(!is_array($data)){
23-
/** @var ChatInfo $data */
24-
$data = json_decode($data,true);
24+
public static function Fabric($data)
25+
{
26+
if (!is_array($data)) {
27+
$data = json_decode($data, true);
2528
}
26-
switch ($data['type']){
27-
case 'private':
29+
switch ($data['type']) {
30+
case self::TYPE_PRIVATE:
2831
return new ChatInfoPrivate($data);
29-
case 'group':
32+
case self::TYPE_GROUP:
3033
return new ChatInfoGroup($data);
31-
case 'channel':
34+
case self::TYPE_CHANNEL:
3235
return new ChatInfoChannel($data);
3336
}
3437
throw new Exception("wrong info type");

src/Entities/ChatInfoChannel.php

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@
44
namespace Antson\IcqBot\Entities;
55

66
/**
7-
* Class ChatInfoChannel
8-
* @package Antson\IcqBot\Entities
7+
* Чат - канал
98
* @method string get_title()
109
* @method string get_about()
1110
* @method string get_rules()

src/Entities/ChatInfoGroup.php

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@
44
namespace Antson\IcqBot\Entities;
55

66
/**
7-
* Class ChatInfoGroup
8-
* @package Antson\IcqBot\Entities
7+
* Чат - группа
98
* @method string get_title()
109
* @method string get_about()
1110
* @method string get_rules()

src/Entities/ChatInfoPrivate.php

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@
44
namespace Antson\IcqBot\Entities;
55

66
/**
7-
* Class ChatInfoPrivate
8-
* @package Antson\IcqBot\Entities
7+
* Чат - приватная беседа
98
* @method string get_firstName()
109
* @method string get_lastName()
1110
* @method string get_nick()

src/Entities/Entity.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22

33
namespace Antson\IcqBot\Entities;
44

5-
5+
/**
6+
* Разбор ответа от АПИ
7+
*/
68
class Entity
79
{
810
/**

0 commit comments

Comments
 (0)