Skip to content

Commit

Permalink
fixed long events
Browse files Browse the repository at this point in the history
  • Loading branch information
Mateodioev committed May 15, 2023
1 parent 5b0913d commit 827df8c
Show file tree
Hide file tree
Showing 6 changed files with 80 additions and 60 deletions.
8 changes: 4 additions & 4 deletions examples/All.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ class All extends AllEvent
public function execute(Api $bot, Context $context, array $args = [])
{
$type = $context->eventType()->prettyName();
$raw = \json_encode($context->getReduced(), JSON_PRETTY_PRINT);
$raw = \json_encode($context->getReduced(), JSON_PRETTY_PRINT) . PHP_EOL;

$this->getLogger()->info('Receive new {type} event', compact('type'));
$this->getLogger()->info('Update: {raw}', compact('raw'));
}
$this->getLogger()->info('Receive new {type} event', ['type' => $type]);
$this->getLogger()->info('Update: {raw}', ['raw' => $raw]);
}
}
13 changes: 6 additions & 7 deletions examples/ButtonCallback.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
<?php

use Mateodioev\Bots\Telegram\Api;
use Mateodioev\Bots\Telegram\Methods\Method;
use Mateodioev\TgHandler\Commands\{CallbackCommand, StopCommand};
use Mateodioev\TgHandler\Context;

Expand All @@ -17,16 +16,16 @@ public function handle(Api $bot, Context $context, array $args = [])
{
$this->getLogger()->info('Button 1 pressed');
// log telegram context
$this->getLogger()->info('Update: {up}', ['up' => json_encode($context->get(), JSON_PRETTY_PRINT)]);
$this->getLogger()->info('Update: {up}', ['up' => \json_encode($context->get(), JSON_PRETTY_PRINT)]);

$payload = $context->getPayload();
// send answerCallbackQuery method
// if payload is empty, StopCommand will be thrown and this method will not be called
$bot->request(Method::create([
'callback_query_id' => $context?->callbackQuery()->id(),
'text' => "Button 1 pressed\nPayload: " . $payload,
'show_alert' => true
], 'answerCallbackQuery'));
$bot->answerCallbackQuery(
$context?->callbackQuery()->id(),
"Button 1 pressed\nPayload: " . $payload,
['show_alert' => true]
);
}
}

Expand Down
15 changes: 10 additions & 5 deletions examples/Start.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,30 @@

class Start extends MessageCommand
{
protected string $name = 'start';
protected string $name = 'start';
protected string $description = 'Start the command';

/**
* Run command
* @throws Exception
*/
public function handle(Api $bot, Context $context, array $args = [])
{
public function handle(Api $bot, Context $context, array $args = [])
{
$bot->replyTo($context->getChatId(), 'Hello world!', $context->getMessageId(), 'HTML', [
'reply_markup' => (string) $this->getButton() // get json button
]);

// log telegram context using psr logger
$this->getLogger()->info('Received new text: ' . $context->message()->text());
$this->getLogger()->info('Received new text: {text}', ['text' => $context->message()->text()]);

$this->getLogger()->info('Waiting 5 seconds...');
\Amp\delay(5); // wait 5 seconds

$bot->replyTo($context->getChatId(), '5 seconds passed!', $context->getMessageId());

// This will throw an exception
Request::GET('https://invalidurl.invalid')->run();
}
}

protected function getButton(): Buttons
{
Expand Down
18 changes: 11 additions & 7 deletions src/Bot.php
Original file line number Diff line number Diff line change
Expand Up @@ -236,12 +236,13 @@ public function longPolling(int $timeout, bool $ignoreOldUpdates = false, bool $
}

if ($async) {
awaitAll(
array_map(function (Update $update) use (&$offset) {
$offset = $update->updateId() + 1;
return async(getAsyncFn(), $update, $this);
}, $updates)
);
array_map(function (Update $update) use (&$offset) {
$offset = $update->updateId() + 1;
async(function (Update $up,): void {
$this->runAsync($up);
}, $update);
}, $updates);
\Amp\delay(1);
} else {
array_map(function (Update $update) use (&$offset) {
$offset = $update->updateId() + 1;
Expand All @@ -252,9 +253,12 @@ public function longPolling(int $timeout, bool $ignoreOldUpdates = false, bool $
}
}

/**
* @deprecated
*/
function getAsyncFn(): Closure
{
return static function (Update $up, Bot &$instance) {
$instance->runAsync($up);
};
}
}
60 changes: 32 additions & 28 deletions src/Log/Logger.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,29 +10,30 @@ class Logger extends AbstractLogger implements LoggerInterface
use BitwiseFlag;

const ALL = 255;
const CRITICAL = 128;
const ERROR = 64;
const EMERGENCY = 32;
const ALERT = 16;
const WARNING = 8;
const NOTICE = 4;
const INFO = 2;
const DEBUG = 1;
const CRITICAL = 128;
const ERROR = 64;
const EMERGENCY = 32;
const ALERT = 16;
const WARNING = 8;
const NOTICE = 4;
const INFO = 2;
const DEBUG = 1;

public static string $messageFormat = "[{time}] [{level}] {message} {EOL}";

public function __construct(private readonly Stream $stream) {
public function __construct(private readonly Stream $stream)
{
$this->setLevel(self::ALL);
}

/**
* Set log level
*/
public function setLevel(int $level, bool $add = true): static
public function setLevel(int $level, bool $add = true): static
{
$this->setFlag($level, $add);
return $this;
}
$this->setFlag($level, $add);
return $this;
}

/**
* @inheritDoc
Expand All @@ -45,43 +46,46 @@ public function log($level, \Stringable|string $message, array $context = []): v
$date = (new \DateTime())->format('Y-m-d H:i:s');

try {
$logMessage = $message;

// only format if $context is not empty
if (!count($context) > 0) {
$logMessage = StringFormatter::format(self::$messageFormat, [
'time' => $date,
'level' => \strtoupper($level),
'message' => $this->makeLogMessage($message, $context),
'EOL' => PHP_EOL
]);
}
$this->stream->push($logMessage);
$logMessage = StringFormatter::format(self::$messageFormat, [
'time' => $date,
'level' => \strtoupper($level),
'message' => $this->makeLogMessage($message, $context),
'EOL' => PHP_EOL
]);

$this->stream->push($logMessage);
} catch (StringFormatterException $th) {
throw new LogInvalidArgumentException($th->getMessage(), $th->getCode(), $th);
}
}

protected function makeLogMessage(string $message, array $context = []): string
{
// if context is empty, delete brackets
if (empty($context))
return $this->deleteBrackets($message);

return StringFormatter::format($message, $context);
}

protected function deleteBrackets(string $message): string
{
return \preg_replace('/\{(.*)\}/', '$1', $message);
}
/**
* Return true if log level can access
*/
protected function canAccess(int $level): bool
{
return $this->isFlagSet($level);
}
return $this->isFlagSet($level);
}

/**
* Convert level string to int
*/
private function levelToInt(string $level): int
{
return match($level) {
return match ($level) {
LogLevel::EMERGENCY => self::EMERGENCY,
LogLevel::ALERT => self::ALERT,
LogLevel::CRITICAL => self::CRITICAL,
Expand Down
26 changes: 17 additions & 9 deletions src/Log/PhpNativeStream.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,13 @@
namespace Mateodioev\TgHandler\Log;

// use Amp\File\FilesystemException;

use Amp\File\FilesystemException;
use Mateodioev\Utils\Exceptions\FileException;
use Mateodioev\Utils\Files;

use Amp\File;

/**
* Log php errors into a file setting an error_handler
*/
Expand All @@ -15,7 +19,7 @@ class PhpNativeStream implements Stream

public function activate(string $dir, ?string $file = null): static
{
if (is_dir($dir) && $file !== null) {
if (\is_dir($dir) && $file !== null) {
throw new FileException('Invalid dir');
}

Expand All @@ -42,6 +46,11 @@ public function activate(string $dir, ?string $file = null): static
public function setFile(string $path): static
{
$this->fileLog = $path;

if (!Files::isFile($path)) {
\fclose(\fopen($path, 'a')); // create file if not exists
}

return $this;
}

Expand Down Expand Up @@ -84,13 +93,12 @@ public function push(string $message): void

protected function write(string $path, string $content)
{
return (bool) file_put_contents($path, $content, FILE_APPEND);

/* try {
\Amp\File\write($path, $content);
try {
$fileContent = File\read($path) . $content;
File\write($path, $fileContent);
return true;
} catch (FilesystemException $e) {
return false;
} */
} catch (FilesystemException) {
return false;
}
}
}
}

0 comments on commit 827df8c

Please sign in to comment.