How to add custom commands to a Telegram bot using Laravel?

I’m building a Telegram bot with Laravel 5.4 and the Telegram Bot SDK. I’m trying to add a custom command called StartCommand, but I’m running into issues.

I put my StartCommand class in app/StartCommand.php, thinking it would be autoloaded. My composer.json has this autoload section:

"autoload": {
    "classmap": ["database"],
    "psr-4": {"App\\": "app/"}
}

In my config/telegram.php, I added the command like this:

'commands' => [
    Telegram\\Bot\\Commands\\HelpCommand::class,
    Vendor\\App\\Commands\\StartCommand::class,
],

But when I try to use it, I get this error:

Command class "Vendor\\App\\Commands\\StartCommand" not found!

What am I doing wrong? How can I properly add and use custom commands in my Telegram bot? Any help would be great!

hey mate, i had the same problem. try moving ur StartCommand.php to app/Commands/ and change the namespace to App\Commands. then update ur config/telegram.php like this:

‘commands’ => [
Telegram\Bot\Commands\HelpCommand::class,
App\Commands\StartCommand::class,
],

should work. good luck!

I encountered a similar issue when building my first Telegram bot with Laravel. The problem lies in your namespace and file structure. Since you’re using Laravel’s default PSR-4 autoloading, your StartCommand class should be in the App namespace.

Try moving your StartCommand.php file to app/Commands/StartCommand.php and update its namespace to App\Commands. Then, in your config/telegram.php, change the command reference to:

'commands' => [
    Telegram\Bot\Commands\HelpCommand::class,
    App\Commands\StartCommand::class,
],

This should resolve the ‘class not found’ error. Remember to run composer dump-autoload after making these changes to refresh the autoloader.

Also, ensure your StartCommand class extends Telegram\Bot\Commands\Command and implements the required methods. This approach has worked well for me in several bot projects.

Based on your configuration, it seems the issue stems from an incorrect namespace and file location. Instead of ‘Vendor\App\Commands\StartCommand’, try using ‘App\StartCommand’ in your config file, as your autoload settings suggest the App namespace for files directly in the app directory.

Alternatively, consider creating a ‘Commands’ folder inside your ‘app’ directory and adjusting your namespace accordingly. This approach often helps with organization as your bot grows. Don’t forget to run ‘composer dump-autoload’ after making these changes.

If you’re still facing issues, double-check that your StartCommand class is properly implementing the necessary interfaces from the Telegram Bot SDK. Sometimes, small oversights in class structure can lead to these kinds of errors.