send message in telegram bot

2019-02-20 07:45发布

问题:

I write telegram bot with php . I save users chatid for send message ; use this command for send message :

 /admin sendall:hellow 

and in php app use this code :

 case '/admin':
                if ($chat_id == 'my chatid') {
                    $array = str_replace('/admin', '', $message);
                    $array = trim($array);
                    $array = explode(':', $array);
                    $Admin = new AdminCommand();
                    $Admin->getCommand($array[0], $array[1]);
                } else {
                    sendMessage($chat_id, 'block ');
                }
                break;

AdminCommand class:

class AdminCommand extends Database {

    public function getCommand($command, $action = null) {
        switch ($command) {
            case 'sendall':
                $this->sendall($action);
                break;
            default:
                # code...
                break;
        }
    }

    public function sendall($message) {
        $sql = $this->con->prepare('SELECT * FROM `users`');
        $sql->execute();
        $res = $sql->fetchAll();
        foreach ($res as $row) {
            sendMessage($row['chatid'], $message);
        }
        exit();
    }

}

sendMessage function:

function sendMessage($chatId, $message) {

    $url = WEBSITE . "/sendMessage?chat_id=" . $chatId . "&text=" . urlencode($message);
    file_get_contents($url);
}

Most of the times it's work fine but sometimes after send message to all users repeats that again and again and don't stop As long as i'm delete database . what's the problem ?

回答1:

As i explained in this answer and in Bots FAQ page in telegram site:

How can I message all of my bot's subscribers at once?
Unfortunately, at this moment we don't have methods for sending bulk messages, e.g. notifications. We may add something along these lines in the future.
In order to avoid hitting our limits when sending out mass notifications, consider spreading them over longer intervals, e.g. 8-12 hours. The API will not allow more than ~30 messages to different users per second, if you go over that, you'll start getting 429 errors. You can't send message this way to all user.

and solution in Bots FAQ page:

My bot is hitting limits, how do I avoid this?
When sending messages inside a particular chat, avoid sending more than one message per second. We may allow short bursts that go over this limit, but eventually you'll begin receiving 429 errors.
If you're sending bulk notifications to multiple users, the API will not allow more than 30 messages per second or so. Consider spreading out notifications over large intervals of 8—12 hours for best results.
Also note that your bot will not be able to send more than 20 messages per minute to the same group.