Giter Site home page Giter Site logo

nutgram / nutgram Goto Github PK

View Code? Open in Web Editor NEW
448.0 448.0 47.0 2.39 MB

The Telegram bot framework that doesn't drive you nuts.

Home Page: https://nutgram.dev

License: MIT License

PHP 100.00%
api bot-framework framework hacktoberfest laravel library php php8 telegram telegram-bot telegram-bot-api telegram-bots wrapper

nutgram's Introduction

SWUbanner


Latest Version on Packagist PHP Total Downloads GitHub API

Test Suite Maintainability Test Coverage

Documentation Laravel Symfony

The Telegram bot framework that doesn't drive you nuts.

This framework takes advantage of the latest PHP 8.2 features, and tries to make the speed, scalability and flexibility of use its strength, it will allow you to quickly make simple bots, but at the same time, it provides more advanced features to handle even the most complicated flows.

<?php

use SergiX44\Nutgram\Nutgram;

$bot = new Nutgram($_ENV['TOKEN']);

$bot->onCommand('start', function(Nutgram $bot) {
    $bot->sendMessage('Ciao!');
});

$bot->onText('My name is {name}', function(Nutgram $bot, string $name) {
    $bot->sendMessage("Hi $name");
});

$bot->run();

πŸš€ Installation

You can install the package via composer:

composer require nutgram/nutgram

Looking for a Laravel or Symfony integration? Check out Nutgram Laravel and Nutgram Symfony Bundle.

πŸ‘“ Usage

Official Documentation on https://nutgram.dev/

🧩 Features

  • Latest PHP 8.2 features
  • Framework agnostic
  • Framework integrations (Laravel and Symfony)
  • Cache system (you can use your own cache system that implements PSR-16 CacheInterface)
  • Logging system (you can use your own logger that implements PSR-3 LoggerInterface)
  • Flexible update processing
  • Supports all types and methods according to the last Telegram Bot API update
  • Handlers system
  • Middleware system
  • Grouping system to apply middleware and scopes to multiple handlers
  • Auto-registration of bot commands with scope support
  • Helpers for common tasks and proxy methods for a shorter syntax
  • Storage system for global and user data
  • Enhanced keyboard management
  • Conversations system
  • InlineMenu class for easy creation of inline menu messages
  • Extend Nutgram class and Telegram types with user-created methods
  • Bulk message sending
  • Chunked message sending
  • Using enums where possible
  • Customizable error handling
  • Web Validation
  • Testing system
  • Deep Link helper class

πŸ”° Supported versions

Nutgram PHP Support Until
^3.0 ^8.0 EOL
^4.0 ^8.2 On going

✨ Projects with this library

Is your project using Nutgram? Let us know, feel free to add yours!

βš—οΈ Testing

composer test

πŸ“ƒ Changelog

Please see CHANGELOG for more information on what has changed recently.

πŸ… Credits

πŸ“– License

The MIT License (MIT). Please see License File for more information.

nutgram's People

Contributors

asanikovich avatar lukasss93 avatar miki131 avatar mkhab7 avatar pe46dro avatar sergix44 avatar shnurok42 avatar stylecibot avatar superxdev avatar tiamenti avatar z3d0x avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nutgram's Issues

[BUG] `Conversation` PHPStan static analysis fail

Nutgram version

3.17.0

Describe the bug

PHPStan static analysis on start Method in SergiX44\Nutgram\Conversations\Conversation

 /**
 * @param  Nutgram  $bot
 *
 * @return never
 */
public function start(Nutgram $bot)
{
    throw new RuntimeException('Attempt to start an empty conversation.');
}

Because of the @return never doc block static analysis of PHPStan fails

Method App\Telegram\Conversations\MyConversation::start() should always throw an exception or
terminate script execution but doesn't do that.

To Reproduce

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior

PHPStan static analysis to work on SergiX44\Nutgram\Conversations\Conversation start method, out of the box

Screenshots

image

Additional context

I know I can fix this by using a PHPStan stub to override the return type in userland (my code).

Feel free to close this if you don't think this is an issue and should addressed

[FEATURE] Bulk Messenger SendMessage to channels

Is your feature request related to a problem? Please describe.

ChatID type is int, but telegram sendMessage api method accepts only string (@channel) format for channels

I think there are multiple ways to achieve this:

Add string type to chats
$bot->getBulkMessenger()->setChats(['@channel'])->setText('Test')->startSync();

Add setChannels method and merge them into chat_id at BulkManager class
$bot->getBulkMessenger()->setChannels(['@channel'])->setText('Test')->startSync();

Describe the solution you'd like

No response

Describe alternatives you've considered

No response

Additional context

No response

[BUG] onMessage not working on Laravel

Nutgram version

3.17.1

Describe the bug

I am using Nutgram on Laravel 9 with webhook. onMessage method is not working while onText is working fine.

To Reproduce

  1. Add this route in telegram.php
$bot->onMessage(function(Nutgram $bot) {
    $bot->sendMessage('TEST');
});

$bot->onText('something',function(Nutgram $bot) {
    $bot->sendMessage('TEST SOMETHING');
});
  1. Test the code, the output is like this

Screenshot 2023-03-25 at 6 38 24 AM

Expected behavior

onMessage method is working without issues.

Screenshots

No response

Additional context

PHP 8.0.27

[BUG] Bot called by other commands

Nutgram version

3.7.9

Describe the bug

My bot reply to commands explicitly addressed to other bots when Group Privacy is disabled in BotFather

To Reproduce

  1. Go to BotFather
  2. Select your bot
  3. Click on "Bot Setting" button
  4. Click on "Group Privacy" button
  5. Click on "Turn off" button
  6. Add your bot in a group with other bots
  7. See the screenshot below

Expected behavior

I expect my bot to respond only to commands addressed to it

Screenshots

immagine

Additional context

No response

No content when asserting multipart methods

Describe the bug
Nutgram returns null when asserting multipart methods,

To Reproduce
Steps to reproduce the behavior:

  1. Send a resource object via sendDocument (or similar methods)
  2. Assert the method

Expected behavior
The right content

Screenshots
immagine

[FEATURE] Message Chunk

Is your feature request related to a problem? Please describe.

Reaching message text limit will throw Telegram HTTP exception

Describe the solution you'd like

Send multiple telegram messages instead off falling to exception

Describe alternatives you've considered

There is a great and simple solution in Telegram Notification Channel

Sending message
https://github.com/laravel-notification-channels/telegram/blob/76299fa06f48cb175e17ea951ccf3b185329a1ac/src/TelegramChannel.php#L70

Message chunk implementation
https://github.com/laravel-notification-channels/telegram/blob/76299fa06f48cb175e17ea951ccf3b185329a1ac/src/TelegramChannel.php#L128

Additional context

No response

[BUG] onMessage() is not working

Describe the bug

I have a code in CodeIgniter based there below :

<?php

namespace App\Controllers;

use SergiX44\Nutgram\Nutgram;
use SergiX44\Nutgram\RunningMode\Webhook;

class Home extends BaseController
{
    public function index()
    {
        $token = 'mybottoken';
        $stelapi = new Nutgram($token);
        $stelapi->setRunningMode(Webhook::class);

        $stelapi->onMessage(function(Nutgram $nutapi) {
            $nutapi->sendMessage('i heard that');
        });

        $stelapi->run();
    }
}

When i call onText() it works, and then when i try onMessageType('photo',$callable) it works too (with message type is photo, i mean i sent a photo),

but when i try with text with onMessage($callable) it looks like it doesn't work, the bot didn't send any message, and onMessage(MessageType::TEXT, $callable) doesn't work too. Why ? idk if its from me or a bug. thankyou.

To Reproduce

explained above.

Expected behavior

When onMessage() called / i texted something in my Telegram bot, it should say back with i heard that

Screenshots

No response

Additional context

No response

[BUG] when split long message is true (Laravel)

Nutgram version

latest

Describe the bug

if in config split long message is on I got a bug in Conversation (InlineMenu used)

To Reproduce

turn on split_long_message in config
use Conversation with InlineMenu

Expected behavior

change button in menu

Screenshots

image

Additional context

No response

[FEATURE] Add command scopes support

Is your feature request related to a problem? Please describe.

No.

Describe the solution you'd like

No response

Describe alternatives you've considered

No response

Additional context

For more information read Command Scopes

[BUG] Test does not working in Symfony

Nutgram version

3.16.0

Describe the bug

Test does not working in Symfony, throw below error:

Class "Illuminate\Testing\Assert" not found

To Reproduce

  1. See error

Expected behavior

Fix error.

Screenshots

No response

Additional context

No response

Syntax error

I set up the environment

` $bot = new Nutgram($_ENV['TELEGRAM_TOKEN']); // new instance
$bot->setRunningMode(Webhook::class);
$bot->onMessage(function (Nutgram $bot) {
$bot->sendMessage('You sent a message!');
});

            $message = $bot->sendMessage('Hi!', ['chat_id' => 1289432718]);

           
      

        $bot->run();

`

The script runs once , and it fails in error with syntax error. (error causing script )
I digged a little , changed the code (on line Webhook.php:37) json_decode($input, flags: JSON_THROW_ON_ERROR),
to json_decode($input) and i got the JsonMapper::map() requires first argument to be an object, NULL given.

the script is working is polling mode . I can't figure it out what's wrong.
any advice would be appriciated. thanks

[BUG] Class "Symfony\Component\HttpFoundation\Response" not found

Nutgram version

3.7.8, 3.8.0

Describe the bug

When I download a file from user

$bot->onMessageType(MessageTypes::DOCUMENT, function (Nutgram $bot) {
    $document = $bot->message()->document;
    $file = $bot->getFile($document->file_id);
    $bot->downloadFile($file, BASE_PATH . FILES_FOLDER . "/" . $document->file_name);
}

the file is downloaded and saved in the folder, but in $bot->onException I get an error:

Error: Class "Symfony\Component\HttpFoundation\Response" not found in D:\projects\report-bot\vendor\nutgram\nutgram\src\Telegram\Client.php:186
Stack trace:
#0 D:\projects\report-bot\receive.php(67): SergiX44\Nutgram\Nutgram->downloadFile()
#1 [internal function]: {closure}() 
#2 D:\projects\report-bot\vendor\nutgram\nutgram\src\Handlers\Handler.php(96): call_user_func()
#3 [internal function]: SergiX44\Nutgram\Handlers\Handler->__invoke()
#4 D:\projects\report-bot\vendor\nutgram\nutgram\src\Middleware\Link.php(41): call_user_func()
#5 D:\projects\report-bot\vendor\nutgram\nutgram\src\Nutgram.php(260): SergiX44\Nutgram\Middleware\Link->__invoke()
#6 D:\projects\report-bot\vendor\nutgram\nutgram\src\Nutgram.php(248): SergiX44\Nutgram\Nutgram->fireHandlers()
#7 D:\projects\report-bot\vendor\nutgram\nutgram\src\RunningMode\Webhook.php(68): SergiX44\Nutgram\Nutgram->processUpdate()
#8 D:\projects\report-bot\vendor\nutgram\nutgram\src\Nutgram.php(220): SergiX44\Nutgram\RunningMode\Webhook->processUpdates()
#9 D:\projects\report-bot\receive.php(91): SergiX44\Nutgram\Nutgram->run() 
#10 {main}

To Reproduce

  1. Send a document to the bot
  2. Save the document on the server
  3. Catch errors

Expected behavior

downloadFile() works without errors

Screenshots

No response

Additional context

No response

[BUG] getUpdates uses POST, but 'offset' must be GET param

Nutgram version

3.8.0

Describe the bug

To mark update as read we need to send offset GET param to Telegram getUpdates endpoint.

But method \SergiX44\Nutgram\Telegram\Client@getUpdates uses requestJson and it always uses POST.

I don't know if it works as expected with $bot->run(), but i'm trying to handle my updates with
$bot->getUpdates(['offset' => $highestId + 1]) and it doesn't mark any updates as read

To Reproduce

$bot = new Nutgram(config('nutgram.token'));

// Send message to the Telegram bot

$updates = $bot->getUpdates();

foreach ($updates as $update) {
    $highestId = $update->update_id;
}

// This should mark all the updates as read
$bot->getUpdates(['offset' => $highestId + 1]);

// But all the updates is still there
$updates = $bot->getUpdates();

assert(count($updates) !== 0); // true

Expected behavior

Updates mark as processed when getUpdates called with offset higher than last update id

Screenshots

No response

Additional context

No response

[FEATURE]

Is your feature request related to a problem? Please describe.

Please can you give example bot code without using composer

[BUG] ArgumentCountError: Too few arguments to function CLASS::__invoke()

Nutgram version

3.8.0

Describe the bug

Hi.

I sent an inline keyboard with a button to my bot that the button have this data:

$tg->sendMessage('TEST', [
    'reply_markup' => json_encode([
        'inline_keyboard' => [
            [
                ['text' => 'TEST BUTTON', 'callback_data' => 'c=uud&pid=1&bid=1']
            ]
        ]
    ])
]);

c=uud&pid=1&bid=1

In above callback_data, c is Command, bid is bot_id and pid is plan_id.

image

===============

Here I have defined that if a data is sent with this pattern (when this button is clicked), it will send the bid and pid values to the BuyCommand class:

image

BuyCommand class:

image

===============

But I get the following error:

[15-Nov-2022 16:33:25 Asia/Tehran] ArgumentCountError: Too few arguments to function App\Commands\BuyCommand::__invoke(), 2 passed and exactly 3 expected in E:\Programs\xampp\htdocs\ph\ds\src\bm\app\Commands\BuyCommand.php:12 Stack trace: #0 [internal function]: App\Commands\BuyCommand->__invoke(Object(SergiX44\Nutgram\Nutgram), '1') #1 E:\Programs\xampp\htdocs\ph\ds\vendor\nutgram\nutgram\src\Handlers\Handler.php(96): call_user_func(Object(App\Commands\BuyCommand), Object(SergiX44\Nutgram\Nutgram), pid: '1') #2 [internal function]: SergiX44\Nutgram\Handlers\Handler->__invoke(Object(SergiX44\Nutgram\Nutgram), NULL) #3 E:\Programs\xampp\htdocs\ph\ds\vendor\nutgram\nutgram\src\Middleware\Link.php(41): call_user_func(Object(SergiX44\Nutgram\Handlers\Handler), Object(SergiX44\Nutgram\Nutgram), NULL) #4 E:\Programs\xampp\htdocs\ph\ds\src\bm\index.php(83): SergiX44\Nutgram\Middleware\Link->__invoke(Object(SergiX44\Nutgram\Nutgram)) #5 [internal function]: {closure}(Object(SergiX44\Nutgram\Nutgram), Object(SergiX44\Nutgram\Middleware\Link)) #6 E:\Programs\xampp\htdocs\ph\ds\vendor\nutgram\nutgram\src\Middleware\Link.php(41): call_user_func(Object(Closure), Object(SergiX44\Nutgram\Nutgram), Object(SergiX44\Nutgram\Middleware\Link)) #7 E:\Programs\xampp\htdocs\ph\ds\vendor\nutgram\nutgram\src\Nutgram.php(260): SergiX44\Nutgram\Middleware\Link->__invoke(Object(SergiX44\Nutgram\Nutgram)) #8 E:\Programs\xampp\htdocs\ph\ds\vendor\nutgram\nutgram\src\Nutgram.php(248): SergiX44\Nutgram\Nutgram->fireHandlers(Array) #9 E:\Programs\xampp\htdocs\ph\ds\vendor\nutgram\nutgram\src\RunningMode\Webhook.php(68): SergiX44\Nutgram\Nutgram->processUpdate(Object(SergiX44\Nutgram\Telegram\Types\Common\Update)) #10 E:\Programs\xampp\htdocs\ph\ds\vendor\nutgram\nutgram\src\Nutgram.php(220): SergiX44\Nutgram\RunningMode\Webhook->processUpdates(Object(SergiX44\Nutgram\Nutgram)) #11 E:\Programs\xampp\htdocs\ph\ds\src\bm\index.php(167): SergiX44\Nutgram\Nutgram->run() #12 {main}

===========================

On the other hand, when I only change the value of one of the bid or pid keys, it works well ! :

$tg->sendMessage('TEST 2', [
    'reply_markup' => json_encode([
        'inline_keyboard' => [
            [
                ['text' => 'TEST BUTTON', 'callback_data' => 'c=uud&pid=1&bid=2'] // bid's value changed from 1 to 2
            ]
        ]
    ])
]);

Result:
image

Where is the problem from?

It seems that both bid and pid cannot have the same value and must be different!

To Reproduce

...

Expected behavior

...

Screenshots

No response

Additional context

No response

[BUG] Wrong permissions for the created directory

Nutgram version

3.8.1

Describe the bug

I'm trying to save a file by using $bot->downloadFile($file, "/home/userqwe/mybasepath/files/username/filename.jpg") on linux host, where directory username doesn't exist. Bot creates directory 'username' but with the permissions 0001, and then I get an error: RuntimeException: Unable to open "/home/userqwe/mybasepath/files/username/filename.jpg" using mode "w+" fopen(/home/userqwe/mybasepath/files/username/filename.jpg): Failed to open stream: Permission denied in /pathtoproject/vendor/guzzlehttp/psr7/src/Utils.php:357 ... and the file is not saved.
In https://github.com/nutgram/nutgram/blob/master/src/Telegram/Client.php#L174 you call mkdir with true as second argument instead of int, so maybe this is a typo and true is converted to 0001.

On win10 (when permissions are ignored) it works without errors.
If I manually change the foder permissions from 0001 to 0755 and then download the file there again, then everything works without errors.

To Reproduce

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior

bot creates folders that are writable

Screenshots

No response

Additional context

No response

[FEATURE] Ability to manage multiple bots in one Laravel project

Is your feature request related to a problem? Please describe.

Now I'm doing a project where I have to manage 2 (possibly more) Telegram bots at the same time. I just made a copy of your NutgramServiceProvider and created

$adminBot = new Nugram('admin token');

But to experience the full pleasure of using such a bot, I also have to create each of the commands separately for this bot. (RunCommand, RegisterCommandsCommand, HookInfoCommand...)

I would like to be able to manage multiple bots in one project out of the box

Describe the solution you'd like

Π‘an make a command that will create ServiceProvider, commands, route file, config file for new bot.
Like a "nutgram:make:bot"

Describe alternatives you've considered

No response

Additional context

No response

[BUG] Unable to test with abstract types

Nutgram version

3.11.0+

Describe the bug

I'm unable to test updates with the abstract class ChatMember

To Reproduce

Consider this code:

bot()
    ->hearUpdateType(UpdateTypes::MY_CHAT_MEMBER, [
        'chat' => ['id' => 321],
        'from' => ['id' => 321],
        'new_chat_member' => ['status' => ChatMemberStatus::MEMBER],
    ])
    ->reply()
    ->assertNoReply();

Nutgram version < 3.11.0:
OK

Nutgramversion >= 3.11.0:
Error : Cannot instantiate abstract class SergiX44\Nutgram\Telegram\Types\Chat\ChatMember

Expected behavior

Restore previous behavior

Screenshots

immagine

Additional context

This problem is caused by old type property inside ChatMemberUpdated.php:

public ChatMember $old_chat_member;
public ChatMember $new_chat_member;

It should be:

public ChatMemberOwner|ChatMemberAdministrator|ChatMemberMember|ChatMemberRestricted|ChatMemberLeft|ChatMemberBanned $old_chat_member;
public ChatMemberOwner|ChatMemberAdministrator|ChatMemberMember|ChatMemberRestricted|ChatMemberLeft|ChatMemberBanned $new_chat_member;

However, it will throw another error:
Error : Call to undefined method ReflectionUnionType::getName()

Because container->get is unable to resolve abstract instances or union types:
immagine

[BUG]

Nutgram version

^3.7

Describe the bug

Hi,

This is my code:

<?php

use App\Commands\StartCommand;
use SergiX44\Nutgram\Nutgram;
use SergiX44\Nutgram\RunningMode\Webhook;

$bot = new Nutgram('TOKEN');
$bot->setRunningMode(Webhook::class);
$bot->onCommand('start', StartCommand::class);
$bot->run();

StartCommand class:

<?php

namespace App\Commands;

use SergiX44\Nutgram\Nutgram;

class StartCommand {
    public function __invoke(Nutgram $bot, $param)
    {
        $bot->sendMessage('START');
    }
}

The above code produces this error:

[08-Oct-2022 16:41:09 Europe/Berlin] PHP Fatal error:  Uncaught Error: Call to a member function setParameters() on bool in E:\Programs\xampp\htdocs\ph\ds\vendor\nutgram\nutgram\src\Nutgram.php:292
Stack trace:
#0 E:\Programs\xampp\htdocs\ph\ds\vendor\nutgram\nutgram\src\Nutgram.php(262): SergiX44\Nutgram\Nutgram->fireExceptionHandlerBy('EXCEPTION', Object(ArgumentCountError))
#1 E:\Programs\xampp\htdocs\ph\ds\vendor\nutgram\nutgram\src\Nutgram.php(247): SergiX44\Nutgram\Nutgram->fireHandlers(Array)
#2 E:\Programs\xampp\htdocs\ph\ds\vendor\nutgram\nutgram\src\RunningMode\Webhook.php(68): SergiX44\Nutgram\Nutgram->processUpdate(Object(SergiX44\Nutgram\Telegram\Types\Common\Update))
#3 E:\Programs\xampp\htdocs\ph\ds\vendor\nutgram\nutgram\src\Nutgram.php(219): SergiX44\Nutgram\RunningMode\Webhook->processUpdates(Object(SergiX44\Nutgram\Nutgram))
#4 E:\Programs\xampp\htdocs\ph\ds\index.php(119): SergiX44\Nutgram\Nutgram->run()
#5 {main}
  thrown in E:\Programs\xampp\htdocs\ph\ds\vendor\nutgram\nutgram\src\Nutgram.php on line 292

where is the problem from ?!

To Reproduce

....

Expected behavior

Sending Β«STARTΒ» to user.

Screenshots

No response

Additional context

No response

[BUG]

Nutgram version

^3.8

Describe the bug

This method onApiError is not working this way (with a pattern):

$bot->onApiError('chat not found', function (Nutgram $bot, TelegramException $ex) {
    $bot->sendMessage('chat not found!');
});

Can you please test it?

And another issue is that when the onApiError method was called, the code execution continued. For example, when in a conversation. Is this normal?

Thank you

To Reproduce

...

Expected behavior

...

Screenshots

No response

Additional context

No response

Call step in another conversation

class FindDrugConversation extends Conversation
{
    public function start(Nutgram $bot)
    {
        // if location not choosed
        (new ChooseLocationConversation)->start($bot);
        return;
 }

// This not work

[FEATURE] Testing/Mocking system

Is your feature request related to a problem? Please describe.
No but I can't test my bot's code

Describe the solution you'd like
Provide a good way to test the bot code like Laravel and/or Botman

Describe alternatives you've considered
None.

Additional context
Example/Idea:
context

[BUG] onMessageType MessageTypes::PHOTO is excuting multiple times for 1 photo

Nutgram version

3.16.0

Describe the bug

I was testing your API today. Met with a bug related to onMessageType : PHOTO. It executes multiple times when only 1 image is sent. The execution doesn't stop until you remove the code from the webhook page.
But the problem not appears on onMessageType : AUDIO. I haven't tested the other media types.

Please find the screenshots attached.

To Reproduce

Use below code

$bot->onMessageType(MessageTypes::PHOTO, function (Nutgram $bot) {
    $bot->sendMessage('Nice pic!');
});

Expected behavior

The function should only execute 1 time for 1 photo.

Screenshots

onMessageType : PHOTO
image

onMessageType : AUDIO
image

Additional context

No response

[BUG] Invalid regex behavior

Nutgram version

3.16.0

Describe the bug

Regexp doesn't work correctly

 $bot->onText('https://(www\.)?[a-z]{2}', function (Nutgram $bot) {
            $bot->sendMessage('url correct');
        });

Incorrect handling of {2}

Here:

SergiX44\Nutgram\Handlers\Handlers.php;
line: 74

$regex = '/^'.preg_replace(self::PARAM_NAME_REGEX, '(?<$1>.*)', $pattern).'?$/miu';

Currently only works like this: {2,2}

To Reproduce

See in description

Expected behavior

See in description

Screenshots

No response

Additional context

No response

Error: Typed property SergiX44\Nutgram\Conversations\Conversation::$bot must not be accessed before initialization in file

Describe the bug

I'm using webhook mode and I'm getting this error.

Error: Typed property SergiX44\Nutgram\Conversations\Conversation::$bot must not be accessed before initialization in file /home/***/public_html/vendor/nutgram/nutgram/src/Conversations/Conversation.php on line 68

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use SergiX44\Nutgram\Conversations\Conversation;
use SergiX44\Nutgram\Nutgram;
use SergiX44\Nutgram\Telegram\Attributes\ParseMode;
use SergiX44\Nutgram\Telegram\Types\Message\Message;
use SergiX44\Nutgram\Telegram\Types\Keyboard\InlineKeyboardButton;
use SergiX44\Nutgram\Telegram\Types\Keyboard\InlineKeyboardMarkup;
use Log;

class TelegramController extends Conversation
{


    public function start(Nutgram $bot)
    {
        
        $bot->sendMessage('What is your name?');
        $this->next('askFlavors');
    }

    public function askFlavors(Nutgram $bot)
    {
        Log::info('DATA');
        Log::info($bot->isCallbackQuery());
    }

To Reproduce

routes/telegram.php


<?php
/** @var SergiX44\Nutgram\Nutgram $bot */

/*
|--------------------------------------------------------------------------
| Nutgram Handlers
|--------------------------------------------------------------------------
|
| Here is where you can register telegram handlers for Nutgram. These
| handlers are loaded by the NutgramServiceProvider. Enjoy!
|
*/

$bot->onCommand('start', [\App\Http\Controllers\TelegramController::class, 'start'])->description('The start command!');

Expected behavior

Go to next step

Screenshots

No response

Additional context

No response

[BUG] User id detection mistake

Nutgram version

3.17.1

Describe the bug

Either i don't understand something or Nutgram detects userId wrong.
In Nutgram::stepConversation userId equal to botId, but when you get currentConversation in ResolveHandlers::currentConversation it detects as valid userId

To Reproduce

  1. Create simple two step conversation
  2. Begin it
  3. In ConversationCache dump userId it will be equal to your botId
  4. Dump same userId while Nutgram trying to restore Conversation it will be equal to userId

Expected behavior

UserId equal to UserId
image

Screenshots

image

Additional context

No response

[BUG] onText => message()->delete() - message object empty

Nutgram version

3.8.0

Describe the bug

// telegram.php

$bot->onText('Rent', RentConversation::class);
// 'Rent' message comes from menu when user click on it
// RentConversation::class

public function start(Nutgram $bot){
      $bot->message()?->delete(); // throw something like message object empty exception
      $bot->deleteMessage($bot->chatId(), $bot->messageId()); // work as expected
}

To Reproduce

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior

Message should be deleted with $bot->message()->delete() as I think

Screenshots

No response

Additional context

No response

[FEATURE] Back to past step in conversations

Is your feature request related to a problem? Please describe.

sometimes in a conversetion we need to back one step back and this cannot be done right now .

Describe the solution you'd like

No response

Describe alternatives you've considered

No response

Additional context

No response

[FEATURE] Send bulk message

Is your feature request related to a problem? Please describe.

Send bulk message to huge number of users and return result of success and fails .

Describe the solution you'd like

No response

Describe alternatives you've considered

No response

Additional context

No response

editMessageText with inline_message_id

When i use edit Inline message with inline_message_id and not chat_id & message_id, I will get : Bad Request: chat not found.

$bot->editMessageText("Text", ['inline_message_id' => $bot->chosenInlineResult()->inline_message_id]);

Please remove chat_id & message_id from json array when they are Null.

issue with the handlers ( onCallbackQueryData , ... )

Discussed in #348

Originally posted by poorbash February 27, 2023
Hi

There is a problem...

My Code :

$bot->onCommand('account', AccountCommand::class); # 1

$bot->onCallbackQueryData("acc/bts", [AccountCommand::class, 'bots']); # 2

$bot->onCallbackQueryData("acc/bts/bt/{botId}", [AccountCommand::class, 'bot']); # 3

$bot->onCallbackQueryData("acc/bts/bt/{botId}/invs", [AccountCommand::class, 'botInvoices']); # 4

when i click on the #4 , the #3 executes and after that the #4 !!
why this happens?
i just wanna the #4 to execute . not the #3 ...

I think the problem is with the acc/bts/bt/{botId} value. but why ?

i tried to put $ sign to the end of patterns . but it's not working ...

[BUG] Each page update triggers a connection to the TG server

Nutgram version

3.17.1

Describe the bug

I use laravel + nutgram, there is also a back office for employees, I noticed that the more intensive requests are received in routing, the more often an error in the bot begins to appear:

$bot->onApiError -> {"msg":"Too Many Requests: retry after 2041","code":429,"file":"/var/www/bot-helper.net/vendor/nutgram/nutgram/src/Telegram/Client.php","line":340}

To Reproduce

'routes' => true,
'mixins' => true,

It's enough to simply update any page about 20 times in a row and this error will begin to pour in

Expected behavior

Every update of the laravel page should not connect to telegram servers

Screenshots

No response

Additional context

I suspect it has to do with the Nut g ram Service Provider and its code:

if ($app->runningInConsole()) {
                $bot->setRunningMode(Polling::class);
            } else {
                $webhook = Webhook::class;
                if (config('nutgram.safe_mode', false)) {
                    // take into account the trust proxy Laravel configuration
                    $webhook = new Webhook(fn () => $app->make('request')?->ip());
                }

                $bot->setRunningMode($webhook);
            }

[BUG] Correct conversation recognition

Describe the bug

Unfortunately, if a user being in conversation in two bots with the same source code on the same server ( using same cache adapter ) ,
there will be Confluence/interference because the chat_id and user_id is same !!!

To Reproduce

just run two bots with same code and same server ( same cache adapter ) then start a conversation !
Because bot_id is not used in conversation step set and recovery, you will see Confluence.

Expected behavior

add bot_id in conversations !

Screenshots

No response

Additional context

No response

[BUG] Nutaram does not get Laravel Cache system by default.

Nutgram version

3.16.0

Describe the bug

I'm using laravel 9. The cache wasn't working so I wasn't able to use Conversations.

In the documentation it says that if you use laravel, you don't need to do anything for the cache to work.

I'm suspecting that in versions prior to laravel 9 the file config/nutgram.php could detect the laravel cache. But in Laravel 9, it can't.

I managed to solve this problem using the following code directly in the controller:

$bot = new Nutgram(env('TELEGRAM_TOKEN'), [
    'cache' => \Cache::store('redis'),
]);

But if I try to implement it as a default setting in config/telegram.php, I got a error:

'config' => [
    'cache' => \Cache::store('redis'),
],

Generates the error:

Class "Cache" not found

To Reproduce

  1. Install laravel 9
  2. Install nutgram
  3. Modify config/nutgram.php 'config' attribute to use 'cache' => \Cache::store('redis'),

Expected behavior

Cache everything

Screenshots

No response

Additional context

No response

Send message to saved chat id not working

Nutgram version

Current

Describe the bug

When I subsantiate the class I then immediately send a message to a chat ID that I have made note of from a prior chat and the message does not show up in the thread on the telegram app

To Reproduce

use SergiX44\Nutgram\Nutgram;

$bot = new Nutgram($_ENV['TOKEN']);

$chatid = 123456;
$bot->sendMessage('Ciao!', ['chat_id'=>$chatid]);

Expected behavior

Sends message to chat

Screenshots

No response

Additional context

No response

[BUG] 405 Method Not Allowed

Nutgram version

3.9

Describe the bug

I have installed the package on my laravel (v9) project. I have done all as writen in documentation here https://nutgram.dev/docs/configuration/laravel

Created TelegramController, published the configuration file, set webhook, filled routes/telegram.php and routes/api.php. Created FrontController. I just copied everything from documentation.

Now if I will send command /start or whatever to but there is error 405 Method Not Allowed

How to fix it? Help

To Reproduce

I have red documentation and issues on github

Expected behavior

I expected answer of bot to command /start. Becouse there is instraction in routes/telegram.php

$bot->onCommand('start', function (Nutgram $bot) {
return $bot->sendMessage('Hello, world!');
})->description('The start command!');

Additionaly I have run command in terminal nutgram:register-commands
Register the bot commands, see automatically-register-bot-commands

Screenshots

image

Additional context

No response

[BUG]

Describe the bug

Hi, I found a bug in this framework
I use Nutgram latest version on Laravel 9
I noticed that sometimes my bot is not working and Telegram showing 500 internal server error on Webhook request attempt, I logged the input from Webhook when error occurred;
this is the error :
SergiX44\Nutgram\Telegram\Exceptions\TelegramException: Bad Request: chat not found in file /var/www/html/vendor/nutgram/nutgram/src/Telegram/Client.php on line 287
and this is the input from telegram api:
{ "update_id": 33826834, "edited_message": { "message_id": 1713, "from": { "id": 743826780, "is_bot": false, "first_name": "Vahid", "last_name": "Khorasani", "username": "v8hid", "language_code": "en" }, "chat": { "id": 743826780, "first_name": "Vahid", "last_name": "Khorasani", "username": "v8hid", "type": "private" }, "date": 1661125877, "edit_date": 1661133451, "dice": { "emoji": "πŸ€", "value": 2 } } }

To Reproduce

You can send this json string and sending a request to a Route that calls run() on Nutgram instance and get the same error.

Expected behavior

I'm not sure what is the expected behavior but pretty sure this is the result of using this command:
$this->nutgram->sendDice();

Screenshots

No response

Additional context

No response

[FEATURE] skip global middleware for group routes

Is your feature request related to a problem? Please describe.

I love new group method, can you also add skiping global middlewares for groups?

Describe the solution you'd like

Now I have

$bot->group(new CheckAdminChatMiddleware(config('bot.chats.withdraw')), function (Nutgram $bot) {
    $bot->onCommand('success, [OperationHandler::class, 'success'])
        ->skipGlobalMiddlewares([SpecifyClientMiddleware::class]);
    $bot->onCommand('cancel', [OperationHandler::class, 'cancel'])
        ->skipGlobalMiddlewares([SpecifyClientMiddleware::class]);
});

I want

$bot->group(new CheckAdminChatMiddleware(config('bot.chats.withdraw')), function (Nutgram $bot) {
    $bot->onCommand('success, [OperationHandler::class, 'success']);
    $bot->onCommand('cancel', [OperationHandler::class, 'cancel']);
})->skipGlobalMiddlewares([SpecifyClientMiddleware::class]);

Describe alternatives you've considered

No response

Additional context

No response

[BUG] Allowed memory size exhausted on nesting group route

Nutgram version

3.17 and 4.x-dev

Describe the bug

for v 3.17
Allowed memory size of .. exhausted in ... vendor\nutgram\nutgram\src\Handlers\CollectHandlers.php on line 97

// commit the handlers
$this->handlers = array_merge_recursive($this->handlers, $this->groupHandlers);

Bug exists only if methods with pattern (onCallbackQueryData and onPreCheckoutQueryPayload) are used in logic on any group level

To Reproduce

$bot->group([
    Middleware\TestMiddlewareB::class,
], function(Nutgram $bot) {
    // works
    $bot->onCallbackQuery([Commands\TestHandler::class, 'test']);
    
    // error
    $bot->onCallbackQueryData('test', [Commands\TestHandler::class, 'test']);
    // OR
    // $bot->onPreCheckoutQueryPayload('test', [Commands\TestHandler::class, 'test']);

    $bot->group([
        Middleware\TestMiddlewareC::class,
        Middleware\TestMiddlewareD::class,
    ], function(Nutgram $bot) {
        $bot->onCommand('start', Commands\TestHandler::class);
        // OR
        // $bot->onPreCheckoutQueryPayload('test', [Commands\TestHandler::class, 'test']);
    });
});

Expected behavior

no errors for nesting groups

Screenshots

No response

Additional context

No response

Error management

Hi , unfortunately when i didn't install Symfony cache and i wanna use stepConversation, it didn't any warning or error

Add a parameter of type string|array $text to the send message function[FEATURE]

Is your feature request related to a problem? Please describe.

I would like to be able to send an array, which is converted into a single message, for example:

public function sendMessage(string|array $text, array $opt = []): Message|array|null
    {
        if (is_array($text)) {
            $text = implode("\n", $text);
        }
        ...
    }

Use:

$message = [
                "Date: $updated",
                "",
                "$code - $productLink",
                "Price: *" . $item['price'] . "*",                
            ];
$bot->sendMessage($message);

Describe the solution you'd like

No response

Describe alternatives you've considered

No response

Additional context

No response

[BUG] Bad Request: invalid file_id when downloading files

Describe the bug

Hi. Thanks for your great package.

I've built a small bot (using self-hosted telegram-bot-api) to compress PDF file.
It needs to download and upload attached files.
It worked well till recently and suddenly I faced this error:

Bad Request: invalid file_id

 #0 /vendor/nutgram/nutgram/src/Telegram/Client.php(269): SergiX44\Nutgram\Nutgram->mapResponse()
 #1 /vendor/nutgram/nutgram/src/Telegram/Endpoints/AvailableMethods.php(482): SergiX44\Nutgram\Nutgram->requestJson()
 #2 /src/Domain/PDF/Actions/CompressPdfAction.php(49): SergiX44\Nutgram\Nutgram->getFile()

It seems it can't download file.
I tried to update telegram-bot-api to latest version but error still is there

Expected behavior

Download attached file

Additional context

PHP: 8.1.2
Laravel: 8.83.16
Bot API: 6.0.2
Nutgram: 3.2.1

[BUG] Nutgram in Laravel integration does not use cache

Nutgram version

^3.13

Describe the bug

I have Nutgram ^.13 and Laravel version ^9.19

Nutgram works in webhook mode on hosting.

I can see that conversation works, but it does not go further that first answer.

I have tried file and database as CACHE_DRIVER for laravel. Made a few tests with cache and both of them works.

Also I have output nutgram service and I can see that it has correct cache driver.

However it never writes any cache item.

To Reproduce

  1. Install Nutgram and laravel with version from bug's description.
  2. try any bot with webhook mode
  3. Nutgram cannot keep converstation, you will not move further that 1 answer .

Expected behavior

use cache , write data

Screenshots

No response

Additional context

No response

Backward conversations

On complex menus, if the update match the condition Nutgram call the last step (also do this for more one step back). Its also come handy on making forms like AskIceCream that user wants to change the previous answers before submit.

(yes its possible to create that condition on every step but for more steps and menus it takes so much duplicated code)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.