├── .dockerignore ├── .env.example ├── .github └── workflows │ └── build_docker.yml ├── .gitignore ├── Dockerfile ├── LICENSE.md ├── README.md ├── app.js ├── cf_worker.js ├── docs ├── cf_worker.md └── puppeteer-error.md ├── images ├── Create_openai_key.png ├── eg1.png ├── eg2.png ├── eg3.png ├── pay.png └── wechaty-docker.png ├── listeners ├── on-login.js ├── on-message.js └── on-scan.js ├── package-lock.json ├── package.json ├── test.js └── utils ├── get-ai-image.js ├── get-chatgpt.js ├── get-openai.js ├── pushmsg.js └── req.js /.dockerignore: -------------------------------------------------------------------------------- 1 | *node_modules 2 | npm-debug.log 3 | .git 4 | README.md 5 | .idea 6 | *card.json 7 | *.idea 8 | *.vscode 9 | *.iml 10 | *.DS_Store -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | #群聊chatgpt自动回复总开关 0为关闭 1为开启 2 | AutoReplyGroup = 1 3 | #开启chatgpt群聊列表,群聊名称必须与微信群聊名称一致,否则无法自动回复 为空则自动回复所有群聊 ["群聊1","群聊2","群聊3"] 4 | RoomList = [ ] 5 | #好友chatgpt自动回复总开关 0为关闭 1为开启 6 | AutoReplyFriend = 1 7 | #开启chatgpt好友列表,好友名称必须与微信好友名称一致,否则无法自动回复 为空则自动回复所有好友 ["好友1","好友2","好友3"] 8 | FriendList = [ ] 9 | 10 | # openai的key,需要自己去获取 ,地址:https://beta.openai.com/account/api-keys 11 | OPENAI_API_KEY ='sk-xxxxxxxxxxxxxxxxx' 12 | 13 | # 反代的api,为空时为默认值 https://api.openai.com 14 | PROXY_API = '' 15 | 16 | -------------------------------------------------------------------------------- /.github/workflows/build_docker.yml: -------------------------------------------------------------------------------- 1 | name: "docker build release" 2 | 3 | 4 | on: 5 | push: 6 | branches: 7 | - 'main' 8 | # on: 9 | # workflow_dispatch: 10 | # inputs: 11 | # project: 12 | # description: 'Project:VERSION' 13 | # required: true 14 | # default: 15 | 16 | jobs: 17 | build: 18 | runs-on: ubuntu-latest 19 | steps: 20 | - name: Checkout 21 | uses: actions/checkout@v3 22 | 23 | - name: Set tag 24 | id: tag 25 | run: | 26 | echo "tag=$(date +%Y)-$(date +%m)-$(date +%d)" >> $GITHUB_ENV 27 | - name: Set up QEMU 28 | uses: docker/setup-qemu-action@v2 29 | 30 | - name: Set up Docker Buildx 31 | uses: docker/setup-buildx-action@v2 32 | 33 | - name: Login Docker Hub 34 | uses: docker/login-action@v2 35 | with: 36 | username: ${{ secrets.DOCKER_USERNAME }} 37 | password: ${{ secrets.DOCKERHUB_TOKEN }} 38 | 39 | - name: Build and push to docker hub 40 | uses: docker/build-push-action@v3 41 | with: 42 | context: . 43 | platforms: linux/amd64,linux/arm64 44 | push: true 45 | build-args: VERSION=${{ env.tag }} 46 | tags: | 47 | ${{ secrets.DOCKER_USERNAME }}/wechaty-bot:latest 48 | ${{ secrets.DOCKER_USERNAME }}/wechaty-bot:${{ env.tag }} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.toptal.com/developers/gitignore/api/node,windows,macos,linux 3 | # Edit at https://www.toptal.com/developers/gitignore?templates=node,windows,macos,linux 4 | 5 | ### Linux ### 6 | *~ 7 | 8 | # temporary files which can be created if a process still has a handle open of a deleted file 9 | .fuse_hidden* 10 | 11 | # KDE directory preferences 12 | .directory 13 | 14 | # Linux trash folder which might appear on any partition or disk 15 | .Trash-* 16 | 17 | # .nfs files are created when an open file is removed but is still being accessed 18 | .nfs* 19 | 20 | ### macOS ### 21 | # General 22 | .DS_Store 23 | .AppleDouble 24 | .LSOverride 25 | 26 | # Icon must end with two \r 27 | Icon 28 | 29 | 30 | # Thumbnails 31 | ._* 32 | 33 | # Files that might appear in the root of a volume 34 | .DocumentRevisions-V100 35 | .fseventsd 36 | .Spotlight-V100 37 | .TemporaryItems 38 | .Trashes 39 | .VolumeIcon.icns 40 | .com.apple.timemachine.donotpresent 41 | 42 | # Directories potentially created on remote AFP share 43 | .AppleDB 44 | .AppleDesktop 45 | Network Trash Folder 46 | Temporary Items 47 | .apdisk 48 | 49 | ### Node ### 50 | # Logs 51 | logs 52 | *.log 53 | npm-debug.log* 54 | yarn-debug.log* 55 | yarn-error.log* 56 | lerna-debug.log* 57 | .pnpm-debug.log* 58 | 59 | # Diagnostic reports (https://nodejs.org/api/report.html) 60 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 61 | 62 | # Runtime data 63 | pids 64 | *.pid 65 | *.seed 66 | *.pid.lock 67 | 68 | # Directory for instrumented libs generated by jscoverage/JSCover 69 | lib-cov 70 | 71 | # Coverage directory used by tools like istanbul 72 | coverage 73 | *.lcov 74 | 75 | # nyc test coverage 76 | .nyc_output 77 | 78 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 79 | .grunt 80 | 81 | # Bower dependency directory (https://bower.io/) 82 | bower_components 83 | 84 | # node-waf configuration 85 | .lock-wscript 86 | 87 | # Compiled binary addons (https://nodejs.org/api/addons.html) 88 | build/Release 89 | 90 | # Dependency directories 91 | node_modules/ 92 | jspm_packages/ 93 | 94 | # Snowpack dependency directory (https://snowpack.dev/) 95 | web_modules/ 96 | 97 | # TypeScript cache 98 | *.tsbuildinfo 99 | 100 | # Optional npm cache directory 101 | .npm 102 | 103 | # Optional eslint cache 104 | .eslintcache 105 | 106 | # Microbundle cache 107 | .rpt2_cache/ 108 | .rts2_cache_cjs/ 109 | .rts2_cache_es/ 110 | .rts2_cache_umd/ 111 | 112 | # Optional REPL history 113 | .node_repl_history 114 | 115 | # Output of 'npm pack' 116 | *.tgz 117 | 118 | # Yarn Integrity file 119 | .yarn-integrity 120 | 121 | # dotenv environment variables file 122 | .env 123 | .env.test 124 | .env.production 125 | 126 | # parcel-bundler cache (https://parceljs.org/) 127 | .cache 128 | .parcel-cache 129 | 130 | # Next.js build output 131 | .next 132 | out 133 | 134 | # Nuxt.js build / generate output 135 | .nuxt 136 | dist 137 | 138 | # Gatsby files 139 | .cache/ 140 | # Comment in the public line in if your project uses Gatsby and not Next.js 141 | # https://nextjs.org/blog/next-9-1#public-directory-support 142 | # public 143 | 144 | # vuepress build output 145 | .vuepress/dist 146 | 147 | # Serverless directories 148 | .serverless/ 149 | 150 | # FuseBox cache 151 | .fusebox/ 152 | 153 | # DynamoDB Local files 154 | .dynamodb/ 155 | 156 | # TernJS port file 157 | .tern-port 158 | 159 | # Stores VSCode versions used for testing VSCode extensions 160 | .vscode-test 161 | 162 | # yarn v2 163 | .yarn/cache 164 | .yarn/unplugged 165 | .yarn/build-state.yml 166 | .yarn/install-state.gz 167 | .pnp.* 168 | 169 | ### Windows ### 170 | # Windows thumbnail cache files 171 | Thumbs.db 172 | Thumbs.db:encryptable 173 | ehthumbs.db 174 | ehthumbs_vista.db 175 | 176 | # Dump file 177 | *.stackdump 178 | 179 | # Folder config file 180 | [Dd]esktop.ini 181 | 182 | # Recycle Bin used on file shares 183 | $RECYCLE.BIN/ 184 | 185 | # Windows Installer files 186 | *.cab 187 | *.msi 188 | *.msix 189 | *.msm 190 | *.msp 191 | 192 | # Windows shortcuts 193 | *.lnk 194 | 195 | # End of https://www.toptal.com/developers/gitignore/api/node,windows,macos,linux 196 | 197 | 198 | node_modules 199 | .DS_Store 200 | dist 201 | dist-ssr 202 | *.local 203 | *card.json 204 | test 205 | my-wechaty-bot -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:18.12.1-alpine 2 | 3 | 4 | # Installs latest Chromium (100) package. 5 | RUN apk add --no-cache \ 6 | chromium \ 7 | nss \ 8 | freetype \ 9 | harfbuzz \ 10 | ca-certificates \ 11 | ttf-freefont \ 12 | && ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \ 13 | && echo "Asia/Shanghai" > /etc/timezone \ 14 | && npm install -g pm2 \ 15 | && rm -rf /var/cache/apk/* \ 16 | && rm -rf /tmp/* \ 17 | && rm -rf /var/tmp/* 18 | 19 | 20 | 21 | # Tell Puppeteer to skip installing Chrome. We'll be using the installed package. 22 | ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true \ 23 | PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser 24 | 25 | 26 | # Create app directory 27 | ADD . /app/ 28 | WORKDIR /app 29 | 30 | # Install app dependencies 31 | RUN npm install 32 | 33 | 34 | EXPOSE 8080 35 | 36 | CMD [ "npm", "start"] 37 | 38 | 39 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 x-dr 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ChatGPT Bot 2 | 3 | [新版微信机器人](https://github.com/x-dr/wechat-bot) 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 旧版,不建议使用 12 | 13 | **封号严重不建议使用** 14 | 15 | 一个 基于 `OpenAI` + `Wechaty` 智能回复、支持上下文回复、AI绘画的微信机器人,可以用来帮助你自动回复微信消息。 16 | 17 | 18 | #### 反向代理 api.openai.com 19 | 20 | api.openai.com 国内无法访问,利用Cloudflare Workers反向代理,[教程](./docs/cf_worker.md) 21 | 22 | 当你的环境无法使用,不想自建,也可以用我的`https://openai.1rmb.tk`。 23 | 24 | ### 准备 25 | 26 |
27 | 28 | 准备 29 | 30 | + 1、先获取自己的 api key,地址 :[创建你的 api key](https://beta.openai.com/account/api-keys) 31 | > API Key 创建成功。复制好这个Key接下来会用到。点击OK后,Key不会再完整显示。只能删了重新生成Key! 32 | > 如果没账号,可以参考V2EX上这个帖子注册 地址[https://www.v2ex.com/t/900126](https://www.v2ex.com/t/900126) 33 | 34 | 35 | 36 | 37 | 38 | 39 | ```bash 40 | # $wechaty-bot 41 | # 执行下面命令,拷贝一份 .env.example 文件 42 | cp .env.example .env 43 | ``` 44 | 45 | ```bash 46 | #群聊chatgpt自动回复总开关 0为关闭 1为开启 47 | AutoReplyGroup = 1 48 | #开启chatgpt群聊列表,群聊名称必须与微信群聊名称一致,否则无法自动回复 为空则自动回复所有群聊 ["群聊1","群聊2","群聊3"] 49 | RoomList = [ ] 50 | #好友chatgpt自动回复总开关 0为关闭 1为开启 51 | AutoReplyFriend = 1 52 | #开启chatgpt好友列表,好友名称必须与微信好友名称一致,否则无法自动回复 为空则自动回复所有好友 ["好友1","好友2","好友3"] 53 | FriendList = [ ] 54 | # openai的key,需要自己去获取 ,地址:https://beta.openai.com/account/api-keys 55 | OPENAI_API_KEY ='sk-xxxxxxxxxxxxxxxxx' 56 | # 反代的api,为空时为默认值 https://api.openai.com 57 | PROXY_API = '' 58 | 59 | 60 | ``` 61 |
62 | 63 | 64 | ### 启动服务 65 |
66 | 使用Docker 67 | #### 1、使用Docker 68 | 69 | 70 | 71 | 下载并编辑`.env`配置文件 72 | ```bash 73 | mkdir my-wechaty-bot && cd my-wechaty-bot 74 | wget -O .env https://raw.githubusercontent.com/x-dr/wechaty-bot/main/.env.example 75 | vim .env 76 | 77 | ``` 78 | 79 | > 运行 80 | ```bash 81 | docker run -itd --name my-wechaty-bot \ 82 | --restart=always \ 83 | -v $PWD/.env:/app/.env \ 84 | gindex/wechaty-bot:latest 85 | 86 | ``` 87 | > 查看日志扫码登录 88 | ```bash 89 | docker logs my-wechaty-bot -f 90 | ``` 91 | 92 | 93 | 94 | 95 | > 自行打包docker镜像 96 | ```bash 97 | docker build -t wechaty-bot . 98 | docker run -it --rm --name wechaty-bot wechaty-bot 99 | ``` 100 |
101 | 102 | #### 2、本地启动 103 | 104 |
105 | 本地启动 106 | 107 | ```bash 108 | git clone https://github.com/x-dr/wechaty-bot.git 109 | npm i 110 | node app.js 111 | ``` 112 | > 就可以扫码登录了。 113 | 114 | 115 | 116 | 117 | 118 | 用pm2启动后台运行 119 | ``` 120 | npm install pm2 -g 121 | 122 | pm2 start app.js 123 | ``` 124 | 125 | 126 | 127 |
128 | 129 | ### 使用 130 | 131 |
132 | 133 | 使用 134 | 135 | + 智能回复 136 | ``` 137 | /c xxxx #对话 138 | 139 | /c 结束对话 #结束本轮对话 140 | 141 | ``` 142 | 143 | chatgpt.png 144 | chatgpt.png 145 | 146 | + AI绘画 147 | ``` 148 | /img xxx 149 | ``` 150 | openai.png 151 | 152 |
153 | 154 | 155 | ### 费用情况 156 | 157 | 158 | openai是要付费的,价格的计算方式不是简单的按照请求次数计算,包括相应内容的文字的多少。新账号有18美元免费额度。 159 | 160 | 161 | > 官方价格:https://openai.com/api/pricing 162 | 163 | pay.png 164 | 165 | ### 故障排除 166 | + [Chrome 依赖](./docs/puppeteer-error.md) 167 | 168 | 169 | 170 | 171 | 172 | ### 感谢 173 | 174 | [@wechaty](https://github.com/wechaty/wechaty) 175 | 176 | [@transitive-bullshit](https://github.com/transitive-bullshit/chatgpt-api) 177 | 178 |
179 | -------------------------------------------------------------------------------- /app.js: -------------------------------------------------------------------------------- 1 | import { WechatyBuilder } from 'wechaty' 2 | import onScan from './listeners/on-scan.js' 3 | import onMessage from './listeners/on-message.js' 4 | import onLogin from './listeners/on-login.js' 5 | 6 | 7 | const bot = WechatyBuilder.build({ 8 | name: "wechat-bot", 9 | puppet: 'wechaty-puppet-wechat', 10 | puppetOptions: { 11 | uos: true, 12 | }, 13 | }) 14 | 15 | bot.on("login", async user => { 16 | onLogin(user, bot); 17 | }) 18 | bot.on('message', async msg => { 19 | onMessage(msg, bot); 20 | }); 21 | bot.on("scan", async (qrcode, status) => { 22 | onScan(qrcode, status); 23 | }); 24 | 25 | bot 26 | .start() 27 | .then(() => console.log("开始登陆微信")) 28 | .catch(e => console.error(e)); 29 | 30 | 31 | -------------------------------------------------------------------------------- /cf_worker.js: -------------------------------------------------------------------------------- 1 | const TELEGRAPH_URL = 'https://api.openai.com'; 2 | 3 | addEventListener('fetch', event => { 4 | event.respondWith(handleRequest(event.request)) 5 | }) 6 | 7 | async function handleRequest(request) { 8 | const url = new URL(request.url); 9 | url.host = TELEGRAPH_URL.replace(/^https?:\/\//, ''); 10 | const modifiedRequest = new Request(url.toString(), { 11 | headers: request.headers, 12 | method: request.method, 13 | body: request.body, 14 | redirect: 'follow' 15 | }); 16 | const response = await fetch(modifiedRequest); 17 | const modifiedResponse = new Response(response.body, response); 18 | // 添加允许跨域访问的响应头 19 | modifiedResponse.headers.set('Access-Control-Allow-Origin', '*'); 20 | return modifiedResponse; 21 | } -------------------------------------------------------------------------------- /docs/cf_worker.md: -------------------------------------------------------------------------------- 1 | 2 | ## cf worker部署 3 | 4 | 1. 首页:https://workers.cloudflare.com 5 | 6 | 2. 注册,登陆,`Start building`,取一个子域名,`Create a Worker`。 7 | 8 | 3. 复制 [cf_worker.js](https://cdn.jsdelivr.net/gh/x-dr/chatgptProxyAPI@main/cf_worker.js) 到左侧代码框,`Save and deploy`。 9 | 10 | 4. 使用 11 | ```bash 12 | curl --location 'https://openai.1rmb.tk/v1/chat/completions' \ 13 | --header 'Authorization: Bearer sk-xxxxxxxxxxxxxxx' \ 14 | --header 'Content-Type: application/json' \ 15 | --data '{ 16 | "model": "gpt-3.5-turbo", 17 | "messages": [{"role": "user", "content": "Hello!"}] 18 | }' 19 | 20 | ``` 21 | 22 | 5. Cloudflare Workers计费,到 overview 页面可参看使用情况。免费版每天有 10 万次免费请求,并且有每分钟1000次请求的限制。 23 | 24 | 如果不够用,可升级到 $5 的高级版本,每月可用 1000 万次请求(超出部分 $0.5/百万次请求)。 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /docs/puppeteer-error.md: -------------------------------------------------------------------------------- 1 | 2 | ### 缺少Chrome 依赖 3 | 4 | 5 | 6 | 7 | > 参考 [https://github.com/puppeteer/puppeteer](https://github.com/puppeteer/puppeteer/blob/main/docs/troubleshooting.md) 8 | 9 | > ubuntu,dabian运行以下命令解决 10 | 11 | ```bash 12 | sudo apt-get update 13 | sudo apt-get install -y libgbm-dev 14 | sudo apt install -y gconf-service libasound2 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 ca-certificates fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils wget 15 | ``` -------------------------------------------------------------------------------- /images/Create_openai_key.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/x-dr/wechaty-bot/006f9efec4fa1cee490a5d360068775e65a5d58d/images/Create_openai_key.png -------------------------------------------------------------------------------- /images/eg1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/x-dr/wechaty-bot/006f9efec4fa1cee490a5d360068775e65a5d58d/images/eg1.png -------------------------------------------------------------------------------- /images/eg2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/x-dr/wechaty-bot/006f9efec4fa1cee490a5d360068775e65a5d58d/images/eg2.png -------------------------------------------------------------------------------- /images/eg3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/x-dr/wechaty-bot/006f9efec4fa1cee490a5d360068775e65a5d58d/images/eg3.png -------------------------------------------------------------------------------- /images/pay.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/x-dr/wechaty-bot/006f9efec4fa1cee490a5d360068775e65a5d58d/images/pay.png -------------------------------------------------------------------------------- /images/wechaty-docker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/x-dr/wechaty-bot/006f9efec4fa1cee490a5d360068775e65a5d58d/images/wechaty-docker.png -------------------------------------------------------------------------------- /listeners/on-login.js: -------------------------------------------------------------------------------- 1 | import Express from 'express'; 2 | import sendmsg from '../utils/pushmsg.js' 3 | /** 4 | * @description 您的机器人上线啦 5 | * @param {} user 6 | */ 7 | async function onLogin(user, bot) { 8 | // console.log('bot'); 9 | 10 | console.log(`Bot${user}已登录了`); 11 | 12 | const app = Express() 13 | 14 | app.set('x-powered-by', false) 15 | app.use(Express.json()) 16 | // 配置中间件 17 | app.use(Express.urlencoded({ extended: false })) 18 | 19 | 20 | 21 | app.post('/send', async (req, res) => { 22 | const {group, user, msg } = req.body 23 | // console.log(req.body); 24 | console.log(group,user, msg); 25 | await sendmsg(bot,group, user, msg) 26 | res.send('ok') 27 | }) 28 | 29 | 30 | 31 | app.all('/', async (req, res) => { 32 | res.send('ok') 33 | } 34 | ) 35 | 36 | 37 | app.listen(3035, () => { 38 | console.log('Start service success! listening port: http://127.0.0.1:' + 3035); 39 | }) 40 | 41 | 42 | } 43 | 44 | 45 | export default onLogin 46 | -------------------------------------------------------------------------------- /listeners/on-message.js: -------------------------------------------------------------------------------- 1 | import * as dotenv from 'dotenv' // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import 2 | dotenv.config() 3 | import chatgptReply from '../utils/get-chatgpt.js' 4 | import replyAiImage from '../utils/get-ai-image.js' 5 | 6 | // const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); 7 | const AutoReplyFriend = parseInt(process.env.AutoReplyFriend) 8 | const AutoReplyGroup = parseInt(process.env.AutoReplyGroup) 9 | const RoomList = JSON.parse(process.env.RoomList); // in your app file 10 | const FriendList = JSON.parse(process.env.FriendList); // in your app file 11 | 12 | 13 | const onMessage = async (msg, bot) => { 14 | const contact = msg.talker(); // 发消息人 15 | const UrlLink = bot.UrlLink; 16 | const content = msg.text().trim(); // 消息内容 17 | const room = msg.room(); // 是否是群消息 18 | const alias = await contact.alias(); // 发消息人备注 19 | const isText = msg.type() === bot.Message.Type.Text; // 是否是文字消息 20 | const receiver = msg.to(); // 消息接收者 21 | 22 | // 不处理 120s前的消息,防止应缓存重复发送 23 | if (msg.age() > 120) { 24 | console.log(`消息在${msg.age()}S 前发送的`) 25 | return; 26 | } 27 | //防止自己和自己对话 28 | if (msg.self()) { 29 | return; 30 | } 31 | 32 | if (room && isText) { 33 | // 如果是群消息 目前只处理文字消息 34 | const topic = await room.topic(); 35 | const mgsfrom = contact.name() 36 | console.log(`群名: ${topic} 发消息人: ${mgsfrom} 内容: ${content}`); 37 | if (AutoReplyGroup) { 38 | if (RoomList.length === 0 || RoomList.includes(topic)) { 39 | if (content.startsWith('/c ')) { 40 | // replyMessage(mgsfrom, room, content.replace('/c ', '')) 41 | chatgptReply(room, contact, content.replace('/c ', '')) 42 | } else if (content.startsWith('/img ')) { 43 | replyAiImage(mgsfrom, room, content.replace('/img ', '')) 44 | } 45 | } else { 46 | console.log(`群名: ${topic} 不在群列表中`); 47 | return 48 | } 49 | } else { 50 | console.log("群消息自动回复已关闭"); 51 | } 52 | 53 | } else if (isText) { 54 | // 如果是好友消息 目前只处理文字消息 55 | if (AutoReplyFriend) { 56 | if (FriendList.length === 0 || FriendList.includes(contact.name())) { 57 | const mgsfrom = false 58 | if (content.startsWith('/c ')) { 59 | chatgptReply(mgsfrom, contact, content.replace('/c ', '')) 60 | // replyMessage(mgsfrom, contact, content.replace('/c ', '')) 61 | } else if (content.startsWith('/img ')) { 62 | replyAiImage(mgsfrom, contact, content.replace('/img ', '')) 63 | } 64 | } else { 65 | console.log(`好友名: ${contact.name()} 不在好友列表中`); 66 | return 67 | } 68 | } else { 69 | console.log("好友消息自动回复已关闭"); 70 | } 71 | } 72 | 73 | } 74 | 75 | export default onMessage -------------------------------------------------------------------------------- /listeners/on-scan.js: -------------------------------------------------------------------------------- 1 | 2 | import QrcodeTerminal from 'qrcode-terminal' 3 | async function onScan (qrcode, status) { 4 | QrcodeTerminal.generate(qrcode, {small: true}) 5 | 6 | const qrcodeImageUrl = [ 7 | 'https://api.qrserver.com/v1/create-qr-code/?data=', 8 | encodeURIComponent(qrcode), 9 | ].join('') 10 | 11 | console.log(status, qrcodeImageUrl) 12 | } 13 | 14 | export default onScan -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "chatgpt", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "app.js", 6 | "type": "module", 7 | "scripts": { 8 | "start": "node app.js" 9 | }, 10 | "keywords": [ 11 | "chatgpt", 12 | "wechat", 13 | "wechaty", 14 | "微信机器人", 15 | "微信助手", 16 | "AI绘画" 17 | ], 18 | "author": "", 19 | "license": "ISC", 20 | "dependencies": { 21 | "chatgpt": "^5.0.4", 22 | "dotenv": "^16.0.3", 23 | "express": "^4.18.2", 24 | "file-box": "^1.4.15", 25 | "node-schedule": "^2.1.1", 26 | "openai": "^3.2.1", 27 | "qrcode-terminal": "^0.12.0", 28 | "wechaty": "^1.20.2", 29 | "wechaty-puppet-wechat": "^1.18.4" 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/x-dr/wechaty-bot/006f9efec4fa1cee490a5d360068775e65a5d58d/test.js -------------------------------------------------------------------------------- /utils/get-ai-image.js: -------------------------------------------------------------------------------- 1 | import { requestPromise } from './req.js' 2 | import * as dotenv from 'dotenv' // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import 3 | dotenv.config() 4 | import { FileBox } from 'file-box' 5 | 6 | 7 | const url = process.env.PROXY_API ? `${process.env.PROXY_API}/v1/images/generations` : "https://api.openai.com/v1/images/generations" 8 | 9 | const createAiImage = async (prompt) => { 10 | let res = await requestPromise({ 11 | url: url, 12 | headers: { 13 | 'Content-Type': 'application/json', 14 | 'Authorization': `Bearer ${process.env.OPENAI_API_KEY}` 15 | }, 16 | body: { 17 | "prompt": prompt, 18 | "n": 1, 19 | "size": "1024x1024" 20 | } 21 | 22 | }); 23 | try { 24 | 25 | if (res.hasOwnProperty('data')) { 26 | return res.data.data[0].url 27 | } else if(res.hasOwnProperty("response")) { 28 | // console.log(res.response); 29 | return res.response.data.error.message 30 | }else{ 31 | return "?????????????" 32 | } 33 | 34 | }catch(e){ 35 | console.log(e) 36 | } 37 | 38 | 39 | } 40 | 41 | 42 | 43 | 44 | const replyAiImage = async (mgsfrom, contact, content) => { 45 | try { 46 | const imgurl = await createAiImage(content); 47 | if(/https:\/\//.test(imgurl)){ 48 | const img = FileBox.fromUrl(imgurl, 'img.png') 49 | if (mgsfrom) { 50 | await contact.say(`@${mgsfrom} 图片生成中...`); 51 | await contact.say(img) 52 | } else { 53 | await contact.say(img); 54 | } 55 | }else{ 56 | if (mgsfrom) { 57 | await contact.say(`@${mgsfrom} ${imgurl}`); 58 | 59 | } else { 60 | await contact.say(imgurl); 61 | } 62 | } 63 | } catch (e) { 64 | console.error(e); 65 | } 66 | } 67 | export default replyAiImage 68 | -------------------------------------------------------------------------------- /utils/get-chatgpt.js: -------------------------------------------------------------------------------- 1 | import { ChatGPTAPI } from 'chatgpt'; 2 | import * as dotenv from 'dotenv' // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import 3 | dotenv.config() 4 | 5 | let apiKey = ''; 6 | const api = new ChatGPTAPI({ 7 | apiKey: apiKey || process.env.OPENAI_API_KEY, 8 | apiBaseUrl: process.env.PROXY_API || 'https://api.openai.com' 9 | }); 10 | 11 | const conversationPool = new Map(); 12 | async function chatgptReply(room, contact, request) { 13 | console.log(`contact: ${contact} request: ${request}`); 14 | let response = '🤒🤒🤒出了一点小问题,请稍后重试下...'; 15 | if(request==="结束对话") { 16 | conversationPool.delete(contact.id); 17 | const target = room || contact; 18 | await send(target, `${contact.name()}的已结束对话`); 19 | return; 20 | }else{ 21 | try { 22 | let opts = {}; 23 | // conversation 24 | let conversation = conversationPool.get(contact.id); 25 | if (conversation) { 26 | opts = conversation; 27 | } 28 | opts.timeoutMs = 2 * 60 * 1000; 29 | let res = await api.sendMessage(request, opts); 30 | response = res.text; 31 | console.log(`contact: ${contact} response: ${response}`); 32 | conversation = { 33 | conversationId: res.conversationId, 34 | parentMessageId: res.id, 35 | }; 36 | conversationPool.set(contact.id, conversation); 37 | } catch (e) { 38 | if (e.message === 'ChatGPTAPI error 429') { 39 | response = '🤯🤯🤯请稍等一下哦,我还在思考你的上一个问题'; 40 | } 41 | console.error(e); 42 | } 43 | response = `${request} \n ------------------------ \n` + response; 44 | const target = room || contact; 45 | await send(target, response); 46 | } 47 | 48 | 49 | } 50 | 51 | 52 | 53 | async function send(contact, message) { 54 | try { 55 | await contact.say(message); 56 | } catch (e) { 57 | console.error(e); 58 | } 59 | } 60 | 61 | 62 | export default chatgptReply -------------------------------------------------------------------------------- /utils/get-openai.js: -------------------------------------------------------------------------------- 1 | import { Configuration, OpenAIApi } from 'openai' 2 | import * as dotenv from 'dotenv' // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import 3 | dotenv.config() 4 | 5 | const configuration = new Configuration({ 6 | apiKey: process.env.OPENAI_API_KEY, 7 | }) 8 | const openai = new OpenAIApi(configuration) 9 | 10 | 11 | 12 | const getOpenAiReply = async (prompt) => { 13 | try { 14 | const response = await openai.createCompletion({ 15 | model: 'text-davinci-003', 16 | prompt: prompt, 17 | temperature: 0.9, 18 | max_tokens: 4000, 19 | top_p: 1, 20 | frequency_penalty: 0.0, 21 | presence_penalty: 0.6, 22 | stop: [' Human:', ' AI:'], 23 | }) 24 | // console.log(response.data); 25 | const reply = response.data.choices[0].text 26 | return reply 27 | } catch (e) { 28 | console.error(e); 29 | // return e 30 | } 31 | } 32 | const replyMessage = async (mgsfrom, contact, content) => { 33 | const reply = await getOpenAiReply(content); 34 | try { 35 | if (mgsfrom) { 36 | await contact.say(`@${mgsfrom} ${reply}`); 37 | } else { 38 | await contact.say(reply); 39 | } 40 | } catch (e) { 41 | console.error(e); 42 | } 43 | } 44 | 45 | 46 | export default replyMessage -------------------------------------------------------------------------------- /utils/pushmsg.js: -------------------------------------------------------------------------------- 1 | const sendmsg = async (bot, group, user, msg) => { 2 | if (group === 1) { 3 | const room = await bot.Room.find({ topic: user }) 4 | if (room) { 5 | await room.say(msg) 6 | } else { 7 | console.log('not found') 8 | } 9 | // await contact.say(msg) 10 | 11 | } 12 | else { 13 | const contact = await bot.Contact.find({ name: user }) // change 'lijiarui' to any of the room member 14 | if (contact) { 15 | await contact.say(msg) 16 | } else { 17 | console.log('not found') 18 | } 19 | } 20 | } 21 | export default sendmsg -------------------------------------------------------------------------------- /utils/req.js: -------------------------------------------------------------------------------- 1 | import axios from 'axios'; 2 | 3 | const headers={ 4 | "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36", 5 | } 6 | export const requestPromise = async (params) => { 7 | // console.log(params); 8 | return axios({ 9 | url: params.url, 10 | method: params.method || 'POST', 11 | headers: params.headers || headers, 12 | data: params.body, 13 | validateStatus: status => { 14 | return status >= 200 && status < 400; 15 | }, 16 | maxRedirects: 0 17 | }) 18 | .then(res => { 19 | return res; 20 | }) 21 | .catch(err => { 22 | // console.log(err); 23 | return err; 24 | }) 25 | } 26 | --------------------------------------------------------------------------------