<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
mohammad-zarifiyan / laravel-telegram-bot example snippets
return [
// The rest of your code
'telegram' => [
'api-key' => env('TELEGRAM_API_KEY'),
],
];
namespace App\Repositories;
use \MohammadZarifiyan\Telegram\Interfaces\ApiKeyRepository;
class TelegramApiKeyRepository implements ApiKeyRepository
{
public function get(): ?string
{
return '123456:abcdefg';// Return API Key
}
}
return [
// The rest of the file
'api-key-repository' => \App\Repositories\TelegramApiKeyRepository::class,// Set your own custom repository
// The rest of the file
];
return [
// The rest of your code
'telegram' => [
'endpoint' => env('TELEGRAM_ENDPOINT'),
],
];
namespace App\Repositories;
use \MohammadZarifiyan\Telegram\Interfaces\EndpointRepository;
class TelegramEndpointRepository implements EndpointRepository
{
public function get(): ?string
{
return 'https://example.com';// Return your own custom endpoint
}
}
return [
// The rest of the file
'endpoint-repository' => \App\Repositories\TelegramEndpointRepository::class,// Set your own custom repository
// The rest of the file
];
return [
// The rest of the file
'verify-endpoint' => (bool) env('TELEGRAM_VERIFY_ENDPOINT', true),
// The rest of the file
];
use \MohammadZarifiyan\Telegram\Interfaces\PendingRequestStack;
use \MohammadZarifiyan\Telegram\Facades\Telegram;
$responses = Telegram::concurrent(fn (PendingRequestStack $pendingRequestStack) => [
$pendingRequestStack->add('sendMessage', [
'text' => 'Message 1',
'chat_id' => 1234
]),
$pendingRequestStack->add('sendMessage', [
'text' => 'Message 2',
'chat_id' => 1234
]),
$pendingRequestStack->add('sendMessage', [
'text' => 'Message 3',
'chat_id' => 1234
]),
]);
$result = $responses[0]->json('ok')
&& $responses[1]->json('ok')
&& $responses[2]->json('ok');
if ($result) {
// All messages have been sent successfully.
}
else {
// There was a problem sending some messages.
}
public function routeNotificationForTelegram($notification)
{
// return telegram id
}
public function via($notifiable): array
{
return ['telegram'];
}
use \MohammadZarifiyan\Telegram\Interfaces\TelegramRequestContent as TelegramRequestContentInterface;
public function toTelegram($notifiable): TelegramRequestContentInterface
{
// Return an instance of \MohammadZarifiyan\Telegram\TelegramRequestContent
}
use App\Notifications\HelloNotification;
use App\Models\User;
use Illuminate\Support\Facades\Notification;
$users = User::all();
Notification::send($users, HelloNotification::class);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
class User extends Model
{
use Notifiable;
protected $fillable = ['telegram_id'];
protected $casts = [
'telegram_id' => 'integer'
];
public function routeNotificationForTelegram($notification)
{
return $this->telegram_id;
}
}
namespace App\Notifications;
use \Illuminate\Notifications\Notification;
use \MohammadZarifiyan\Telegram\Interfaces\TelegramRequestContent as TelegramRequestContentInterface;
use \MohammadZarifiyan\Telegram\TelegramRequestContent;
class PaymentPaidNotification extends Notification
{
public function via($notifiable): array
{
return ['telegram'];
}
public function toTelegram($notifiable): TelegramRequestContentInterface
{
return TelegramRequestContent::fresh()
->setMethod('sendMessage')
->setData([
'text' => 'Hello'
]);
}
}
namespace App\Telegram\ReplyMarkups;
use \MohammadZarifiyan\Telegram\Interfaces\ReplyMarkup;
class MyKeyboard implements ReplyMarkup
{
public function __invoke(): array
{
return [
'resize_keyboard' => true,
'keyboard' => [
[
// This array contains a row
[
// This array contains a column
'text' => 'top left button'
],
[
// This array contains a column
'text' => 'top right button'
]
],
[
// This array contains a row
[
// This array contains a column
'text' => 'bottom left button'
],
[
// This array contains a column
'text' => 'bottom right button'
]
]
]
];
}
}
use \App\Telegram\ReplyMarkups\MyKeyboard;
use \MohammadZarifiyan\Telegram\Facades\Telegram;
Telegram::perform(
'sendMessage',
[
'text' => 'Hello world!',
'chat_id' => 1234
],
MyKeyboard::class
);
namespace App\Notifications;
use \App\Telegram\ReplyMarkups\MyKeyboard;
use \Illuminate\Notifications\Notification;
use MohammadZarifiyan\Telegram\Interfaces\TelegramRequestContent as TelegramRequestContentInterface;
use \MohammadZarifiyan\Telegram\TelegramRequestContent;
class PaymentPaidNotification extends Notification
{
public function via($notifiable): array
{
return ['telegram'];
}
public function toTelegram($notifiable): TelegramRequestContentInterface
{
return TelegramRequestContent::fresh()
->setMethod('sendMessage')
->setData([
'text' => 'Hello'
])
->setReplyMarkup(MyKeyboard::class);
}
}
use MohammadZarifiyan\Telegram\Facades\Telegram;
use MohammadZarifiyan\Telegram\Attachment;
$file_contents = file_get_contents('path/to/file.png');
$file_name = 'my-file.png';
Telegram::perform('sendPhoto', [
'photo' => new Attachment($file_contents, $file_name),
'chat_id' => 1234
]);
return [
// The rest of the file
'pending-request-manipulator' => App\Telegram\PendingRequestManipulator::class,
// The rest of the file
];
namespace App\Telegram;
use MohammadZarifiyan\Telegram\Interfaces\PendingRequest as PendingRequestInterface;
class PendingRequestManipulator implements PendingRequestInterface
{
public function __construct(public PendingRequestInterface $pendingRequest)
{
//
}
public function getUrl(): string
{
return $this->pendingRequest->getUrl();// You can change the URL of the request here.
}
public function getBody(): array
{
return $this->pendingRequest->getBody();// You can change the body of the request here.
}
public function getAttachments(): array
{
return $this->pendingRequest->getAttachments();// You can change the attachments of the request here.
}
}
use MohammadZarifiyan\Telegram\Facades\Telegram;
$response = Telegram::perform('getFile', [
'file_id' => 'abcdefg'// Your file id
]);
if ($response->json('ok')) {
$file_path = $response->json('result.file_path');
$file_url = Telegram::generateFileUrl($file_path);
// You can use $file_url to download the file.
}
else {
$error = $response->json('description');
// There was an error receiving file information. You can use $error to display the error.
}
use MohammadZarifiyan\Telegram\Facades\Telegram;
echo Telegram::getBotId();// Output: 123456
return [
// The rest of your code
'telegram' => [
'secure-token' => env('TELEGRAM_SECURE_TOKEN'),
],
];
namespace App\Repositories;
use MohammadZarifiyan\Telegram\Interfaces\SecureTokenRepository;
class TelegramSecureTokenRepository implements SecureTokenRepository
{
public function get(): ?string
{
return 'abcdefg';// Return your secure token
}
}
return [
// The rest of the file
'secure-token-repository' => \App\Repositories\TelegramSecureTokenRepository::class,// Set your own custom repository
// The rest of the file
];
use MohammadZarifiyan\Telegram\Facades\Telegram;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::post('telegram-update', function (Request $request) {
Telegram::handleRequest($request);
});
return [
// The rest of the file
'middlewares' => [
App\Telegram\Middlewares\YourMiddleware::class,
],
// The rest of the file
];
return [
// The rest of the file
'command_handlers' => [
App\Telegram\CommandHandlers\YourCommandHandler::class,
],
// The rest of the file
];
namespace App\Telegram\CommandHandlers;
use MohammadZarifiyan\Telegram\Interfaces\CommandHandler;
use MohammadZarifiyan\Telegram\Update;
class StartCommandHandler implements CommandHandler
{
/**
* The signature(s) of the Telegram bot command that can be handled by current CommandHandler.
*
* @param Update $update
* @return string|array
*/
public function getSignature(Update $update): string|array
{
return 'start';
}
/**
* Handles the Telegram command.
*
* @param Update $update
*/
public function handle(Update $update)
{
// Handle command here
}
}
namespace App\Telegram\CommandHandlers;
use MohammadZarifiyan\Telegram\Interfaces\AnonymousCommandHandler;
use MohammadZarifiyan\Telegram\Update;
class MyAnonymousCommandHandler implements AnonymousCommandHandler
{
/**
* Checks whether the current CommandHandler can process the command.
*
* @param Update $update
* @return bool
*/
public function matchesSignature(Update $update): bool
{
$signature = $update->toCommand()->getSignature();
return $signature === 'start';
}
/**
* Handles the Telegram command.
*
* @param Update $update
*/
public function handle(Update $update)
{
// Handle command here
}
}
return [
// The rest of the file
'breakers' => [
App\Telegram\Breakers\YourBreaker::class,
],
// The rest of the file
];
namespace App\Telegram\Breakers;
use MohammadZarifiyan\Telegram\Breaker;
use MohammadZarifiyan\Telegram\Update;
class CancelBulkNotificationBreaker extends Breaker
{
public function handleCallbackQuery(Update $update): bool
{
if ($update->input('callback_query.data') === 'cancel-sending-all-notifications') {
// Cancel sending notifications
/*
* Stop processing request by other Telegram breakers,
* Because we already handled the Update and the is no need to continue processing this Update in our application
*/
return $this->stop();
}
else {
/*
* Continue processing the Telegram Update using other Telegram Breakers or Telegram Stages,
* Because this Telegram breaker could was not able to handle the Telegram update
*/
return $this->continue();
}
}
}
return [
// The rest of the file
'gainer-resolver' => \App\Telegram\GainerResolver::class,// Set your own class name
// The rest of the file
];
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $fillable = ['telegram_id'];
protected $casts = [
'telegram_id' => 'integer',
];
}
use App\Models\User;
use MohammadZarifiyan\Telegram\Update;
use MohammadZarifiyan\Telegram\Interfaces\GainerResolver as GainerResolverInterface;
class GainerResolver implements GainerResolverInterface
{
public function handle(Update $update)
{
if ($update->type() === 'message') {
return User::firstOrCreate([
'telegram_id' => $update->input('message.from.id')
]);
}
return null;
}
}
use MohammadZarifiyan\Telegram\Facades\Telegram;
use App\Models\User;
$update = Telegram::getUpdate();
$gainer = $update->gainer();
if ($gainer instanceof User) {
echo 'The user became a member of the bot on date ' . $gainer->created_at;
}
else {
echo 'The $gainer value is null.';
}
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('telegram_id');
$table->string('stage')->nullable();
$table->unsignedTinyInteger('age')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
};
namespace App\Models;
use MohammadZarifiyan\Telegram\Interfaces\Gainer as GainerInterface;
use MohammadZarifiyan\Telegram\Traits\Gainer;
use Illuminate\Database\Eloquent\Model;
class User extends Model implements GainerInterface
{
use Gainer;
protected $fillable = [
'telegram_id',
'age',
];
protected $casts = [
'telegram_id' => 'integer',
'age' => 'integer',
];
}
namespace App\Telegram\Stages;
use App\Telegram\Updates\AgeUpdate;
use MohammadZarifiyan\Telegram\Facades\Telegram;
class Age
{
public function handleMessage(AgeUpdate $update): void
{
$update->gainer()->update([
'stage' => null,
'age' => $update->integer('message.text')
]);
Telegram::perform('sendMessage', [
'text' => 'Your age has been saved in the database.',
'chat_id' => $update->integer('message.chat.id'),
]);
}
}
namespace App\Telegram\Updates;
use MohammadZarifiyan\Telegram\FormUpdate;
class AgeUpdate extends FormUpdate
{
public function rules(): array
{
return [
'message.text' => ['bail', '
use MohammadZarifiyan\Telegram\Facades\Telegram;
use App\Telegram\Stages\Age;
$gainer = Telegram::getUpdate()->gainer();
$gainer->update(['stage' => Age::class]);
Telegram::perform('sendMessage', [
'chat_id' => $gainer->telegram_id,
'text' => 'How old are you?'
]);