Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance Update Class to Support Command Extraction from "callback_query" #1135

Open
wants to merge 5 commits into
base: 3.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "irazasyed/telegram-bot-sdk",
"name": "miladkhodaverdi23/telegram-bot-sdk",
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Revert this change

"description": "The Unofficial Telegram Bot API PHP SDK",
"license": "BSD-3-Clause",
"type": "library",
Expand Down
8 changes: 5 additions & 3 deletions src/Commands/Command.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Telegram\Bot\Commands;

use Illuminate\Support\Collection;
use Mockery\Exception;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wrong import

use Telegram\Bot\Answers\Answerable;
use Telegram\Bot\Api;
use Telegram\Bot\Objects\MessageEntity;
Expand Down Expand Up @@ -165,6 +166,7 @@
return [];
}


// Generate the regex needed to search for this pattern
[$pattern, $arguments] = $this->makeRegexPattern();

Expand Down Expand Up @@ -206,7 +208,7 @@
$commandOffsets = $this->allCommandOffsets();

if ($commandOffsets->isEmpty()) {
return $this->getUpdate()->getMessage()->text ?? '';
return $this->getUpdate()->getText() ?? '';

Check warning on line 211 in src/Commands/Command.php

View check run for this annotation

Codecov / codecov/patch

src/Commands/Command.php#L211

Added line #L211 was not covered by tests
}

//Extract the current offset for this command and, if it exists, the offset of the NEXT bot_command entity
Expand All @@ -228,7 +230,7 @@
private function cutTextBetween(Collection $splice): string
{
return mb_substr(
$this->getUpdate()->getMessage()->text ?? '',
$this->getUpdate()->getText() ?? '',
$splice->first(),
$splice->last() - $splice->first()
);
Expand All @@ -237,7 +239,7 @@
private function cutTextFrom(Collection $splice): string
{
return mb_substr(
$this->getUpdate()->getMessage()->text ?? '',
$this->getUpdate()->getText() ?? '',
$splice->first()
);
}
Expand Down
75 changes: 35 additions & 40 deletions src/Commands/CommandBus.php
Original file line number Diff line number Diff line change
Expand Up @@ -127,11 +127,9 @@
}

// remove leading slash
$command = substr(
$text,
$command = substr($text,
$offset + 1,
$length - 1
);
$length - 1);

// When in group - Ex: /command@MyBot. Just get the command name.
return Str::of($command)->explode('@')->first();
Expand All @@ -142,13 +140,23 @@
*/
protected function handler(Update $update): Update
{
if ($update->detectType() == "callback_query") {
preg_match('/\A(\/callback:::\w*)\s*(.*)/', $update->getText(), $command);
[$text, $command] = $command;
$entity = [
'offset' => 0,
'length' => strlen($command)
];
$this->process($entity, $update);
return $update;

Check warning on line 151 in src/Commands/CommandBus.php

View check run for this annotation

Codecov / codecov/patch

src/Commands/CommandBus.php#L144-L151

Added lines #L144 - L151 were not covered by tests
}

$message = $update->getMessage();

if ($message->has('entities')) {
$this->parseCommandsIn($message)->each(fn ($entity) => $this->process(
$entity instanceof MessageEntity ? $entity->all() : $entity,
$update
));
$this->parseCommandsIn($message)->each(fn($entity) => $this->process($entity instanceof
MessageEntity ? $entity->all() : $entity,
$update));

Check warning on line 159 in src/Commands/CommandBus.php

View check run for this annotation

Codecov / codecov/patch

src/Commands/CommandBus.php#L157-L159

Added lines #L157 - L159 were not covered by tests
}

return $update;
Expand All @@ -159,22 +167,21 @@
*/
private function parseCommandsIn(Collection $message): Collection
{
return Collection::wrap($message->get('entities'))
->filter(static fn (MessageEntity $entity): bool => $entity->type === 'bot_command');
return Collection::wrap($message->get('entities'))->filter(static fn(MessageEntity $entity): bool => $entity->type ===
'bot_command');

Check warning on line 171 in src/Commands/CommandBus.php

View check run for this annotation

Codecov / codecov/patch

src/Commands/CommandBus.php#L170-L171

Added lines #L170 - L171 were not covered by tests
}


/**
* Execute a bot command from the update text.
*
* @param array<string, mixed> $entity {@see MessageEntity} object attributes.
*/
private function process(array $entity, Update $update): void
{
$command = $this->parseCommand(
$update->getMessage()->text,
$command = $this->parseCommand($update->getText(),

Check warning on line 182 in src/Commands/CommandBus.php

View check run for this annotation

Codecov / codecov/patch

src/Commands/CommandBus.php#L182

Added line #L182 was not covered by tests
$entity['offset'],
$entity['length']
);
$entity['length']);

Check warning on line 184 in src/Commands/CommandBus.php

View check run for this annotation

Codecov / codecov/patch

src/Commands/CommandBus.php#L184

Added line #L184 was not covered by tests

$this->execute($command, $update, $entity);
}
Expand All @@ -187,10 +194,10 @@
*/
protected function execute(string $name, Update $update, array $entity): mixed
{
$command = $this->commands[$name]
?? $this->commandAliases[$name]
?? $this->commands['help']
?? collect($this->commands)->first(fn ($command): bool => $command instanceof $name);
$command = $this->commands[$name] ?? $this->commandAliases[$name] ?? $this->commands['help'] ??
collect($this->commands)->first(fn($command): bool => $command
instanceof
$name);

Check warning on line 200 in src/Commands/CommandBus.php

View check run for this annotation

Codecov / codecov/patch

src/Commands/CommandBus.php#L197-L200

Added lines #L197 - L200 were not covered by tests

return $command?->make($this->telegram, $update, $entity) ?? false;
}
Expand All @@ -202,14 +209,10 @@
*/
private function resolveCommand(CommandInterface|string $command): CommandInterface
{
if (! is_a($command, CommandInterface::class, true)) {
throw new TelegramSDKException(
sprintf(
'Command class "%s" should be an instance of "%s"',
is_object($command) ? $command::class : $command,
CommandInterface::class
)
);
if (!is_a($command, CommandInterface::class, true)) {
throw new TelegramSDKException(sprintf('Command class "%s" should be an instance of "%s"',
is_object($command) ? $command::class : $command,
CommandInterface::class));
}

$commandInstance = $this->buildDependencyInjectedClass($command);
Expand All @@ -227,23 +230,15 @@
private function checkForConflicts(CommandInterface $command, string $alias): void
{
if (isset($this->commands[$alias])) {
throw new TelegramSDKException(
sprintf(
'[Error] Alias [%s] conflicts with command name of "%s" try with another name or remove this alias from the list.',
$alias,
$command::class
)
);
throw new TelegramSDKException(sprintf('[Error] Alias [%s] conflicts with command name of "%s" try with another name or remove this alias from the list.',
$alias,
$command::class));
}

if (isset($this->commandAliases[$alias])) {
throw new TelegramSDKException(
sprintf(
'[Error] Alias [%s] conflicts with another command\'s alias list: "%s", try with another name or remove this alias from the list.',
$alias,
$command::class
)
);
throw new TelegramSDKException(sprintf('[Error] Alias [%s] conflicts with another command\'s alias list: "%s", try with another name or remove this alias from the list.',
$alias,
$command::class));
}
}
}
5 changes: 0 additions & 5 deletions src/Laravel/Facades/Telegram.php
Original file line number Diff line number Diff line change
Expand Up @@ -136,11 +136,6 @@
* @method static \Telegram\Bot\Objects\WebhookInfo getWebhookInfo()
* @method static \Telegram\Bot\Objects\Update getWebhookUpdate(bool $shouldDispatchEvents = true, ?\Psr\Http\Message\RequestInterface $request = null)
* @method static bool removeWebhook()
* @method static \Telegram\Bot\Objects\ForumTopic createForumTopic(array $params)
* @method static bool editForumTopic(array $params)
* @method static bool closeForumTopic(array $params)
* @method static bool reopenForumTopic(array $params)
* @method static bool deleteForumTopic(array $params)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are these removed?

*
* @see \Telegram\Bot\Commands\CommandBus
*
Expand Down
1 change: 0 additions & 1 deletion src/Methods/Message.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace Telegram\Bot\Methods;

use Illuminate\Support\Arr;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this removed? It's in use.

use Telegram\Bot\Actions;
use Telegram\Bot\Exceptions\TelegramSDKException;
use Telegram\Bot\Objects\Message as MessageObject;
Expand Down
12 changes: 12 additions & 0 deletions src/Objects/Update.php
Original file line number Diff line number Diff line change
Expand Up @@ -180,4 +180,16 @@
{
return (bool) $this->getMessage()->get('entities', collect())->contains('type', 'bot_command');
}

public function getText()
{
return match ($this->detectType()) {
'message' => $this->message->text,
'edited_message' => $this->editedMessage->text,
'channel_post' => $this->channelPost->text,
'edited_channel_post' => $this->editedChannelPost->text,
'callback_query' => "/callback:::".$this->callbackQuery->data,

Check warning on line 191 in src/Objects/Update.php

View check run for this annotation

Codecov / codecov/patch

src/Objects/Update.php#L188-L191

Added lines #L188 - L191 were not covered by tests
default => "",
};
}
}