773 次浏览

通过微信公众号客服 API 集成 OpenAI 的 AI 聊天机器人

有关 ChatGPT 的话题,最近十分火热,通过 Python 脚本编写了一个基于 和 OpenAI 的微信公众号服务器,从而支撑微信公众号集成 OpenAI 的智能聊天机器人的需求。代码如下,

  • 这里通过公众号方式,解决了 OpenAI 被封禁的问题;
  • 通过客服 API 解决了消息超过 5 秒,未回复会被报错的问题。
import threading
# https://github.com/openai/openai-python
# https://platform.openai.com

import openai
# https://github.com/offu/WeRoBot
# https://werobot.readthedocs.io/zh_CN/latest/
# 实例参考 https://blog.csdn.net/IkerIkerIker/article/details/110914641

import werobot
from werobot.replies import TransferCustomerServiceReply

WEB_HOST_URL = "0.0.0.0"
WEB_HOST_PORT = 80
WECHAT_APP_ID = "{{微信公众号的 APP ID}}"
WECHAT_APP_SECRET = "{{微信公众号的 APP SECRET}}"
WECHAT_ENCODING_AES_KEY = "{{微信公众号的 AES 加密密钥}}"
WECHAT_API_TOKEN = "{{微信公众号的 API 设置中配置的 Token,这个可以随意编写}}"
OPEN_AI_API_KEY = "{{ChatGPT 的 API KEY}}"

openai.api_key = OPEN_AI_API_KEY
robot = werobot.WeRoBot(token=WECHAT_API_TOKEN)

def get_chatgpt_response(prompt):
    response = openai.Completion.create(
        model="text-davinci-003",
        prompt=prompt,
        temperature=0,
        max_tokens=1024,
        top_p=1,
        frequency_penalty=0.0,
        presence_penalty=0.0,
    )
    message = response.choices[0].text
    return message.strip()

def post_wechat_customer_service_reply(messages):
    chatGptResponse = get_chatgpt_response(messages.content)
    # https://werobot.readthedocs.io/zh_CN/latest/client.html#
    # https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Service_Center_messages.html
    # 获取 Access Token,发送消息的客服账户 等 API
    return robot.client.send_text_message(user_id=messages.source, content=chatGptResponse, kf_account=None)

@robot.handler
def hello(messages):
    thread = threading.Thread(
        target=post_wechat_customer_service_reply, args=(messages,))
    thread.start()
    # https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Passive_user_reply_message.html
    # 假如服务器无法保证在五秒内处理并回复,必须做出下述回复,这样微信服务器才不会对此作任何处理,
    # 并且不会发起重试(这种情况下,可以使用客服消息接口进行异步回复),否则,将出现严重的错误提示: “该公众号暂时无法提供服务,请稍后再试”
    # 将消息转发至客服:
    # https://developers.weixin.qq.com/doc/offiaccount/Customer_Service/Forwarding_of_messages_to_service_center.html
    return TransferCustomerServiceReply(messages)

robot.config["HOST"] = WEB_HOST_URL
robot.config["PORT"] = WEB_HOST_PORT
robot.config["APP_ID"] = WECHAT_APP_ID
robot.config["APP_SECRET"] = WECHAT_APP_SECRET
robot.config["ENCODING_AES_KEY"] = WECHAT_ENCODING_AES_KEY
robot.run()

About nista

THERE IS NO FATE BUT WHAT WE MAKE.

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注