PHP code example of goletter / hyperf-telegram-bot

1. Go to this page and download the library: Download goletter/hyperf-telegram-bot library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

goletter / hyperf-telegram-bot example snippets


BASE_PATH . '/packages/goletter/hyperf-telegram-bot/src',

return [
    'default' => env('TELEGRAM_BOT', 'default'),
    'bots' => [
        // 可选静态 Bot;动态场景可留空
    ],
    'http' => [
        'base_uri' => env('TELEGRAM_API_BASE_URI', 'https://api.telegram.org'),
        'timeout' => (float) env('TELEGRAM_HTTP_TIMEOUT', 30),
        'proxy' => env('TELEGRAM_HTTP_PROXY'), // 例如 http://127.0.0.1:7890
    ],
];

'bots' => [
    'default' => [
        'token' => env('TELEGRAM_BOT_TOKEN', ''),
        'webhook_secret' => env('TELEGRAM_WEBHOOK_SECRET', ''),
    ],
],

use Goletter\Telegram\Factory\BotFactory;
use Hyperf\Di\Annotation\Inject;

#[Inject]
protected BotFactory $bots;

// 按 Token 创建(默认缓存名:bot:{bot_id},如 123456:ABC -> bot:123456)
$bot = $this->bots->token($row->token);

// 推荐:用业务 ID 作为名称,便于 Token 轮换后命中同一缓存槽
$bot = $this->bots->token($row->token, (string) $row->id, [
    'webhook_secret' => (string) $row->webhook_secret,
]);

$bot->sendMessage([
    'chat_id' => 123456,
    'text' => 'Hello',
]);

// Token 更新后再 resolve,旧实例自动失效
$bot = $this->bots->resolve((string) $row->id, $newToken, [
    'webhook_secret' => $newSecret,
]);

// 主动丢弃缓存
$this->bots->forget((string) $row->id);

$bot = $this->bots->get('default');
// 或省略名称,取 telegram.default
$bot = $this->bots->get();

use Goletter\Telegram\Contract\BotInterface;
use Goletter\Telegram\Factory\BotFactory;

return [
    BotInterface::class => static fn ($c) => $c->get(BotFactory::class)->get(),
];

use Goletter\Telegram\Factory\BotFactory;
use Goletter\Telegram\Helper\Webhook;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;

#[Controller]
class TelegramWebhookController
{
    public function __construct(
        protected BotFactory $bots,
        protected Webhook $webhook,
        protected BotRepository $repo, // 你们自己的仓储
    ) {
    }

    #[PostMapping(path: '/telegram/webhook/{id}')]
    public function handle(int $id, RequestInterface $request)
    {
        $entity = $this->repo->find($id);

        $bot = $this->bots->token($entity->token, (string) $entity->id, [
            'webhook_secret' => $entity->webhook_secret,
        ]);

        $update = $this->webhook->parseRequest($request, $bot);

        if ($update->isCommand('start')) {
            $bot->sendMessage([
                'chat_id' => $update->getChatId(),
                'text' => 'Welcome!',
            ]);
        }

        return ['ok' => true];
    }
}

$bot->setWebhook([
    'url' => 'https://example.com/telegram/webhook/' . $entity->id,
    'allowed_updates' => ['message', 'callback_query', 'my_chat_member', 'chat_member', 'chat_join_request'],
]);

// 业务中间件(在 VerifyTelegramWebhookMiddleware 之前)
$entity = $repo->find($request->getAttribute('id'));
$request = $webhook->attach($request, $entity->token, (string) $entity->id, [
    'webhook_secret' => $entity->webhook_secret,
]);

$update = $this->webhook->parseRequest($request); // 从 request attribute 取 Bot
$bot = $this->webhook->bot(null, $request);

$updates = $bot->getUpdates([
    'offset' => $offset,
    'timeout' => 30,
]);

foreach ($updates as $item) {
    $update = $bot->parseUpdate($item);
    // 使用 $update->getChatId() / isCommand() 等
}

$bot->sendMessage([
    'chat_id' => 123456,
    'text' => 'Hello',
]);

$bot->sendDocument([
    'chat_id' => 123456,
    'document' => fopen('/path/to/file.pdf', 'r'),
    'caption' => '报表',
]);
// document 也支持 SplFileInfo,或 ['contents' => ..., 'filename' => 'a.pdf']

$bot->call('sendVenue', [/* ... */]);

$chatId = -1001234567890;

$users = $bot->getGroupUsers($chatId);
// ['chat_id' => ..., 'count' => 128, 'administrators' => [...]]

$count = $bot->getGroupMemberCount($chatId);
$admins = $bot->getGroupAdmins($chatId);
$member = $bot->getGroupMember($chatId, 123456789);
// $member['status'] => creator|administrator|member|restricted|left|kicked

$map = $bot->getGroupMembers($chatId, [111, 222, 333]);
// 不在群内 / 查询失败的为 null

$chat = $bot->getChat(['chat_id' => $chatId]);

$info = $bot->getGroupInfo($chatId);
// ['chat_id' => ..., 'chat' => [...], 'count' => 128, 'administrators' => [...]]

$map = $bot->getGroupsInfo([-100111, -100222]);
// chat_id 字符串键 => 资料|null

if ($changed = $update->getChatMemberUpdate()) {
    $user = $changed['new_chat_member']['user'];
    $status = $changed['new_chat_member']['status']; // member / left / ...
    // 写入群成员表,之后用 getGroupMembers 回查
}

use Goletter\Telegram\Service\BotChatTracker;

public function __construct(
    protected BotFactory $bots,
    protected Webhook $webhook,
    protected BotChatTracker $chats,
    protected BotRepository $repo,
) {
}

public function handle(int $id, RequestInterface $request)
{
    $entity = $this->repo->find($id);
    $bot = $this->bots->token($entity->token, (string) $entity->id, [
        'webhook_secret' => $entity->webhook_secret,
    ]);

    $update = $this->webhook->parseRequest($request, $bot);
    $this->chats->sync($bot, $update); // 写入 my_chat_member / 群消息中的 chat

    return ['ok' => true];
}

// 本地已同步记录
$groups = $this->chats->getGroups($bot);

// 并对每条调用 getChat + 人数等刷新(失败会标记 inactive)
$groups = $this->chats->getGroups($bot, refresh: true);

// 单群
$group = $this->chats->getGroup($bot, -1001234567890, refresh: true);

// config/autoload/dependencies.php
use Goletter\Telegram\Contract\BotChatRepositoryInterface;
use App\Telegram\DbBotChatRepository;

return [
    BotChatRepositoryInterface::class => DbBotChatRepository::class,
];

$link = $bot->inviteToChat(-1001234567890, [
    'name' => '活动拉群',
    'member_limit' => 100,
    'expire_date' => time() + 86400,
    // 'creates_join_request' => true,
]);
// $link['invite_link'] => https://t.me/+xxxx

$url = $bot->exportChatInviteLink(['chat_id' => -1001234567890]);

if ($join = $update->getChatJoinRequest()) {
    $bot->approveChatJoinRequest([
        'chat_id' => $update->getChatId(),
        'user_id' => $update->getUserId(),
    ]);
    // 或:$bot->declineChatJoinRequest([...]);
}

$bot->revokeChatInviteLink([
    'chat_id' => -1001234567890,
    'invite_link' => $link['invite_link'],
]);

use Goletter\Telegram\Exceptions\TelegramApiException;

try {
    $bot->sendMessage(['chat_id' => 1, 'text' => 'hi']);
} catch (TelegramApiException $e) {
    $e->getDescription();
    $e->getErrorCode();
    $e->getParameters(); // 如 retry_after
    $e->getResponse();
}
bash
php bin/hyperf.php vendor:publish goletter/hyperf-telegram-bot
bash
composer rf.php vendor:publish goletter/hyperf-telegram-bot