0基础将ChatGPT接入微信公众号

最近,朋友圈、抖音都能看到ChatGPT甚是火爆,也能看到股市中的机器人、人工智能概念股也因此大涨。我怀着好奇的心情来玩一玩这个东西。

一开始,我是设想去做一个收费公众号来提供问答服务,后面觉得太复杂了(PS:我承认我懒)。于是我又想要不写个中转服务来做个API再写个页面给大家玩玩也不错,但是我还是高估了我零碎时间里自己的积极性,算了,我摊牌了。听说这玩意儿会写代码,索性让他自己写不就完了。

第一步、注册账号

打开OpenAI的官网,去注册一个账号先
图片
注册完成之后登录获取API KEY
图片

好了,万事大吉,现在要开始表演了,先来两个问题考考

图片

我觉得可能是我没表达清楚的原因,不过结果自己改改也能用,还算不错。那接下来就开始?

图片

写出来的代码如下!有点厉害!

<?php

$access_token = "your_access_token";
$api_key = "your_api_key";

// Verify the request from WeChat
if ($_SERVER["REQUEST_METHOD"] == "GET") {
    $signature = $_GET["signature"];
    $timestamp = $_GET["timestamp"];
    $nonce = $_GET["nonce"];
    if (!isset($signature) || !isset($timestamp) || !isset($nonce)) {
        http_response_code(400);
        exit;
    }

    // Perform the signature verification
    $sorted_args = [$access_token, $timestamp, $nonce];
    sort($sorted_args, SORT_STRING);
    $sorted_str = implode("", $sorted_args);
    $hash = sha1($sorted_str);
    if ($hash != $signature) {
        http_response_code(401);
        exit;
    }

    echo $_GET["echostr"];
    exit;
}

// Handle the message sent from the user
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $message = $_POST["Content"];
    $response = chat_with_chatgpt($message, $api_key);
    echo $response;
    exit;
}

// Chat with ChatGPT
function chat_with_chatgpt($message, $api_key) {
    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://api.openai.com/v1/engines/text-davinci-002/jobs",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => json_encode([
            "prompt" => $message,
            "max_tokens" => 50
        ]),
        CURLOPT_HTTPHEADER => array(
            "Authorization: Bearer " . $api_key,
            "Content-Type: application/json"
        ),
    ));

    $response = curl_exec($curl);
    curl_close($curl);
    $response_json = json_decode($response, true);

    if (!isset($response_json["choices"][0]["text"])) {
        return "Sorry, there was a problem communicating with ChatGPT.";
    }

    return $response_json["choices"][0]["text"];
}

请注意,此代码仅作为示例,您可能需要进行一些修改才能在您的微信公众号中使用。此外,您需要提前订阅 OpenAI 的 API 并获取 API 密钥。你也需要完成微信公众号的开发者配置。

把代码中的”your_access_token"和“your_api_key"替换为公众号的token和openAI的key

测试之后有问题,原来是公众号个人号是XML格式通信,但是他给出的代码是json

,所以要把接收和发送方式改一下。


if ($_SERVER["REQUEST_METHOD"] == "POST") {
     $data = file_get_contents('php://input'); 
     $XML = simplexml_load_string($data, "SimpleXMLElement", LIBXML_NOCDATA);
     $json = json_encode($XML,true);
     $arr = json_decode($json,TRUE);
     $message = $arr["Content"];
     $response = chat_with_chatgpt($message, $api_key);
     $ToUserName = $arr['FromUserName'];
     $FromUserName = $arr['ToUserName'];
     $CreateTime =  time();
    //echo $response;header("Content-Type: text/xml");
echo "<xml>
<ToUserName><![CDATA[$ToUserName]]></ToUserName>
<FromUserName><![CDATA[$FromUserName]]></FromUserName>
<CreateTime>[$CreateTime]</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[$response]]></Content>
</xml>";

    exit;
}

再提交一次,通过是通过了,但是又出现了新的问题,返回了这个数据:

{
    "error": {
        "message": "That model does not exist",
        "type": "invalid_request_error",
        "param": null,
        "code": null
    }
}

最后发现是模型的问题,修改一下模型即可,当有所回应的时候还是有点小激动!!

图片

ChatGPT做为一款自然语言处理(NLP)聊天机器人。它可以通过在给定的语言环境中解码和生成简单的聊天会话,来帮助用户或机器实现聊天交互。ChatGPT使用了最新的NLP技术,包括最先进的文本生成模型,可以在不针对特定用户的情况下对话。该技术以有效利用面向对话及语音接口的方式进行实现,可以帮助用户快速地理解和处理自然语言输入。ChatGPT还可以用来实现自动客服,或者为受众提供一种个性化和更有活力的在线交流方式。它可以连接到微信,Facebook,网页等应用,可以更好地理解受众发出的消息。ChatGPT可以用于从聊天会话中收集数据并进行文本分析,从而进一步改善系统的表现,并让客户服务更加智能。

最后附上修改完成的代码如下:

<?php

$access_token = "your_access_token";
$api_key = "your_api_key";

// Verify the request from WeChat
if ($_SERVER["REQUEST_METHOD"] == "GET") {
    $signature = $_GET["signature"];
    $timestamp = $_GET["timestamp"];
    $nonce = $_GET["nonce"];
    if (!isset($signature) || !isset($timestamp) || !isset($nonce)) {
        http_response_code(400);
        exit;
    }

    // Perform the signature verification
    $sorted_args = [$access_token, $timestamp, $nonce];
    sort($sorted_args, SORT_STRING);
    $sorted_str = implode("", $sorted_args);
    $hash = sha1($sorted_str);
    if ($hash != $signature) {
        http_response_code(401);
        exit;
    }

    echo $_GET["echostr"];
    exit;
}

// Handle the message sent from the user
if ($_SERVER["REQUEST_METHOD"] == "POST") {
     $data = file_get_contents('php://input'); 
     $XML = simplexml_load_string($data, "SimpleXMLElement", LIBXML_NOCDATA);
     $json = json_encode($XML,true);
     $arr = json_decode($json,TRUE);
     $message = $arr["Content"];
     $response = chat_with_chatgpt($message, $api_key);
     $ToUserName = $arr['FromUserName'];
     $FromUserName = $arr['ToUserName'];
     $CreateTime =  time();
    //echo $response;header("Content-Type: text/xml");
echo "<xml>
<ToUserName><![CDATA[$ToUserName]]></ToUserName>
<FromUserName><![CDATA[$FromUserName]]></FromUserName>
<CreateTime>[$CreateTime]</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[$response]]></Content>
</xml>";

    exit;
}

// Chat with ChatGPT
function chat_with_chatgpt($message, $api_key) {
    //$message = "ChatGPT";
    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://api.openai.com/v1/completions",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => json_encode([
            "model" => "text-davinci-003", // 机器人模型,不同型号有不同功能
            "prompt" => $message,
            "max_tokens" => 2048
        ]),
        CURLOPT_HTTPHEADER => array(
            "Authorization: Bearer " . $api_key,
            "Content-Type: application/json"
        ),
    ));

    $response = curl_exec($curl);
    curl_close($curl);
    file_put_contents('./test.txt', "【".date('Y-m-d H:i:s')."】\r\n". $response."\r\n\r\n",FILE_APPEND);
    $response_json = json_decode($response, true);

    if (!isset($response_json["choices"][0]["text"])) {
        return "Sorry, there was a problem communicating with ChatGPT.";
    }
    
    return $response_json["choices"][0]["text"];
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容