Skip to content

I'd like to offer save users language_code and publish class with main logic for fast start #721

Description

@VitalyEvrica

HI,
Want to offer this to pull. Can I make pull request or you will handle it by yourself lately?

Telegramers are using different langs, so we can add language_code column to store the user’s language preferences:

database/migrations/create_telegraph_chats_table.php

$table->string('language_code')->nullable();

src/Handlers/WebhookHandler.php

protected function setupChat(){
//your code...
if (!$this->chat->exists) {
            if (!$this->allowUnknownChat()) {
                throw new NotFoundHttpException();
            }

            if (config('telegraph.security.store_unknown_chats_in_db', false)) {
                $this->createChat($telegramChat, $this->chat);
                //mine part:
                //save original lang and if it is not supported by you, will save the suppored lang code to DB
                $tgData = $this->message->toArray();
                $lang = lng_def();
                if(isset($tgData['from']['language_code']) and ctype_alpha($tgData['from']['language_code'])){
                    $lang = $tgData['from']['language_code'];
                    TelegraphChat::where([
                        'id'               => $this->chat['id'],
                        'chat_id'          => $this->chat['chat_id'],
                        'telegraph_bot_id' => $this->chat['telegraph_bot_id'],
                    ])->update(['language_code' => $lang]);
                }
                $this->chat->language_code = $this->TC_set_supported_lang($lang);
                //end of mine part
            }
    }
}

helpers/main.php or put them to TeleGraphAndGram

if (!function_exists('lng_def')) { function lng_def(){return /**set your**/ 'ru';}}
if (!function_exists('lng_falbk')) { function lng_falbk(){return 'en';/**because Laravel default is English**/}}
if (!function_exists('lng_sup_arr')) { function lng_sup_arr(){return ['ru'];}}
if (!function_exists('t')) { function t($w,$assocParams=[],$hardLocale=null){return __('t.'.$w,$assocParams,$hardLocale);}}

I also think programmers always add custom class to use Telegram, so
config/telegraph.php

'webhook' => [
        //your code....
        'handler' => App\Http\Telegas\TeleGraphAndGram::class,
         //...
]

Add to README this:
"
and we can publish it with command

php artisan vendor:publish --tag=telegraph-add-default-controller-to-http-folder

"

Then make command working
src/TelegraphServiceProvider.php

$this->publishes([
    __DIR__ . '/Http/TeleGraphAndGram.php' => app_path('Http/TeleGraphAndGram.php'),
], 'telegraph-add-default-controller-to-http-folder');

src/Http/TeleGraphAndGram.php

<?php

namespace App\Http;

use DefStudio\Telegraph\Facades\Telegraph;
use DefStudio\Telegraph\Handlers\WebhookHandler;
use Illuminate\Support\Stringable;

class TeleGraphAndGram extends WebhookHandler
{
    protected $lang_of_user_supported = true;
    protected $lang_of_user_orig = '';

    public function __construct()
    {
        parent::__construct();
        app()->setLocale(lng_def());//hardcode, but only when you have 1 language and it is no English and you want start fast
    }

    public function handleUnknownCommand(Stringable $text): void
    {
        $this->reply('<b>No such command</b>');
        // some help to juniors:
        // or Telegraph::message('...')->send();
        // or $this->chat->html('Your text is: <i>'.$text.'</i>')->send();
    }

    public function start(): void
    {
        $lang_of_user_supported = $this->lang_of_user_supported ? '' : t('lang_not_supported',['LANG'=>$this->lang_of_user_orig], lng_falbk());
        if($lang_of_user_supported){
            $this->chat->html($lang_of_user_supported)->send();
        }
        $this->reply('Time to start');
    }

    public function handleChatMessage(Stringable $text): void
    {
        $this->chat->html('Your text is: <i>'.$text.'</i>')->send();

        /**
         * To receive a photo (not a document!!)
         */
        //$photo = $this->message->photos()->toArray();
        //$data = count($photo)-1;
        //$id_photo = $photo[$data]['id'];
        //$this->bot->store($id_photo, $this->folder_for_photo(), Str::random(11).'.jpg');
    }

    public function TC_set_supported_lang($lang_from_user){
        // if lang is not supported , set 1st supported and answer with fallback
        // and continue with RU
        $lang_from_user = mb_strtolower($lang_from_user);
        $this->lang_of_user_orig = $lang_from_user;
        if(!in_array($lang_from_user, lng_sup_arr())){
            $set_lang = lng_def();
            $this->chat->language_code = $set_lang;
            TelegraphChat::where([
                'id'               => $this->chat['id'],
                'chat_id'          => $this->chat['chat_id'],
                'telegraph_bot_id' => $this->chat['telegraph_bot_id'],
            ])->update(['language_code' => $set_lang]);
            $this->lang_of_user_supported = false;
        }else{$set_lang = $lang_from_user;}
    
        return $set_lang;
    }

}

I guess I not forgot anything) Please, let me know what do you think

Activity

  1. MarioGattolla commented on Aug 25, 2025

    @MarioGattolla
    Contributor

    Hi @VitalyEvrica . I don't understand the purpose of this request. The language_code is not related to the Chat but is related to the User.
    Actually the language_code is already implemented in the User DTO and you can access from the ->languageCode() method. Tell me if I'm wrong or missing something

  2. VitalyEvrica commented on Aug 26, 2025

    @VitalyEvrica
    Author

    Hi @VitalyEvrica . I don't understand the purpose of this request. The language_code is not related to the Chat but is related to the User. Actually the language_code is already implemented in the User DTO and you can access from the ->languageCode() method. Tell me if I'm wrong or missing something

    Hi!
    Tell me pls where can I save now user's lang preference if I use your package to build a bot? Maybe I missed a place where you save it now.

    So, when user intereacts with a bot, developer needs to save language preference. Also there is a chance that user's Telegram is in English but user wants to use bot in another language.
    So the idea to implement this - save user's lang in chats table and be able to change it. Then we can use built in Laravel translations like Button::make(__('i18.translation_key'))->...
    Thus my code handles situation when bot is not translated to the language desired by user and it informs a user about that and starts bot with fallback lang.
    Also user will be able to change bot language when translation will be ready.

    Looking forward to hear your thoughts

  3. locked and limited conversation to collaborators on Aug 29, 2025
  4. converted this issue into a discussion #722 on Aug 29, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions