这个类可以轻松使用,用于与 Mirai 后端交互。

<?php

namespace Mirai;

use Exception;

/**
 * Mirai QQ机器人
 * @param string $_url         MiraiHTTP接口地址
 * @param string $_verifyKey     Mirai认证Key
 * @param string $_sessionKey  Mirai会话Key
 */
class Bot
{
    private $_url;
    private $_verifyKey;
    private $_sessionKey;

    /**
     * 构造函数 
     * @param string $url       MiraiHTTP接口地址
     * @param string $verifyKey   Mirai认证Key
     */
    function __construct(string $url, string $verifyKey)
    {
        $this->_url = $url;
        $this->_verifyKey = array('verifyKey' => $verifyKey);
        $this->_sessionKey = "UnVerifiedSession";
    }


    /**
     * cURL获取数据
     * @param  string    $url           发送请求的链接
     * @param  int       $ifPost        是否为post请求(1||0)
     * @param  mixed     $postFields    post的数据
     * @param  string    $cookie        发送请求携带的cookie
     * @param  mixed     $cookieFile    cookie文件
     * @param  int       $ifHeader      是否获取响应头信息(1||0)
     * @throws           Exception      请求失败
     * @return mixed                    响应结果
     */
    private function httpRequest(string $url, int $ifPost = 0, $postFields = '', string $cookie = '', $cookieFile = '', int $ifHeader = 0)
    {
        // 模拟http请求header头
        $header = array(
            "Connection: Keep-Alive",
            "Accept: text/html, application/xhtml+xml, */*",
            "Pragma: no-cache",
            "Accept-Language: zh-Hans-CN,zh-Hans;q=0.8,en-US;q=0.5,en;q=0.3",
            "User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)",
            "Authorization: session " . $this->_sessionKey
        );

        // 初始化一个cURL会话
        $ch = curl_init();

        // 设置cURL传输选项
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, $ifHeader);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        $ifPost && curl_setopt($ch, CURLOPT_POST, $ifPost);
        $ifPost && curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        $cookie && curl_setopt($ch, CURLOPT_COOKIE, $cookie);  // 发送cookie变量
        $cookieFile && curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);  // 发送cookie文件
        $cookieFile && curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);  // 写入cookie到文件
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);  // 允许执行的最长秒数
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        // 执行cURL会话
        $result = curl_exec($ch);

        // 失败则抛出异常
        if ($result === false) {
            throw new Exception('Sending request to ' . $url . ' failed!');
        }
        // 关闭 cURL 会话
        curl_close($ch);

        // 释放$ch
        unset($ch);

        return $result;
    }


    /**
     * 进行认证
     * @throws Exception 认证失败
     * @return bool
     */
    public function verify(): bool
    {
        $url = $this->_url . '/verify';
        $postData = json_encode($this->_verifyKey);
        $response = json_decode($this->httpRequest($url, 1, $postData));
        if ($response !== false && $response->code === 0) {
            $this->_sessionKey = $response->session;
            return true;
        } else {
            throw new Exception('Mirai authentication failed!');
        }
    }

    /**
     * 校验Session
     * @param  int   $qq         Session将要绑定的Bot的qq号
     * @throws       Exception   校验Session失败
     * @return bool
     */
    public function bind(int $qq): bool
    {
        $url = $this->_url . '/bind';
        $postData = json_encode(
            array(
                'sessionKey' => $this->_sessionKey,
                'qq' => $qq
            )
        );
        $response = json_decode($this->httpRequest($url, 1, $postData));
        if ($response !== false && $response->code === 0) {
            return true;
        } else {
            throw new Exception('Validation session failed!' . 'The QQ number is ' . $qq . '.');
        }
    }

    /**
     * 释放Session
     * @param  int  $qq        与该Session绑定Bot的QQ号码
     * @throws      Exception  释放Session失败
     * @return bool
     */
    public function release(int $qq): bool
    {
        $url = $this->_url . '/release';
        $postData = json_encode(
            array(
                'sessionKey' => $this->_sessionKey,
                'qq' => $qq
            )
        );
        $response = json_decode($this->httpRequest($url, 1, $postData));
        if ($response !== false && $response->code === 0) {
            return true;
        } else {
            throw new Exception('Failed to release session! The QQ number is ' . $qq . '!');
        }
    }

    /**
     * 查看队列大小
     * @return int
     */
    public function countMessage(int $qq): bool
    {
        $url = $this->_url . '/countMessage';
        $response = json_decode($this->httpRequest($url, 0));
        if ($response !== false && $response->code === 0) {
            return $response->data;
        } else {
            throw new Exception('Failed to release session! The QQ number is ' . $qq . '!');
        }
    }

    /**
     * 发送好友消息
     * @param int   $qq             发送消息目标好友的QQ号
     * @param array $messageChain   消息链,消息对象构成的数组
     * @param int   $quote          回复消息的messageId
     * @throws      Exception       发送消息失败 
     * @return int  messageId       可引用进行回复
     */
    public function sendFriendMessage(int $qq, array $messageChain, $quote = null): int
    {
        $url = $this->_url . '/sendFriendMessage';
        $postData = json_encode(
            array(
                'target' => $qq,
                'quote' => $quote,
                'messageChain' => $messageChain
            )
        );
        $response = json_decode($this->httpRequest($url, 1, $postData));
        if ($response !== false && $response->code === 0) {
            return $response->messageId;
        } else {
            throw new Exception('Failed to send friend message to qq:' . $qq . '!');
        }
    }

    /**
     * 发送群组消息
     * @param int   $qq             发送消息目标群组的QQ群号
     * @param array $messageChain   消息链,消息对象构成的数组
     * @param int   $quote          回复消息的messageId
     * @throws      Exception       发送消息失败 
     * @return int  messageId       可引用进行回复
     */
    public function sendGroupMessage(int $qq, array $messageChain, $quote = null): int
    {
        $url = $this->_url . '/sendGroupMessage';
        $postData = json_encode(
            array(
                'target' => $qq,
                'quote' => $quote,
                'messageChain' => $messageChain
            )
        );
        $response = json_decode($this->httpRequest($url, 1, $postData));
        if ($response !== false && $response->code === 0) {
            return $response->messageId;
        } else {
            throw new Exception('Failed to send friend message to qq:' . $qq . '!');
        }
    }

    /**
     * 发送临时会话消息
     * @param int   $qq             发送消息目标临时会话对象QQ号
     * @param array $messageChain   消息链,消息对象构成的数组
     * @param int $group 临时会话群号
     * @param int   $quote          回复消息的messageId
     * @throws      Exception       发送消息失败 
     * @return int  messageId       可引用进行回复
     */
    public function sendTempMessage(int $qq, int $group, array $messageChain, $quote = null): int
    {
        $url = $this->_url . '/sendTempMessage';
        $postData = json_encode(
            array(
                'target' => $qq,
                'quote' => $quote,
                'group' => $group,
                'messageChain' => $messageChain
            )
        );
        $response = json_decode($this->httpRequest($url, 1, $postData));
        if ($response !== false && $response->code === 0) {
            return $response->messageId;
        } else {
            throw new Exception('Failed to send friend message to qq:' . $qq . '!');
        }
    }

    /**
     * 获取群员设置
     * @param int   $target         指定群的群号
     * @param int $memberId 群员QQ号
     * @param int $group 临时会话群号
     * @throws      Exception       发送消息失败 
     * @return array  info       可引用进行回复
     */
    public function getMemberInfo(int $target, int $group): array
    {
        $url = $this->_url . '/memberInfo?target=' . $group . "&memberId=" . $target;
        $response = json_decode($this->httpRequest($url, 0));
        if ($response !== false && $response->code === 0) {
            return $response;
        } else {
            throw new Exception('Failed to send friend message to qq:' . $target . '!');
        }
    }
}
Last modification:June 13, 2021
如果您觉得我的文章有用,给颗糖糖吧~