J
J
JohnnyParazit2017-09-01 08:07:09
PHP
JohnnyParazit, 2017-09-01 08:07:09

How to take value from array in my bot example?

Good day! I'll try quickly and without water! There is a bot for telegrams, below is a piece of working code:

$message = mb_strtolower($message); // все сообщения от пользователей в нижний регистр
 $hello = 'привет'; //на эту фразу реагирует бот
 $bot_hello      = strripos($message, $hello);
 $bot_otv = array(); //это массив ответов на фразу привет!
  $bot_otv[] = 'И тебе привет';
  $bot_otv[] = 'Ку';
  $bot_otv[] = 'Доброго времени суток';
  $bot_otv[] = 'Привет привет';
  $bot_otv[] = ('Привет '. $first_name . '!' );
  $bot_otv[] = 'Здорова!!!';
  $bot_otv[] = 'Я покупаю биток!';
  $bot_otv[] = 'Здрасте!';
  
  $bot_resp = $bot_otv[rand(0, (count($bot_otv) - 1))]; //в эту переменную мы пихаем случайный ответ бота
  
if ($bot_hello === false) { //Если фраза привет не присутствует в контексте ничего не делаем
  } else { //в другом случае отправляем наш рандомный ответ
    sendMsg($group_id, $bot_resp );
}

Everything seems to be great! Maybe the code is crap in places, I don’t know how to shorten it!
QUESTION: How can I make an array of phrases so that it is not just hello, but several "hello, great, grow up, etc." So that the bot can respond to any phrase from this array and substitute its own random answer!
Thank you in advance

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
link_irk, 2017-09-01
@link_irk

$message = mb_strtolower($message);
$hello = ['привет', 'доброго дня', 'здравствуйте'];
if(in_array($message, $hello)) {
    // Сообщение от пользователя соответствует одному из элементов массива
} else {

}

S
Stanislav B, 2017-09-01
@S_Borchev

like this

function contain(string $str, array $search): bool
{
    foreach ($search as $needle) {
        if (false !== strpos($str, $needle)) {
            return true;
        }
    }

    return false;
}

$message = mb_strtolower($message);
$hello = [
    'привет',
    'здрасти',
];
$bot_otv = [
    'И тебе привет',
    'Ку',
    'Доброго времени суток',
    'Привет привет',
    'Здорова!!!',
    'Я покупаю биток!',
    'Здрасте!',
];
if (contain($message, $hello)) {
    sendMsg($group_id, $bot_otv[rand(0, (count($bot_otv) - 1))]);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question