赵阿朵/telegram-bot

dev-master 2018-10-29 13:45 UTC

This package is auto-updated.

Last update: 2024-08-29 04:59:41 UTC


README

[PHP] 基于TelegramBot/Api库的Telegram机器人

此机器人用于Telegram频道 https://t.me/bidbaits_bids

需求

PHP: >=7.1.0

扩展

Memcache: * (任何版本)

依赖

Composer

安装

composer require pavelzotikov/telegram-bot

初始化类

class Bot extends \TelegramBot\Handler

路由

['GET|POST', '/bot', [Bot::class => 'execute']]

添加命令

命令 /start

public function commandStart(string $service_name, string $chat_id)

添加捕获器

在命令 /filter 之前捕获消息

public function commandFilter(string $service_name, string $chat_id)
{
    $this->startCatcher($service_name, $chat_id);
    return 'Напишите слово для фильтрации обьвлений.';
}
public function catcherFilter(string $service_name, string $chat_id, string $message)
{
    $this->stopCatcher($service_name, $chat_id);
    return sprintf('Фильтр по слову «%s» успешно добавлен.', $message);
}

添加默认捕获器

在任意命令捕获器关闭时获取用户消息

public function catcherDefault(string $service_name, string $chat_id, string $message)
{
    return sprintf('Ваше сообщение: %s', $message)
}

示例

class Bot extends \TelegramBot\Handler
{

    protected $services = [
        Telegram::class => '12345567890:XXX-XxX-XxxXxXxxXxxXXXxXXXXxXXX' // Your token
    ];

    public function commandStart(string $service_name, string $chat_id)
    {
        // Save enabled flag in database
        // <code> ... </code>

        return 'Теперь вы будете получать новые товары с сайта bidbaits.ru';
    }

    public function commandStop(string $service_name, string $chat_id)
    {
        // Save disabled flag in database
        // <code> ... </code>

        return 'Рассылка остановлена. Чтобы снова начать получать новые товары с сайта bidbaits.ru вызовите команду /start';
    }

    public function commandFilter(string $service_name, string $chat_id)
    {
        $this->commandStop($service_name, $chat_id);
        $this->startCatcher($service_name, $chat_id);

        return 'Напишите слово для фильтрации обьвлений.';
    }

    public function catcherFilter(string $service_name, string $chat_id, string $message)
    {
        $this->stopCatcher($service_name, $chat_id);
        $this->commandStart($service_name, $chat_id);

        // Save filter in database
        // <code> ... </code>

        return sprintf('Фильтр по слову «%s» успешно добавлен.', $message);
    }

    public function commandReset(string $service_name, string $chat_id)
    {
        // Reset filter in database
        // <code> ... </code>

        return 'Фильтр по слову успешно сброшен.';
    }

    public function commandHelp(string $service_name, string $chat_id)
    {
        $text = [];

        $text[] = 'Команды:';
        $text[] = '/start – запустить';
        $text[] = '/stop – остановить';
        $text[] = '/filter – фильтр по слову';
        $text[] = '/reset – сброс фильтра';
        $text[] = '/help – помощь';

        return implode("\r\n", $text);
    }

}