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

Commit

Permalink
Сделал получение событий от API
Browse files Browse the repository at this point in the history
  • Loading branch information
Muraveiko committed Apr 10, 2020
1 parent 147b133 commit 3a15038
Show file tree
Hide file tree
Showing 29 changed files with 613 additions and 43 deletions.
45 changes: 45 additions & 0 deletions examples/get_events.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php
require_once "../vendor/autoload.php";
require_once "config.php";

use Antson\IcqBot\Entities\IcqEvent;
use Antson\IcqBot\Entities\PayloadMessage;
use Antson\IcqBot\Entities\PayloadNewChatMembers;

try {
$icq = new Antson\IcqBot\Client(TOKEN);
$events = $icq->getEvents();
foreach ($events as $event){
echo $event->get_eventId().') ['.$event->get_type().'] ';

$payload = $event->get_payload();

echo 'Payload instance of '.get_class($payload);
echo '<br>';

switch ($event->get_type()){
case IcqEvent::NEW_MESSAGE:
/** @var PayloadMessage $payload */
echo "<b>Сообщение</b> от ".$payload->get_from()->get_firstName().' '.$payload->get_from()->get_lastName().'(@'.$payload->get_from()->get_userId()."):<br>";
echo "<i>".$payload->get_text()."</i><br>";
break;

case IcqEvent::NEW_CHAT_MEMBERS:
/** @var PayloadNewChatMembers $payload */
echo "Пользователь ".$payload->get_addedBy()->get_firstName()." <b>добавил</b> в ".$payload->get_chat()->get_title().":<br>";
$members = $payload->get_newMembers();
foreach ($members as $member){
echo $member->get_userId().' '.$member->get_firstName().' '.$member->get_lastName();
echo "<br>";
}
break;

/**
* other IcqEvent::CONST
*/
}
}
} catch (Exception $e) {
echo $e->getMessage();
}

125 changes: 107 additions & 18 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Antson\IcqBot;

use Antson\IcqBot\Entities\Entity;
use Antson\IcqBot\Entities\IcqEvent;
use Antson\IcqBot\Entities\SendResult;
use Antson\IcqBot\Entities\SendFileResult;
use Antson\IcqBot\Entities\BotInfo;
Expand All @@ -16,6 +17,10 @@
use CurlFile;
use Muraveiko\PhpCurler\Curler;

/**
* Выполнение запросов к ICQ API
* @package Antson\IcqBot
*/
class Client
{
/**
Expand All @@ -34,29 +39,43 @@ class Client
private $uin = '';

/**
* @var Curler
* @var int see __constructor
*/
private $curler;
private $get_timeout;

/**
* @var int
*/
private $post_timeout = 10000 ;

/**
* Если для отправки большого файла нехватает времени
* @param int $post_timeout в миллисекундах
*/
public function setPostTimeout($post_timeout)
{
$this->post_timeout = $post_timeout;
}

/**
* Client constructor.
* @param string $token
* @param string|null $api_url
* @param int $timeout в милисекундах для гет запросов к апи
* @throws Exception
*/
public function __construct($token, $api_url = null)
public function __construct($token, $api_url = null,$timeout = 5000)
{
$this->token = $token;
$this->get_timeout = $timeout;

list(, $this->uin) = explode(':', $token);
if (empty($this->uin)) {
throw new Exception("wrong token");
}
if (!is_null($api_url)) {
$this->api_url = $api_url;
}
$this->curler = new Curler([
'validMimeTypes' => 'application/json'
]);
}

/**
Expand Down Expand Up @@ -84,10 +103,17 @@ private function _get_default_param($chatId = null)
*/
private function _do_request($method, $param)
{
$r = $this->curler->get($this->api_url . $method . '?' . http_build_query($param));
if($r === false){
$curler_error = $this->curler->getError();
throw new Exception($curler_error['message']);
/**
* @var Curler
*/
$curler = new Curler([
'timeout' => $this->get_timeout,
'validMimeTypes' => 'application/json'
]);
$r = $curler->get($this->api_url . $method . '?' . http_build_query($param));
if ($r === false) {
$curler_error = $curler->getError();
throw new ExceptionLan($curler_error['message']);
}
return $r;
}
Expand All @@ -106,7 +132,7 @@ public function myUIN()
// =======================================================================================================

/**
* Метод можно использовать для проверки валидности токена.
* Метод можно использовать для проверки валидности токена. Информация об самом боте
* @return BotInfo
* @throws Exception
*/
Expand Down Expand Up @@ -169,7 +195,7 @@ public function sendPresentFile($chatId, $fileId, $caption = null, $replyMsgId =
{
$param = $this->_get_default_param($chatId);
$param['fileId'] = $fileId;
if(!is_null($caption)) {
if (!is_null($caption)) {
$param['caption'] = $caption;
}
if (!is_null($replyMsgId)) {
Expand Down Expand Up @@ -199,11 +225,12 @@ public function sendPresentFile($chatId, $fileId, $caption = null, $replyMsgId =
* @param string|null $forwardChatId
* @param string|null $inlineKeyboardMarkup
* @return SendFileResult
* @throws ExceptionLan
*/
public function sendNewFile($chatId, $curlFile, $caption = null, $replyMsgId = null, $forwardMsgId = null, $forwardChatId = null, $inlineKeyboardMarkup = null)
{
$param = $this->_get_default_param($chatId);
if(!is_null($caption)) {
if (!is_null($caption)) {
$param['caption'] = $caption;
}
if (!is_null($replyMsgId)) {
Expand All @@ -219,7 +246,20 @@ public function sendNewFile($chatId, $curlFile, $caption = null, $replyMsgId = n
$param['inlineKeyboardMarkup'] = $inlineKeyboardMarkup;
}
$param['file'] = $curlFile;
$response = $this->curler->post($this->api_url . 'messages/sendFile',$param,false) ;

/**
* @var Curler
*/
$curler = new Curler([
'timeout' => $this->post_timeout,
'validMimeTypes' => 'application/json'
]);

$response = $curler->post($this->api_url . 'messages/sendFile', $param, false);
if ($response === false) {
$curler_error = $curler->getError();
throw new ExceptionLan($curler_error['message']);
}
return new SendFileResult($response);
}

Expand Down Expand Up @@ -264,8 +304,9 @@ public function sendPresentVoice($chatId, $fileId, $replyMsgId = null, $forwardM
* @param string|null $forwardChatId
* @param string|null $inlineKeyboardMarkup
* @return SendFileResult
* @throws ExceptionLan
*/
public function sendNewVoice($chatId, $curlFile, $replyMsgId = null, $forwardMsgId = null, $forwardChatId = null, $inlineKeyboardMarkup = null)
public function sendNewVoice($chatId, $curlFile, $replyMsgId = null, $forwardMsgId = null, $forwardChatId = null, $inlineKeyboardMarkup = null)
{
$param = $this->_get_default_param($chatId);
if (!is_null($replyMsgId)) {
Expand All @@ -281,7 +322,21 @@ public function sendNewVoice($chatId, $curlFile, $replyMsgId = null, $forwardMs
$param['inlineKeyboardMarkup'] = $inlineKeyboardMarkup;
}
$param['file'] = $curlFile;
$response = $this->curler->post($this->api_url . 'messages/sendVoice',$param,false) ;

/**
* @var Curler
*/
$curler = new Curler([
'timeout' => $this->post_timeout,
'validMimeTypes' => 'application/json'
]);

$response = $curler->post($this->api_url . 'messages/sendVoice', $param, false);
if ($response === false) {
$curler_error = $curler->getError();
throw new ExceptionLan($curler_error['message']);
}

return new SendFileResult($response);
}

Expand Down Expand Up @@ -340,12 +395,15 @@ public function answerCallbackQuery($queryId, $text, $showAlert = false, $url =
// API: CHATS
// =======================================================================================================

const ACTION_LOOKING = "looking";
const ACTION_TYPING = "typing";
/**
* Отправить текущие действия в чат
* @param string $chatId
* @param [string] $actions - 'looking','typing' или пустой значение, если все действия завершены
* @param string[] $actions - ACTION_LOOKING ,ACTION_TYPING или пустой значение, если все действия завершены
* @return Entity
* @throws Exception
* @see Client::ACTION_TYPING, Client::ACTION_LOOKING
*/
public function sendActions($chatId, $actions)
{
Expand Down Expand Up @@ -630,5 +688,36 @@ public function fileGetInfo($fileId)
// API: EVENTS
// =======================================================================================================

/* Coming soon */
/**
* Сообщения к боту
* @param int $lastEventId
* @param int $pollTime
* @return IcqEvent[]
* @throws Exception
*/
public function getEvents($lastEventId = 0, $pollTime = 25)
{
$events = [];

$timeout = $pollTime + 1; // добавляем секунду, чтобы мы не завершали соединение раньше сервера
$param = $this->_get_default_param();
$param['lastEventId'] = $lastEventId;
$param['pollTime'] = $pollTime;
$listener = new Curler([
'maxFilesize' => 16777216, // 16M
'validMimeTypes' => 'application/json',
'timeout' => $timeout * 1000,
]);
$response = $listener->get($this->api_url . 'events/get?' . http_build_query($param));
if ($response === false) {
$curler_error = $listener->getError();
throw new ExceptionLan($curler_error['message']);
}

$data = json_decode($response);
foreach ($data->events as $ev) {
$events[] = new IcqEvent((array)$ev);
}
return $events;
}
}
12 changes: 12 additions & 0 deletions src/Entities/Author.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php


namespace Antson\IcqBot\Entities;

/**
* Отправитель сообщения / Автор действия
*/
class Author extends Member
{

}
3 changes: 1 addition & 2 deletions src/Entities/BotInfo.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
namespace Antson\IcqBot\Entities;

/**
* Class BotInfo
* @package Antson\IcqBot\Entities
* Информация о боте
* @method string get_userId()
* @method string get_nick()
* @method string get_firstName()
Expand Down
25 changes: 14 additions & 11 deletions src/Entities/ChatInfo.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,29 +6,32 @@
use Antson\IcqBot\Exception;

/**
* Class ChatInfo
* @package Antson\IcqBot\Entities
* Чаты бывают трех типов
* @method string get_type()
*/
abstract class ChatInfo extends Entity
abstract class ChatInfo extends Entity
{
const TYPE_PRIVATE = "private";
const TYPE_GROUP = "group";
const TYPE_CHANNEL = "channel";

/**
* Decode response for ChatInfo query
* @param $data
* @return ChatInfoPrivate|ChatInfoGroup|ChatInfoChannel
* @throws Exception
*/
public static function Fabric($data){
if(!is_array($data)){
/** @var ChatInfo $data */
$data = json_decode($data,true);
public static function Fabric($data)
{
if (!is_array($data)) {
$data = json_decode($data, true);
}
switch ($data['type']){
case 'private':
switch ($data['type']) {
case self::TYPE_PRIVATE:
return new ChatInfoPrivate($data);
case 'group':
case self::TYPE_GROUP:
return new ChatInfoGroup($data);
case 'channel':
case self::TYPE_CHANNEL:
return new ChatInfoChannel($data);
}
throw new Exception("wrong info type");
Expand Down
3 changes: 1 addition & 2 deletions src/Entities/ChatInfoChannel.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
namespace Antson\IcqBot\Entities;

/**
* Class ChatInfoChannel
* @package Antson\IcqBot\Entities
* Чат - канал
* @method string get_title()
* @method string get_about()
* @method string get_rules()
Expand Down
3 changes: 1 addition & 2 deletions src/Entities/ChatInfoGroup.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
namespace Antson\IcqBot\Entities;

/**
* Class ChatInfoGroup
* @package Antson\IcqBot\Entities
* Чат - группа
* @method string get_title()
* @method string get_about()
* @method string get_rules()
Expand Down
3 changes: 1 addition & 2 deletions src/Entities/ChatInfoPrivate.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
namespace Antson\IcqBot\Entities;

/**
* Class ChatInfoPrivate
* @package Antson\IcqBot\Entities
* Чат - приватная беседа
* @method string get_firstName()
* @method string get_lastName()
* @method string get_nick()
Expand Down
4 changes: 3 additions & 1 deletion src/Entities/Entity.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

namespace Antson\IcqBot\Entities;


/**
* Разбор ответа от АПИ
*/
class Entity
{
/**
Expand Down
Loading

0 comments on commit 3a15038

Please sign in to comment.