irazasyed / telegram-bot-sdk

🤖 Telegram Bot API PHP SDK. Lets you build Telegram Bots easily! Supports Laravel out of the box.

Home Page:https://telegram-bot-sdk.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

make a command with dynamical name

irpcpro opened this issue · comments

PHP version
8.1
irazasyed/telegram-bot-sdk version
3.10
Laravel version
10

hi
i want to make a command with dynamic name.
i saw another issue #196 but this is not gonna work for me.
because i have so many posts which i want to user edit each one of them.
i have to write a command-link beside of each post like this :

#post1
lorem ipsum
/edit_post_1  -  /remove_post_1

#post2
lorem ipsum
/edit_post_2  -  /remove_post_2

and i want to route these commands to edit_post_ & remove_post_ but i don't know how.
i've tried this: /edit_post 2 - /remove_post 2
but this isn't clickable for user to send post_id with it.
this will just send command by itself. not with the number.

This is an interesting use case. Here's how I would do it tho:

# Your post IDs...from database?
$postIds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

$editPostCommands = array_map(fn($postId) => new \App\Telegram\Commands\EditPostCommand($postId), $postIds);

# This should always be before commands handler.
Telegram::addCommands($editPostCommands);

$update = Telegram::commandsHandler(true);
// EditPostCommand.php
<?php

namespace App\Telegram\Commands;

use Telegram\Bot\Commands\Command;

/**
 * Class EditPostCommand.
 */
class EditPostCommand extends Command
{
    /**
     * @var string Command Name
     */
    protected string $name = 'edit_post';

    /**
     * @var string Command Description
     */
    protected string $description = 'Edit a post by ID.';

    public function __construct(int $postId)
    {
        $this->setName("{$this->name}_{$postId}");
    }

    /**
     * {@inheritdoc}
     */
    public function handle(): void
    {
        // Get the post ID from the command name
        $postId = str_replace('edit_post_', '', $this->name);

        // Do something with the post ID

        $this->replyWithMessage(['text' => 'You are editing Post ID: ' . $postId]);
    }
}

Doesn't this take a lot of resources?
because if every user has 20 posts and they never wanna edit them every time.
It is supposed to be used for each user for posts and categories.

@irpcpro You could add pagination and limit it in that case but it shouldn't be a problem as such.

I don't know what you're trying to do. I gave you a solution to build dynamic commands, just what you asked for.

If I was to do this, I would either go for one command with arguments like /edit_post 1 or use callback query with pagination built into it, so when the user taps the edit button, it would send info for that particular post.