defstudio / telegraph

Telegraph is a Laravel package for fluently interacting with Telegram Bots
MIT License
694 stars 118 forks source link

Messages send only one user #456

Closed AntonNosovich closed 10 months ago

AntonNosovich commented 10 months ago

have such custom webhook ,its dont work when 2 or more users,how to fix them


<?php

namespace App\Telegram;

use App\Admin\Controllers\ExercisesController;
use App\Admin\Enums\GoalsEnum;
use App\Admin\Enums\MuscleGroupEnum;

use App\Admin\Enums\TimeEnum;
use App\Admin\Helper\TrainingBuilder;
use App\Models\Exercise;
use DefStudio\Telegraph\Facades\Telegraph;
use DefStudio\Telegraph\Keyboard\Button;
use DefStudio\Telegraph\Keyboard\Keyboard;
use DefStudio\Telegraph\Models\TelegraphChat;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Stringable;

class Handler extends \DefStudio\Telegraph\Handlers\WebhookHandler
{

    public function get_trainings()
    {
        TelegraphChat::where('chat_id', $this->chat->chat_id)->update([
            'unlike_exercises_ids' => null,
            'actual_exercises' =>null
        ]);

        $this->reply('Для начала ответь на пару вопросов');

        $this->set_main_muscle_group();
    }

    public function start()
    {
        $this->reply('<b>Привет!👋</b> Я создан для того чтоб помогать тебе в зале! Нажми команду /get_trainings и получи свою тренировку');
    }

    public function handleUnknownCommand($text): void
    {
        $this->reply('К сожалению я не знаю такую команду ' . $text . ' 😞');

    }

    public function get_answers()
    {
        $this->reply('<b>Ваши настройки</b>:
Время тренировки: ' . $this->chat->time . '
Цель тренировок: ' . $this->chat->goal . '
Группа мышц: ' . $this->chat->main_muscle_group . '
Чтобы изменить:
- Изменить цель тренировок: /set_goal
');
    }

    public function set_goal()
    {
        $buttons = [];
        foreach (GoalsEnum::getGoals() as $item) {
            $buttons[] = Button::make($item)->action('save_goal')->param('goal', $item)->param('send_training',true);
        }

        Telegraph::message('Выбери цель тренировки 🎯')
            ->keyboard(Keyboard::make()->buttons($buttons))
            ->send();
    }

    public function set_time()
    {
        $buttons = [];
        foreach (TimeEnum::getTrainigTime() as $item) {
            $buttons[] = Button::make($item)->action('save_time')->param('time', $item);
        }

        Telegraph::message('Выбери время тренировки ⏳')
            ->keyboard(Keyboard::make()->buttons($buttons))
            ->send();
    }

    public function set_main_muscle_group()
    {
        $buttons = [];
        foreach (MuscleGroupEnum::getMainGroups() as $item) {
            $buttons[] = Button::make($item)->action('save_muscle')->param('main_muscle_group', $item);
        }

        Telegraph::message('Выбери группу мышц для тренировок 💪')
            ->keyboard(Keyboard::make()->buttons($buttons))
            ->send();
    }

    public function change_exercise()
    {
        $exerciseId = $this->data->get('exercise_id');
        $exercise = Exercise::find($exerciseId);

        $unlikeExercisesIds = $this->chat->unlike_exercises_ids ?? '';
        $actualExercises = $this->chat->actual_exercises ?? '';

        $unlikeIdsArray = explode(',', $unlikeExercisesIds);
        $unlikeIdsArray = array_filter($unlikeIdsArray); // Удаляем пустые значения

        $newExercise = Exercise::where('target_muscle_group', $exercise->target_muscle_group)
            ->where('id', '!=', $exerciseId)
            ->when(!empty($unlikeIdsArray), function ($query) use ($unlikeIdsArray) {
                return $query->whereNotIn('id', $unlikeIdsArray);
            })
            ->when(trim($actualExercises) !== '', function ($query) use ($actualExercises) {
                $actualExercisesArray = array_filter(array_unique(explode(',', $actualExercises)));
                return $query->whereNotIn('id', $actualExercisesArray);
            })
            ->inRandomOrder()
            ->first();

        TelegraphChat::where('chat_id', $this->chat->chat_id)
            ->update([
                'unlike_exercises_ids' => $unlikeExercisesIds . ',' . $exerciseId
            ]);

        if (!$newExercise) {
            $this->reply('К сожалению, я не знаю больше упражнений на группу мышц: ' . $exercise->target_muscle_group);
        }
        else {
            $this->reply('Меняю ' . $exercise->title . ' на ' . $newExercise->title);

            TelegraphChat::where('chat_id', $this->chat->chat_id)
                ->update([
                    'actual_exercises' => $actualExercises . ',' . $newExercise->id
                ]);

            $training = Exercise::whereIn('id', explode(',',$this->chat->actual_exercises))->get();
            $program = TrainingBuilder::createFile($training, $this->chat->goal);

            Telegraph::document(Storage::path($program))
                ->message('Держи альтернативу🏋️ ')
                ->send();

            $buttons = [];
            foreach ($training as $item) {
                $buttons[] = Button::make('Заменить ' . $item->title)
                    ->action('change_exercise')
                    ->param('exercise_id', $item->id);
            }

            Telegraph::message('Ты можешь заменить упражнения ♻')
                ->keyboard(Keyboard::make()->buttons($buttons))
                ->send();
        }
    }    public function save_muscle()
{
    $main_muscle_group = $this->data->get('main_muscle_group');

    TelegraphChat::where('chat_id', $this->chat->chat_id)->update([
        'main_muscle_group' => $main_muscle_group
    ]);

    $this->set_time();

}

    public function save_time()
    {
        $time = $this->data->get('time');

        TelegraphChat::where('chat_id', $this->chat->chat_id)->update([
            'time' => $time
        ]);
        if($this->chat->goal == null){
            $this->set_goal();
        }
        else if ($this->chat->time != null && $this->chat->main_muscle_group != null && $this->chat->goal != null){
            $this->buildGuid();
        }
    }

    public function save_goal()
    {
        $goal = $this->data->get('goal');

        TelegraphChat::where('chat_id', $this->chat->chat_id)->update([
            'goal' => $goal
        ]);

        if ($this->chat->time != null && $this->chat->main_muscle_group != null){

            $this->buildGuid();
        }
    }

    private function buildGuid()
    {

        $exercises = ExercisesController::build_program($this->chat);
        $this->send_guid($exercises);
    }

    protected function send_guid($exercises){
        $this->chat->actual_exercises = implode(',', $exercises->pluck('id')->toArray());
        $this->chat->save();
        $program = TrainingBuilder::createFile($exercises, $this->chat->goal);

        Telegraph::document(Storage::path($program))->message('Удачной тренировки🏋️')->send();

        $buttons = [];

        foreach ($exercises as $item) {
            $buttons[] = Button::make('Заменить ' . $item->title)->action('change_exercise')->param('exercise_id', $item->id);
        }
        Telegraph::message('Ты можешь заменить упражнения ♻')
            ->keyboard(Keyboard::make()->buttons($buttons))
            ->send();
    }

}
dostonadilov commented 10 months ago

Same problem, The message is sent only to the first user in telegraph_chats, and after that other users are also added to this telegraph_chats table, but the web hook does not react to them in any way

dostonadilov commented 10 months ago

Как найдешь решение дай знать

dostonadilov commented 10 months ago

$this->chat->message попробуй это использовать может быть поможет тебе, так как бот не понимает чье это сообщение поэтому поумочанию 1 пользователю отправляет, попробуй после дай знать

AntonNosovich commented 10 months ago

Yes,it's work