├── .npmignore ├── docs └── images │ └── mock.png ├── .eslintrc.cjs ├── tsconfig.cjs.json ├── src ├── mod.ts ├── package-json.ts ├── package-json.spec.ts ├── puppet-oicq.spec.ts ├── config.ts ├── monkey-patch.ts ├── qq-id.ts ├── qq-id.spec.ts └── puppet-oicq.ts ├── tests ├── integration.spec.ts └── fixtures │ └── smoke-testing.ts ├── .markdownlintrc ├── .editorconfig ├── tsconfig.json ├── scripts ├── package-publish-config-tag.sh ├── generate-package-json.sh └── npm-pack-testing.sh ├── .gitignore ├── package.json ├── .vscode └── settings.json ├── .github └── workflows │ └── npm.yml ├── examples └── ding-dong-bot.ts ├── README.md └── LICENSE /.npmignore: -------------------------------------------------------------------------------- 1 | docs/ 2 | -------------------------------------------------------------------------------- /docs/images/mock.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wechaty/puppet-oicq/HEAD/docs/images/mock.png -------------------------------------------------------------------------------- /.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | 2 | const rules = { 3 | } 4 | 5 | module.exports = { 6 | extends: '@chatie', 7 | rules, 8 | } 9 | -------------------------------------------------------------------------------- /tsconfig.cjs.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "module": "CommonJS", 5 | "outDir": "dist/cjs", 6 | }, 7 | } 8 | -------------------------------------------------------------------------------- /src/mod.ts: -------------------------------------------------------------------------------- 1 | import { VERSION } from './config.js' 2 | import { PuppetOICQ } from './puppet-oicq.js' 3 | export { 4 | VERSION, 5 | PuppetOICQ, 6 | } 7 | export default PuppetOICQ 8 | -------------------------------------------------------------------------------- /tests/integration.spec.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ts-node 2 | 3 | import { 4 | test, 5 | } from 'tstest' 6 | 7 | test('integration testing', async (t) => { 8 | await t.skip('tbw') 9 | }) 10 | -------------------------------------------------------------------------------- /.markdownlintrc: -------------------------------------------------------------------------------- 1 | { 2 | "default": true, 3 | "no-trailing-punctuation": { 4 | "punctuation": ".,;:!" 5 | }, 6 | "MD013": false, 7 | "MD033": false, 8 | "first-line-h1": false, 9 | "no-hard-tabs": true, 10 | "no-trailing-spaces": { 11 | "br_spaces": 2 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/package-json.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file will be overwrite when we publish NPM module 3 | * by scripts/generate_version.ts 4 | */ 5 | import type { PackageJson } from 'type-fest' 6 | 7 | /** 8 | * Huan(202108): 9 | * The below default values is only for unit testing 10 | */ 11 | export const packageJson: PackageJson = {} 12 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see http://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | end_of_line = lf 9 | insert_final_newline = true 10 | trim_trailing_whitespace = true 11 | 12 | [*.md] 13 | max_line_length = 0 14 | trim_trailing_whitespace = false 15 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@chatie/tsconfig", 3 | "compilerOptions": { 4 | "outDir": "dist/esm", 5 | }, 6 | "exclude": [ 7 | "node_modules/", 8 | "dist/", 9 | "tests/fixtures/", 10 | ], 11 | "include": [ 12 | "bin/*.ts", 13 | "examples/**/*.ts", 14 | "scripts/**/*.ts", 15 | "src/**/*.ts", 16 | "tests/**/*.spec.ts", 17 | ], 18 | } 19 | -------------------------------------------------------------------------------- /src/package-json.spec.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env -S node --no-warnings --loader ts-node/esm 2 | 3 | import { test } from 'tstest' 4 | 5 | import { packageJson } from './package-json.js' 6 | 7 | test('Make sure the packageJson is fresh in source code', async t => { 8 | const keyNum = Object.keys(packageJson).length 9 | t.equal(keyNum, 0, 'packageJson should be empty in source code, only updated before publish to NPM') 10 | }) 11 | -------------------------------------------------------------------------------- /scripts/package-publish-config-tag.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e 3 | 4 | VERSION=$(npx pkg-jq -r .version) 5 | 6 | if npx --package @chatie/semver semver-is-prod $VERSION; then 7 | npx pkg-jq -i '.publishConfig.tag="latest"' 8 | echo "production release: publicConfig.tag set to latest." 9 | else 10 | npx pkg-jq -i '.publishConfig.tag="next"' 11 | echo 'development release: publicConfig.tag set to next.' 12 | fi 13 | 14 | -------------------------------------------------------------------------------- /src/puppet-oicq.spec.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env -S node --no-warnings --loader ts-node/esm 2 | 3 | import { test } from 'tstest' 4 | 5 | import { PuppetOICQ } from './puppet-oicq.js' 6 | 7 | // TODO: restore perfect restart testing 8 | test.skip('perfect restart', async t => { 9 | const puppet = new PuppetOICQ({ qq: 12345 }) 10 | 11 | for (let n = 0; n < 3; n++) { 12 | await puppet.start() 13 | await puppet.stop() 14 | t.pass('perfect restart succeed at #' + n) 15 | } 16 | }) 17 | -------------------------------------------------------------------------------- /src/config.ts: -------------------------------------------------------------------------------- 1 | import { 2 | FileBox, 3 | } from 'file-box' 4 | 5 | import { packageJson } from './package-json.js' 6 | 7 | const CHATIE_OFFICIAL_ACCOUNT_QRCODE = 'http://weixin.qq.com/r/qymXj7DEO_1ErfTs93y5' 8 | 9 | function qrCodeForChatie (): FileBox { 10 | return FileBox.fromQRCode(CHATIE_OFFICIAL_ACCOUNT_QRCODE) 11 | } 12 | 13 | const VERSION = packageJson.version || '0.0.0' 14 | 15 | export { 16 | VERSION, 17 | CHATIE_OFFICIAL_ACCOUNT_QRCODE, 18 | qrCodeForChatie, 19 | } 20 | -------------------------------------------------------------------------------- /scripts/generate-package-json.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e 3 | 4 | SRC_PACKAGE_JSON_TS_FILE='src/package-json.ts' 5 | 6 | [ -f ${SRC_PACKAGE_JSON_TS_FILE} ] || { 7 | echo ${SRC_PACKAGE_JSON_TS_FILE}" not found" 8 | exit 1 9 | } 10 | 11 | cat <<_SRC_ > ${SRC_PACKAGE_JSON_TS_FILE} 12 | /** 13 | * This file was auto generated from scripts/generate-version.sh 14 | */ 15 | import type { PackageJson } from 'type-fest' 16 | export const packageJson: PackageJson = $(cat package.json) as any 17 | _SRC_ 18 | -------------------------------------------------------------------------------- /tests/fixtures/smoke-testing.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ts-node 2 | 3 | import { 4 | PuppetOICQ, 5 | VERSION, 6 | } from 'wechaty-puppet-oicq' 7 | 8 | async function main () { 9 | const puppet = new PuppetOICQ({ qq: 12345 }) 10 | 11 | if (VERSION === '0.0.0') { 12 | throw new Error('version should not be 0.0.0 when prepare for publishing') 13 | } 14 | 15 | console.info(`Puppet v${puppet.version()} smoke testing passed.`) 16 | return 0 17 | } 18 | 19 | main() 20 | .then(process.exit) 21 | .catch(e => { 22 | console.error(e) 23 | process.exit(1) 24 | }) 25 | -------------------------------------------------------------------------------- /src/monkey-patch.ts: -------------------------------------------------------------------------------- 1 | import type oicq from 'oicq' 2 | import { log } from 'wechaty-puppet' 3 | 4 | import { bindInternalListeners } from 'oicq/lib/internal/listeners.js' 5 | 6 | ;(bindInternalListeners as any).originalCall = bindInternalListeners.call 7 | 8 | /** 9 | * Skip generate QR Code png file 10 | * by disabling the event `system.login.qrcode` 11 | * 12 | * use event `internal.qrcode` instead 13 | */ 14 | bindInternalListeners.call = (( 15 | client: oicq.Client, 16 | ) => { 17 | log.verbose('PuppetOICQ', 'monkeyPatch() bindInternalListeners.call()') 18 | 19 | const wrappedClient = { 20 | on: (eventName: any, callback: any) => { 21 | if (eventName === 'internal.qrcode') { 22 | log.verbose('PuppetOICQ', 'monkeyPatch() bindInternalListeners.call() skipped event `internal.qrcode`') 23 | } else { 24 | client.on(eventName, callback) 25 | } 26 | }, 27 | } 28 | 29 | log.verbose('PuppetOICQ', 'monkeyPatch() bindInternalListeners.call() passing wrapped client to original call') 30 | ;(bindInternalListeners as any).originalCall(wrappedClient) 31 | }) as any 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | # next.js build output 61 | .next 62 | /dist/ 63 | /package-lock.json 64 | .DS_Store 65 | t/ 66 | t.* 67 | data/ 68 | -------------------------------------------------------------------------------- /scripts/npm-pack-testing.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e 3 | 4 | VERSION=$(npx pkg-jq -r .version) 5 | 6 | if npx --package @chatie/semver semver-is-prod "$VERSION"; then 7 | NPM_TAG=latest 8 | else 9 | NPM_TAG=next 10 | fi 11 | 12 | npm run dist 13 | npm pack 14 | 15 | TMPDIR="/tmp/npm-pack-testing.$$" 16 | mkdir "$TMPDIR" 17 | mv ./*-*.*.*.tgz "$TMPDIR" 18 | cp tests/fixtures/smoke-testing.ts "$TMPDIR" 19 | 20 | cd $TMPDIR 21 | 22 | npm init -y 23 | npm install --production ./*-*.*.*.tgz \ 24 | @chatie/tsconfig@$NPM_TAG \ 25 | pkg-jq \ 26 | "wechaty-puppet@$NPM_TAG" \ 27 | "wechaty@$NPM_TAG" \ 28 | 29 | # 30 | # CommonJS 31 | # 32 | ./node_modules/.bin/tsc \ 33 | --target es6 \ 34 | --module CommonJS \ 35 | \ 36 | --moduleResolution node \ 37 | --esModuleInterop \ 38 | --lib esnext \ 39 | --noEmitOnError \ 40 | --noImplicitAny \ 41 | --skipLibCheck \ 42 | smoke-testing.ts 43 | 44 | echo 45 | echo "CommonJS: pack testing..." 46 | node smoke-testing.js 47 | 48 | # 49 | # ES Modules 50 | # 51 | npx pkg-jq -i '.type="module"' 52 | 53 | 54 | ./node_modules/.bin/tsc \ 55 | --target es2020 \ 56 | --module es2020 \ 57 | \ 58 | --moduleResolution node \ 59 | --esModuleInterop \ 60 | --lib esnext \ 61 | --noEmitOnError \ 62 | --noImplicitAny \ 63 | --skipLibCheck \ 64 | smoke-testing.ts 65 | 66 | echo 67 | echo "ES Module: pack testing..." 68 | node smoke-testing.js 69 | -------------------------------------------------------------------------------- /src/qq-id.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Template Literal Types 3 | * 4 | * Template literal types build on string literal types, 5 | * and have the ability to expand into many strings via unions. 6 | * 7 | * They have the same syntax as template literal strings in JavaScript, 8 | * but are used in type positions. When used with concrete literal types, 9 | * a template literal produces a new string literal type by concatenating the contents. 10 | * 11 | * @see https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html 12 | */ 13 | type QQ_USER_ID = `user_${string}` 14 | type QQ_GROUP_ID = `group_${string}` 15 | 16 | const isGroupId = (id: string): id is QQ_GROUP_ID => id.startsWith('group_') 17 | const isUserId = (id: string): id is QQ_USER_ID => id.startsWith('user_') 18 | 19 | const toGroupId = (id: number): QQ_GROUP_ID => `group_${id}` 20 | const toUserId = (id: number): QQ_USER_ID => `user_${id}` 21 | 22 | const toQqNumber = (id: string): number => { 23 | const num = id.replace(/^[^\d]+/, '') 24 | if (!num) throw new Error('Invalid QQ ID: ' + id) 25 | 26 | const qq = Number(num) 27 | if (isNaN(qq)) throw new Error('Invalid QQ ID: ' + id) 28 | if (qq === 0) throw new Error('Invalid QQ ID: ' + id) 29 | 30 | return qq 31 | } 32 | 33 | export type { 34 | QQ_USER_ID, 35 | QQ_GROUP_ID, 36 | } 37 | export { 38 | toQqNumber, 39 | isGroupId, 40 | isUserId, 41 | toGroupId, 42 | toUserId, 43 | } 44 | -------------------------------------------------------------------------------- /src/qq-id.spec.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env -S node --no-warnings --loader ts-node/esm 2 | 3 | import { 4 | test, 5 | AssertEqual, 6 | } from 'tstest' 7 | 8 | import { 9 | isGroupId, 10 | isUserId, 11 | QQ_GROUP_ID, 12 | QQ_USER_ID, 13 | toGroupId, 14 | toQqNumber, 15 | toUserId, 16 | } from './qq-id.js' 17 | 18 | test('QQ user id', async t => { 19 | const QQ_USER_FIXTURES = [ 20 | ['user_12345678', true], 21 | ['group_123456789', false], 22 | ['1234567890', false], 23 | ] as const 24 | 25 | for (const [id, expected] of QQ_USER_FIXTURES) { 26 | t.equal(isUserId(id), expected, `${id} is ${expected ? '' : 'not '}a QQ user id`) 27 | } 28 | }) 29 | 30 | test('QQ group id', async t => { 31 | const QQ_GROUP_FIXTURES = [ 32 | ['group_12345678', true], 33 | ['user_123456789', false], 34 | ['1234567890', false], 35 | ] as const 36 | 37 | for (const [id, expected] of QQ_GROUP_FIXTURES) { 38 | t.equal(isGroupId(id), expected, `${id} is ${expected ? '' : 'not '}a QQ group id`) 39 | } 40 | }) 41 | 42 | test('QQ group id type guard', async t => { 43 | const userId: QQ_USER_ID = 'user_12345678' 44 | const groupId: QQ_GROUP_ID = 'group_12345678' 45 | 46 | const userTypeTest: AssertEqual< 47 | typeof userId, 48 | QQ_USER_ID 49 | > = true 50 | t.ok(userTypeTest, 'QQ user id type') 51 | 52 | const groupTypeTest: AssertEqual< 53 | typeof groupId, 54 | QQ_GROUP_ID 55 | > = true 56 | t.ok(groupTypeTest, 'QQ group id type') 57 | }) 58 | 59 | test('QQ user id builder', async t => { 60 | const USER_FIXTURES = [ 61 | [12345678, 'user_12345678'], 62 | ] as const 63 | 64 | for (const [numId, strId] of USER_FIXTURES) { 65 | t.equal(toUserId(numId), strId, `${numId} is ${strId}`) 66 | t.equal(toQqNumber(strId), numId, `${strId} is ${numId}`) 67 | } 68 | }) 69 | 70 | test('QQ group id builder', async t => { 71 | const GROUP_FIXTURES = [ 72 | [12345678, 'group_12345678'], 73 | ] as const 74 | 75 | for (const [numId, strId] of GROUP_FIXTURES) { 76 | t.equal(toGroupId(numId), strId, `${numId} is ${strId}`) 77 | t.equal(toQqNumber(strId), numId, `${strId} is ${numId}`) 78 | } 79 | }) 80 | 81 | test('QQ ID invalidation check', async t => { 82 | const FIXTURE = [ 83 | null, 84 | undefined, 85 | '', 86 | [], 87 | {}, 88 | 0, 89 | ] 90 | 91 | for (const value of FIXTURE) { 92 | t.throws(() => toQqNumber(value as any), `should throw for ${typeof value}: "${JSON.stringify(value)}"`) 93 | } 94 | }) 95 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "wechaty-puppet-oicq", 3 | "version": "1.10.2", 4 | "description": "QQ Puppet for Wechaty", 5 | "type": "module", 6 | "exports": { 7 | ".": { 8 | "import": "./dist/esm/src/mod.js", 9 | "require": "./dist/cjs/src/mod.js" 10 | } 11 | }, 12 | "typings": "./dist/esm/src/mod.d.ts", 13 | "engines": { 14 | "wechaty": ">=1.0", 15 | "node": ">=16", 16 | "npm": ">=7" 17 | }, 18 | "scripts": { 19 | "build": "tsc && tsc -p tsconfig.cjs.json", 20 | "clean": "shx rm -fr dist/*", 21 | "dist": "npm-run-all clean build dist:commonjs", 22 | "dist:commonjs": "jq -n \"{ type: \\\"commonjs\\\" }\" > dist/cjs/package.json", 23 | "start": "cross-env NODE_OPTIONS=\"--no-warnings --loader=ts-node/esm\" node examples/ding-dong-bot.ts", 24 | "lint": "npm-run-all lint:es lint:ts lint:md", 25 | "lint:md": "markdownlint README.md", 26 | "lint:ts": "tsc --isolatedModules --noEmit", 27 | "lint:es": "eslint \"src/**/*.ts\" \"tests/**/*.spec.ts\" --ignore-pattern tests/fixtures/", 28 | "test": "npm-run-all lint test:unit", 29 | "test:pack": "bash -x scripts/npm-pack-testing.sh", 30 | "test:unit": "cross-env NODE_OPTIONS=\"--no-warnings --loader=ts-node/esm\" tap \"src/**/*.spec.ts\" \"tests/**/*.spec.ts\"" 31 | }, 32 | "repository": { 33 | "type": "git", 34 | "url": "git+https://github.com/anaivebird/wechaty-puppet-oicq.git" 35 | }, 36 | "keywords": [ 37 | "chatie", 38 | "wechaty", 39 | "chatbot", 40 | "bot", 41 | "wechat", 42 | "sdk", 43 | "puppet", 44 | "mock" 45 | ], 46 | "author": "naivebird <29398611+anaivebird@users.noreply.github.com>", 47 | "license": "Apache-2.0", 48 | "bugs": { 49 | "url": "https://github.com/anaivebird/wechaty-puppet-oicq/issues" 50 | }, 51 | "homepage": "https://github.com/anaivebird/wechaty-puppet-oicq#readme", 52 | "devDependencies": { 53 | "@chatie/eslint-config": "^1.0.4", 54 | "@chatie/git-scripts": "^0.6.2", 55 | "@chatie/semver": "^0.4.7", 56 | "@chatie/tsconfig": "^4.5.3", 57 | "tstest": "^1.0.1" 58 | }, 59 | "peerDependencies": { 60 | "wechaty-puppet": "^1.10.2" 61 | }, 62 | "dependencies": { 63 | "oicq": "^2.1.4" 64 | }, 65 | "publishConfig": { 66 | "access": "public", 67 | "tag": "next" 68 | }, 69 | "files": [ 70 | "bin/", 71 | "dist/", 72 | "src/" 73 | ], 74 | "tap": { 75 | "check-coverage": false 76 | }, 77 | "git": { 78 | "scripts": { 79 | "pre-push": "npx git-scripts-pre-push" 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "typescript.tsdk": "./node_modules/typescript/lib", 3 | 4 | "editor.fontFamily": "Consolas, 'Courier New', monospace", 5 | "editor.fontLigatures": true, 6 | 7 | "editor.tokenColorCustomizations": { 8 | "textMateRules": [ 9 | { 10 | "scope": [ 11 | //following will be in italics (=Pacifico) 12 | "comment", 13 | // "entity.name.type.class", //class names 14 | "keyword", //import, export, return… 15 | "support.class.builtin.js", //String, Number, Boolean…, this, super 16 | "storage.modifier", //static keyword 17 | "storage.type.class.js", //class keyword 18 | "storage.type.function.js", // function keyword 19 | "storage.type.js", // Variable declarations 20 | "keyword.control.import.js", // Imports 21 | "keyword.control.from.js", // From-Keyword 22 | "entity.name.type.js", // new … Expression 23 | "keyword.control.flow.js", // await 24 | "keyword.control.conditional.js", // if 25 | "keyword.control.loop.js", // for 26 | "keyword.operator.new.js", // new 27 | ], 28 | "settings": { 29 | "fontStyle": "italic", 30 | }, 31 | }, 32 | { 33 | "scope": [ 34 | //following will be excluded from italics (My theme (Monokai dark) has some defaults I don't want to be in italics) 35 | "invalid", 36 | "keyword.operator", 37 | "constant.numeric.css", 38 | "keyword.other.unit.px.css", 39 | "constant.numeric.decimal.js", 40 | "constant.numeric.json", 41 | "entity.name.type.class.js" 42 | ], 43 | "settings": { 44 | "fontStyle": "", 45 | }, 46 | } 47 | ] 48 | }, 49 | 50 | "files.exclude": { 51 | "dist/": true, 52 | "doc/": true, 53 | "node_modules/": true, 54 | "package/": true, 55 | }, 56 | "alignment": { 57 | "operatorPadding": "right", 58 | "indentBase": "firstline", 59 | "surroundSpace": { 60 | "colon": [1, 1], // The first number specify how much space to add to the left, can be negative. The second number is how much space to the right, can be negative. 61 | "assignment": [1, 1], // The same as above. 62 | "arrow": [1, 1], // The same as above. 63 | "comment": 2, // Special how much space to add between the trailing comment and the code. 64 | // If this value is negative, it means don't align the trailing comment. 65 | } 66 | }, 67 | "editor.formatOnSave": false, 68 | "python.pythonPath": "python3", 69 | "eslint.validate": [ 70 | "javascript", 71 | "typescript", 72 | ], 73 | "cSpell.words": [ 74 | "Miniprogram" 75 | ], 76 | } 77 | -------------------------------------------------------------------------------- /.github/workflows/npm.yml: -------------------------------------------------------------------------------- 1 | name: NPM 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | name: Build 8 | strategy: 9 | matrix: 10 | os: 11 | - ubuntu-latest 12 | node-version: 13 | - 16 14 | 15 | runs-on: ${{ matrix.os }} 16 | steps: 17 | - uses: actions/checkout@v2 18 | - name: Use Node.js ${{ matrix.node-version }} 19 | uses: actions/setup-node@v2 20 | with: 21 | node-version: ${{ matrix.node-version }} 22 | cache: npm 23 | cache-dependency-path: package.json 24 | 25 | - name: Install Dependencies 26 | run: npm install 27 | 28 | - name: Test 29 | run: npm test 30 | 31 | pack: 32 | name: Pack 33 | needs: build 34 | runs-on: ubuntu-latest 35 | 36 | steps: 37 | - uses: actions/checkout@v2 38 | - uses: actions/setup-node@v2 39 | with: 40 | node-version: 16 41 | cache: npm 42 | cache-dependency-path: package.json 43 | 44 | - name: Install Dependencies 45 | run: npm install 46 | 47 | - name: Generate Package JSON 48 | run: ./scripts/generate-package-json.sh 49 | 50 | - name: Pack Testing 51 | run: ./scripts/npm-pack-testing.sh 52 | 53 | publish: 54 | if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/heads/v')) 55 | name: Publish 56 | needs: [build, pack] 57 | runs-on: ubuntu-latest 58 | steps: 59 | - uses: actions/checkout@v2 60 | - uses: actions/setup-node@v2 61 | with: 62 | node-version: 16 63 | registry-url: https://registry.npmjs.org/ 64 | cache: npm 65 | cache-dependency-path: package.json 66 | 67 | - name: Install Dependencies 68 | run: npm install 69 | 70 | - name: Generate Package JSON 71 | run: ./scripts/generate-package-json.sh 72 | 73 | - name: Set Publish Config 74 | run: ./scripts/package-publish-config-tag.sh 75 | 76 | - name: Build Dist 77 | run: npm run dist 78 | 79 | - name: Check Branch 80 | id: check-branch 81 | run: | 82 | if [[ ${{ github.ref }} =~ ^refs/heads/(main|v[0-9]+\.[0-9]+.*)$ ]]; then 83 | echo ::set-output name=match::true 84 | fi # See: https://stackoverflow.com/a/58869470/1123955 85 | - name: Is A Publish Branch 86 | if: steps.check-branch.outputs.match == 'true' 87 | run: | 88 | NAME=$(npx pkg-jq -r .name) 89 | VERSION=$(npx pkg-jq -r .version) 90 | if npx version-exists "$NAME" "$VERSION" 91 | then echo "$NAME@$VERSION exists on NPM, skipped." 92 | else npm publish 93 | fi 94 | env: 95 | NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} 96 | - name: Is Not A Publish Branch 97 | if: steps.check-branch.outputs.match != 'true' 98 | run: echo 'Not A Publish Branch' 99 | -------------------------------------------------------------------------------- /examples/ding-dong-bot.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Wechaty - https://github.com/chatie/wechaty 3 | * 4 | * @copyright 2016-2018 Huan LI 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | * 18 | */ 19 | import type { 20 | EventLogout, 21 | EventLogin, 22 | EventScan, 23 | EventError, 24 | EventMessage, 25 | } from 'wechaty-puppet/payloads' 26 | 27 | import { 28 | PuppetOICQ, 29 | } from '../src/mod.js' 30 | 31 | /** 32 | * 33 | * 1. Declare your Bot! 34 | * 35 | */ 36 | const puppet = new PuppetOICQ() 37 | 38 | /** 39 | * 40 | * 2. Register event handlers for Bot 41 | * 42 | */ 43 | puppet 44 | .on('logout', onLogout) 45 | .on('login', onLogin) 46 | .on('scan', onScan) 47 | .on('error', onError) 48 | .on('message', onMessage) 49 | 50 | /** 51 | * 52 | * 3. Start the bot! 53 | * 54 | */ 55 | puppet.start() 56 | .catch(async e => { 57 | console.error('Bot start() fail:', e) 58 | await puppet.stop() 59 | process.exit(-1) 60 | }) 61 | 62 | /** 63 | * 64 | * 4. You are all set. ;-] 65 | * 66 | */ 67 | 68 | /** 69 | * 70 | * 5. Define Event Handler Functions for: 71 | * `scan`, `login`, `logout`, `error`, and `message` 72 | * 73 | */ 74 | function onScan (payload: EventScan) { 75 | if (payload.qrcode) { 76 | const qrcodeImageUrl = [ 77 | 'https://wechaty.js.org/qrcode/', 78 | encodeURIComponent(payload.qrcode), 79 | ].join('') 80 | console.info(`[${payload.status}] ${qrcodeImageUrl}\nScan QR Code above to log in: `) 81 | } else { 82 | console.info(`[${payload.status}]`) 83 | } 84 | } 85 | 86 | function onLogin (payload: EventLogin) { 87 | console.info(`${payload.contactId} login`) 88 | puppet.messageSendText(payload.contactId, 'Wechaty login').catch(console.error) 89 | } 90 | 91 | function onLogout (payload: EventLogout) { 92 | console.info(`${payload.contactId} logouted`) 93 | } 94 | 95 | function onError (payload: EventError) { 96 | console.error('Bot error:', payload.data) 97 | /* 98 | if (bot.logonoff()) { 99 | bot.say('Wechaty error: ' + e.message).catch(console.error) 100 | } 101 | */ 102 | } 103 | 104 | /** 105 | * 106 | * 6. The most important handler is for: 107 | * dealing with Messages. 108 | * 109 | */ 110 | async function onMessage (payload: EventMessage) { 111 | const msgPayload = await puppet.messagePayload(payload.messageId) 112 | console.info(JSON.stringify(msgPayload)) 113 | if (msgPayload.text === 'ding') { 114 | await puppet.messageSendText(msgPayload.fromId!, 'dong') 115 | } 116 | } 117 | 118 | /** 119 | * 120 | * 7. Output the Welcome Message 121 | * 122 | */ 123 | const welcome = ` 124 | Puppet Version: ${puppet.version()} 125 | 126 | Please wait... I'm trying to login in... 127 | 128 | ` 129 | console.info(welcome) 130 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WECHATY PUPPET OICQ (基于[OICQ](https://github.com/takayama-lily/oicq)项目的QQ机器人) 2 | 3 | [![Powered by Wechaty](https://img.shields.io/badge/Powered%20By-Wechaty-brightgreen.svg)](https://wechaty.js.org) 4 | 5 | [![NPM Version](https://badge.fury.io/js/wechaty-puppet-oicq.svg)](https://www.npmjs.com/package/wechaty-puppet-oicq) 6 | [![npm (tag)](https://img.shields.io/npm/v/wechaty-puppet-oicq/next.svg)](https://www.npmjs.com/package/wechaty-puppet-oicq?activeTab=versions) 7 | 8 | ## 运行方法 9 | 10 | ### 配置系统环境变量 11 | 12 | 1. `WECHATY_PUPPET_OICQ_QQ`:要登录的QQ号 13 | 14 | ### 安装依赖 15 | 16 | 将代码clone到本地,执行`npm install` 17 | 18 | ### 运行示例代码 19 | 20 | `npm run start` 21 | 22 | 按照提示完成扫码完成后按下回车,即可运行示例机器人 23 | 24 | ## Getting Started with Wechaty 25 | 26 | ```sh 27 | export WECHATY_PUPPET=wechaty-puppet-oicq 28 | npm start 29 | ``` 30 | 31 | Learn more for building your first Wechaty bot at 32 | 33 | ## 项目介绍 34 | 35 | “开源软件供应链点亮计划-暑期2021”(以下简称 暑期2021)是由中科院软件所与 openEuler 社区共同举办的一项面向高校学生的暑期活动,旨在鼓励在校学生积极参与开源软件的开发维护,促进国内优秀开源软件社区的蓬勃发展。 36 | 37 | 根据项目的难易程度和完成情况,参与者还可获取“开源软件供应链点亮计划-暑期2021”活动奖金和奖杯。 38 | 39 | 官网: 40 | 41 | ## Wechaty 42 | 43 | [Wechaty](https://wechaty.js.org) 是一个开源聊天机器人框架SDK,具有高度封装、高可用的特性,支持NodeJs, Python, Go 和Java 等多语言版本。在过去的5年中,服务了数万名开发者,收获了 Github 的 9600 Star。同时配置了完整的DevOps体系并持续按照Apache 的方式管理技术社区。 44 | 45 | ## 项目名称 46 | 47 | 开发支持 QQ 聊天软件的 [Wechaty Puppet Provider](https://wechaty.js.org/docs/puppet-providers/) 模块 48 | 49 | ## 背景介绍 50 | 51 | Wechaty 社区目前已经支持微信、Whatsapp、企业微信、飞书等常见流行即时通讯工具,并且能够通过多语言 SDK (比如 Python Wechaty) 进行调用。 52 | 53 | QQ 是国内和微信并列的两大聊天软件。我们在本次 Summer 2021 的项目中,Wechaty 希望可以实现对 QQ Chatbot 的支持。通过 Wechaty Puppet 的接口,可以将 QQ 进行 RPA 封装,使其成为 `wechaty-puppet-qq` 供 Wechaty 开发者方便接入 QQ 平台,使其成为 Wechaty 可以使用的社区生态模块。 54 | 55 | ## 需求介绍 56 | 57 | 使用 项目作为模版,参考社区其他的 [Wechaty Puppet Provider](https://wechaty.js.org/docs/puppet-providers/) 代码模块,对 QQ 进行规划、RPA选型、原型测试,和最终的代码封装。 58 | 59 | 这里有一个专门讲解如何开发 Wechaty Puppet Provider 的 workshop 视频,它以 `wechaty-puppet-official-account` 作为例子,做了从0到1的入门讲解:[Wechaty Workshop for Puppet Makers: How to make a Puppet for Wechaty](https://wechaty.js.org/2020/08/05/wechaty-puppet-maker/)。通过观看这一个小时的视频,应该可以系统性的了解如何完成构建一个 Wechaty Puppet Provider 模块。 60 | 61 | 在初期开发中,能够实现文本消息的接收和发送,即可完成原型验证 POC 。 62 | 63 | 还可以参考以下链接: 64 | 65 | 1. TypeScript Puppet Official Documentation: 66 | 1. Wechaty Puppet Specification: 67 | 1. 68 | 69 | ## 导师联系方式 70 | 71 | 1. [李佳芮](https://wechaty.js.org/contributors/lijiarui/): Wechaty co-creator, Founder & CEO of Juzi.BOT (rui@chatie.io) 72 | 1. [李卓桓](https://wechaty.js.org/contributors/huan):Wechaty creator, Tencent TVP of Chatbot (huan@chatie.io) 73 | 74 | ## 项目产出目标 75 | 76 | 1. 每日代码 commit 77 | 1. 每周提交一份 report (回复本 issue) 78 | 1. 每两周一次在线会议 79 | 1. 发布 Git Repo `wechaty-puppet-qq` 80 | 1. 可以通过 Wechaty 加载 wechaty-puppet-qq 模块,并通过 QQ RPA 底层,实现文本消息的收发功能 81 | 1. 提供一个 `examples/ding-dong-bot.ts` ,完成“接收到文字消息`ding`时,自动回复消息`dong`\"的功能 82 | 1. 配置 GitHub Actions 实现自动化测试* (可选) 83 | 84 | ## 项目技术栈 85 | 86 | 1. TypeScript programming language 87 | 2. Git 88 | 3. [RPA](https://wechaty.js.org/docs/explainations//rpa) 89 | 90 | ## Links 91 | 92 | - ", 93 | 94 | ## 相关链接 95 | 96 | - [Wechaty](https://wechaty.js.org/v/zh/) 97 | - [Express](https://www.runoob.com/nodejs/nodejs-express-framework.html) 98 | - [TypeScripts中文手册](https://www.tslang.cn/docs/handbook/basic-types.html) 99 | 100 | ## History 101 | 102 | ### main v1.0 (Oct 29, 2021) 103 | 104 | Release v1.0 of Wechaty Puppet Provider for QQ. 105 | 106 | - v0.1 (Sep 22, 2021): ES Modules support 107 | 108 | ### v0.0.1 (Jun 22, 2021) 109 | 110 | - [OSPP 2021 Project started](https://github.com/wechaty/summer/issues/81) 111 | 112 | ## Author 113 | 114 | [@naivebird](https://wechaty.js.org/contributors/anaivebird/) 115 | 116 | ## Copyright & License 117 | 118 | - Code & Docs © 2021-2021 @naivebird and Wechaty Contributors 119 | - Code released under the Apache-2.0 License 120 | - Docs released under Creative Commons 121 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/puppet-oicq.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-console */ 2 | /** 3 | * Wechaty - https://github.com/chatie/wechaty 4 | * 5 | * @copyright 2016-2018 Huan LI 6 | * 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * 19 | */ 20 | 21 | import * as PUPPET from 'wechaty-puppet' 22 | import { log } from 'wechaty-puppet' 23 | 24 | import { 25 | FileBox, 26 | } from 'file-box' 27 | import type { 28 | FileBoxInterface, 29 | } from 'file-box' 30 | import oicq from 'oicq' 31 | 32 | import { 33 | VERSION, 34 | } from './config.js' 35 | import * as qqId from './qq-id.js' 36 | 37 | /** 38 | * Skip generate QR Code png file 39 | * by disabling the event `system.login.qrcode` 40 | * 41 | * use event `internal.qrcode` instead 42 | */ 43 | import './monkey-patch.js' 44 | import type { EventScanPayload } from 'wechaty-puppet/dist/esm/src/schemas/event' 45 | 46 | type PuppetOICQOptions = PUPPET.PuppetOptions & { 47 | qq?: number 48 | } 49 | 50 | class PuppetOICQ extends PUPPET.Puppet { 51 | 52 | static override readonly VERSION = VERSION 53 | 54 | protected _oicqClient?: oicq.Client 55 | protected get oicqClient (): oicq.Client { 56 | if (!this._oicqClient) { 57 | throw new Error('no oicq client!') 58 | } 59 | return this._oicqClient 60 | } 61 | 62 | private messageStore : { [id: string]: oicq.PrivateMessageEvent | oicq.GroupMessageEvent | oicq.DiscussMessageEvent} 63 | private contactStore : { [id: string]: any } 64 | private roomStore : { [id: string]: any } 65 | private loginCheckInterval: any 66 | qq: number 67 | 68 | constructor ( 69 | public override options: PuppetOICQOptions = {}, 70 | ) { 71 | super(options) 72 | log.verbose('PuppetOICQ', 'constructor("%s")', JSON.stringify(options)) 73 | 74 | if (options.qq) { 75 | this.qq = options.qq 76 | } else { 77 | const qq = parseInt(process.env['WECHATY_PUPPET_OICQ_QQ'] || '') 78 | if (isNaN(qq)) { 79 | throw new Error('WECHATY_PUPPET_OICQ_QQ should be set a qq number') 80 | } 81 | this.qq = qq 82 | } 83 | 84 | this.messageStore = {} 85 | this.contactStore = {} 86 | this.roomStore = {} 87 | } 88 | 89 | override async onStart (): Promise { 90 | log.verbose('PuppetOICQ', 'onStart()') 91 | 92 | this._oicqClient = oicq.createClient(this.qq, { 93 | log_level: 'off', 94 | }) 95 | 96 | const that = this 97 | 98 | /** 99 | * Huan(202111): emit qrcode event 100 | * @link https://github.com/takayama-lily/oicq/blob/b4288473745e8a9a50d7f56ab4a03d1df99aa5d6/lib/internal/listeners.ts#L92 101 | */ 102 | const emitQrCode = this.wrapAsync(async function ( 103 | this : oicq.Client, 104 | image : Buffer, 105 | ) { 106 | const qrcode = await FileBox.fromBuffer(image).toQRCode() 107 | const payload: EventScanPayload = { 108 | qrcode, 109 | status: PUPPET.types.ScanStatus.Waiting, 110 | } 111 | that.emit('scan', payload) 112 | }) 113 | this.oicqClient.on('internal.qrcode', emitQrCode) 114 | 115 | this.oicqClient 116 | .on('internal.qrcode', function ( 117 | this: oicq.Client, 118 | ) { 119 | if (that.loginCheckInterval === undefined) { 120 | that.loginCheckInterval = setInterval(() => { 121 | that.wrapAsync(this.login()) 122 | log.verbose('check if QR code is scanned (try to login) if not scanned, new QR code will be shown') 123 | }, 15 * 1000) 124 | } 125 | }) 126 | .on('system.login.error', function ( 127 | this, 128 | error, 129 | ) { 130 | if (error.code < 0) { that.wrapAsync(this.login()) } 131 | }) 132 | .login() 133 | .catch(e => this.emit('error', e)) 134 | 135 | this.oicqClient.on('message', function ( 136 | this, 137 | oicqMessage, 138 | ) { 139 | that.messageStore[oicqMessage.message_id] = oicqMessage 140 | 141 | // Case 1: for group or discuss message 142 | // Case 2: new friend added after bot start 143 | // should set unknown contact info 144 | const senderInfo = oicqMessage.sender 145 | const senderId = qqId.toUserId(senderInfo.user_id) 146 | 147 | if (!(senderId in that.contactStore)) { 148 | that.contactStore[senderId] = senderInfo 149 | } 150 | 151 | if (oicqMessage.message_type === 'group') { 152 | const groupId = qqId.toGroupId(oicqMessage.group_id) 153 | const groupName = oicqMessage.group_name 154 | 155 | that.roomStore[groupId] = { 156 | id: groupId, 157 | topic: groupName, 158 | } 159 | } 160 | 161 | if (oicqMessage.message_type === 'discuss') { 162 | /** 163 | * Huan(202110): what is a message_type === 'discuss'? 164 | */ 165 | const discussId = qqId.toGroupId(oicqMessage.discuss_id) 166 | const discussName = oicqMessage.discuss_name 167 | 168 | that.roomStore[discussId] = { 169 | id: discussId, 170 | topic: discussName, 171 | } 172 | } 173 | 174 | that.emit('message', { messageId: oicqMessage.message_id }) 175 | }) 176 | 177 | this.oicqClient.on('system.online', function ( 178 | this: oicq.Client, 179 | ) { 180 | // puppetThis.state.on(true) 181 | clearInterval(that.loginCheckInterval) 182 | 183 | for (const [id, friend] of this.fl.entries()) { 184 | that.contactStore[qqId.toUserId(id)] = friend 185 | } 186 | that.login(qqId.toUserId(that.qq)) 187 | }) 188 | } 189 | 190 | override async onStop (): Promise { 191 | log.verbose('PuppetOICQ', 'onStop()') 192 | 193 | // TODO: should we close the oicqClient? 194 | const oicqClient = this.oicqClient 195 | this._oicqClient = undefined 196 | oicqClient.terminate() 197 | } 198 | 199 | override ding (data?: string): void { 200 | log.silly('PuppetOICQ', 'ding(%s)', data || '') 201 | // FIXME: do the real job 202 | setTimeout(() => this.emit('dong', { data: data || '' }), 1000) 203 | } 204 | 205 | override async messageRawPayloadParser ( 206 | rawPayload: oicq.PrivateMessageEvent | oicq.GroupMessageEvent | oicq.DiscussMessageEvent, 207 | ): Promise { 208 | // OICQ qq message Payload -> Puppet message payload 209 | let roomId : undefined | string 210 | let toId : undefined | string 211 | 212 | if (rawPayload.message_type === 'private') { 213 | toId = qqId.toUserId(rawPayload.to_id) 214 | } else if (rawPayload.message_type === 'group') { 215 | roomId = qqId.toGroupId(rawPayload.group_id) 216 | } else { // (rawPayload.message_type === 'discuss') { 217 | /** 218 | * Huan(202110): what is a message_type === 'discuss'? 219 | */ 220 | roomId = qqId.toGroupId(rawPayload.discuss_id) 221 | } 222 | 223 | const payloadBase = { 224 | fromId: qqId.toUserId(rawPayload.sender.user_id), 225 | id: rawPayload.message_id, 226 | text: rawPayload.raw_message, 227 | timestamp: Date.now(), 228 | type: PUPPET.types.Message.Text, // TODO: need to change if message type changed to image and so on 229 | } 230 | 231 | let payload: PUPPET.payloads.Message 232 | 233 | if (toId) { 234 | payload = { 235 | ...payloadBase, 236 | toId, 237 | } 238 | } else if (roomId) { 239 | payload = { 240 | ...payloadBase, 241 | roomId, 242 | } 243 | } else { 244 | throw new Error('neither roomId nor toId') 245 | } 246 | 247 | return payload 248 | } 249 | 250 | override async messageRawPayload (oicqMessageId: string): Promise { 251 | const rawPayload = this.messageStore[oicqMessageId] 252 | if (!rawPayload) { 253 | throw new Error('NOPAYLOAD') 254 | } 255 | return rawPayload 256 | } 257 | 258 | override async messageSendText (conversationId: string, text: string, _mentionIdList?: string[]): Promise { 259 | // test if conversationId starts with group_ or qq_ 260 | 261 | const conversationNumber = qqId.toQqNumber(conversationId) 262 | 263 | if (qqId.isGroupId(conversationId)) { 264 | await this.oicqClient.sendGroupMsg(conversationNumber, text) 265 | } else if (qqId.isUserId(conversationId)) { 266 | await this.oicqClient.sendPrivateMsg(conversationNumber, text) 267 | } else { 268 | throw new Error('conversationId: ' + conversationId + ' is neither QQ_USER_TYPE nor QQ_GROUP_TYPE') 269 | } 270 | } 271 | 272 | override async messageSendContact (_conversationId: string, _contactId: string): Promise { 273 | throw new Error('Method not implemented.') 274 | } 275 | 276 | override async messageSendFile (_conversationId: string, _file: FileBoxInterface): Promise { 277 | throw new Error('Method not implemented.') 278 | } 279 | 280 | override async messageSendMiniProgram (_conversationId: string, _miniProgramPayload: PUPPET.payloads.MiniProgram): Promise { 281 | throw new Error('Method not implemented.') 282 | } 283 | 284 | override async messageSendUrl (_conversationId: string, _urlLinkPayload: PUPPET.payloads.UrlLink): Promise { 285 | throw new Error('Method not implemented.') 286 | } 287 | 288 | override contactSelfName (_name: string): Promise { 289 | throw new Error('Method not implemented.') 290 | } 291 | 292 | override contactSelfQRCode (): Promise { 293 | throw new Error('Method not implemented.') 294 | } 295 | 296 | override contactSelfSignature (_signature: string): Promise { 297 | throw new Error('Method not implemented.') 298 | } 299 | 300 | override tagContactAdd (_tagId: string, _contactId: string): Promise { 301 | throw new Error('Method not implemented.') 302 | } 303 | 304 | override tagContactDelete (_tagId: string): Promise { 305 | throw new Error('Method not implemented.') 306 | } 307 | 308 | override tagContactList(): Promise 309 | override tagContactList(contactId: string): Promise 310 | override tagContactList (_contactId?: any): Promise { 311 | throw new Error('Method not implemented.') 312 | } 313 | 314 | override tagContactRemove (_tagId: string, _contactId: string): Promise { 315 | throw new Error('Method not implemented.') 316 | } 317 | 318 | override contactAlias(contactId: string): Promise 319 | override contactAlias(contactId: string, alias: string): Promise 320 | override contactAlias (_contactId: any, _alias?: any): Promise | Promise { 321 | throw new Error('Method not implemented.') 322 | } 323 | 324 | override contactAvatar(contactId: string): Promise 325 | override contactAvatar(contactId: string, file: FileBoxInterface): Promise 326 | override contactAvatar (_contactId: any, _file?: any): Promise | Promise { 327 | throw new Error('Method not implemented.') 328 | } 329 | 330 | override contactPhone (_contactId: string, _phoneList: string[]): Promise { 331 | throw new Error('Method not implemented.') 332 | } 333 | 334 | override contactCorporationRemark (_contactId: string, _corporationRemark: string): Promise { 335 | throw new Error('Method not implemented.') 336 | } 337 | 338 | override contactDescription (_contactId: string, _description: string): Promise { 339 | throw new Error('Method not implemented.') 340 | } 341 | 342 | override contactList (): Promise { 343 | throw new Error('Method not implemented.') 344 | } 345 | 346 | override async contactRawPayload (_contactId: string): Promise { 347 | log.verbose('PuppetOICQ', 'contactRawPayload(%s)', _contactId) 348 | return this.contactStore[_contactId]! 349 | } 350 | 351 | override async contactRawPayloadParser (_rawPayload: any): Promise { 352 | const genderStringToType: { [key: string]: PUPPET.types.ContactGender } = { 353 | female: PUPPET.types.ContactGender.Female, 354 | male: PUPPET.types.ContactGender.Male, 355 | unknown: PUPPET.types.ContactGender.Unknown, 356 | } 357 | 358 | return { 359 | avatar : 'unknown', 360 | gender : genderStringToType[_rawPayload.sex]!, 361 | id : _rawPayload.user_id, 362 | name : _rawPayload.nickname, 363 | phone : ['unkown'], 364 | type : PUPPET.types.Contact.Individual, 365 | } 366 | } 367 | 368 | override friendshipAccept (_friendshipId: string): Promise { 369 | throw new Error('Method not implemented.') 370 | } 371 | 372 | override friendshipAdd (_contactId: string, _option?: PUPPET.types.FriendshipAddOptions): Promise { 373 | throw new Error('Method not implemented.') 374 | } 375 | 376 | override friendshipSearchPhone (_phone: string): Promise { 377 | throw new Error('Method not implemented.') 378 | } 379 | 380 | override friendshipSearchWeixin (_weixin: string): Promise { 381 | throw new Error('Method not implemented.') 382 | } 383 | 384 | override friendshipRawPayload (_friendshipId: string): Promise { 385 | throw new Error('Method not implemented.') 386 | } 387 | 388 | override friendshipRawPayloadParser (_rawPayload: any): Promise { 389 | throw new Error('Method not implemented.') 390 | } 391 | 392 | override conversationReadMark (_conversationId: string, _hasRead?: boolean): Promise { 393 | throw new Error('Method not implemented.') 394 | } 395 | 396 | override messageContact (_messageId: string): Promise { 397 | throw new Error('Method not implemented.') 398 | } 399 | 400 | override messageFile (_messageId: string): Promise { 401 | throw new Error('Method not implemented.') 402 | } 403 | 404 | override messageImage (_messageId: string, _imageType: PUPPET.types.Image): Promise { 405 | throw new Error('Method not implemented.') 406 | } 407 | 408 | override messageMiniProgram (_messageId: string): Promise { 409 | throw new Error('Method not implemented.') 410 | } 411 | 412 | override messageUrl (_messageId: string): Promise { 413 | throw new Error('Method not implemented.') 414 | } 415 | 416 | override messageForward (_conversationId: string, _messageId: string): Promise { 417 | throw new Error('Method not implemented.') 418 | } 419 | 420 | override messageRecall (_messageId: string): Promise { 421 | throw new Error('Method not implemented.') 422 | } 423 | 424 | override roomInvitationAccept (_roomInvitationId: string): Promise { 425 | throw new Error('Method not implemented.') 426 | } 427 | 428 | override roomInvitationRawPayload (_roomInvitationId: string): Promise { 429 | throw new Error('Method not implemented.') 430 | } 431 | 432 | override roomInvitationRawPayloadParser (_rawPayload: any): Promise { 433 | throw new Error('Method not implemented.') 434 | } 435 | 436 | override roomAdd (_roomId: string, _contactId: string, _inviteOnly?: boolean): Promise { 437 | throw new Error('Method not implemented.') 438 | } 439 | 440 | override roomAvatar (_roomId: string): Promise { 441 | throw new Error('Method not implemented.') 442 | } 443 | 444 | override roomCreate (_contactIdList: string[], _topic?: string): Promise { 445 | throw new Error('Method not implemented.') 446 | } 447 | 448 | override roomDel (_roomId: string, _contactId: string): Promise { 449 | throw new Error('Method not implemented.') 450 | } 451 | 452 | override async roomList (): Promise { 453 | log.verbose('PuppetOICQ', 'roomList()') 454 | // TODO: implement 455 | return [] 456 | } 457 | 458 | override roomQRCode (_roomId: string): Promise { 459 | throw new Error('Method not implemented.') 460 | } 461 | 462 | override roomQuit (_roomId: string): Promise { 463 | throw new Error('Method not implemented.') 464 | } 465 | 466 | override roomTopic(roomId: string): Promise 467 | override roomTopic(roomId: string, topic: string): Promise 468 | override roomTopic (_roomId: any, _topic?: any): Promise | Promise { 469 | throw new Error('Method not implemented.') 470 | } 471 | 472 | override roomRawPayload (_roomId: string): Promise { 473 | log.verbose('PuppetOICQ', 'roomRawPayload(%s)', _roomId) 474 | return this.roomStore[_roomId]! 475 | } 476 | 477 | override roomRawPayloadParser (_rawPayload: any): Promise { 478 | log.verbose('PuppetOICQ', 'roomRawPayloadParser(%s)', _rawPayload) 479 | return _rawPayload 480 | } 481 | 482 | override roomAnnounce(roomId: string): Promise 483 | override roomAnnounce(roomId: string, text: string): Promise 484 | override roomAnnounce (_roomId: any, _text?: any): Promise | Promise { 485 | throw new Error('Method not implemented.') 486 | } 487 | 488 | override async roomMemberList (_roomId: string): Promise { 489 | log.verbose('PuppetOICQ', 'roomMemberList(%s)', _roomId) 490 | return [] 491 | } 492 | 493 | override roomMemberRawPayload (_roomId: string, _contactId: string): Promise { 494 | throw new Error('Method not implemented.') 495 | } 496 | 497 | override roomMemberRawPayloadParser (_rawPayload: any): Promise { 498 | throw new Error('Method not implemented.') 499 | } 500 | 501 | } 502 | 503 | export type { 504 | PuppetOICQOptions, 505 | } 506 | export { PuppetOICQ } 507 | export default PuppetOICQ 508 | --------------------------------------------------------------------------------