就像有人键入命令一样"!用户123456";则发送消息";数字被禁止";
我试过了,但不起作用。。。
$ban = array('112233','123456'); if(strpos($message, "!user $ban") ===0){ sendMessage($chatId, "<u>Number Banned!</u>", $message_id); }
如果要执行更多命令,则应该从消息中解析出操作和数据,而不是使用strpos,然后可以使用逻辑在user
和foobar
等上执行某些操作,将消息的其余部分用作数据或将其进一步拆分。
<?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);
}
然后,如果像下面这样的东西将在多个地方使用:
if (in_array($command['data'], $banned_users)) {
//sendMessage($chatId, "<u>Number Banned!</u>", $message_id);
echo 'Number Banned!';
}
生成一个函数:
function is_banned($number) {
return in_array($number, ['123456', '112233']);
}
然后使用它而不是in_array
// ...
if ($command['action'] === 'user') {
if (is_banned($command['data'])) {
sendMessage($chatId, "<u>Number Banned!</u>", $message_id);
}
// ...
}
$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);
}