Skip to content

Instantly share code, notes, and snippets.

@BoShurik
Last active March 28, 2024 04:19
Show Gist options
  • Save BoShurik/a7cc435fd6374760d2db30a11c1890e5 to your computer and use it in GitHub Desktop.
Save BoShurik/a7cc435fd6374760d2db30a11c1890e5 to your computer and use it in GitHub Desktop.
Symfony MadelineProto Factory
<?php
namespace App\Madeline;
use danog\MadelineProto\API;
use danog\MadelineProto\Logger;
use danog\MadelineProto\Settings;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
class MadelineFactory
{
private const LEVEL_MAP = [
Logger::LEVEL_FATAL => LogLevel::CRITICAL,
Logger::LEVEL_ERROR => LogLevel::ERROR,
Logger::LEVEL_WARNING => LogLevel::WARNING,
Logger::LEVEL_NOTICE => LogLevel::NOTICE,
Logger::LEVEL_VERBOSE => LogLevel::INFO,
Logger::LEVEL_ULTRA_VERBOSE => LogLevel::DEBUG,
];
public function __construct(
private LoggerInterface $logger,
private string $cacheDir
) {
}
public function create(
int $appId,
string $appHash,
string $botToken
): API {
$parts = explode(':', $botToken);
$id = $parts[0];
$session = "{$this->cacheDir}/madeline/$id";
if (!is_dir($session)) {
mkdir($session, recursive: true);
}
$exceptionHandler = set_exception_handler(null);
$errorHandler = set_error_handler(null);
$api = new API($session, $this->buildSettings($appId, $appHash));
$api->botLogin($botToken);
$api->start();
set_exception_handler($exceptionHandler);
set_error_handler($errorHandler);
return $api;
}
private function buildSettings(int $appId, string $appHash): Settings
{
$settings = new Settings();
$settings->getAppInfo()
->setApiId($appId)
->setApiHash($appHash)
;
$settings->getLogger()
->setType(Logger::LOGGER_CALLABLE)
->setExtra($this->log(...))
;
return $settings;
}
private function log(string $message, int $level): void
{
$this->logger->log(self::LEVEL_MAP[$level], $message);
}
}
services:
danog\MadelineProto\API:
factory: ['@App\Madeline\MadelineFactory', 'create']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment