User Rating: 5 / 5

Star ActiveStar ActiveStar ActiveStar ActiveStar Active
 
hello.png

So, after a while o writing few Telegram bots, I realized that multiple language support is always appreciated if the public doesn't speak the original language. To work around this, I got inspired by the Laravel approach, a big associative array.

The code is published at https://github.com/daniel-lucio/multilingual-support after you download you have to create the language files, for example, es.php, en.php, fr.php and so on. The following example is just for the /start command utilizing the Longman PHP library.

Code Example

This small code will answer hello in the language the Telegram user has configured.

composer.json


...
"autoload": {
        "files": [
	    ...
            "language/language.php"
        ]
    },
...

StartCommand.php 


declare(strict_types=1);
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Entities\ServerResponse;
use Longman\TelegramBot\Entities\Chat;
use Longman\TelegramBot\Exception\TelegramException;
use Longman\TelegramBot\TelegramLog;
use Longman\TelegramBot\Request;
use okayinc;

class StartCommand extends UserCommand {

protected $name = 'start';
protected $description = 'Start command';
protected $version = '0.2.0';
protected $usage = '/start';
protected $private_only = true;

public function execute(): ServerResponse
{
    $message = $this->getMessage();
    $from_user = $message->getFrom();
    $from_user_language = $from_user->getLanguageCode();
    $l = new okayinc\language($from_user_language, 'en');

    $answer = $l->get('hello');
    return $this->replyToChat($answer,[]);
}
}

en.php


	return ['hello' => 'hello'];

es.php


	return ['hello' => 'hola'];
blog comments powered by Disqus

About

Read about IT, Migration, Business, Money, Marketing and other subjects.

Some subjects: FusionPBX, FreeSWITCH, Linux, Security, Canada, Cryptocurrency, Trading.