Python实现chatgpt微信机器人

写在前面

本篇文章通过Hook方式操作微信,非web协议无账号限制不封号。项目代码完全开源,因为需要将程序注入微信,杀毒软件可能会误报,关闭即可,如若不放心,可以查看开源代码,源代码编译即可。开源项目地址如下:

快速开始


前置条件

安装使用


pip install openai
pip install wxchat

打开微信客户端,弹出控制台消息,则服务启动成功

服务已启动, 端口号1: 10086, 端口号2: 10010

编写python代码,接收微信消息,发送到chatgpt,并自动回复消息。

import openai, re
from wxchat import WeixinClient, MsgType, Message

openai.api_key = "填入你的apikey"

def get_response(text: str) -> [str]:
    response = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=[{"role": "user", "content": text}])
    return [choice["message"]["content"] for choice in response["choices"]]

if __name__ == '__main__':
    client = WeixinClient("192.168.0.104")
    profile = client.login()

    @client.message(wxid="wxid_.*", msgtype=MsgType.TEXT)
    def friend_message(message: Message):
        reply = get_response(message.content)
        for msg in reply:
            client.send_text(message.wxid, msg)

    @client.message(wxid=".*@chatroom", msgtype=MsgType.TEXT, at_users=[profile.wxid])
    def chatroom_message(message: Message):
        content = re.sub(r"\s*@\S+?\s*(:| |$)", "", message.content)
        reply = get_response(content)
        for msg in reply:
            client.send_text(message.wxid, msg)

    client.run_forever()

这样一个chatgpt机器人就做好啦,很简单吧。你可以通过好友向机器人发送消息,也可以在群聊中艾特机器人发送消息,获取chatgpt回复。如果有问题,请查看B站教程视频

演示.gif

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容