Skip to content

Commit

Permalink
Added new webhook options in configuration
Browse files Browse the repository at this point in the history
  • Loading branch information
luzrain committed Feb 28, 2024
1 parent 4c2f2b7 commit 532946e
Show file tree
Hide file tree
Showing 4 changed files with 92 additions and 45 deletions.
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,12 @@ telegram_bot:
request_factory: GuzzleHttp\Psr7\HttpFactory # Psr\Http\Message\RequestFactoryInterface implementation
stream_factory: GuzzleHttp\Psr7\HttpFactory # Psr\Http\Message\StreamFactoryInterface implementation
api_token: API_TOKEN # Bot api token
#secret_token: CHANGE_ME # Optional. Secret token to protect webhook endpoint from unauthenticated requests (update webhook url after change)
#allowed_updates: ['message'] # Optional. List of the update types you want your bot to receive (update webhook url after change)
#allowed_updates: ['message'] # Optional. List of the update types you want your bot to receive (run telegram:webhook:set after change)
#webhook: # run telegram:webhook:set command after change webhook settings
# url: https://localhost/tg-webhook # Optional. Webhook url
# max_connections: 40 # Optional. The maximum allowed number of simultaneous connections to the webhook
# secret_token: CHANGE_ME # Optional. Secret token to protect webhook endpoint from unauthenticated requests
# certificate: /path/to/certificate # Optional. Public key certificate
```

### Optional. Configure webhook route
Expand Down
25 changes: 16 additions & 9 deletions src/TelegramBot/Command/SetWebhookCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Luzrain\TelegramBotApi\BotApi;
use Luzrain\TelegramBotApi\Exception\TelegramApiException;
use Luzrain\TelegramBotApi\Method\SetWebhook;
use Luzrain\TelegramBotApi\Type\InputFile;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
Expand All @@ -17,41 +18,46 @@ final class SetWebhookCommand extends Command
{
public function __construct(
private BotApi $botApi,
private string|null $secretToken,
/** @var list<string> */
private array $allowedUpdates,
private string|null $webhookUrl,
private int|null $maxConnections,
private string|null $secretToken,
private string|null $certificate,
) {
parent::__construct();
}

public static function getDefaultName(): string
{
return 'telegram:webhook:set';
return 'telegram:webhook:update';
}

public static function getDefaultDescription(): string
{
return 'Set webhook url';
return 'Update webhook settings';
}

protected function configure(): void
{
$this->addOption('url', null, InputOption::VALUE_REQUIRED, 'Webhook url');
$this->addOption('max-connections', null, InputOption::VALUE_REQUIRED, 'Max connections', 40);
$this->addOption('max-connections', null, InputOption::VALUE_REQUIRED, 'Max connections');
}

protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);

if ($input->getOption('url') === null) {
$io->error('You should provide "--url" option');
$webhookUrl = $input->getOption('url') ?? $this->webhookUrl;
$maxConnections = (int) ($input->getOption('max-connections') ?? $this->maxConnections ?? 40);

if ($webhookUrl === null) {
$io->error('webhook_url config option is not set up. Provide "--url" option');

return Command::FAILURE;
}

try {
$url = $this->urlValidate($input->getOption('url'));
$url = $this->urlValidate($webhookUrl);
} catch (\RuntimeException $e) {
$io->error($e->getMessage());

Expand All @@ -61,7 +67,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int
try {
$this->botApi->call(new SetWebhook(
url: $url,
maxConnections: (int) $input->getOption('max-connections'),
certificate: $this->certificate === null ? null : new InputFile($this->certificate),
maxConnections: $maxConnections,
allowedUpdates: $this->allowedUpdates,
secretToken: $this->secretToken,
));
Expand Down
47 changes: 33 additions & 14 deletions src/config/configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
/** @php-cs-fixer-ignore */
return static function (DefinitionConfigurator $definition) {
$definition->rootNode()
->addDefaultsIfNotSet()
->children()
->scalarNode('http_client')
->isRequired()
Expand All @@ -27,23 +28,41 @@
->isRequired()
->cannotBeEmpty()
->end()
->scalarNode('secret_token')
->defaultNull()
->end()
->arrayNode('allowed_updates')
->prototype('scalar')->end()
->beforeNormalization()
->always(fn ($values) => array_map(strval(...), $values))
->beforeNormalization()
->always(fn ($values) => array_map(strval(...), $values))
->end()
->validate()
->ifTrue(fn ($configArray) => array_diff($configArray, Update::getUpdateTypes()) !== [])
->then(function ($configArray) {
if (array_diff($configArray, Update::getUpdateTypes()) !== []) {
$allowedKeys = implode(', ', Update::getUpdateTypes());
throw new \InvalidArgumentException(sprintf('Invalid updates list. Allowed updates: %s', $allowedKeys));
}
return $configArray;
})
->end()
->end()
->validate()
->ifTrue(fn ($configArray) => array_diff($configArray, Update::getUpdateTypes()) !== [])
->then(function ($configArray) {
if (array_diff($configArray, Update::getUpdateTypes()) !== []) {
$allowedKeys = implode(', ', Update::getUpdateTypes());
throw new \InvalidArgumentException(sprintf('Invalid updates list. Allowed updates: %s', $allowedKeys));
}
return $configArray;
})
->arrayNode('webhook')
->info('Webhook options')
->addDefaultsIfNotSet()
->children()
->scalarNode('url')
->defaultNull()
->end()
->integerNode('max_connections')
->defaultNull()
->min(1)
->max(100)
->end()
->scalarNode('secret_token')
->defaultNull()
->end()
->scalarNode('certificate')
->defaultNull()
->end()
->end()
->end()
->end()
->end();
Expand Down
57 changes: 37 additions & 20 deletions src/config/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,12 @@
return static function (array $config, ContainerBuilder $container) {
$container
->autowire(BotApi::class)
->setArgument('$requestFactory', new Reference($config['request_factory']))
->setArgument('$streamFactory', new Reference($config['stream_factory']))
->setArgument('$client', new Reference($config['http_client']))
->setArgument('$token', $config['api_token'])
->setArguments([
new Reference($config['request_factory']),
new Reference($config['stream_factory']),
new Reference($config['http_client']),
$config['api_token'],
])
;

$container
Expand All @@ -35,57 +37,72 @@

$container
->register('telegram_bot.webhook_controller', WebHookController::class)
->setArgument('$updateHandler', new Reference('telegram_bot.update_handler'))
->setArgument('$secretToken', $config['secret_token'])
->addTag('controller.service_arguments')
->setArguments([
new Reference('telegram_bot.update_handler'),
$config['webhook']['secret_token'],
])
;

$container
->register('telegram_bot.long_polling_service', LongPollingService::class)
->setArgument('$botApi', new Reference(BotApi::class))
->setArgument('$allowedUpdates', $config['allowed_updates'])
->setArguments([
new Reference(BotApi::class),
$config['allowed_updates'],
])
;

$container
->register('telegram_bot.set_webhook_command', SetWebhookCommand::class)
->setArgument('$botApi', new Reference(BotApi::class))
->setArgument('$secretToken', $config['secret_token'])
->setArgument('$allowedUpdates', $config['allowed_updates'])
->addTag('console.command')
->setArguments([
new Reference(BotApi::class),
$config['allowed_updates'],
$config['webhook']['url'],
$config['webhook']['max_connections'],
$config['webhook']['secret_token'],
$config['webhook']['certificate'],
])
;

$container
->register('telegram_bot.get_webhook_command', WebhookInfoCommand::class)
->setArgument('$botApi', new Reference(BotApi::class))
->addTag('console.command')
->setArguments([new Reference(BotApi::class)])
;

$container
->register('telegram_bot.delete_webhook_command', DeleteWebhookCommand::class)
->setArgument('$botApi', new Reference(BotApi::class))
->addTag('console.command')
->setArguments([new Reference(BotApi::class)])
;

$container
->register('telegram_bot.polling_command', PolllingStartCommand::class)
->setArgument('$longPollingService', new Reference('telegram_bot.long_polling_service'))
->setArgument('$updateHandler', new Reference('telegram_bot.update_handler'))
->setArgument('$botApi', new Reference(BotApi::class))
->addTag('console.command')
->setArguments([
new Reference('telegram_bot.long_polling_service'),
new Reference('telegram_bot.update_handler'),
new Reference(BotApi::class),
])

;

$container
->register('telegram_bot.menu_button_set_commands', ButtonSetCommandsCommand::class)
->setArgument('$botApi', new Reference(BotApi::class))
->setArgument('$commandMetadataProvider', new Reference('telegram_bot.command_metadata_provider'))
->setArgument('$descriptionProcessor', new Reference('telegram_bot.description_processor'))
->addTag('console.command')
->setArguments([
new Reference(BotApi::class),
new Reference('telegram_bot.command_metadata_provider'),
new Reference('telegram_bot.description_processor'),
])

;

$container
->register('telegram_bot.menu_button_delete_command', ButtonDeleteCommand::class)
->setArgument('$botApi', new Reference(BotApi::class))
->addTag('console.command')
->setArguments([new Reference(BotApi::class)])
;

$container
Expand Down

0 comments on commit 532946e

Please sign in to comment.