setEventHandler for new sessions

This commit is contained in:
Alexander Pankratov 2020-01-26 23:29:23 +03:00
parent 2a35aa7a40
commit feaf01fd26
3 changed files with 20 additions and 7 deletions

View File

@ -120,6 +120,11 @@ Fast, simple, async php telegram api server:
Bot:
* `http://127.0.0.1:9503/api/bot/botLogin?token=34298141894:aflknsaflknLKNFS`
After authorization eventHandler need to be set, to receive updates for new session in `/events` websocket:
* `http://127.0.0.1:9503/api/users/xtrime/setEventHandler`
* `http://127.0.0.1:9503/api/bot/setEventHandler`
* EventHandler updates via websocket. Connect to `ws://127.0.0.1:9503/events`. You will get all events in json.
Each event is json object in [json-rpc 2.0 format](https://www.jsonrpc.org/specification#response_object). Example:

View File

@ -10,16 +10,18 @@ class EventHandler extends \danog\MadelineProto\EventHandler
{
/** @var callable[] */
public static array $eventListeners = [];
private string $sessionName;
public function __construct(?API $MadelineProto)
public function __construct(API $MadelineProto)
{
parent::__construct($MadelineProto);
echo 'Event observer CONSTRUCTED' . PHP_EOL;
$this->sessionName = Client::getSessionName($MadelineProto->session);
Logger::getInstance()->warning("Event observer CONSTRUCTED: {$this->sessionName}");
}
public function __destruct()
{
echo 'Event observer DESTRUCTED' . PHP_EOL;
Logger::getInstance()->warning("Event observer DESTRUCTED {$this->sessionName}");
}
public static function addEventListener($clientId, callable $callback)
@ -41,12 +43,11 @@ class EventHandler extends \danog\MadelineProto\EventHandler
public function onAny($update): void
{
$session = Client::getSessionName($this->API->wrapper->session ?? null);
Logger::getInstance()->info("Received update from session: {$session}");
Logger::getInstance()->info("Received update from session: {$this->sessionName}");
foreach (static::$eventListeners as $clientId => $callback) {
Logger::getInstance()->notice("Pass update to callback. ClientId: {$clientId}");
$callback($update, $session);
$callback($update, $this->sessionName);
}
}
}

View File

@ -10,6 +10,7 @@ use Amp\Producer;
use Amp\Promise;
use danog\MadelineProto\TL\Conversion\BotAPI;
use OutOfRangeException;
use TelegramApiServer\EventObservers\EventHandler;
use UnexpectedValueException;
use function Amp\call;
use \danog\MadelineProto;
@ -474,7 +475,13 @@ class ApiExtensions
});
}
private function getByteRange(?string $header) {
public function setEventHandler(): void
{
$this->madelineProto->setEventHandler(EventHandler::class);
}
private function getByteRange(?string $header): array
{
$matches = [
'start' => 0,
'end' => -1