1

like if someone type command "!user 123456" then send message "number banned"

I tried this but won't worked...

$ban = array('112233','123456'); if(strpos($message, "!user $ban") ===0){ sendMessage($chatId, "<u>Number Banned!</u>", $message_id); }

Wiker Bem
  • 29
  • 3
  • Turn on error reporting ([How do I get PHP errors to display?](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display?rq=1)) and you'd get a "_Warning: Array to string conversion in..._" – brombeer May 09 '21 at 17:59

2 Answers2

1
$ban = array('112233','123456'); 
$isbanned = false;
foreach ($ban as $b) {
  if(strpos($message, "!user $b") ===0) $isbanned = true;
}

if ($isbanned) { 
sendMessage($chatId, "<u>Number Banned!</u>", $message_id); 
}
Kinglish
  • 23,358
  • 3
  • 22
  • 43
1

Instead of using strpos, if you're going to do more commands you should parse out the action and data from the message, then you can use logic to do something on user and something on foobar etc, using the rest of the message as the data or splitting it up further.

<?php

$banned_users = ['123456', '112233'];

// parse out command from the message
$command = [
 'action' => '', // will contain user
 'data' => ''    // will contain 123456
];
if (isset($message[0], $message[1]) && $message[0] === '!') {
    $message = substr($message, 1);
    list($command['action'], $command['data']) = explode(' ', trim($message), 2);
}

// do commands
if ($command['action'] === 'user') {
    if (in_array($command['data'], $banned_users)) {
        sendMessage($chatId, "<u>Number Banned!</u>", $message_id);
    } else {
        sendMessage($chatId, "<u>Not Banned!</u>", $message_id);
    }
} elseif ($command['action'] === 'foobar') {
    //...
    echo 'Do foobar with: ' . $command['data'];
} else {
    sendMessage($chatId, "<u>Invalid command!</u>", $message_id);
}

Then if some thing like the following is going to be used in multiple places:

if (in_array($command['data'], $banned_users)) {
    //sendMessage($chatId, "<u>Number Banned!</u>", $message_id);
    echo 'Number Banned!';
}

Make a function:

function is_banned($number) {
    return in_array($number, ['123456', '112233']);
}

Then use it instead of the in_array

// ...
if ($command['action'] === 'user') {
    if (is_banned($command['data'])) {
        sendMessage($chatId, "<u>Number Banned!</u>", $message_id);
    }
    // ...
}
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106