PHP code example of irwinlopez1023 / magma4telegram
1. Go to this page and download the library: Download irwinlopez1023/magma4telegram library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
irwinlopez1023 / magma4telegram example snippets
rwinlopez1023\Magma4telegram\Magma;
try {
// Automatically discover your app's structure
Magma::autoDiscoverCommands(__DIR__ . '/Modules', 'Modules\\');
Magma::autoDiscoverConversations(__DIR__ . '/Conversations', 'Conversations\\');
Magma::autoDiscoverJobs(__DIR__ . '/Jobs', 'Jobs\\');
// Instantiate Magma with your bot token
$botToken = 'YOUR_TELEGRAM_BOT_TOKEN_HERE';
$magma = new Magma($botToken);
} catch (Exception $exception) {
echo $exception->getMessage();
}
namespace Modules;
use irwinlopez1023\Magma4telegram\MagmaCommand;
use irwinlopez1023\Magma4telegram\MagmaSend;
use Exception;
class info extends MagmaCommand {
use MagmaSend;
// Define the command route and expected arguments
protected string $command = "/info {name}";
// The chatId is automatically injected by Magma
protected ?string $chatId = null;
public function handle(): void
{
try {
// Retrieve argument magically and send a response
$this->sendTelegramMessage($this->chatId, "Hello " . $this->argument('name'));
} catch (Exception $e) {
echo $e->getMessage() . "\n";
}
}
}
namespace Modules;
use irwinlopez1023\Magma4telegram\MagmaCommand;
use irwinlopez1023\Magma4telegram\MagmaSend;
class ping extends MagmaCommand {
use MagmaSend;
protected static string $command = '/ping';
protected static array $aliases = ['ping', 'pong'];
protected ?string $chatId = null;
public function handle(): void
{
$this->sendTelegramMessage($this->chatId, 'Pong!');
}
}
namespace Conversations;
use irwinlopez1023\Magma4telegram\MagmaConversation;
class RegistrationConversation extends MagmaConversation
{
public function start(): void
{
$this->ask("Hello! Let's get you registered. What is your name?");
// The next incoming message will be passed to the 'askAge' method
$this->next('askAge');
}
public function askAge(string $response): void
{
// Save the received data (the name) in the conversation state
$this->saveData('name', $response);
$this->ask("Nice to meet you, {$response}. How old are you?");
// The next incoming message will be handled by 'finish'
$this->next('finish');
}
public function finish(string $response): void
{
$name = $this->getData('name');
$age = $response;
$this->ask("Perfect! You've successfully registered.\nName: {$name}\nAge: {$age}");
// End the conversation and clear the state
$this->end();
}
}
namespace Modules;
use irwinlopez1023\Magma4telegram\Magma;
use irwinlopez1023\Magma4telegram\MagmaCommand;
use irwinlopez1023\Magma4telegram\MagmaSend;
use Conversations\RegistrationConversation;
use Exception;
class register extends MagmaCommand {
use MagmaSend;
protected string $command = "/register";
protected ?string $chatId = null;
public function handle(): void
{
try {
// Initialize Magma again for the conversation instance
$magma = new Magma($this->botToken);
$conversation = new RegistrationConversation($magma, $this->chatId);
$conversation->start();
} catch (Exception $e) {
echo $e->getMessage() . "\n";
}
}
}
namespace Modules;
use irwinlopez1023\Magma4telegram\MagmaCommand;
use irwinlopez1023\Magma4telegram\MagmaSend;
use Conversations\ColorMenuConversation;
use Exception;
class menu extends MagmaCommand {
use MagmaSend;
protected string $command = "/menu";
protected ?string $chatId = null;
public function handle(): void
{
try {
$magma = new \irwinlopez1023\Magma4telegram\Magma($this->botToken);
$conversation = new ColorMenuConversation($magma, (string) $this->chatId);
$conversation->start();
} catch (Exception $e) {
error_log("Menu Command Error: " . $e->getMessage());
}
}
}
namespace Jobs;
use irwinlopez1023\Magma4telegram\MagmaJob;
use irwinlopez1023\Magma4telegram\MagmaSend;
use irwinlopez1023\Magma4telegram\ProgressBar;
use Exception;
class MyBackgroundJob extends MagmaJob {
use MagmaSend;
protected static bool $magmaRunnerLogging = true; // Enable logging (disabled by default)
public function handle(array $payload): void {
try {
$chatId = $payload['chatId'];
$messageId = $payload['messageId'];
// To use MagmaSend within a Job, you must set the token from the injected Magma instance
$this->MagmaSetBotToken($this->magma->getBotToken());
// You can reconstruct a ProgressBar created by the command using fromIds()
$progressBar = ProgressBar::fromIds($this, $chatId, $messageId, 15);
// Perform your long-running task here...
for ($i = 10; $i <= 100; $i += 10) {
sleep(1); // Simulating heavy work
$progressBar->update($i, "Processing task in background... ($i%)");
}
$this->editTelegramMessage(
$chatId,
$messageId,
"? Asynchronous task successfully finished in background!"
);
} catch (Exception $e) {
error_log("Error in MyBackgroundJob: " . $e->getMessage());
}
}
}
namespace Modules;
use irwinlopez1023\Magma4telegram\MagmaCommand;
use irwinlopez1023\Magma4telegram\MagmaSend;
use Jobs\MyBackgroundJob;
class test_job extends MagmaCommand {
use MagmaSend;
protected string $command = "/testjob";
protected ?string $chatId = null;
public function handle(): void {
// If your Jobs are in custom namespaces, specify the file that boots the app (e.g. webhook.php)
$this->setBootstrapPath(realpath(__DIR__ . '/../webhook.php'));
$progressBar = $this->createProgressBar($this->chatId, "? Starting asynchronous task...");
$payload = [
'chatId' => $progressBar->getChatId(),
'messageId' => $progressBar->getMessageId()
];
// Dispatch the job and pass the payload
$this->dispatchAsync(MyBackgroundJob::class, $payload);
// The script continues immediately. We can send a fast response.
$this->sendTelegramMessage($this->chatId, "?? The job is being processed in the background!");
}
}
namespace Modules;
use irwinlopez1023\Magma4telegram\Keyboard;
use irwinlopez1023\Magma4telegram\MagmaCommand;
use irwinlopez1023\Magma4telegram\MagmaSend;
use Exception;
class buttons extends MagmaCommand {
use MagmaSend;
protected string $command = "/button {something} {something}";
protected ?string $chatId = null;
// Map button's callback_data to local methods
protected array $callbacks = [
'ok' => 'confirm',
'cancel' => 'cancel'
];
/**
* @throws Exception
*/
public function handle(): void
{
// Build the inline keyboard
$botones = Keyboard::inline()
->row()->button('Confirm', 'ok')
->row()->button('Cancel', 'cancel')
->get();
$this->sendTelegramMessage($this->chatId, "Choose an option:", "html", $botones);
}
public function confirm(): void
{
// $this->answerCallback() is provided by the MagmaSend trait.
$this->answerCallback("You have successfully confirmed the action!");
}
public function cancel(): void
{
$this->answerCallback("Operation cancelled. Everything is fine.");
}
}
$keyboard = Keyboard::inline()
// First row: Two buttons side-by-side using callback_data
->row()
->button('Approve', 'approve_action')
->button('Decline', 'decline_action')
// Second row: A single button spanning the whole line.
// Because the second parameter is a valid URL, Magma creates a URL button!
->row()
->button('Visit our Website', 'https://example.com')
->get();
namespace Modules;
use irwinlopez1023\Magma4telegram\MagmaCommand;
use irwinlopez1023\Magma4telegram\MagmaSend;
use Exception;
class process extends MagmaCommand {
use MagmaSend;
protected string $command = "/process {task}";
protected ?string $chatId = null;
public function handle(): void
{
try {
$taskName = $this->argument('task');
// 1. Initialize the Progress Bar
// This sends the initial message and returns a ProgressBar instance
$bar = $this->createProgressBar($this->chatId, "? Starting the '{$taskName}' task...");
sleep(1); // Simulating work
// 2. Update the Progress Bar with a percentage and an optional new text
$bar->update(25, "?? Fetching
use irwinlopez1023\Magma4telegram\MagmaSend;
class NotificationService {
use MagmaSend;
public function sendAlert(string $chatId, string $message): void
{
// You MUST manually set the token when using the trait standalone
$this->MagmaSetBotToken('YOUR_TELEGRAM_BOT_TOKEN_HERE');
$this->sendTelegramMessage($chatId, $message);
}
}
use irwinlopez1023\Magma4telegram\Magma;
Magma::setProxy('http://127.0.0.1:8888');
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.