westacks / telebot Goto Github PK
View Code? Open in Web Editor NEWEasy way to create Telegram bots in PHP
Home Page: https://westacks.github.io/telebot/
License: MIT License
Easy way to create Telegram bots in PHP
Home Page: https://westacks.github.io/telebot/
License: MIT License
Unable to properly handle update request with empty parameter because of dynamic calls inside TelegramObject class.
I would propose to add check()
method to the TelegramObject class or cast null on undefined values.
Example WeStacks\TeleBot\Objects\Update object (ids and usernames were replaced):
WeStacks\TeleBot\Objects\Update {#859
#properties: array:2 [
"update_id" => 848141909
"message" => WeStacks\TeleBot\Objects\Message {#860
#properties: array:8 [
"message_id" => 400
"from" => WeStacks\TeleBot\Objects\User {#861
#properties: array:5 [
"id" => "",
"is_bot" => false
"first_name" => "first_name"
"username" => "username"
"language_code" => "en"
]
id: "",
is_bot: false
first_name: "first_name"
username: "username"
language_code: "en"
}
"chat" => WeStacks\TeleBot\Objects\Chat {#862
#properties: array:4 [
"id" => "",
"first_name" => "first_name"
"username" => "username"
"type" => "private"
]
id: 372234806
first_name: "first_name"
username: "username"
type: "private"
}
"date" => 1619653425
"forward_from" => WeStacks\TeleBot\Objects\User {#863
#properties: array:4 [
"id" => "",
"is_bot" => true
"first_name" => "first_name"
"username" => "username"
]
id: "",
is_bot: true
first_name: "first_name"
username: "username"
}
"forward_date" => 1619564252
"invoice" => WeStacks\TeleBot\Objects\Payments\Invoice {#864
#properties: array:5 [
"title" => "Product"
"description" => "description"
"start_parameter" => ""
"currency" => "UAH"
"total_amount" => 1810
]
title: "Product"
description: "description"
start_parameter: ""
currency: "UAH"
total_amount: 1810
}
"reply_markup" => WeStacks\TeleBot\Objects\Keyboard\InlineKeyboardMarkup {#865
#properties: array:1 [
"inline_keyboard" => array:1 [
0 => array:1 [
0 => WeStacks\TeleBot\Objects\InlineKeyboardButton {#866
#properties: array:2 [
"text" => "Pay 18,10UAH"
"pay" => true
]
text: "Pay 18,10UAH"
pay: true
}
]
]
]
inline_keyboard: array:1 [
0 => array:1 [
0 => WeStacks\TeleBot\Objects\InlineKeyboardButton {#866}
]
]
}
]
message_id: 400
from: WeStacks\TeleBot\Objects\User {#861}
chat: WeStacks\TeleBot\Objects\Chat {#862}
date: 1619653425
forward_from: WeStacks\TeleBot\Objects\User {#863}
forward_date: 1619564252
invoice: WeStacks\TeleBot\Objects\Payments\Invoice {#864}
reply_markup: WeStacks\TeleBot\Objects\Keyboard\InlineKeyboardMarkup {#865}
}
]
update_id: 848141909
message: WeStacks\TeleBot\Objects\Message {#860}
}
None of these examples work without throwing an Exception:
public static function trigger(Update $update, TeleBot $bot)
{
if ($update->message->get('text') === 'message') {
return false;
}
if ($update->message->text === 'message') {
return false;
}
if ($update?->message?->text === 'message') {
return false;
}
if (($update->message->text ?? false) && $update->message->text === 'message') {
return false;
}
}
Exception:
$ php artisan telebot:polling
Polling telegram updates...
Bot: 'bot'; update: 848141909; type: 'message'
ErrorException
Undefined array key "text"
at E:\domains\telebot-payment-test\vendor\westacks\telebot\src\Interfaces\TelegramObject.php:37
33▕ }
34▕
35▕ public function __get($key)
36▕ {
➜ 37▕ return $this->properties[$key];
38▕ }
39▕
40▕ public function __set($key, $value)
41▕ {
1 E:\domains\telebot-payment-test\vendor\westacks\telebot\src\Interfaces\TelegramObject.php:37
Illuminate\Foundation\Bootstrap\HandleExceptions::handleError()
2 E:\domains\telebot-payment-test\app\Services\Telegram\Guard\MessageHandlers\PhotoTestMessageHandler.php:24
WeStacks\TeleBot\Interfaces\TelegramObject::__get()
Hello!
Pls make an php8 support for this lbrary :)
В последнее время бот стал часто вылетать с исключением:
cURL error 7: Failed to connect to api.telegram.org port 443: Connection timed out (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://api.telegram.org/{bot}/getUpdates
Полез в конструктор класса TeleBot для того, чтобы прокинуть конфиг для таймаута в GuzzleHttp\Client
, но это нельзя сделать.
Предлагаю либо ввести возможность установки своего экземпляра GuzzleHttp\Client
, либо увеличить таймаут, т.к. 0 секунд по умолчанию - это мало.
Recently, the bot began to crash frequently with an exception:
cURL error 7: Failed to connect to api.telegram.org port 443: Connection timed out (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https: //api.telegram. org / {bot} / getUpdates
I got into the constructor of the TeleBot class in order to edit the config for the timeout in GuzzleHttp\Client
, but this cannot be done by librarys config.
I suggest either to introduce the ability to install your own instance of GuzzleHttp\Client
, or to increase the timeout, because 0 seconds by default is not enough.
Hi,
I cant seem to get the webhook artisan command to work.. I can get the help command for it but it fails to execute no matter the options I try!
The error is more or less the same each time:
WeStacks\TeleBot\Exception\TeleBotRequestException
Not Found
at vendor/westacks/telebot/src/Exception/TeleBotRequestException.php:17
13▕ $parameters = ResponseParameters::create($result->parameters ?? null);
14▕ $text .= '; Parameters: '.$parameters;
15▕ }
16▕
➜ 17▕ return new TeleBotRequestException($text, $result->error_code);
18▕ }
19▕ }
20▕
+30 vendor frames
31 artisan:37
Illuminate\Foundation\Console\Kernel::handle()
Any help appreciated! :)
I'm getting an error when i'm using
$keyboard = Keyboard::create([
'keyboard' => [[[
'text' => 'Test Keyboard Button',
]]],
]);
The error is "Unable to cast "boolean" variable to type "bookean".
I think there is a mistake in the bolded part of the code below.
class ReplyKeyboardMarkup extends Keyboard
{
protected function relations()
{
return [
'keyboard' => [[KeyboardButton::class]],
'resize_keyboard' => 'boolean',
'one_time_keyboard' => 'boolean',
'selective' => 'bookean', // typo in boolean
];
}
}
I read the documentation but it is not clear where the application entry point is, I tried a lot and nothing works
I tried to do something like that, but it doesn`t work:
class AppCommand extends CommandHandler
{
protected static $aliases = ['/app'];
protected static $description = 'Run application';
public function handle()
{
$webAppInfo = WebAppInfo::create([
'url' => 'https://example.com/app',
]);
$menuButtonWebApp = MenuButtonWebApp::create([
'type' => 'web_app',
'text' => 'App',
'web_app' => $webAppInfo,
]);
return $menuButtonWebApp;
}
}
or
return $this->setChatMenuButton([
'chat_id' => env('TELEGRAM_CHAT_ID'),
'menu_button' => $menuButtonWebApp
]);
Laravel 9
Describe the bug
Broken symfony logging bundle
To Reproduce
Steps to reproduce the behavior:
laravel
Expected behavior
Message sent to the chat id
Additional context
Bundle v2.7.1
Hello. Have you plan add support for this new function on Bot API 6.0?
Thanks in advance.
Laravel ERROR (local):
Value of type null is not callable {"exception":"[object] (Error(code: 0): Value of type null is not callable at /project/vendor/westacks/telebot/src/Handlers/UpdateHandler.php:89)"} []
'handlers' => [
HomeCommands::class,
ProjectAdminsCommands::class,
AddNewFilm::class
]
If I use one handler (does not matter which one) it works without any problems
If I use two, it gives an error, but both of them work without any problems
If I use more than two, it gives an error and only the last two run
i have this problem just in version ^2 of telebot
I tried the php artisan telebot:webhook --setup
but it seems that it is not working, when I try using long polling everything works fine.
WeStacks\TeleBot\BotManager
....
/**
* Get bot by name.
* @param string $name bot name
* @throws TeleBotObjectException
* @return null|TeleBot
*/
public function bot(string $name = null)
{
$bot = $name ?? $this->default ?? null;
if (is_null($bot)) {
throw TeleBotObjectException::defaultBotIsNotSet();
}
if (!isset($this->bots[$bot])) {
throw TeleBotObjectException::botNotFound($bot);
}
if (!($this->bots[$bot] instanceof TeleBot)) {
$this->bots[$bot] = new TeleBot($this->bots[$bot]);
}
return $this->bots[$bot];
}
hello, how can this method return null?
Hi.
I can't send answerInlineQuery
I got from Telegram this error:
Bad Request: can't parse inline query result: Can't find field "message_text"
Here is the code.
What wrong I do? I cant understand.
if ($update->callback_query) {
$callback_query_id = $update->callback_query->id;
$results = [[
'type' => 'article',
'id' => '001',
'title' => 'Test',
'message_text' => 'Text of the first message'
]];
$message = $bot->answerInlineQuery([
'inline_query_id' => $callback_query_id,
'results' => $results
]);
}
Please help.
Thank you.
I need help with this error.
I want to use commands with my bot.
I followed all the documentation but I still get 403 error on my webhook.
I use Laravel 8
for example my StarCommand
sendMessage([ 'parse_mode' => 'HTML', 'text' => mb_convert_encoding('Hello, How are you?', 'UTF-8', mb_list_encodings()) ]); } } Then in the terminal I use the commands: php artisan telebot:command --setup php artisan telebot:webhook --setup but the webhook gives me: "last_error_message": "Wrong response from the webhook: 403 Forbidden", please help meHello
Sorry to trouble you again.
I am trying to get callback data that orignates from a command.
$test = $this->sendMessage([
'text' => 'testing' ,
'reply_markup' => [
'resize_keyboard' => true,
'one_time_keyboard' => true,
'inline_keyboard' => [[
['text' => 'summary','callback_data' => "1"],
['text' => 'listvalidators','callback_data' => "2"]
]]
]
]);
Once a callback button is clicked.
How do I go about getting that data? Sorry and thank you
For there is no point in pretending to be a sympathetic eyewitness. We are programmers, not felt boots.
When I add in Laravel config: config/telebot.php
to key descriptor:
\App\Services\Telegram\Commands\StartCommand::class
gives the error: The specified update handler type 'App\Services\Telegram\Commands\StartCommand" is not a valid update handler.
And another question, where to process the handle with php artisan telebot:polling
?
Originally posted by roelofr September 21, 2021
Hey there,
I just discovered this package via my GitHub homepage (I didn't know it did that).
It looks great, but I'm seeing no docs on testing from an end-user perspective (which is something a lot of Telegram bot packages don't have).
What would be the best way to test this, I'd be glad to help.
How to save (implement) bot config,
token, name, etc, on database instead on .env, so in production we can easily update value of those setting ?
if any documentation, can anyone share the link or any method to implement my question
thanks in advanced
My config telebot:
<?php
return [
/*-------------------------------------------------------------------------
| Default Bot Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the bots you wish to use as
| your default bot for regular use.
|
*/
'default' => 'bot',
/*-------------------------------------------------------------------------
| Your Telegram Bots
|--------------------------------------------------------------------------
| You may use multiple bots. Each bot that you own should be configured here.
|
| See the docs for parameters specification:
| https://westacks.github.io/telebot/#/configuration
|
*/
'bots' => [
'bot' => [
'token' => env('TELEGRAM_BOT_TOKEN'),
'name' => env('TELEGRAM_BOT_NAME', null),
'api_url' => env('TELEGRAM_API_URL', 'https://api.telegram.org/bot{TOKEN}/{METHOD}'),
'exceptions' => true,
'async' => false,
'storage' => \WeStacks\TeleBot\Storage\JsonStorage::class,
'http' => [
'http_errors' => false,
],
'webhook' => [
'url' => env('TELEGRAM_BOT_WEBHOOK_URL', env('APP_URL').'/telebot/webhook/bot/'.env('TELEGRAM_BOT_TOKEN')),
// 'certificate' => env('TELEGRAM_BOT_CERT_PATH', storage_path('app/ssl/public.pem')),
// 'ip_address' => '8.8.8.8',
// 'max_connections' => 40,
// 'allowed_updates' => ["message", "edited_channel_post", "callback_query"],
// 'secret_token' => env('TELEGRAM_KEY', null),
],
'poll' => [
// 'limit' => 100,
// 'timeout' => 0,
// 'allowed_updates' => ["message", "edited_channel_post", "callback_query"]
],
'handlers' => [
function(TeleBot $bot, Update $update, $next) {
if ($update->message->text === 'test') {
return $bot->sendMessage([
'chat_id' => $update->chat()->id,
'text' => 'Hello, World!'
]);
}
return $next();
}
],
],
// 'second_bot' => [
// 'token' => env('TELEGRAM_BOT2_TOKEN', '123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11'),
// ],
],
];
I see error:
Polling telegram updates...
Bot: 'bot'; Update: 674966770; Type: 'message'
TypeError
Illuminate\Foundation\Bootstrap\LoadConfiguration::{closure}(): Argument #1 ($bot) must be of type TeleBot, WeStacks\TeleBot\TeleBot given, called in /home/user/tests/bot/vendor/westacks/telebot/src/Kernel.php on line 75
at config/telebot.php:53
49▕ // 'allowed_updates' => ["message", "edited_channel_post", "callback_query"]
50▕ ],
51▕
52▕ 'handlers' => [
➜ 53▕ function(TeleBot $bot, Update $update, $next) {
54▕ if ($update->message->text === 'test') {
55▕ return $bot->sendMessage([
56▕ 'chat_id' => $update->chat()->id,
57▕ 'text' => 'Hello, World!'
+17 vendor frames
18 artisan:35
Illuminate\Foundation\Console\Kernel::handle()
What it is
Hi,
The exceptions property is set to true but I still cannot handle the error because no error was thrown but only logged.
On my investigation, the telegram notification channel is just handling the error and logging a warning on send, then returns a null
To share, what I'd like to do why I wanted to catch an errors is because I wanted to remove the registered telegram ID of a user if I get a request exception that contains "user deactivated" or "bot was blocked"
Hello
Just a fresh Laravel 5.6 install, all work.
But composer require westacks/telebot
throw error:
...
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover
In Container.php line 767:
Class mailer does not exist
Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1
First of all, I want to thank author for this great lib, you are truly awesome!
As I understood correctly, composer.json states that 2.0 supports PHP 7.4, but there are some features used in the code, that are available only on ^8.0.
For example https://github.com/westacks/telebot/blob/master/src/Helpers/Type.php#L67
PHP 7.4 shows this error "Parse error: syntax error, unexpected '|', expecting variable (T_VARIABLE)"
Thank you for your work!
Очень нубский вопрос.
Можно ли как то перехватить TelegramRequestException для всех уже существующих хендлеров.
Дописывать в каждом хендлере try..catch совсем не комильфо.
Как лучше перегрузить или переопределить и какой именно класс
It's there a way to access to local config data in an update handler? When an update is received, how I know the related bot?. I can get Telegram bot info, but I don't know how to get local config info. Perhaps new methods in TeleBot class?
NOTICE: PHP message: PHP Fatal error: Uncaught Error: Class "WeStacks\TeleBot\Traits\get_class" not found in /var/www/vendor/westacks/telebot/src/Traits/HandlesUpdates.php:40
Laravel v8.80.0 (PHP v8.1.1)
Looks like this commit is wrong 76f9607
Describe the bug
Hello, The library does not support Inline mode and I tested it with a simple bot and got
Cannot cast value of type NULL to type string error in log channel
To Reproduce
Steps to reproduce the behavior:
1.Turn on Inline mode in BotFather
2.use Inline mode : @bot_username some_thing
Then you will receive the following error in log channel if you add it:
Laravel ERROR (local): Cannot cast value of type NULL to type string {"exception":"[object] (WeStacks\\TeleBot\\Exceptions\\TeleBotException(code: 0): Cannot cast value of type NULL to type string at /var/www/vendor/westacks/telebot/src/Helpers/Type.php:96)"} []
Additional context
The first time I encountered this problem was September 3. on September 2nd you released version 2.2.2 but I installed earlier versions and it still didn't work.
How can I answer inline queries in telegram bots in php(laravel) with Telebot plugin? I'm working on a bot project in laravel and I'm using the Telebot package.
does Telebot support answerInlineQuery method? I can't find it.
\WeStacks\TeleBot\Laravel\TeleBot::answerInlineQuery([]); //this doesn't exist.how should I answer Inline Queries?
Would it be possible to add a delete message after say 60 seconds from being sent. I beleive the Telegram API supports this.
Thank you
Hello. I have the following problem (most likely a bug).
Let's sum up:
I am attaching below:
[2023-06-01 14:58:46] local.ERROR: Bad Request: message thread not found {"exception":"[object] (WeStacks\\TeleBot\\Exceptions\\TeleBotException(code: 400): Bad Request: message thread not found at /home/social13/myBot/vendor/westacks/telebot/src/Exceptions/TeleBotException.php:21)
[stacktrace]
#0 /home/social13/myBot/vendor/westacks/telebot/src/Contracts/TelegramMethod.php(97): WeStacks\\TeleBot\\Exceptions\\TeleBotException::requestError(Array)
#1 /home/social13/myBot/vendor/guzzlehttp/promises/src/Promise.php(209): WeStacks\\TeleBot\\Contracts\\TelegramMethod->WeStacks\\TeleBot\\Contracts\\{closure}(Array)
#2 /home/social13/myBot/vendor/guzzlehttp/promises/src/Promise.php(158): GuzzleHttp\\Promise\\Promise::callHandler(1, Object(GuzzleHttp\\Psr7\\Response), NULL)
#3 /home/social13/myBot/vendor/guzzlehttp/promises/src/TaskQueue.php(52): GuzzleHttp\\Promise\\Promise::GuzzleHttp\\Promise\\{closure}()
#4 /home/social13/myBot/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php(159): GuzzleHttp\\Promise\\TaskQueue->run()
#5 /home/social13/myBot/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php(185): GuzzleHttp\\Handler\\CurlMultiHandler->tick()
#6 /home/social13/myBot/vendor/guzzlehttp/promises/src/Promise.php(251): GuzzleHttp\\Handler\\CurlMultiHandler->execute(true)
#7 /home/social13/myBot/vendor/guzzlehttp/promises/src/Promise.php(227): GuzzleHttp\\Promise\\Promise->invokeWaitFn()
#8 /home/social13/myBot/vendor/guzzlehttp/promises/src/Promise.php(272): GuzzleHttp\\Promise\\Promise->waitIfPending()
#9 /home/social13/myBot/vendor/guzzlehttp/promises/src/Promise.php(229): GuzzleHttp\\Promise\\Promise->invokeWaitList()
#10 /home/social13/myBot/vendor/guzzlehttp/promises/src/Promise.php(69): GuzzleHttp\\Promise\\Promise->waitIfPending()
#11 /home/social13/myBot/vendor/westacks/telebot/src/Contracts/TelegramMethod.php(104): GuzzleHttp\\Promise\\Promise->wait()
#12 /home/social13/myBot/vendor/westacks/telebot/src/TeleBot.php(119): WeStacks\\TeleBot\\Contracts\\TelegramMethod->__invoke(Array)
#13 /home/social13/myBot/vendor/westacks/telebot/src/Handlers/UpdateHandler.php(64): WeStacks\\TeleBot\\TeleBot->__call(Object(WeStacks\\TeleBot\\Methods\\SendMessageMethod), Array)
#14 /home/social13/myBot/app/Telegram/HandlersUpdates/Updates.php(25): WeStacks\\TeleBot\\Handlers\\UpdateHandler->__call('sendMessage', Array)
#15 /home/social13/myBot/vendor/westacks/telebot/src/Handlers/UpdateHandler.php(94): App\\Telegram\\HandlersUpdates\\Updates->handle()
#16 /home/social13/myBot/vendor/westacks/telebot/src/Kernel.php(74): WeStacks\\TeleBot\\Handlers\\UpdateHandler->__invoke(Object(Closure))
#17 /home/social13/myBot/vendor/westacks/telebot/src/Kernel.php(46): WeStacks\\TeleBot\\Kernel->WeStacks\\TeleBot\\{closure}(Object(WeStacks\\TeleBot\\Objects\\Update), Object(Closure))
#18 /home/social13/myBot/vendor/westacks/telebot/src/Traits/HandlesUpdates.php(25): WeStacks\\TeleBot\\Kernel->run(Object(WeStacks\\TeleBot\\TeleBot), Object(WeStacks\\TeleBot\\Objects\\Update))
#19 /home/social13/myBot/vendor/westacks/telebot/src/Laravel/Controllers/WebhookController.php(13): WeStacks\\TeleBot\\TeleBot->handleUpdate(Object(WeStacks\\TeleBot\\Objects\\Update))
#20 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(54): WeStacks\\TeleBot\\Laravel\\Controllers\\WebhookController->__invoke(Object(WeStacks\\TeleBot\\Laravel\\Requests\\UpdateRequest), 'chatgrouphelpv2', '5810466407:AAHJ...')
#21 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(43): Illuminate\\Routing\\Controller->callAction('__invoke', Array)
#22 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Routing/Route.php(259): Illuminate\\Routing\\ControllerDispatcher->dispatch(Object(Illuminate\\Routing\\Route), Object(WeStacks\\TeleBot\\Laravel\\Controllers\\WebhookController), '__invoke')
#23 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Routing/Route.php(205): Illuminate\\Routing\\Route->runController()
#24 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Routing/Router.php(799): Illuminate\\Routing\\Route->run()
#25 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(141): Illuminate\\Routing\\Router->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#26 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(116): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#27 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Routing/Router.php(798): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))
#28 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Routing/Router.php(777): Illuminate\\Routing\\Router->runRouteWithinStack(Object(Illuminate\\Routing\\Route), Object(Illuminate\\Http\\Request))
#29 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Routing/Router.php(741): Illuminate\\Routing\\Router->runRoute(Object(Illuminate\\Http\\Request), Object(Illuminate\\Routing\\Route))
#30 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Routing/Router.php(730): Illuminate\\Routing\\Router->dispatchToRoute(Object(Illuminate\\Http\\Request))
#31 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(200): Illuminate\\Routing\\Router->dispatch(Object(Illuminate\\Http\\Request))
#32 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(141): Illuminate\\Foundation\\Http\\Kernel->Illuminate\\Foundation\\Http\\{closure}(Object(Illuminate\\Http\\Request))
#33 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#34 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ConvertEmptyStringsToNull.php(31): Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#35 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Foundation\\Http\\Middleware\\ConvertEmptyStringsToNull->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#36 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#37 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TrimStrings.php(40): Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#38 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Foundation\\Http\\Middleware\\TrimStrings->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#39 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php(27): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#40 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#41 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/PreventRequestsDuringMaintenance.php(86): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#42 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Foundation\\Http\\Middleware\\PreventRequestsDuringMaintenance->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#43 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Http/Middleware/HandleCors.php(49): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#44 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Http\\Middleware\\HandleCors->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#45 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Http/Middleware/TrustProxies.php(39): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#46 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Http\\Middleware\\TrustProxies->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#47 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(116): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#48 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(175): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))
#49 /home/social13/myBot/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(144): Illuminate\\Foundation\\Http\\Kernel->sendRequestThroughRouter(Object(Illuminate\\Http\\Request))
#50 /home/social13/myBot/public/index.php(51): Illuminate\\Foundation\\Http\\Kernel->handle(Object(Illuminate\\Http\\Request))
#51 {main}
"}
{
"update_id": 29166232,
"message": {
"message_id": 4730393,
"from": {
"id": 5733982572,
"is_bot": false,
"first_name": "FirstName",
"last_name": "lastName"
},
"chat": {
"id": -100123456789,
"title": "title chat",
"username": "_chat",
"type": "supergroup"
},
"date": 1685631455,
"message_thread_id": 4730005,
"text": "message text"
}
}
Laravel Framework 9.0.2
PHP 8.0.6 &
PHP 7.4.9
composer require westacks/telebot
Output:
Problem 1
- Root composer.json requires laravel/framework ^9.0, found laravel/framework[v9.0.0-beta.1, ..., 9.x-dev] but the package is fixed to v8.81.0 (lock file version) by a partial update and that version does not match. Make sure yo
u list it as an argument for the update command.
Problem 2
- Root composer.json requires nunomaduro/collision ^6.1, found nunomaduro/collision[v6.1.0] but the package is fixed to v5.11.0 (lock file version) by a partial update and that version does not match. Make sure you list it as an
argument for the update command.
Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.
When using composer require westacks/telebot -W
Your requirements could not be resolved to an installable set of packages.
Problem 1
- Root composer.json requires laravel/framework ^9.0, found laravel/framework[v9.0.0-beta.1, ..., 9.x-dev] but these were not loaded, likely because it conflicts with another require.
Problem 2
- Root composer.json requires nunomaduro/collision ^6.1, found nunomaduro/collision[v6.1.0] but the package is fixed to v5.11.0 (lock file version) by a partial update and that version does not match. Make sure you list it as an
argument for the update command.
Problem 3
- laravel/sanctum is locked to version v2.14.0 and an update of this package was not requested.
- laravel/sanctum v2.14.0 requires illuminate/database ^6.9|^7.0|^8.0|^9.0 -> found illuminate/database[v6.10.0, ..., 6.x-dev, v7.0.0, ..., 7.x-dev, v8.0.0, ..., 8.x-dev, v9.0.0-beta.1, ..., 9.x-dev] but these were not loaded, l
ikely because it conflicts with another require.
Problem 4
- laravel/tinker is locked to version v2.7.0 and an update of this package was not requested.
- laravel/tinker v2.7.0 requires illuminate/console ^6.0|^7.0|^8.0|^9.0 -> found illuminate/console[v6.0.0, ..., 6.x-dev, v7.0.0, ..., 7.x-dev, v8.0.0, ..., 8.x-dev, v9.0.0-beta.1, ..., 9.x-dev] but these were not loaded, likely
because it conflicts with another require.
Problem 5
- laravel/sail is locked to version v1.13.1 and an update of this package was not requested.
- laravel/sail v1.13.1 requires illuminate/console ^8.0|^9.0 -> found illuminate/console[v8.0.0, ..., 8.x-dev, v9.0.0-beta.1, ..., 9.x-dev] but these were not loaded, likely because it conflicts with another require.
Installation failed, reverting ./composer.json and ./composer.lock to their original content.
php artisan telebot:polling
ErrorException
Use of undefined constant SIGINT - assumed 'SIGINT' (this will throw an Error in a future version of PHP)
at *******\vendor\westacks\telebot\src\Laravel\Artisan\LongPollCommad.php:72
68▕ }
php -v
PHP 7.4.4 (cli) (built: Mar 17 2020 13:49:19) ( ZTS Visual C++ 2017 x64 )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
"require": {
"php": "^7.3|^8.0",
"fruitcake/laravel-cors": "^2.0",
"guzzlehttp/guzzle": "^7.0.1",
"laravel/framework": "^8.75",
"laravel/sanctum": "^2.11",
"laravel/tinker": "^2.5",
"westacks/telebot": "^1.14"
},
p.s. "westacks/telebot": "1.13.0" - OK
version > 1.13.0 - error
I'm using laravel + telebot to create my telegram bot. While testing I found that when user sends a file to the bot, it fails and webhook responses with 500 internal server error.
In the laravel.log file we can see that it says:
local.ERROR: Undefined array key "text" {"exception":"[object] (ErrorException(code: 0): Undefined array key \"text\" at C:\\Users\\aizek\\Documents\\*********\\vendor\\westacks\\telebot\\src\\Interfaces\\TelegramObject.php:37)
Here is 37th line of that file:
return $this->properties[$key];
We have to add ?? NULL
in order to solve the problem. So it'll be:
return $this->properties[$key] ?? NULL;
Then everything would be fine with files.
I would ask the author to fix this in the next commits :) Bless you.
hey sir,
i got issue WeStacks\TeleBot\Exception\TeleBotObjectException. You should specify at least 1 bot to use BotManager.
in local run perfect. but in cloud always return like that.
thanks.
As titled, is it supported?
У вас ошибка в документации на веб-сайте.
Вместо
WeStacks\TeleBot\Laravel\Providers\TeleBotServiceProvider::class,
Указано
WeStacks\TeleBot\Laravel\TeleBotServiceProvider::class,
P.S.
Спасибо что исправили)
Originally posted by mgksmv November 14, 2023
It seems like JsonStorage is not creating a file to keep track of input states. I'm using default configuration for storage (JsonStorage). Maybe there's something that I don't understand? Thanks in advance.
Here's my code.
Bot config:
'bots' => [
'taxi' => [
'token' => env('TELEGRAM_TAXI_BOT_TOKEN'),
'name' => env('TELEGRAM_TAXI_BOT_NAME'),
'api_url' => env('TELEGRAM_API_URL', 'https://api.telegram.org/bot{TOKEN}/{METHOD}'),
'exceptions' => true,
'async' => false,
'storage' => \WeStacks\TeleBot\Storage\JsonStorage::class,
'http' => [
'http_errors' => false,
],
'handlers' => [
\App\Libs\Telegram\Handlers\Taxi\StartHandler::class,
\App\Libs\Telegram\Handlers\Taxi\AskContactHandler::class,
],
],
],
Start command handler:
<?php
namespace App\Libs\Telegram\Handlers\Taxi;
use App\Libs\Telegram\Keyboards\Reply\TaxiReplyKeyboard;
use App\Libs\Telegram\Services\BotService;
use WeStacks\TeleBot\Handlers\CommandHandler;
class StartHandler extends CommandHandler
{
protected static $aliases = ['/start'];
public function handle(): void
{
$userId = $this->update->user()->id;
$chatId = $this->update->chat()->id;
$isUserAlreadyRegistered = BotService::checkIfUserAlreadyRegistered($userId);
if ($isUserAlreadyRegistered) {
$this->sendMessage([
'chat_id' => $chatId,
'text' => 'Вы уже регистрировались в системе!',
]);
} else {
AskContactHandler::requestInput($this->bot, $userId);
$this->sendMessage([
'chat_id' => $chatId,
'text' => 'Пожалуйста, отправьте свой номер телефона в качестве контакта для регистрации. После этого мы пригласим Вас в группу таксистов.',
TaxiReplyKeyboard::requestPhoneNumber()
]);
}
}
}
AskContactHandler for registering a user:
<?php
namespace App\Libs\Telegram\Handlers\Taxi;
use App\Libs\Telegram\Models\TelegramUser;
use Illuminate\Support\Facades\Validator;
use WeStacks\TeleBot\Handlers\RequestInputHandler;
class AskContactHandler extends RequestInputHandler
{
public function trigger(): bool
{
return isset($this->update->message);
}
public function handle()
{
$message = $this->update->message;
$data = $message->toArray();
$validator = Validator::make($data, [
'contact' => ['required'],
]);
if ($validator->fails()) {
return $this->sendMessage([
'text' => 'Отправьте контакт для продолжения регистрации!'
]);
}
$this->acceptInput();
$phone = $message->contact->phone_number;
TelegramUser::query()->create([
'user_id' => $message->from->id,
'phone' => $phone,
]);
return $this->sendMessage([
'text' => 'Вы успешно зарегистрировались.',
]);
}
}
```</div>
Upgrading from v1 to v2.4
When trying to start up polling or setup webhook I get the below error:
Trying to access array offset on value of type null
at vendor/westacks/telebot/src/Contracts/TelegramMethod.php:97
Hello!
I was writing tests for my application, and noticed that some tests are failing if i use $bot->handleUpdate()
in a loop. The exception message was Not Found
, so it seems that after first iteration bot is not considered fake anymore. This only occures in loops and only if i need to send something through bot : message, photo, location, etc.
Here is an code example :
public function testIssueExample(): void
{
$bot = LaravelWrapper::bot()->fake(); // LaravelWrapper is a Facade for Laravel
$bot->clearHandlers();
$bot->addHandler(
[
function (TeleBot $bot, Update $update, $next) {
return $bot->sendMessage(
[
'chat_id' => -1,
'text' => $update->message->text,
]
);
},
]
);
$messages = ['random', 'text'];
foreach ($messages as $message) {
$update = Update::create(
[
'message' => [
'chat' => [
'id' => -1,
],
'text' => $message,
],
]
);
// On second iteration will try to send message like a real bot and will fail test
$response = $bot->handleUpdate($update);
$this->assertEquals($response->text, $message);
}
}
If you dump bot on each iteration, you can see that on first iteration bot fake
property will be set to true
:
WeStacks\TeleBot\TeleBot^ {
// ommited config and other properties
+"fake": true
}
And on the second iteration and further it will be set to null
:
WeStacks\TeleBot\TeleBot^ {
// ommited config and other properties
+"fake": null
}
So to make my tests work i need to manually call fake()
on each iteration :
public function testIssueExample(): void
{
$bot = LaravelWrapper::bot()->fake(); // LaravelWrapper is a Facade for Laravel
$bot->clearHandlers();
$bot->addHandler(
[
function (TeleBot $bot, Update $update, $next) {
return $bot->sendMessage(
[
'chat_id' => -1,
'text' => $update->message->text,
]
);
},
]
);
$messages = ['random', 'text'];
foreach ($messages as $message) {
$update = Update::create(
[
'message' => [
'chat' => [
'id' => -1,
],
'text' => $message,
],
]
);
// Will pass
$response = $bot->fake()->handleUpdate($update);
$this->assertEquals($response->text, $message);
}
}
I've investigated a bit more and i think problem can be in this lines of code : https://github.com/westacks/telebot/blob/master/src/TeleBot.php#L101-L103.
Can this be fixed somehow or is it intentional behaviour?
I would also like to thank you for all your hard work with this library, it made my development so much easier and fast 😍 😍
Hello, The library does not support Inline mode and I tested it with a simple bot and got
Cannot cast value of type NULL to type string
error in log channel
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.