PHP code example of haikiri / messenger-routing

1. Go to this page and download the library: Download haikiri/messenger-routing 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/ */

    

haikiri / messenger-routing example snippets


#   This method is optional, and will contain your implementation if no one command is found.
protected final function catch_all(): void
{
	echo "Realize this method if you need to handle the event in your own way if more than one command was not found.";
	echo "For example: send a message that such a command has not been found.";
}

// This method accepts only POST requests from Telegram.
#[Route(path: "/api/telegram/controller", name: "controller_post", methods: ["POST"])]
public function controller_post(): Response
{
	(new \App\Messenger\TelegramMessenger())->handleUpdate();
	return new Response("ok");
}

	use Symfony\Contracts\Service\ServiceProviderInterface;

	#[Route("/api/telegram/controller", name: "controller_post", methods: "POST")]
	public function callback(
		#[AutowireLocator(services: "tg", indexAttribute: "chat.type")]
		ServiceProviderInterface $serviceProvider,
	): Response
	{
		$update = $this->myMessenger->getResponse(); # get your update from messenger
		$this->myMessenger->setUpdate($update); # write your update in your messenger SDK

		try {
			# Get your chat type.
			$chatType = $update["type"] ?? null;

			# Here searching for your service with the specified type of chat in `const CHAT_TYPE`
			if ($chatType && $serviceProvider->has($chatType)) {
				$serviceProvider->get($chatType)();
			}
		} catch (Throwable $ex) {
			// Catch and handle all exception errors from your command controllers here.
		}

		return new Response("ok");
	}


use Symfony\Component\DependencyInjection\Attribute;

#[Attribute\AsTaggedItem(index: self::CHAT_TYPE)]
#[Attribute\AutoconfigureTag("tg", ["chat.type" => self::CHAT_TYPE])]
class TelegramMessenger extends TelegramContract
{
	const CHAT_TYPE = "message_new"; # This is the chat type that was assigned to your controller in your `update` of your messenger.
}

class TelegramMessenger extends TelegramContract
{
	public \Developer\OF\MyWonderfulTelegramSDK $bot;

	public function __construct()
	{
		# Your Telegram Api Bots SDK Here: $this->bot
		$this->bot = new \Developer\OF\MyWonderfulTelegramSDK(
			your_api_server: $_ENV['TELEGRAM_API_HOST'],
			your_api_token: $_ENV['TELEGRAM_API_TOKEN'],
		);
	}

	public function handleUpdate(): void
	{

		# Check for message type.
		$messageType = $this->bot->getMessage()->getType();
		switch ($messageType) {
			case "private":
				(new Telegram\PrivateRoom($this))(); # Pass `$this` to your private room for using MessengerContract and Tg API.
//			case "group":
//				(new Telegram\GroupRoom($this))(); # Pass `$this` to your private room for using MessengerContract and Tg API.
//			case "supergroup":
//				(new Telegram\SuperGroupRoom($this))(); # Pass `$this` to your private room for using MessengerContract and Tg API.
			default:
				throw new \Exception("sorry. this chat is not supported: `{$messageType}`");
		}

	}

namespace App\Messenger;

abstract class TelegramContract implements \Haikiri\MessengerRouting\MessengerContractInterface
{
	/**
	 * Note: that your library returns getUpdate() objects.
	 * This is just a source of your bot sdk.
	 * @see https://core.telegram.org/bots/api#update
	 */
	public function getUpdate(): object
	{
		return $this->bot->getUpdate(); # or $this->bot["update"]; // etc...
	}

	public function getBotName(): string
	{
		return "MyNewBOT"; # without at `@`. your bot name must be ends at `bot` or `_bot`.
//		return $_ENV["TG_BOT_NAME"] ?? null; # or use data from your .ENV
	}

	public function isAppAuthorized(): bool
	{
		return false; // TODO: Implement isAppAuthorized() method.
	}

	public function isSenderAdmin(): bool
	{
		return false; // TODO: Implement verification for the chat administrator.
	}

	public function isSenderOwner(): bool
	{
		return false; // TODO: Implement verification for the chat creator.
	}

	public function isSenderEnvAdmin(): bool
	{
		return
		$env = $_ENV["TG_ADMINS_LIST"] ?? null; # use var from .ENV
		$env = "1872656523,387456823,237864528,3457862300"; # or write manually (unsafe)
		return !empty($env) && in_array($this->getUpdate()->getUser()->getId(), explode(",", $env));
	}

	public function getSenderText(): ?string
	{
		$message = $this->getUpdate()->getMessage(); # get Message object.
		return $message ? $message->getText() : null; # example for return message text
	}

	public function getSenderCallbackQueryData(): string|null
	{
		return null; // TODO: Stay null, if your messenger doesn't support callback query, or u dont work with it.
	}

}



declare(strict_types=1);

namespace App\Messenger\Telegram;

use Haikiri\MessengerRouting\OnCommand;
use Haikiri\MessengerRouting\CommandsRouter;
use App\Messenger\TelegramMessenger;

class PrivateRoom extends CommandsRouter
{
	private TelegramMessenger $messenger;

	public function __construct(TelegramMessenger $controller)
	{
		$this->messenger = $controller; # using your parent controller for working with telegram sdk
		parent::__construct($controller); # Always at end
	}

	# Use this method for catch unhandled commands. remove it if u dnt need it.
	protected final function catch_all(): void
	{
		$chat_id = $this->messenger->bot->getUpdate()->getChat()->getId();
		$message = "Command not found: {$this->messenger->getSenderText()}";

		$this->messenger->server->sendMessage(chatId: $chat_id, text: $message);
	}

	#[OnCommand(commands: "/start")]
	public function start()
	{
		$this->messenger->bot->sendMessage(
			chatId: $this->messenger->bot->getUpdate()->getChat()->getId(),
			text: "You are call: `/start`!",
		);
	}

	#[OnCommand(commands: "/stop", isOwner: true)] # Only the chat creator and ENV Admins can stop this bot!
	public function start(): void
	{
		$this->messenger->bot->sendMessage(
			chatId: $this->messenger->bot->getUpdate()->getChat()->getId(),
			text: "Implement this method as u need. Only owner and ENV admin can use it.",
		);
	}

	#[OnCommand(
		commands: [
			"/balance", "баланс", "сколько денег", "сколько денек", "мой счет", "сколько средств",
			"сколько денег", "у меня денег", "у меня бабок","остаток денег", "остаток средств",
			"сколько у меня", "скок у меня", "баланс лицевого счёта", "баланс лицевого счёта",
		],
		return_data: false, # temperature not worked if return_data is true.
	    temperature: 60, # The threshold of a match.
	    fuzzy: true, # If true, allows matching a command anywhere within the full text string. see tests!
	)]
	public function balance()
	{
		$this->messenger->bot->sendMessage(
			chatId: $this->messenger->bot->getUpdate()->getChat()->getId(),
			text:
			"The built-in `similar_text` function allows small errors in the text." .
			"This method will work if there is a match for the specified temperature and above." . 
		);
	}

	#[OnCommand(
		commands: ["ban", "бан"],
		return_data: true, # temperature not worked if return_data is true.