Initial Telegram support

This commit is contained in:
Matteo Gheza 2023-06-06 23:50:52 +02:00
parent e69d25661f
commit da20cf7bf6
10 changed files with 1229 additions and 472 deletions

View File

@ -0,0 +1,80 @@
<?php
namespace TheCodingMachine\Discovery;
/**
* Use this class to access data stored in the discovery.json files at the root of your packages.
*/
class Discovery implements DiscoveryInterface
{
private static $instance;
/**
* @var string[]
*/
private $values;
/**
* @var AssetType[]
*/
private $assetTypes;
/**
* @var array[]
*/
private $assetTypesArray;
/**
* Singleton. Noone creates this object directly.
*/
private function __construct()
{
$this->values = require __DIR__.'/discovery_values.php';
$this->assetTypesArray = require __DIR__.'/discovery_asset_types.php';
}
/**
* Returns the unique instance of this class (singleton).
*
* @return self
*/
public static function getInstance(): self
{
if (!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Returns the asset values of the requested type.
*
* If no assets are found, an empty array is returned.
*
* @param string $assetType
* @return string[]
*/
public function get(string $assetType) : array
{
return $this->values[$assetType] ?? [];
}
/**
* Returns an asset type object for the requested type.
*
* If no assets are found, an AssetType object containing no assets is returned.
*
* @param string $assetType
* @return AssetTypeInterface
*/
public function getAssetType(string $assetType) : AssetTypeInterface
{
if (!isset($this->assetTypes[$assetType])) {
if (isset($this->assetTypesArray[$assetType])) {
$this->assetTypes[$assetType] = ImmutableAssetType::fromArray($assetType, $this->assetTypesArray[$assetType]);
} else {
$this->assetTypes[$assetType] = ImmutableAssetType::fromArray($assetType, []);
}
}
return $this->assetTypes[$assetType];
}
}

View File

@ -0,0 +1,3 @@
<?php
return array (
);

View File

@ -0,0 +1,3 @@
<?php
return array (
);

View File

@ -25,6 +25,10 @@ DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
TELEGRAM_BOT_TOKEN=123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11
TELEGRAM_WEBHOOK_DOMAIN=
TELEGRAM_WEBHOOK_PATH=/api/telegram
BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DISK=local

View File

@ -0,0 +1,38 @@
<?php
namespace App\Listeners;
use Telegram\Bot\Events\UpdateEvent;
use Telegram\Bot\Exceptions\TelegramSDKException;
/**
* Class ProcessInboundPhoto
*/
class ProcessInboundPhoto
{
/**
* Handle the event.
*
*
* @throws TelegramSDKException
*/
public function handle(UpdateEvent $event)
{
$update = $event->update;
$bot = $event->bot;
/*
//TODO: update if needed
// Download the largest image to the storage/app directory.
$photo = collect($update['message']['photo'])->last();
$bot->downloadFile($photo, storage_path('app/photos'));
// Reply the user.
$text = 'Thanks for uploading the pic!';
$bot->sendMessage([
'chat_id' => $update['message']['chat']['id'],
'text' => $text,
]);
*/
}
}

View File

@ -0,0 +1,35 @@
<?php
namespace App\Telegram\Commands;
use Telegram\Bot\Commands\Command;
use Throwable;
class Start extends Command
{
protected string $description = 'Start command to process initial request!';
/**
* Execute the bot command.
*/
public function handle()
{
$message = $this->getUpdate()->message;
$firstName = $message->from->first_name;
$text = "Hello, $firstName! Welcome to our bot!\nType /help to get a list of available commands.";
$this->bot->sendMessage([
'chat_id' => $message->chat->id,
'text' => $text,
]);
}
/**
* Triggered on failure.
*/
public function failed(array $arguments, Throwable $exception): void
{
//
}
}

View File

@ -7,6 +7,7 @@
"require": {
"php": "^8.1",
"guzzlehttp/guzzle": "^7.2",
"telegram-bot-sdk/laravel": "^4.0",
"lab404/laravel-impersonate": "^1.7",
"laravel/framework": "^10.0",
"laravel/sanctum": "^3.2",
@ -60,9 +61,10 @@
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true,
"php-http/discovery": true
"php-http/discovery": true,
"thecodingmachine/discovery": true
}
},
"minimum-stability": "stable",
"minimum-stability": "dev",
"prefer-stable": true
}

1360
backend/composer.lock generated

File diff suppressed because it is too large Load Diff

165
backend/config/telegram.php Normal file
View File

@ -0,0 +1,165 @@
<?php
return [
/**
*--------------------------------------------------------------------------
* Default Bot Name
*--------------------------------------------------------------------------
*
* Here you may specify which of the bots below you wish to use as
* your default bot for regular use. Of course, you may use many
* bots at once using the manager class.
*/
'use' => 'default',
/**
*--------------------------------------------------------------------------
* Your Telegram Bots
*--------------------------------------------------------------------------
*
* You may use multiple bots at once using the manager class. Each bot
* that you own should be configured here.
*
* Here are each of the telegram bots config parameters.
*
* Supported Params:
*
* - name: The *personal* name you would like to refer to your bot as.
*
* - token: Your Telegram Bot Token.
* Refer for more details: https://core.telegram.org/bots#botfather
* Example: (string) '123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11'.
*
* - commands: (Optional) Commands to register for this bot,
* Supported Values: "Command Group Name", "Command Repository Name", "Command => Full Path to Class".
* Default: Registers Global Commands.
* Example: (array) [
* 'admin', // Command Group Name.
* 'status', // Command Repository Name.
* 'hello' => App\Telegram\Commands\HelloCommand::class,
* 'bye' => App\Telegram\Commands\ByeCommand::class,
* ]
*/
'bots' => [
'default' => [
'token' => env('TELEGRAM_BOT_TOKEN', 'YOUR-BOT-TOKEN'),
'commands' => [
'start' => App\Telegram\Commands\Start::class,
],
'listen' => [
'update' => [],
'webhook.failed' => [],
// Example of various events fired.
'message' => [],
//'message.photo' => [ \App\Listeners\ProcessInboundPhoto::class ],
'poll' => [],
'message.left_chat_member' => [],
'inline_query.location' => [],
],
]
],
/**
*--------------------------------------------------------------------------
* Webhook [Optional]
*--------------------------------------------------------------------------
*
* Domain: If you want to set a custom domain for your webhook.
* Path: Path is used to construct a webhook route. Default: /telegram
* Controller: Responsible to listen to updates and acknowledge to Telegram.
*
* Default path: telegram
* Webhook path: /telegram/{bot}/webhook
*/
'webhook' => [
'domain' => env('TELEGRAM_WEBHOOK_DOMAIN', null),
'path' => env('TELEGRAM_WEBHOOK_PATH', 'telegram'),
'controller' => \Telegram\Bot\Laravel\Http\Controllers\WebhookController::class,
],
/**
*--------------------------------------------------------------------------
* HTTP [Optional]
*--------------------------------------------------------------------------
*
* - config: To set HTTP Client config (Ex: proxy).
* - async: When set to True, All the requests would be made non-blocking (Async).
* - api_url: To set the Base API URL.
* - client: To set HTTP Client. Should be an instance of @see \Telegram\Bot\Contracts\HttpClientInterface::class
*/
'http' => [
'config' => [],
'async' => env('TELEGRAM_ASYNC_REQUESTS', false),
'api_url' => 'https://api.telegram.org',
'client' => \Telegram\Bot\Http\GuzzleHttpClient::class,
],
/**
*--------------------------------------------------------------------------
* Register Global Commands [Optional]
*--------------------------------------------------------------------------
*
* If you'd like to use the SDK's built in command handler system,
* You can register all the global commands here.
*
* Global commands will apply to all the bots in system and are always active.
*
* The command class should extend the \Telegram\Bot\Commands\Command class.
*
* Default: The SDK registers, a help command which when a user sends /help
* will respond with a list of available commands and description.
*/
'commands' => [
'help' => Telegram\Bot\Commands\HelpCommand::class,
],
/**
*--------------------------------------------------------------------------
* Command Groups [Optional]
*--------------------------------------------------------------------------
*
* You can organize a set of commands into groups which can later,
* be re-used across all your bots.
*
* You can create [4] types of groups!
*
* 1. Group using full path to command classes.
*
* 2. Group using command repository: Provide the key name of the command from the command repository
* and the system will automatically resolve to the appropriate command.
*
* 3. Group using other groups of commands: You can create a group which uses other
* groups of commands to bundle them into one group.
*
* 4. You can create a group with a combination of 1, 2 and 3 all together in one group.
*
* Examples shown below are by the group type for you to understand each of them.
*/
'command_groups' => [
],
/**
*--------------------------------------------------------------------------
* Command Repository [Optional]
*--------------------------------------------------------------------------
*
* Command Repository lets you register commands that can be shared between,
* one or more bots across the project.
*
* This will help you prevent from having to register same set of commands,
* for each bot over and over again and make it easier to maintain them.
*
* Command Repository are not active by default, You need to use the key name to register them,
* individually in a group of commands or in bot commands.
*
* Think of this as a central storage, to register, reuse and maintain them across all bots.
*/
'command_repository' => [
// 'start' => App\Telegram\Commands\StartCommand::class,
// 'stop' => App\Telegram\Commands\StopCommand::class,
],
];

View File

@ -7,6 +7,8 @@ use App\Http\Controllers\ScheduleSlotsController;
use App\Http\Controllers\AvailabilityController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Telegram\Bot\Laravel\Http\Middleware\ValidateWebhook;
use Telegram\Bot\Laravel\Http\Controllers\WebhookController;
/*
|--------------------------------------------------------------------------
@ -57,3 +59,8 @@ Route::post('/cron/execute', function(Request $request) {
return response('Access Denied', 403);
}
});
//TODO: remove this and open issue on https://github.com/telegram-bot-sdk/laravel since named route not working
Route::group(['middleware' => ValidateWebhook::class], function (): void {
Route::post('/telegram/{bot}/webhook', Telegram\Bot\Laravel\Http\Controllers\WebhookController::class)->name('telegram.bot.webhook');
});