diff --git a/.github/workflows/node.js.yml b/.github/workflows/node.js.yml index ea94dd5..0d49afe 100644 --- a/.github/workflows/node.js.yml +++ b/.github/workflows/node.js.yml @@ -14,6 +14,8 @@ on: jobs: build: + permissions: + contents: read strategy: matrix: os: diff --git a/.markdownlint.json b/.markdownlint.json new file mode 100644 index 0000000..be4598c --- /dev/null +++ b/.markdownlint.json @@ -0,0 +1,18 @@ +{ + "default": true, + "no-trailing-punctuation": { + "punctuation": ".,;:!" + }, + "MD013": false, + "MD033": { + "allowed_elements": ["dl", "dt", "dd", "code", "var", "cite", "div", "a", "img"] + }, + "MD055": false, + "MD059": false, + "MD060": false, + "first-line-h1": false, + "no-hard-tabs": true, + "no-trailing-spaces": { + "br_spaces": 2 + } +} diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..4a99771 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,15 @@ +# Instructions for coding agents + +- This repository is ESM-only (`"type": "module"`) and targets Node.js 26+ and npm 10+ via `engines`. Do not add `package-lock.json` (see `DEVELOPMENT.md`). +- Node.js runs `.ts` sources directly with built-in type stripping; compilation to `dist/` happens only via `npm run build`. +- Relative imports must end in `.ts`, type-only imports must use `import type` or inline `type` modifiers (`verbatimModuleSyntax`), and only erasable TypeScript syntax is allowed (`erasableSyntaxOnly`: no enums, value namespaces, or constructor parameter properties). +- Prefer WinterTC web-standard APIs (`fetch`, `URL`, `URLSearchParams`, `AbortController`, `EventTarget`) over Node-only legacy packages when writing or updating examples and tests. +- Write portable smoke tests using `node:test` and `node:assert/strict` in `tests/*.test.ts`. Register `t.after()` cleanup before starting bots. +- Keep `npm run lint` (`lint:biome`, `lint:ts`, `lint:md`), `npm run build`, and `npm test` passing. +- Reference GitHub Actions by version tags (for example, `@v7`), not commit hashes. + +### Source Code Documentation (AI-First) + +- Begin each source and test file with a concise header comment explaining why it exists and what it owns. +- Document exported functions and nontrivial helpers with TSDoc-compatible `/** ... */` comments. +- Keep documentation accurate and concise; update comments whenever code changes. diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index aa44dc6..cf15f20 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -1,8 +1,9 @@ # DEVELOPMENT -This repository is the Wechaty getting-started tutorial. Its toolchain follows -[wechaty/wechaty](https://github.com/wechaty/wechaty) 2.0. The bot examples stay -on the Wechaty 1.x API (`wechaty` `^1.20.2`). +This repository is the Wechaty getting-started tutorial. Its toolchain and +starter bots follow [wechaty/wechaty](https://github.com/wechaty/wechaty) 2.0 +(`wechaty` `>=2.0.0-0 <3`). `examples/cqrs` is kept for a future Wechaty 2 +upgrade and is excluded from the root `tsconfig.json`. ## Node, TypeScript, and modules @@ -28,9 +29,7 @@ TypeScript's semantic check remains required. Type stripping does not check types, so a file that Node.js can execute is not a substitute for `npm run lint:ts`. Deno runs with `--no-check` for the same reason. -`examples/third-parties/maodou` and `examples/third-parties/xiaoli` keep their -own `package.json` and their own dependencies. Root `npm install` does not -install those modules, and root `tsc` does not include them. +`examples/cqrs` is excluded from `tsconfig.json` until its Wechaty 2 upgrade. ## Why `package-lock.json` is not committed @@ -47,10 +46,10 @@ off, because there is no lockfile to cache from. ## Tests -Smoke tests use `node:test` and `node:assert/strict`. `npm test` lints, then -runs `tests/*.test.ts` with Node.js directly. The runner uses -`--test-force-exit` because a puppet can leave sockets open after `bot.stop()`, -and `--test-timeout=180000` because a scan can take up to two minutes. +Smoke tests use `node:test` and `node:assert/strict`, registering `t.after()` +cleanup before starting bots. `npm test` lints (`lint:biome`, `lint:ts`, +`lint:md`), then runs `tests/*.test.ts` with Node.js directly. The runner uses +`--test-timeout=180000` because a scan can take up to two minutes. The same suite has an experimental Deno 2.9.8 job, `npm run test:unit:deno`. Deno is not a supported runtime yet. That CI job diff --git a/README.md b/README.md index a7e0714..de4868d 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ This repository tracks Wechaty 2. It needs Node.js 26 or newer and TypeScript 7. ### Wechaty Getting Started video tutorial
- +Wechaty Getting Started video tutorial
Above is a short run-through of the ding-dong bot. @@ -106,7 +106,7 @@ You are all set! #### Step 4: Troubleshooting -If you run into problems while following the above steps, check the items below. You are also welcome to ask questions in our [gitter chatroom](https://gitter.im/wechaty/wechaty). +If you run into problems while following the above steps, check the items below. You are also welcome to ask questions in our [Discord community](https://discord.gg/7q8NBZbQzt). 1. `node -v` is v26 or newer, and `npm -v` is 10 or newer. 1. On Linux, `ldd --version` reports glibc 2.38 or newer. @@ -137,7 +137,7 @@ Learn more about installing Wechaty on windows from this [blog post](https://wec ### 1. Wechaty Tutorial
- +Wechaty 10 minute video tutorial
Above is a 10 minute video tutorial. It is using version 0.14 or older versions of Wechaty therefore it is also outdated. It is a good way to start if you are new to Wechaty. @@ -146,9 +146,19 @@ Above is a 10 minute video tutorial. It is using version 0.14 or older versions > Note: Before you attempt more examples, make sure you have tried out the wechaty getting started project in this repository. -- [Official Wechaty Examples Directory](https://github.com/wechaty/getting-started/tree/master/examples) +- [Official Wechaty Examples Directory](https://github.com/wechaty/getting-started/tree/main/examples) -The files under `examples/` other than the two starter bots are v1-era samples. The root package does not install them. +`examples/cqrs/` is kept for a future Wechaty 2 upgrade and is excluded from the root TypeScript check. + +#### Verification + +Run linting, TypeScript checks, and smoke tests locally: + +```sh +npm run lint +npm test +npm run test:unit:deno +``` ## API REFERENCE diff --git a/biome.json b/biome.json index ab2aaf6..7e54633 100644 --- a/biome.json +++ b/biome.json @@ -1,5 +1,5 @@ { - "$schema": "https://biomejs.dev/schemas/2.6.8/schema.json", + "$schema": "https://biomejs.dev/schemas/2.6.9/schema.json", "vcs": { "enabled": true, "clientKind": "git", diff --git a/examples/README.md b/examples/README.md index d6aad8b..26b4c80 100644 --- a/examples/README.md +++ b/examples/README.md @@ -1,60 +1,23 @@ -# WECHATY OFFICIAL EXAMPLES LIST DIRECTORY +# Wechaty Official Examples Directory -The `wechaty-getting-started/examples` directory is provided for people who want to learn coding wechaty, for them to get an easier start. If you start coding wechaty for the first time, we highly recommend to start with the [ding-dong-bot.ts](basic/ding-dong-bot.ts), the best starter template for you. +The `examples/` directory provides starter bots for learning Wechaty 2 with Node.js 26 and TypeScript 7. If you are new to Wechaty, start with [ding-dong-bot.ts](ding-dong-bot.ts). -The starter bots, [ding-dong-bot.ts](ding-dong-bot.ts) and [ding-dong-bot.js](basic/ding-dong-bot.js), run on Wechaty 2 with Puppet Neo. The other files in this directory are v1-era samples. The root `package.json` does not install them. +## Starter & Basic Examples -| Filename | Description | 描述 | -| --- | --- | --- | -| ding-dong-bot.ts | The Best Starter Template for You | | +| Filename | Description | +| --- | --- | +| [ding-dong-bot.ts](ding-dong-bot.ts) | Recommended starter template using `PuppetNeo` | +| [basic/ding-dong-bot.ts](basic/ding-dong-bot.ts) | Basic ding-dong bot with `PuppetNeo` | +| [basic/the-worlds-shortest-chatbot-code-in-6-lines.ts](basic/the-worlds-shortest-chatbot-code-in-6-lines.ts) | Minimal 6-line Wechaty chatbot example | -Moreover, +## CQRS (Pending Upgrade) -- All the other examples have been carefully arranged into different categories so as to better guide you for what to choose/see, as you move along. -- In order to keep things simple, we just put the examples in the subdirectory of the examples/ directory, so that they each can just run out-of-the-box. -- We also recommend that you at least read through them all, before starting coding, for a even better, smoother ride. -- More demos are welcome. If you have anything interesting to add, please don't hesitate to reach out to us. +| Filename | Description | +| --- | --- | +| [cqrs/ding-dong-bot.ts](cqrs/ding-dong-bot.ts) | CQRS ding-dong bot example (excluded from root `tsconfig.json` pending Wechaty 2 upgrade) | -## 1. BASIC +## Tutorials -Wechaty Basic Functions (demos under the `basic/` directory) - -| FileName | Description | 描述 | -| --- | --- | --- | -| the-worlds-shortest-chatbot-code-in-6-lines.ts | The very first wechaty example showcasing how easy it is to get started | | -| ding-dong-bot.ts | Practical example illustrates on how to do message handling | | -| contact-bot.ts | List all contacts by Wechat ID & Name | 在终端下输出微信号下所有联系的人微信ID和昵称。| - -## 2. ADVANCED - -Wechaty Advanced Functions (demos under the `advanced/` directory) - -| FileName | Description | 描述 | -| --- | --- | --- | -| demo-in-tutorial.ts | the demo bot from the tutorial | | -| busy-bot.ts | auto response "busy" message for you when you are | | -| media-file-bot.ts | Save Media Attachment in Message to local files | 将消息中的文件、图片、视频等非文本信息存到本地。 | -| room-bot.ts,room-say-cli.ts | Practical example illustrates on how to do room handling | | -| friend-bot.ts | Practical example illustrates on how to do friend handling | | -| gist-bot/ | Best template for bigger modules, with each handler in separated files | | - -## 3. PROFESSIONAL - -Wechaty Integrated with Other Modules/Services (demos under the `professional/` directory) - -| FileName | Description | 描述 | -| --- | --- | --- | -| ctrl-c-signal-bot.ts | Ctrl-C signal handling demo | | -| api-ai-bot.ts | Wechaty bot that uses ApiAi.com brain | | -| speech-to-text-bot.ts | bot that uses baidu speech (vop.baidu.com) | | -| tuling123-bot.ts | Connect to [tuling123](http://www.tuling123.com/) chatbot | 接入[tuling123机器人](http://www.tuling123.com/) | -| telegram-roger-bot.ts | single bot that runs under/for both Telegram and WeChaty | | -| blessed-twins-bot/ | Wechaty multi-instance support (v0.16+) demo | | - -## Multi-lang Wechaty Examples Directories - -1. Python: -1. Java: -1. Go: - -I hope you will enjoy them, cheers! +| Filename | Description | +| --- | --- | +| [tutorials/google-cloud-shell-tutorial.md](tutorials/google-cloud-shell-tutorial.md) | Interactive Google Cloud Shell walkthrough | diff --git a/examples/advanced/busy-bot.ts b/examples/advanced/busy-bot.ts deleted file mode 100755 index 9fd3124..0000000 --- a/examples/advanced/busy-bot.ts +++ /dev/null @@ -1,176 +0,0 @@ -#!/usr/bin/env node -/** - * Wechaty - https://github.com/chatie/wechaty - * - * @copyright 2016-2018 Huan LI - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -import qrTerm from 'qrcode-terminal' - -import { - IoClient, - WechatyBuilder, - config, - log, - type Wechaty, -} from 'wechaty' - -console.log(` -=============== Powered by Wechaty =============== --------- https://github.com/Chatie/wechaty -------- - -I'm the BUSY BOT, I can do auto response message for you when you are BUSY. - -Send command to FileHelper to: - -1. '#busy' - set busy mode ON -2. '#busy I'm busy' - set busy mode ON and set a Auto Reply Message -3. '#free' - set busy mode OFF -4. '#status' - check the current Busy Mode and Auto Reply Message. - -Loading... please wait for QrCode Image Url and then scan to login. -`) - -let bot: Wechaty - -const token = config.token - -if (token) { - log.info('Wechaty', 'TOKEN: %s', token) - - bot = WechatyBuilder.build({ name: token, ioToken: token }) - const ioClient = new IoClient({ - token, - wechaty: bot, - }) - - ioClient.start().catch(e => { - log.error('Wechaty', 'IoClient.init() exception: %s', e) - const error = e instanceof Error ? e : new Error(String(e)) - ;(bot as unknown as { emit: (event: 'error', error: Error) => void }).emit('error', error) - }) -} else { - log.verbose('Wechaty', 'TOKEN: N/A') - bot = WechatyBuilder.build() -} - -bot -.on('scan', (qrcode, status) => { - qrTerm.generate(qrcode, { small: true }) - console.log(`${status}: ${qrcode} - Scan QR Code of the url to login:`) -}) -.on('logout' , user => log.info('Bot', `${user.name()} logouted`)) -.on('error' , e => log.info('Bot', 'error: %s', e)) - -.on('login', async function(user) { - const msg = `${user.name()} logined` - - log.info('Bot', msg) - await bot.say(msg) - -}) - -/** - * Global Event: message - */ - -let busyIndicator = false -let busyAnnouncement = `Automatic Reply: I cannot read your message because I'm busy now, will talk to you when I get back.` - -bot.on('message', async function(msg) { - log.info('Bot', '(message) %s', msg) - - const filehelper = await bot.Contact.find({ id: 'filehelper' }) - - const sender = msg.from() - const receiver = msg.to() - const text = msg.text() - const room = msg.room() - - // if (msg.age() > 60) { - // log.info('Bot', 'on(message) skip age(%d) > 60 seconds: %s', msg.age(), msg) - // return - // } - - if (!sender || !receiver) { - return - } - - if (receiver.id === 'filehelper') { - if (!filehelper) { - log.error('Bot', 'filehelper contact is not available') - return - } - if (text === '#status') { - await filehelper.say('in busy mode: ' + busyIndicator) - await filehelper.say('auto reply: ' + busyAnnouncement) - - } else if (text === '#free') { - busyIndicator = false - await filehelper.say('auto reply stopped.') - - } else if (/^#busy/i.test(text)) { - - busyIndicator = true - await filehelper.say('in busy mode: ' + 'ON') - - const matches = text.match(/^#busy (.+)$/i) - if (!matches || !matches[1]) { - await filehelper.say('auto reply message: "' + busyAnnouncement + '"') - - } else { - busyAnnouncement = matches[1] - await filehelper.say('set auto reply to: "' + busyAnnouncement + '"') - - } - } - - return - } - - if (sender.type() !== bot.Contact.Type.Individual) { - return - } - - if (!busyIndicator) { - return // free - } - - if (msg.self()) { - return - } - - /** - * 1. Send busy anoncement to contact - */ - if (!room) { - await msg.say(busyAnnouncement) - return - } - - /** - * 2. If there's someone mentioned me in a room, - * then send busy annoncement to room and mention the contact who mentioned me. - */ - const contactList = await msg.mention() - const contactIdList = contactList.map(c => c.id) - if (contactIdList.includes(bot.currentUser.id)) { - await room.say(busyAnnouncement, sender) - } - -}) - -bot.start() -.catch(e => console.error(e)) diff --git a/examples/advanced/demo-in-tutorial.ts b/examples/advanced/demo-in-tutorial.ts deleted file mode 100755 index 3101781..0000000 --- a/examples/advanced/demo-in-tutorial.ts +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/env node -import qrTerm from 'qrcode-terminal' - -import { - WechatyBuilder, - types, - type Contact, - type Friendship, - type Message, - type ScanStatus, -} from 'wechaty' - -const bot = WechatyBuilder.build() - -bot.on('scan', function (qrcode: string, _status: ScanStatus) { - qrTerm.generate(qrcode, { small: true }) -}) - -bot.on('login', function (user: Contact) { - console.log(`${user} login`) -}) - -bot.on('logout', function (user: Contact) { - console.log(`${user} logout`) -}) - -bot.on('friendship', async function (friendship: Friendship) { - console.log(`get FRIENDSHIP event!`) - - switch (friendship.type()) { - case types.Friendship.Receive: - await friendship.accept() - console.log(`accept friendship!`) - break - case types.Friendship.Confirm: - await friendship.contact().say(`Nice to meet you~`) - break - } -}) - -bot.on('message', async function (msg: Message) { - const contact = msg.from() - const text = msg.text() - const room = msg.room() - - if (msg.self() || !contact) { - return - } - - if (room) { - const topic = await room.topic() - console.log(`Room: ${topic} Contact: ${contact.name()} Text: ${text}`) - } else { - console.log(`Contact: ${contact.name()} Text: ${text}`) - } - - if (/Hello/.test(text)) { - await msg.say('Welcome to wechaty, I am wechaty bot RUI!') - } - - if (/room/.test(text)) { - const keyroom = await bot.Room.find({topic: 'wechaty test room'}) - - if (keyroom) { - const topic = await keyroom.topic() - await keyroom.add(contact) - await keyroom.say(`Welcome to join ${topic}`, contact) - } - } - - if (/fword/.test(text)) { - const keyroom = await bot.Room.find({topic: 'wechaty test room'}) - - if (keyroom) { - await keyroom.say('You said fword, I will remove from the room', contact) - await keyroom.del(contact as never) - } - } - -}) - -bot.start() - .catch(console.error) diff --git a/examples/advanced/dump-room-member.ts b/examples/advanced/dump-room-member.ts deleted file mode 100755 index 8aa0eff..0000000 --- a/examples/advanced/dump-room-member.ts +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env node -/** - * Wechaty - Conversational RPA SDK for Chatbot Makers. - * - https://github.com/wechaty/wechaty - */ -import { - ScanStatus, - WechatyBuilder, - log, - type Contact, -} from 'wechaty' - -import qrcodeTerminal from 'qrcode-terminal' - -function onScan (qrcode: string, status: ScanStatus) { - if (status === ScanStatus.Waiting || status === ScanStatus.Timeout) { - const qrcodeImageUrl = [ - 'https://wechaty.js.org/qrcode/', - encodeURIComponent(qrcode), - ].join('') - log.info('DumpRoomMemberBot', 'onScan: %s(%s) - %s', ScanStatus[status], status, qrcodeImageUrl) - - qrcodeTerminal.generate(qrcode, { small: true }) // show qrcode on console - - } else { - log.info('DumpRoomMemberBot', 'onScan: %s(%s)', ScanStatus[status], status) - } -} - -function onLogin (user: Contact) { - log.info('DumpRoomMemberBot', '%s login', user) -} - -const bot = WechatyBuilder.build({ - name: 'ding-dong-bot', - puppet: 'wechaty-puppet-wechat', -}) - -const onReady = async () => { - log.info('DumpRoomMemberBot', '%s ready', bot.name()) - - const roomTopicRegex = /TEEC人工智能委员会/ - - const dump = async () => { - const room = await bot.Room.find({ topic: roomTopicRegex }) - if (!room) { - log.error('DumpRoomMemberBot', 'no room found, wait 3 seconds') - log.info('DumpRoomMemberBot', 'Tip: if you are using web protocol, you can try to say something in the room so that the puppet can discover it') - setTimeout(dump, 3 * 1000) - return - } - - log.info('DumpRoomMemberBot', 'dumping members for room: %s ...', room) - for await (const member of room) { - console.info(member.name()) - } - log.info('DumpRoomMemberBot', 'dumping members for room: %s ... done', room) - - process.exit(0) - } - - dump() -} - -bot.on('scan', onScan) -bot.on('login', onLogin) -bot.on('ready', onReady) - -bot.start() - .then(() => log.info('DumpRoomMemberBot', 'DumpRoomMember Bot Started.')) - .catch(e => log.error('DumpRoomMemberBot', e)) diff --git a/examples/advanced/friend-bot.ts b/examples/advanced/friend-bot.ts deleted file mode 100755 index 43dc67b..0000000 --- a/examples/advanced/friend-bot.ts +++ /dev/null @@ -1,132 +0,0 @@ -#!/usr/bin/env node -/** - * Wechaty - https://github.com/chatie/wechaty - * - * @copyright 2016-2018 Huan LI - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -/* tslint:disable:variable-name */ -import qrTerm from 'qrcode-terminal' - -import { - log, - types, - WechatyBuilder, -} from 'wechaty' - -const welcome = ` -=============== Powered by Wechaty =============== --------- https://github.com/Chatie/wechaty -------- - -Hello, - -I'm a Wechaty Botie with the following super powers: - -1. Send Friend Request -2. Accept Friend Request -3. Recongenize Verify Message - -If you send friend request to me, -with a verify message 'ding', -I will accept your request automaticaly! -__________________________________________________ - -Hope you like it, and you are very welcome to -upgrade me for more super powers! - -Please wait... I'm trying to login in... - -` - -console.log(welcome) -const bot = WechatyBuilder.build({ name: 'friend-bot' }) - -bot -.on('login' , user => log.info('Bot', `${user.name()} logined`)) -.on('logout' , user => log.info('Bot', `${user.name()} logouted`)) -.on('error' , e => log.info('Bot', 'error: %s', e)) -.on('scan', (qrcode, status) => { - qrTerm.generate(qrcode) - console.log(`${qrcode}\n[${status}] Scan QR Code in above url to login: `) -}) -/** - * - * Wechaty Event: `friend` - * - */ -.on('friendship', async friendship => { - let logMsg - const fileHelper = await bot.Contact.find({ id: 'filehelper' }) - - try { - logMsg = 'received `friend` event from ' + friendship.contact().name() - if (fileHelper) { - await fileHelper.say(logMsg) - } else { - log.error('Bot', 'filehelper contact is not available') - } - console.log(logMsg) - - switch (friendship.type()) { - /** - * - * 1. New Friend Request - * - * when request is set, we can get verify message from `request.hello`, - * and accept this request by `request.accept()` - */ - case types.Friendship.Receive: - if (friendship.hello() === 'ding') { - logMsg = 'accepted automatically because verify messsage is "ding"' - console.log('before accept') - await friendship.accept() - - // if want to send msg , you need to delay sometimes - await new Promise(r => setTimeout(r, 1000)) - await friendship.contact().say('hello from Wechaty') - console.log('after accept') - - } else { - logMsg = 'not auto accepted, because verify message is: ' + friendship.hello() - } - break - - /** - * - * 2. Friend Ship Confirmed - * - */ - case types.Friendship.Confirm: - logMsg = 'friend ship confirmed with ' + friendship.contact().name() - break - } - } catch (e) { - logMsg = e instanceof Error ? e.message : String(e) - } - - console.log(logMsg) - if (fileHelper && logMsg) { - await fileHelper.say(logMsg) - } - -}) - -bot.start() -.catch(async e => { - log.error('Bot', 'init() fail: %s', e) - await bot.stop() - process.exit(-1) -}) diff --git a/examples/advanced/gist-bot/index.ts b/examples/advanced/gist-bot/index.ts deleted file mode 100755 index 309f1ab..0000000 --- a/examples/advanced/gist-bot/index.ts +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env node -/** - * Wechaty - https://github.com/chatie/wechaty - * - * @copyright 2016-2018 Huan LI - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -import { - WechatyBuilder, - log, -} from 'wechaty' - -import { onMessage } from './on-message.ts' -import { onFriendship } from './on-friend.ts' -import { onRoomJoin } from './on-room-join.ts' - -import qrTerm from 'qrcode-terminal' - -const welcome = ` -=============== Powered by Wechaty =============== --------- https://github.com/Chatie/wechaty -------- - -Please wait... I'm trying to login in... - -` -console.info(welcome) - -const bot = WechatyBuilder.build({ name: 'gist-bot' }) - -bot - .on('scan', (qrcode, status) => { - qrTerm.generate(qrcode) - console.info(`${qrcode}\n[${status}] Scan QR Code in above url to login: `) - }) - - .on('login', async function (user) { - log.info('Bot', `${user.name()} logined`) - await bot.say(`wechaty logined`) - }) - - .on('logout', user => log.info('Bot', `${user.name()} logouted`)) - .on('error', error => log.info('Bot', 'error: %s', error)) - - .on('message', message => onMessage.call(bot, message)) - .on('friendship', friendship => onFriendship.call(bot, friendship)) - .on('room-join', (room, inviteeList, inviter) => onRoomJoin.call(bot, room, inviteeList, inviter)) - - .start() - .catch(e => console.error(e)) diff --git a/examples/advanced/gist-bot/on-friend.ts b/examples/advanced/gist-bot/on-friend.ts deleted file mode 100644 index d8f4f52..0000000 --- a/examples/advanced/gist-bot/on-friend.ts +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Wechaty - https://github.com/chatie/wechaty - * - * @copyright 2016-2018 Huan LI - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -import { - types, - type Friendship, - type Wechaty, -} from 'wechaty' - -export async function onFriendship ( - this: Wechaty, - request: Friendship, -) { - try { - const contact = request.contact() - - if (request.type() === types.Friendship.Confirm) { - console.info('New friend ' + contact.name() + ' relationship confirmed!') - return - } - - /******************************************** - * - * 从这里开始修改 vvvvvvvvvvvv - * - */ - await request.accept() - - setTimeout( - async () => { - await contact.say('thank you for adding me') - }, - 3000, - ) - - if (request.hello() === 'ding') { - const myRoom = await this.Room.find({ topic: 'ding' }) - if (!myRoom) return - setTimeout( - async () => { - await myRoom.add(contact) - await myRoom.say('welcome ' + contact.name()) - }, - 3000, - ) - } - - /** - * - * 到这里结束修改 ^^^^^^^^^^^^ - * - */ - /*******************************************/ - } catch (e) { - console.info(e) - } -} - -export default onFriendship diff --git a/examples/advanced/gist-bot/on-message.ts b/examples/advanced/gist-bot/on-message.ts deleted file mode 100644 index 3f5e580..0000000 --- a/examples/advanced/gist-bot/on-message.ts +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Wechaty - https://github.com/chatie/wechaty - * - * @copyright 2016-2018 Huan LI - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -import { - type Message, - type Wechaty, -} from 'wechaty' - -export async function onMessage(this: Wechaty, message: Message) { - try { - const room = message.room() - const sender = message.from() - const content = message.text() - - console.info((room ? '[' + await room.topic() + ']' : '') - + '<' + (sender && sender.name()) + '>' - + ':' + message, - ) - - if (message.self() || room) { - console.info('message is sent from myself, or inside a room.') - return - } - - /******************************************** - * - * 从下面开始修改vvvvvvvvvvvv - * - */ - if (!sender) return - - if (content === 'ding') { - await message.say('thanks for ding me') - - const myRoom = await this.Room.find({ topic: 'ding' }) - if (!myRoom) return - - if (await myRoom.has(sender)) { - await sender.say('no need to ding again, because you are already in ding room') - return - } - - await sender.say('ok, I will put you in ding room!') - await myRoom.add(sender) - return - - } else if (content === 'dong') { - await sender.say('ok, dong me is welcome, too.') - return - } - - /** - * - * 到这里结束修改^^^^^^^^^^^^ - * - */ - /*********************************************/ - } catch (e) { - console.error(e) - } -} - -export default onMessage diff --git a/examples/advanced/gist-bot/on-room-join.ts b/examples/advanced/gist-bot/on-room-join.ts deleted file mode 100644 index 18d08dd..0000000 --- a/examples/advanced/gist-bot/on-room-join.ts +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Wechaty - https://github.com/chatie/wechaty - * - * @copyright 2016-2018 Huan LI - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -import { - type Contact, - type Room, - type Wechaty, -} from 'wechaty' - -export async function onRoomJoin ( - this: Wechaty, - room: Room, - inviteeList: Contact[], - inviter: Contact, -) { - try { - const inviteeName = inviteeList.map(c => c.name()).join(', ') - /******************************************** - * - * 从这里开始修改 vvvvvvvvvvvv - * - */ - - if (await room.topic() !== 'ding') { - await this.say('Room ' + await room.topic() - + ' got new memeber ' + inviteeName - + ' invited by ' + inviter.name(), - ) - return - } - - const inviterIsMyself = inviter.self() - - if (inviterIsMyself) { - await room.say('Welcome to my room: ' + inviteeName) - return - } - - await room.say('请勿私自拉人。需要拉人请加我', inviter) - await room.say('请先加我好友,然后我来拉你入群。先把你移出啦。', ...inviteeList) - - inviteeList.forEach(async c => { - await room.del(c as never) - }) - - /** - * - * 到这里结束修改^^^^^^^^^^^^ - * - */ - /*********************************************/ - - } catch (e) { - console.info(e) - } - -} - -export default onRoomJoin diff --git a/examples/advanced/media-file-bot.ts b/examples/advanced/media-file-bot.ts deleted file mode 100755 index 38e1821..0000000 --- a/examples/advanced/media-file-bot.ts +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env node -import qrTerm from 'qrcode-terminal' - -import { - WechatyBuilder, - types, - type Contact, - type Message, - type ScanStatus, -} from 'wechaty' - -const welcome = ` -=============== Powered by Wechaty =============== --------- https://github.com/chatie/wechaty -------- - -I'm a bot, I can save file to local for you! -__________________________________________________ - -Please wait... I'm trying to login in... - -` -console.log(welcome) - -const bot = WechatyBuilder.build() - -bot.on('scan', onScan) -bot.on('login', onLogin) -bot.on('logout', onLogout) -bot.on('message', onMessage) -bot.on('error', onError) - -bot.start() - .catch(console.error) - -function onScan (qrcode: string, _status: ScanStatus) { - qrTerm.generate(qrcode, { small: true }) // show qrcode on console -} - -function onLogin (user: Contact) { - console.log(`${user} login`) -} - -function onLogout (user: Contact) { - console.log(`${user} logout`) -} - -function onError (e: unknown) { - console.error(e) -} - -async function onMessage(msg: Message) { - console.log(`RECV: ${msg}`) - - if (msg.type() !== types.Message.Text) { - const file = await msg.toFileBox() - const name = file.name - console.log('Save file to: ' + name) - await file.toFile(name) - } -} diff --git a/examples/advanced/plugin-bot.ts b/examples/advanced/plugin-bot.ts deleted file mode 100755 index 1f52034..0000000 --- a/examples/advanced/plugin-bot.ts +++ /dev/null @@ -1,107 +0,0 @@ -#!/usr/bin/env node -/** - * Wechaty Chatbot SDK - https://github.com/wechaty/wechaty - * - * @copyright 2016 Huan LI (李卓桓) , and - * Wechaty Contributors . - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -import { - WechatyBuilder, - types, -} from 'wechaty' - -/** - * Wechaty Plugin Support with Kickout Example #1939 - * https://github.com/wechaty/wechaty/issues/1939 - */ -import { - QRCodeTerminal, - EventLogger, - DingDong, - OneToManyRoomConnector, - ManyToOneRoomConnector, - ManyToManyRoomConnector, -} from 'wechaty-plugin-contrib' -/** - * - * 1. Declare your Bot! - * - */ -const bot = WechatyBuilder.build({ - name : 'ding-dong-bot', -}) - -/** - * - * 2. Register event handlers for Bot - * - */ -bot.use( - QRCodeTerminal(), - EventLogger(), - DingDong(), - OneToManyRoomConnector({ - blacklist: [async () => true], - many: [ - '20049383519@chatroom', // 小句子测试 - '5611663299@chatroom', // 'ChatOps - Mike BO' - ], - map: async message => message.from()?.name() + '(one to many): ' + message.text(), - one: '17237607145@chatroom', // PreAngel 动态 - whitelist: [async message => message.type() === types.Message.Text], - }), - ManyToOneRoomConnector({ - blacklist: [async () => true], - many: [ - '20049383519@chatroom', // 小句子测试 - '5611663299@chatroom', // 'ChatOps - Mike BO' - ], - map: async message => message.from()?.name() + '(many to one): ' + message.text(), - one: '17237607145@chatroom', // PreAngel 动态 - whitelist: [async message => message.type() === types.Message.Text], - }), - ManyToManyRoomConnector({ - blacklist: [async () => true], - many: [ - '20049383519@chatroom', // 小句子测试 - '5611663299@chatroom', // 'ChatOps - Mike BO' - ], - map: async message => message.from()?.name() + '(many to many): ' + message.text(), - whitelist: [async message => message.type() === types.Message.Text], - }), - -) - -/** - * - * 3. Start the bot! - * - */ -bot.start() - .catch(async e => { - console.error('Bot start() fail:', e) - await bot.stop() - process.exit(-1) - }) - -bot.once('login', () => { - bot.Room.findAll().then(async roomList => { - for (const room of roomList) { - console.info(room.id, await room.topic()) - } - return undefined - }).catch(console.error) -}) diff --git a/examples/advanced/room-bot.ts b/examples/advanced/room-bot.ts deleted file mode 100755 index fd955d4..0000000 --- a/examples/advanced/room-bot.ts +++ /dev/null @@ -1,441 +0,0 @@ -#!/usr/bin/env node -/** - * Wechaty - https://github.com/chatie/wechaty - * - * @copyright 2016-2018 Huan LI - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -/** - * - * Known ISSUES: - * - BUG1: can't find member by this NickName: - * ' leaver: 艾静JOY - * - BUG2: leave event not right: sometimes can not found member (any more, because they left) - * create a room need at least three people - * when we create a room, the following one is the 3rd people. - * - * put name of one of your friend here, or room create function will not work. - * - * ::::::::: ___CHANGE ME___ ::::::::: - * vvvvvvvvv - * vvvvvvvvv - * vvvvvvvvv - */ -const HELPER_CONTACT_NAME = '李卓桓' - -/** - * ^^^^^^^^^ - * ^^^^^^^^^ - * ^^^^^^^^^ - * ::::::::: ___CHANGE ME___ ::::::::: - * - */ - -/* tslint:disable:variable-name */ -import qrTerm from 'qrcode-terminal' - -import { - WechatyBuilder, - log, - type Contact, - type Room, -} from 'wechaty' - -function errorDetail (e: unknown): string { - if (e instanceof Error) { - return e.stack ?? e.message - } - return String(e) -} - -const welcome = ` -=============== Powered by Wechaty =============== --------- https://github.com/Chatie/wechaty -------- - -Hello, - -I'm a Wechaty Botie with the following super powers: - -1. Find a room -2. Add people to room -3. Del people from room -4. Change room topic -5. Monitor room events -6. etc... - -If you send a message of magic word 'ding', -you will get a invitation to join my own room! -__________________________________________________ - -Hope you like it, and you are very welcome to -upgrade me for more super powers! - -Please wait... I'm trying to login in... - -` -console.log(welcome) -const bot = WechatyBuilder.build({ name: 'room-bot' }) - -bot -.on('scan', (qrcode, status) => { - qrTerm.generate(qrcode, { small: true }) - console.log(`${qrcode}\n[${status}] Scan QR Code in above url to login: `) -}) -.on('logout' , user => log.info('Bot', `"${user.name()}" logouted`)) -.on('error' , e => log.info('Bot', 'error: %s', e)) - -/** - * Global Event: login - * - * do initialization inside this event. - * (better to set a timeout, for browser need time to download other data) - */ -.on('login', async function(user) { - let msg = `${user.name()} logined` - - log.info('Bot', msg) - await bot.say(msg) - - msg = `setting to manageDingRoom() after 3 seconds ... ` - log.info('Bot', msg) - await bot.say(msg) - - setTimeout(manageDingRoom, 3000) -}) - -/** - * Global Event: room-join - */ -.on('room-join', async function(room, inviteeList, inviter) { - log.info( 'Bot', 'EVENT: room-join - Room "%s" got new member "%s", invited by "%s"', - await room.topic(), - inviteeList.map(c => c.name()).join(','), - inviter.name(), - ) - console.log('bot room-join room id:', room.id) - const topic = await room.topic() - const invitee = inviteeList[0] - if (invitee) { - await room.say(`welcome to "${topic}"!`, invitee) - } -}) - -/** - * Global Event: room-leave - */ -.on('room-leave', async function(room, leaverList) { - log.info('Bot', 'EVENT: room-leave - Room "%s" lost member "%s"', - await room.topic(), - leaverList.map(c => c.name()).join(','), - ) - const topic = await room.topic() - const name = leaverList[0] ? leaverList[0].name() : 'no contact!' - await room.say(`kick off "${name}" from "${topic}"!` ) -}) - -/** - * Global Event: room-topic - */ -.on('room-topic', async function(room, topic, oldTopic, changer) { - try { - log.info('Bot', 'EVENT: room-topic - Room "%s" change topic from "%s" to "%s" by member "%s"', - room, - oldTopic, - topic, - changer, - ) - await room.say(`room-topic - change topic from "${oldTopic}" to "${topic}" by member "${changer.name()}"` ) - } catch (e) { - log.error('Bot', 'room-topic event exception: %s', errorDetail(e)) - } -}) - -/** - * Global Event: message - */ -.on('message', async function(msg) { - if (msg.age() > 3 * 60) { - log.info('Bot', 'on(message) skip age("%d") > 3 * 60 seconds: "%s"', msg.age(), msg) - return - } - - const room = msg.room() - const from = msg.from() - const text = msg.text() - - if (!from) { - return - } - - console.log((room ? '[' + await room.topic() + ']' : '') - + '<' + from.name() + '>' - + ':' + msg, - ) - - if (msg.self()) { - return // skip self - } - - /** - * `dong` will be the magic(toggle) word: - * bot will quit current room by herself. - */ - if (/^dong$/i.test(text)) { - if (room) { - await room.say('You said dong in the room, I will quit by myself!', from) - await room.quit() - } else { - await from.say('Nothing to do. If you say "dong" in a room, I will quit from the room.') - } - return - } - - /** - * `ding` will be the magic(toggle) word: - * 1. say ding first time, will got a room invitation - * 2. say ding in room, will be removed out - */ - if (/^ding$/i.test(text)) { - - /** - * in-room message - */ - if (room) { - if (/^ding/i.test(await room.topic())) { - /** - * move contact out of room - */ - await getOutRoom(from, room) - } - - /** - * peer to peer message - */ - } else { - - /** - * find room name start with "ding" - */ - try { - const dingRoom = await bot.Room.find({ topic: /^ding/i }) - if (dingRoom) { - /** - * room found - */ - log.info('Bot', 'onMessage: got dingRoom: "%s"', await dingRoom.topic()) - - if (await dingRoom.has(from)) { - /** - * speaker is already in room - */ - const topic = await dingRoom.topic() - log.info('Bot', 'onMessage: sender has already in dingRoom') - await dingRoom.say(`I found you have joined in room "${topic}"!`, from) - await from.say(`no need to ding again, because you are already in room: "${topic}"`) - // sendMessage({ - // content: 'no need to ding again, because you are already in ding room' - // , to: sender - // }) - - } else { - /** - * put speaker into room - */ - log.info('Bot', 'onMessage: add sender("%s") to dingRoom("%s")', from.name(), dingRoom.topic()) - await from.say('ok, I will put you in ding room!') - await putInRoom(from, dingRoom) - } - - } else { - /** - * room not found - */ - log.info('Bot', 'onMessage: dingRoom not found, try to create one') - /** - * create the ding room - */ - const newRoom = await createDingRoom(from) - if (!newRoom) { - return - } - console.log('createDingRoom id:', newRoom.id) - /** - * listen events from ding room - */ - await manageDingRoom() - } - } catch (e) { - log.error('Bot', '%s', errorDetail(e)) - } - } - } -}) -.start() -.catch(e => console.error(e)) - -async function manageDingRoom() { - log.info('Bot', 'manageDingRoom()') - - /** - * Find Room - */ - try { - const room = await bot.Room.find({ topic: /^ding/i }) - if (!room) { - log.warn('Bot', 'there is no room topic ding(yet)') - return - } - log.info('Bot', 'start monitor "ding" room join/leave/topic event') - - /** - * Event: Join - */ - room.on('join', function(inviteeList, inviter) { - log.verbose('Bot', 'Room EVENT: join - "%s", "%s"', - inviteeList.map(c => c.name()).join(', '), - inviter.name(), - ) - console.log('room.on(join) id:', room.id) - void checkRoomJoin(room, inviteeList, inviter) - }) - - /** - * Event: Leave - */ - room.on('leave', (leaverList, remover) => { - log.info('Bot', 'Room EVENT: leave - "%s" leave(remover "%s"), byebye', leaverList.join(','), remover || 'unknown') - }) - - /** - * Event: Topic Change - */ - room.on('topic', (topic, oldTopic, changer) => { - log.info('Bot', 'Room EVENT: topic - changed from "%s" to "%s" by member "%s"', - oldTopic, - topic, - changer.name(), - ) - }) - } catch (e) { - log.warn('Bot', 'Room.find rejected: "%s"', errorDetail(e)) - } -} - -async function checkRoomJoin(room: Room, inviteeList: Contact[], inviter: Contact) { - log.info('Bot', 'checkRoomJoin("%s", "%s", "%s")', - await room.topic(), - inviteeList.map(c => c.name()).join(','), - inviter.name(), - ) - - try { - // let to, content - const userSelf = bot.currentUser - - if (inviter.id !== userSelf.id) { - - await room.say('RULE1: Invitation is limited to me, the owner only. Please do not invit people without notify me.', - inviter, - ) - await room.say('Please contact me: by send "ding" to me, I will re-send you a invitation. Now I will remove you out, sorry.', - ...inviteeList, - ) - - await room.topic('ding - warn ' + inviter.name()) - setTimeout( - () => inviteeList.forEach(c => { void room.del(c as never) }), - 10 * 1000, - ) - - } else { - - await room.say('Welcome to my room! :)') - - let welcomeTopic - welcomeTopic = inviteeList.map(c => c.name()).join(', ') - await room.topic('ding - welcome ' + welcomeTopic) - } - - } catch (e) { - log.error('Bot', 'checkRoomJoin() exception: %s', errorDetail(e)) - } - -} - -async function putInRoom(contact: Contact, room: Room) { - log.info('Bot', 'putInRoom("%s", "%s")', contact.name(), await room.topic()) - - try { - await room.add(contact) - setTimeout( - _ => room.say('Welcome ', contact), - 10 * 1000, - ) - } catch (e) { - log.error('Bot', 'putInRoom() exception: ' + errorDetail(e)) - } -} - -async function getOutRoom(contact: Contact, room: Room) { - log.info('Bot', 'getOutRoom("%s", "%s")', contact, room) - - try { - await room.say('You said "ding" in my room, I will remove you out.') - await room.del(contact as never) - } catch (e) { - log.error('Bot', 'getOutRoom() exception: ' + errorDetail(e)) - } -} - -function getHelperContact() { - log.info('Bot', 'getHelperContact()') - - // create a new room at least need 3 contacts - return bot.Contact.find({ name: HELPER_CONTACT_NAME }) -} - -async function createDingRoom(contact: Contact) { - log.info('Bot', 'createDingRoom("%s")', contact) - - try { - const helperContact = await getHelperContact() - - if (!helperContact) { - log.warn('Bot', 'getHelperContact() found nobody') - await contact.say(`You don't have a friend called "${HELPER_CONTACT_NAME}", - because create a new room at least need 3 contacts, please set [HELPER_CONTACT_NAME] in the code first!`) - return - } - - log.info('Bot', 'getHelperContact() ok. got: "%s"', helperContact.name()) - - const contactList = [contact, helperContact] - log.verbose('Bot', 'contactList: "%s"', contactList.join(',')) - - await contact.say(`There isn't ding room. I'm trying to create a room with "${helperContact.name()}" and you`) - const room = await bot.Room.create(contactList, 'ding') - log.info('Bot', 'createDingRoom() new ding room created: "%s"', room) - - await room.topic('ding - created') - await room.say('ding - created') - - return room - - } catch (e) { - log.error('Bot', 'getHelperContact() exception:', errorDetail(e)) - throw e - } -} diff --git a/examples/advanced/room-say-cli.ts b/examples/advanced/room-say-cli.ts deleted file mode 100755 index f63cc4d..0000000 --- a/examples/advanced/room-say-cli.ts +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env node -/** - * Wechaty - https://github.com/chatie/wechaty - * - * @copyright 2016-2018 Huan LI - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -/* tslint:disable:variable-name */ -import qrTerm from 'qrcode-terminal' - -import { - WechatyBuilder, - log, -} from 'wechaty' - -async function main () { - const bot = WechatyBuilder.build({ name: 'room-say-cli' }) - - bot - .on('scan', (qrcode, status) => { - qrTerm.generate(qrcode, { small: true }) - // Generate a QR Code online via - // http://goqr.me/api/doc/create-qr-code/ - const qrcodeImageUrl = [ - 'https://wechaty.js.org/qrcode/', - encodeURIComponent(qrcode), - ].join('') - console.log(`[${status}] ${qrcodeImageUrl}\nScan QR Code above to log in: `) - }) - .on('logout' , user => log.info('Bot', `"${user.name()}" logouted`)) - .on('error' , e => log.info('Bot', 'error: %s', e)) - - /** - * Global Event: login - * - * do initialization inside this event. - * (better to set a timeout, for browser need time to download other data) - */ - .on('login', user => { - console.log(`${user} logined`) - }) - - /** - * Global Event: message - */ - .on('message', async function(msg) { - console.log(msg.toString()) - }) - - await bot.start() - - const searchTopic = process.argv[2] - if (!searchTopic) { - throw new Error('no arg 1 defined as search topic!') - } - - const sayText = process.argv[3] - if (!sayText) { - throw new Error('no arg 2 defined as say text!') - } - - console.log('searching topic: ', searchTopic) - - const searchRegex = new RegExp(searchTopic) - - // wait the bot for logging in - while (!bot.isLoggedIn) { - await new Promise(r => setTimeout(r, 100)) - } - - const room = await bot.Room.find({ topic: searchRegex }) - - console.log(searchRegex) - - if (!room) { - console.log('not found') - return - } - - console.log(await room.topic(), 'found') - await room.say(sayText) - - return 0 -} - -main() -.then(process.exit) -.catch(e => { - console.error(e) - process.exit(1) -}) diff --git a/examples/advanced/self-testing-bot.ts b/examples/advanced/self-testing-bot.ts deleted file mode 100755 index 60c9d0b..0000000 --- a/examples/advanced/self-testing-bot.ts +++ /dev/null @@ -1,302 +0,0 @@ -#!/usr/bin/env node -/** - * Wechaty - https://github.com/chatie/wechaty - * - * @copyright 2016-2018 Huan LI - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -/* tslint:disable:variable-name */ -import qrTerm from 'qrcode-terminal' -import { FileBox } from 'file-box' - -import { - WechatyBuilder, - log, -} from 'wechaty' - -const BOT_QR_CODE_IMAGE_FILE_BOX = FileBox - .fromUrl('https://wechaty.js.org/img/friday-qrcode.svg') - -const bot = WechatyBuilder.build({ name: 'self-testing-bot' }) - -const welcome = ` -| __ __ _ _ -| \\ \\ / /__ ___| |__ __ _| |_ _ _ -| \\ \\ /\\ / / _ \\/ __| '_ \\ / _\` | __| | | | -| \\ V V / __/ (__| | | | (_| | |_| |_| | -| \\_/\\_/ \\___|\\___|_| |_|\\__,_|\\__|\\__, | -| |___/ - -=============== Powered by Wechaty =============== --------- https://github.com/chatie/wechaty -------- - Version: ${bot.version()} - -I'm a bot, my superpower is talk in Wechat. - -If you send me a 'ding', I will reply you a 'dong'! -__________________________________________________ - -Hope you like it, and you are very welcome to -upgrade me to more superpowers! - -Please wait... I'm trying to login in... - -` - -console.log(welcome) - -bot -.on('logout' , user => log.info('Bot', `${user.name()} logouted`)) -.on('login' , user => { - log.info('Bot', `${user.name()} login`) - bot.say('Wechaty login').catch(console.error) -}) -.on('scan', (qrcode, status) => { - qrTerm.generate(qrcode, { small: true }) - console.log(`${qrcode}\n[${status}] Scan QR Code in above url to login: `) -}) -.on('message', async msg => { - const from = msg.from() - - if (!from) { - log.info('Bot', 'on(message) skip no-from() message: %s', msg) - return - } - - if (msg.type() !== bot.Message.Type.Text) { - log.info('Bot', 'on(message) skip non-text message: %s', msg) - return - } - - if (msg.age() > 60) { - log.info('Bot', 'on(message) skip message older(%d) than 60 seconds: %s', msg.age(), msg) - return - } - - try { - console.log(msg.toString()) // on(message) exception: Error: no file - const text = msg.text() - - // Room.findAll() - if (/^testRoom$/i.test(text)) { - const roomList = await bot.Room.findAll() - const topicList = await Promise.all( - roomList.map(async room => await room.topic()), - ) - - const totalNum = roomList.length - let n = 0 - - const replyText = [ - `Total room number: ${totalNum}`, - ...topicList - .slice(0, 17) - .map(topic => ++n + '. ' + topic), - ].join('\n') - - await msg.say(replyText) - - return - } - - // Contact.findAll() - if (/^testContact$/i.test(text)) { - const contactList = await bot.Contact.findAll() - console.log('bot.Contact.findAll() done.') - - const totalNum = contactList.length - let n = 0 - - const replyText = [ - `Total contact number: ${totalNum}`, - contactList - .slice(0, 17) - .map(contact => contact.name()) - .map(name => ++n + '. ' + name), - ].join('\n') - - await from.say(replyText) - - return - } - - if (/^fcontact$/.test(text)) { - console.log('begin to check msg forward contact') - // const contact = await bot.Contact.find({ - // name: /李佳芮/, - // }) - const contact = await bot.Contact.find({ id: 'qq512436430' }) - if (!contact) { - console.error('contact not found') - return - } - await msg.forward(contact) - return - } - - if (/^froom$/.test(text)) { - console.log('begin to check msg forward room') - const dingRoom = await bot.Room.find({ topic: /^ding/i }) - if (dingRoom) { - await msg.forward(dingRoom) - } else { - await msg.say('Cannot find dingRoom, please create a ding room first!') - } - return - } - - if (/^geta$/.test(text)) { - console.log('begin to check get contact alias') - await from.say((await from.alias()) || 'no alias') - return - } - - if (/^seta$/.test(text)) { - console.log('begin to check set contact alias') - await from.alias('wechaty-alias') - setTimeout(async () => { - await from.say((await from.alias()) || 'no alais') - }, 3 * 1000) - return - } - - if (/^avatar$/.test(text)) { - console.log('begin to check get contact avatar') - const file = await from.avatar() - await from.say(file) - return - } - - if (/^(ding|ping|bing|code)$/i.test(msg.text()) /*&& !msg.self()*/) { - /** - * 1. reply 'dong' - */ - log.info('Bot', 'REPLY: dong') - await msg.say('dong') - - const joinWechaty = `Join Wechaty Developers' Community\n\n` + - `Wechaty is used in many ChatBot projects by hundreds of developers.\n\n` + - `If you want to talk with other developers, just scan the following QR Code in WeChat with secret code: wechaty,\n\n` + - `you can join our Wechaty Developers' Home at once` - await msg.say(joinWechaty) - - /** - * 2. reply qrcode image - */ - // const fileBox = FileBox.packStream( - // fs.createReadStream(BOT_QR_CODE_IMAGE_FILE), - // BOT_QR_CODE_IMAGE_FILE, - // ) - - log.info('Bot', 'REPLY: %s', BOT_QR_CODE_IMAGE_FILE_BOX) - await msg.say(BOT_QR_CODE_IMAGE_FILE_BOX) - - /** - * 3. reply 'scan now!' - */ - await msg.say('Scan now, because other Wechaty developers want to talk with you too!\n\n(secret code: wechaty)') - - } - } catch (e) { - log.error('Bot', 'on(message) exception: %s' , e) - console.error(e) - } -}) - -bot.on('error', async e => { - log.error('Bot', 'error: %s', e) - if (bot.isLoggedIn) { - await bot.say('Wechaty error: ' + e.message).catch(console.error) - } - // await bot.stop() -}) - -// let killChrome: NodeJS.SignalsListener - -bot.start() -.then(() => { - const listenerList = process.listeners('SIGINT') - for (const listener of listenerList) { - if (listener.name === 'killChrome') { - process.removeListener('SIGINT', listener) - // killChrome = listener - } - } -}) -.catch(async e => { - log.error('Bot', 'start() fail: %s', e) - await bot.stop() - process.exit(-1) -}) - -// let quiting = false -// finis((code, signal) => { -// log.info('Bot', 'finis(%s, %s)', code, signal) - -// if (!bot.logonoff()) { -// log.info('Bot', 'finis() bot had been already stopped') -// doExit(code) -// } - -// if (quiting) { -// log.warn('Bot', 'finis() already quiting... return and wait...') -// return -// } - -// quiting = true -// let done = false -// // let checkNum = 0 - -// const exitMsg = `Wechaty will exit ${code} because of ${signal} ` - -// log.info('Bot', 'finis() broadcast quiting message for bot') -// bot.say(exitMsg) -// // .then(() => bot.stop()) -// .catch(e => log.error('Bot', 'finis() catch rejection: %s', e)) -// .then(() => done = true) - -// setImmediate(checkForExit) - -// function checkForExit() { -// // if (checkNum++ % 100 === 0) { -// log.info('Bot', 'finis() checkForExit() checking done: %s', done) -// // } -// if (done) { -// log.info('Bot', 'finis() checkForExit() done!') -// setTimeout(() => doExit(code), 1000) // delay 1 second -// return -// } -// // death loop to wait for `done` -// // process.nextTick(checkForExit) -// // setImmediate(checkForExit) -// setTimeout(checkForExit, 100) -// } -// }) - -// function doExit(code: number): void { -// log.info('Bot', 'doExit(%d)', code) -// if (killChrome) { -// killChrome('SIGINT') -// } -// process.exit(code) -// } - -// process.on('SIGINT', function() { -// console.log('Nice SIGINT-handler') -// const listeners = process.listeners('SIGINT') -// for (let i = 0; i < listeners.length; i++) { -// console.log(listeners[i].toString()) -// } -// }) diff --git a/examples/advanced/shell-bot.ts b/examples/advanced/shell-bot.ts deleted file mode 100755 index 2e0508e..0000000 --- a/examples/advanced/shell-bot.ts +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/env node -import repl from 'node:repl' - -import { WechatyBuilder } from 'wechaty' - -async function main () { - const wechaty = WechatyBuilder.build({ - name: 'shell-bot', - }) - - console.info('Starting...') - - await wechaty.start() - - const shell = repl.start('wechaty> ') - shell.context['wechaty'] = wechaty - shell.on('exit', () => wechaty.stop()) -} - -main() - .catch(console.error) diff --git a/examples/ambient-modules.d.ts b/examples/ambient-modules.d.ts deleted file mode 100644 index e56138c..0000000 --- a/examples/ambient-modules.d.ts +++ /dev/null @@ -1,90 +0,0 @@ -/** - * Optional example dependencies. They are not installed by the root - * package so that `npm install` stays the starter set. These declarations - * let `npm run lint:ts` check the examples that import them. - */ - -declare module 'apiai' { - interface TextRequest { - on (event: 'response', cb: (response: { result?: { fulfillment?: { speech?: string } } }) => void): this - on (event: 'error', cb: (error: Error) => void): this - end (): void - } - interface Client { - textRequest (text: string): TextRequest - } - function ApiAi (key: string): Client - export default ApiAi -} - -declare module 'finis' { - export function finis ( - callback: (code: number, signal: NodeJS.Signals | undefined) => void | Promise, - ): void -} - -declare module 'request' { - interface RequestCallback { - (err: Error | null, response: unknown, body: string): void - } - interface RequestApi { - post (url: string, options: { headers: Record }, cb: RequestCallback): NodeJS.ReadWriteStream - } - const request: RequestApi - export default request -} - -declare module 'fluent-ffmpeg' { - import type { Readable } from 'node:stream' - interface Command { - fromFormat (format: string): Command - toFormat (format: string): Command - pipe (dest: NodeJS.WritableStream): Command - on (event: 'error', cb: (err: Error) => void): Command - } - function Ffmpeg (input: Readable): Command - export default Ffmpeg -} - -declare module 'tuling123-client' { - export default class Tuling123 { - constructor (apiKey: string) - ask (text: string, options: { userid: unknown }): Promise<{ text: string }> - } -} - -declare module 'node-telegram-bot-api' { - interface TelegramMessage { - chat: { id: number } - } - export default class TelegramBot { - constructor (token: string, options?: Record) - on (event: 'message', listener: (msg: TelegramMessage) => void): void - onText (regexp: RegExp, listener: (msg: TelegramMessage, match: RegExpExecArray | null) => void): void - sendMessage (chatId: number, text: string): void - } -} - -declare module 'wechaty-telegram' { - import TelegramBot from 'node-telegram-bot-api' - export default TelegramBot -} - -declare module 'wechaty-puppet-padchat' { - export class PuppetPadchat { - constructor () - } -} - -declare module 'blessed' { - interface Blessed { - screen (options: Record): any - } - const blessed: Blessed - export default blessed -} - -declare module 'blessed-contrib' { - const contrib: any - export default contrib -} diff --git a/examples/basic/contact-bot.ts b/examples/basic/contact-bot.ts deleted file mode 100755 index b21a1a2..0000000 --- a/examples/basic/contact-bot.ts +++ /dev/null @@ -1,132 +0,0 @@ -#!/usr/bin/env node -/** - * Wechaty - https://github.com/wechaty/wechaty - * - * @copyright 2016-now Huan LI - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -import qrTerm from 'qrcode-terminal' - -import { - log, - WechatyBuilder, - type Contact, - type ScanStatus, -} from 'wechaty' - -const welcome = ` -=============== Powered by Wechaty =============== --------- https://github.com/Chatie/wechaty -------- - -I can list all your contacts with weixn id & name -__________________________________________________ - -Please wait... I'm trying to login in... -` - -console.log(welcome) -const bot = WechatyBuilder.build() - -bot.on('scan', onScan) -bot.on('login', onLogin) -bot.on('logout', onLogout) -bot.on('error', onError) - -bot.start() - .catch(console.error) - -function onScan (qrcode: string, _status: ScanStatus) { - qrTerm.generate(qrcode, { small: true }) // show qrcode on console -} - -function onLogin (user: Contact) { - console.log(`${user} login`) - void main() -} - -function onLogout (user: Contact) { - console.log(`${user} logout`) -} - -function onError (e: unknown) { - console.error(e) -} - -/** - * Main Contact Bot - */ -async function main() { - const contactList = await bot.Contact.findAll() - - log.info('Bot', '#######################') - log.info('Bot', 'Contact number: %d\n', contactList.length) - - /** - * official contacts list - */ - for (let i = 0; i < contactList.length; i++) { - const contact = contactList[i] - if (!contact) { - continue - } - if (contact.type() === bot.Contact.Type.Official) { - log.info('Bot', `official ${i}: ${contact}`) - } - } - - /** - * personal contact list - */ - - for (let i = 0; i < contactList.length; i++) { - const contact = contactList[i] - if (!contact) { - continue - } - if (contact.type() === bot.Contact.Type.Individual) { - log.info('Bot', `personal ${i}: ${contact.name()} : ${contact.id}`) - } - } - - const MAX = 17 - for (let i = 0; i < contactList.length; i++ ) { - const contact = contactList[i] - if (!contact) { - continue - } - - /** - * Save avatar to file like: "1-name.jpg" - */ - const file = await contact.avatar() - const name = file.name - await file.toFile(name, true) - - log.info('Bot', 'Contact: "%s" with avatar file: "%s"', - contact.name(), - name, - ) - - if (i > MAX) { - log.info('Bot', 'Contacts too many, I only show you the first %d ... ', MAX) - break - } - } - - const SLEEP = 7 - log.info('Bot', 'I will re-dump contact weixin id & names after %d second... ', SLEEP) - setTimeout(main, SLEEP * 1000) - -} diff --git a/examples/basic/ding-dong-bot.ts b/examples/basic/ding-dong-bot.ts index ccb1435..235f9cd 100755 --- a/examples/basic/ding-dong-bot.ts +++ b/examples/basic/ding-dong-bot.ts @@ -22,6 +22,7 @@ import 'dotenv/config.js' import { ScanStatus, WechatyBuilder, + helpers, log, type Contact, type Message, @@ -38,10 +39,10 @@ function onScan (qrcode: string, status: ScanStatus) { encodeURIComponent(qrcode), ].join('') - log.info('StarterBot', 'onScan: %s(%s) - %s', ScanStatus[status], status, qrcodeImageUrl) + log.info('StarterBot', 'onScan: %s(%s) - %s', helpers.typeName(ScanStatus, status), status, qrcodeImageUrl) } else { - log.info('StarterBot', 'onScan: %s(%s)', ScanStatus[status], status) + log.info('StarterBot', 'onScan: %s(%s)', helpers.typeName(ScanStatus, status), status) } } @@ -67,7 +68,8 @@ async function onMessage (msg: Message) { */ const bot = WechatyBuilder.build({ name: 'ding-dong-bot', - puppet: new PuppetNeo(), + // wechaty-puppet-neo@0.1.1 still bundles wechaty-puppet@1.x types + puppet: new PuppetNeo() as unknown as Exclude[0]>['puppet'], string | undefined>, }) bot.on('scan', onScan) diff --git a/examples/ding-dong-bot.ts b/examples/ding-dong-bot.ts index 2d375d2..2f9610a 100755 --- a/examples/ding-dong-bot.ts +++ b/examples/ding-dong-bot.ts @@ -2,46 +2,58 @@ /** * Wechaty - Conversational RPA SDK for Chatbot Makers. * - https://github.com/wechaty/wechaty + * + * Starter ding-dong bot using `PuppetNeo`. Prints a terminal QR code on `scan` + * and replies `dong` to incoming `ding` messages. */ -// https://stackoverflow.com/a/42817956/1123955 -// https://github.com/motdotla/dotenv/issues/89#issuecomment-587753552 import 'dotenv/config.js' import { ScanStatus, WechatyBuilder, + helpers, log, type Contact, type Message, -} from 'wechaty' +} from 'wechaty' import { PuppetNeo } from 'wechaty-puppet-neo' - import qrcodeTerminal from 'qrcode-terminal' -function onScan (qrcode: string, status: ScanStatus) { +/** + * Renders the login QR code in the terminal when waiting for a scan. + */ +function onScan (qrcode: string, status: ScanStatus): void { if (status === ScanStatus.Waiting || status === ScanStatus.Timeout) { const qrcodeImageUrl = [ 'https://wechaty.js.org/qrcode/', encodeURIComponent(qrcode), ].join('') - log.info('StarterBot', 'onScan: %s(%s) - %s', ScanStatus[status], status, qrcodeImageUrl) - - qrcodeTerminal.generate(qrcode, { small: true }) // show qrcode on console + log.info('StarterBot', 'onScan: %s(%s) - %s', helpers.typeName(ScanStatus, status), status, qrcodeImageUrl) + qrcodeTerminal.generate(qrcode, { small: true }) } else { - log.info('StarterBot', 'onScan: %s(%s)', ScanStatus[status], status) + log.info('StarterBot', 'onScan: %s(%s)', helpers.typeName(ScanStatus, status), status) } } -function onLogin (user: Contact) { +/** + * Logs when the bot account signs in. + */ +function onLogin (user: Contact): void { log.info('StarterBot', '%s login', user) } -function onLogout (user: Contact) { +/** + * Logs when the bot account signs out. + */ +function onLogout (user: Contact): void { log.info('StarterBot', '%s logout', user) } -async function onMessage (msg: Message) { +/** + * Replies `dong` when an incoming text message equals `ding`. + */ +async function onMessage (msg: Message): Promise { log.info('StarterBot', msg.toString()) if (msg.text() === 'ding') { @@ -55,14 +67,15 @@ async function onMessage (msg: Message) { */ const bot = WechatyBuilder.build({ name: 'ding-dong-bot', - puppet: new PuppetNeo(), + // wechaty-puppet-neo@0.1.1 still bundles wechaty-puppet@1.x types + puppet: new PuppetNeo() as unknown as Exclude[0]>['puppet'], string | undefined>, }) -bot.on('scan', onScan) -bot.on('login', onLogin) -bot.on('logout', onLogout) +bot.on('scan', onScan) +bot.on('login', onLogin) +bot.on('logout', onLogout) bot.on('message', onMessage) bot.start() .then(() => log.info('StarterBot', 'Starter Bot Started.')) - .catch(e => log.error('StarterBot', e)) + .catch((e) => log.error('StarterBot', e)) diff --git a/examples/professional/api-ai-bot.ts b/examples/professional/api-ai-bot.ts deleted file mode 100755 index ccb8217..0000000 --- a/examples/professional/api-ai-bot.ts +++ /dev/null @@ -1,219 +0,0 @@ -#!/usr/bin/env node -/** - * Wechaty - https://github.com/chatie/wechaty - * - * @copyright 2016-2018 Huan LI - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -/** - * Wechaty bot use a ApiAi.com brain - * - * Apply Your Own ApiAi Developer API_KEY at: - * http://www.api.ai - * - * Enjoy! - */ -/* tslint:disable:variable-name */ -import QrcodeTerminal from 'qrcode-terminal' - -import { Brolog as log } from 'brolog' -/* tslint:disable:no-var-requires */ -// import co from 'co' -/* tslint:disable:variable-name */ -import ApiAi from 'apiai' -import { EventEmitter } from 'node:events' - -/** - * Change `import { ... } from '../.js'` - * to `import { ... } from 'wechaty'` - * when you are runing with Docker or NPM instead of Git Source. - */ -import { - WechatyBuilder, - type Message, -} from 'wechaty' - -// log.level = 'verbose' -// log.level = 'silly' - -/** - * - * `7217d7bce18c4bcfbe04ba7bdfaf9c08` for Wechaty demo - * - */ -const APIAI_API_KEY = '7217d7bce18c4bcfbe04ba7bdfaf9c08' -const brainApiAi = ApiAi(APIAI_API_KEY) - -const bot = WechatyBuilder.build({ name: 'api-ai-bot' }) - -console.log(` -Welcome to api.AI Wechaty Bot. -Api.AI Doc: https://docs.api.ai/v16/docs/get-started - -Notice: This bot will only active in the room which name contains 'wechaty'. -/* if (m.room() && /Wechaty/i.test(m.room().name())) { */ - -Loading... please wait for QrCode Image Url and then scan to login. -`) - -bot -.on('scan', (qrcode, status) => { - QrcodeTerminal.generate(qrcode) - console.log(`${qrcode}\n[${status}] Scan QR Code in above url to login: `) -}) -.on('login' , user => log.info('Bot', `bot login: ${user}`)) -.on('logout' , user => log.info('Bot', 'bot %s logout.', user)) -.on('message', async m => { - if (m.self()) { return } - - // co(function* () { - // const msg = yield m.load() - const room = m.room() - - if (room && /Wechaty/i.test(await room.topic())) { - log.info('Bot', 'talk: %s' , m) - talk(m) - } else { - log.info('Bot', 'recv: %s' , m) - } - // }) - // .catch(e => log.error('Bot', 'on message rejected: %s' , e)) -}) - -bot.start() -.catch(async e => { - log.error('Bot', 'init() fail:' + e) - await bot.stop() - process.exit(-1) -}) - -class Talker extends EventEmitter { - private thinker: (text: string) => Promise - private obj: { - text: string[], - time: number[], - } - private timer?: ReturnType | number - - constructor( - thinker: (text: string) => Promise, - ) { - log.verbose('Talker()') - super() - this.thinker = thinker - this.obj = { - text: [], - time: [], - } - } - - public save(text: string) { - log.verbose('Talker', 'save(%s)', text) - this.obj.text.push(text) - this.obj.time.push(Date.now()) - } - public load() { - const text = this.obj.text.join(', ') - log.verbose('Talker', 'load(%s)', text) - this.obj.text = [] - this.obj.time = [] - return text - } - - public updateTimer(delayTime?: number) { - delayTime = delayTime || this.delayTime() - log.verbose('Talker', 'updateTimer(%s)', delayTime) - - if (this.timer) { clearTimeout(this.timer) } - this.timer = setTimeout(this.say.bind(this), delayTime, 3) - } - - public hear(text: string) { - log.verbose('Talker', `hear(${text})`) - this.save(text) - this.updateTimer() - } - public async say() { - log.verbose('Talker', 'say()') - const text = this.load() - await this.thinker(text) - .then(reply => this.emit('say', reply)) - this.timer = undefined - } - - public delayTime() { - const minDelayTime = 5000 - const maxDelayTime = 15000 - const delayTime = Math.floor(Math.random() * (maxDelayTime - minDelayTime)) + minDelayTime - return delayTime - } -} - -/* tslint:disable:variable-name */ -const Talkers: { - [index: string]: Talker, - } = {} - -function talk(m: Message) { - const from = m.from() - const fromId = from && from.id - - const room = m.room() - const roomId = room && room.id - - const content = m.text() - - const talkerName = roomId + (fromId || '') - let talker = Talkers[talkerName] - if (!talker) { - talker = new Talker(function(text: string) { - return new Promise((resolve, reject) => { - brainApiAi.textRequest(text) - .on('response', function(response: any) { - console.log(response) - /* -{ id: 'a09381bb-8195-4139-b49c-a2d03ad5e014', - timestamp: '2016-05-27T17:22:46.597Z', - result: - { source: 'domains', - resolvedQuery: 'hi', - action: 'smalltalk.greetings', - parameters: { simplified: 'hello' },w - metadata: {}, - fulfillment: { speech: 'Hi there.' }, - score: 0 }, - status: { code: 200, errorType: 'success' } } - */ - const reply: string = response.result.fulfillment.speech - if (!reply) { - log.info('ApiAi', `Talker do not want to talk for "${text}"`) - return reject() - } - log.info('ApiAi', 'Talker reply:"%s" for "%s" ', reply, text) - return resolve(reply) - }) - .on('error', function(error: Error) { - log.error('ApiAi', error) - reject(error) - }) - .end() - }) - }) - Talkers[talkerName] = talker - talker.on('say', (reply: string) => { void m.say(reply) }) - } - talker.hear(content) -} diff --git a/examples/professional/blessed-twins-bot/README.md b/examples/professional/blessed-twins-bot/README.md deleted file mode 100644 index 69e4de3..0000000 --- a/examples/professional/blessed-twins-bot/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# BLESSED TWINS BOT - -[![blessed twins bot](https://wechaty.github.io/wechaty/images/blessed-twins-bot.png)](https://asciinema.org/a/177857) - -## How to run - -```bash -npm install blessed blessed-contrib @types/blessed -node bless-twins-bot.ts -``` - -## See Also - -* Example Source Code: -* Blog: [New Feature: Multi-Instance Support for Wechaty v0.16(WIP)](https://blog.chatie.io/blessed-twins-bot/) diff --git a/examples/professional/blessed-twins-bot/bless-twins-bot.ts b/examples/professional/blessed-twins-bot/bless-twins-bot.ts deleted file mode 100755 index fc81055..0000000 --- a/examples/professional/blessed-twins-bot/bless-twins-bot.ts +++ /dev/null @@ -1,346 +0,0 @@ -#!/usr/bin/env node -/** - * Wechaty Twins Bot + Blessed Contrib Demo - * Credit: https://github.com/yaronn/blessed-contrib/blob/06a05f107a3b54c91b5200a041ad8c15e6489de9/examples/dashboard.js - */ -import blessed from 'blessed' -import contrib from 'blessed-contrib' - -import { generate } from 'qrcode-terminal' - -import { - WechatyBuilder, - type Wechaty, -} from 'wechaty' - -const screen = blessed.screen({ - smartCSR: true, - fullUnicode: true, // https://github.com/chjj/blessed/issues/226#issuecomment-188777457 -}) - -// create layout and widgets - -const grid = new contrib.grid({rows: 12, cols: 12, screen: screen}) - -/** - * Donut Options - * self.options.radius = options.radius || 14; // how wide is it? over 5 is best - * self.options.arcWidth = options.arcWidth || 4; //width of the donut - * self.options.yPadding = options.yPadding || 2; //padding from the top - */ -const donut = grid.set(8, 8, 4, 2, contrib.donut, - { - label: 'Percent Donut', - radius: 16, - arcWidth: 4, - yPadding: 2, - data: [{label: 'Storage', percent: 87}], -}) - -// const latencyLine = grid.set(8, 8, 4, 2, contrib.line, -// { style: -// { line: "yellow" -// , text: "green" -// , baseline: "black"} -// , xLabelPadding: 3 -// , xPadding: 5 -// , label: 'Network Latency (sec)'}) - -const gauge = grid.set(8, 10, 2, 2, contrib.gauge, {label: 'Storage', percent: [80, 20]}) -const gaugeTwo = grid.set(2, 9, 2, 3, contrib.gauge, {label: 'Deployment Progress', percent: 80}) - -const sparkline = grid.set(10, 10, 2, 2, contrib.sparkline, - { label: 'Throughput (bits/sec)' - , tags: true - , style: { fg: 'blue', titleFg: 'white' }}) - -const bar = grid.set(4, 6, 4, 3, contrib.bar, - { label: 'Server Utilization (%)' - , barWidth: 4 - , barSpacing: 6 - , xOffset: 2 - , maxHeight: 9}) - -const table = grid.set(4, 9, 4, 3, contrib.table, - { keys: true - , fg: 'green' - , label: 'Active Processes' - , columnSpacing: 1 - , columnWidth: [24, 10, 10]}) - -/* - * - * LCD Options -//these options need to be modified epending on the resulting positioning/size - options.segmentWidth = options.segmentWidth || 0.06; // how wide are the segments in % so 50% = 0.5 - options.segmentInterval = options.segmentInterval || 0.11; // spacing between the segments in % so 50% = 0.5 - options.strokeWidth = options.strokeWidth || 0.11; // spacing between the segments in % so 50% = 0.5 -//default display settings - options.elements = options.elements || 3; // how many elements in the display. or how many characters can be displayed. - options.display = options.display || 321; // what should be displayed before anything is set - options.elementSpacing = options.spacing || 4; // spacing between each element - options.elementPadding = options.padding || 2; // how far away from the edges to put the elements -//coloring - options.color = options.color || "white"; -*/ -const lcdLineOne = grid.set(0, 9, 2, 3, contrib.lcd, - { - label: 'LCD Test', - segmentWidth: 0.06, - segmentInterval: 0.11, - strokeWidth: 0.1, - elements: 5, - display: 3210, - elementSpacing: 4, - elementPadding: 2, - }, -) - -const errorsLine = grid.set(0, 6, 4, 3, contrib.line, { - style: { - line: 'red', - text: 'white', - baseline: 'black', - }, - label: 'Errors Rate', - maxY: 60, - showLegend: true, -}) - -const boyConsole = grid.set(0, 0, 6, 6, contrib.log, { - fg: 'green', - selectedFg: 'green', - label: 'Boy Bot', -}) - -const girlConsole = grid.set(6, 0, 6, 6, contrib.log, { - fg: 'red', - selectedFg: 'red', - label: 'Girl Bot', -}) - -const log = grid.set(8, 6, 4, 2, contrib.log, { - fg: 'green', - selectedFg: 'green', - label: 'Server Log', -}) - -// dummy data -const servers = ['US1', 'US2', 'EU1', 'AU1', 'AS1', 'JP1'] -const commands = ['grep', 'node', 'java', 'timer', '~/ls -l', 'netns', 'watchdog', 'gulp', 'tar -xvf', 'awk', 'npm install'] - -// set dummy data on gauge -let gaugePercent = 0 -setInterval(function() { - gauge.setData([gaugePercent, 100 - gaugePercent]) - gaugePercent++ - if (gaugePercent >= 100) gaugePercent = 0 -}, 200) - -let gaugePercentTwo = 0 -setInterval(function() { - gaugeTwo.setData(gaugePercentTwo) - gaugePercentTwo++ - if (gaugePercentTwo >= 100) gaugePercentTwo = 0 -}, 200) - -// set dummy data on bar chart -function fillBar() { - const arr: number[] = [] - for (let i = 0; i < servers.length; i++) { - arr.push(Math.round(Math.random() * 10)) - } - bar.setData({titles: servers, data: arr}) -} -fillBar() -setInterval(fillBar, 2000) - -// set dummy data for table -function generateTable() { - const data: any[] = [] - - for (let i = 0; i < 30; i++) { - const row: any[] = [] - row.push(commands[Math.round(Math.random() * (commands.length - 1))]) - row.push(Math.round(Math.random() * 5)) - row.push(Math.round(Math.random() * 100)) - - data.push(row) - } - - table.setData({headers: ['Process', 'Cpu (%)', 'Memory'], data: data}) -} - -generateTable() -table.focus() -setInterval(generateTable, 3000) - -// set log dummy data -setInterval(function() { - const rnd = Math.round(Math.random() * 2) - if (rnd === 0) log.log('starting process ' + commands[Math.round(Math.random() * (commands.length - 1))]) - else if (rnd === 1) log.log('terminating server ' + servers[Math.round(Math.random() * (servers.length - 1))]) - else if (rnd === 2) log.log('avg. wait time ' + Math.random().toFixed(2)) - screen.render() -}, 500) - -// set spark dummy data -const spark1 = [1, 2, 5, 2, 1, 5, 1, 2, 5, 2, 1, 5, 4, 4, 5, 4, 1, 5, 1, 2, 5, 2, 1, 5, 1, 2, 5, 2, 1, 5, 1, 2, 5, 2, 1, 5] -const spark2 = [4, 4, 5, 4, 1, 5, 1, 2, 5, 2, 1, 5, 4, 4, 5, 4, 1, 5, 1, 2, 5, 2, 1, 5, 1, 2, 5, 2, 1, 5, 1, 2, 5, 2, 1, 5] - -refreshSpark() -setInterval(refreshSpark, 1000) - -function refreshSpark() { - spark1.shift() - spark1.push(Math.random() * 5 + 1) - spark2.shift() - spark2.push(Math.random() * 5 + 1) - sparkline.setData(['Server1', 'Server2'], [spark1, spark2]) -} - -// set line charts dummy data - -const errorsData = { - title: 'server 1', - x: ['00:00', '00:05', '00:10', '00:15', '00:20', '00:25'], - y: [30, 50, 70, 40, 50, 20], -} - -// const latencyData = { -// x: ['t1', 't2', 't3', 't4'], -// y: [5, 1, 7, 5], -// } - -setLineData([errorsData], errorsLine) -// setLineData([latencyData], latencyLine) - -setInterval(function() { - setLineData([errorsData], errorsLine) -}, 1500) - -setInterval(function() { - const colors = ['green', 'magenta', 'cyan', 'red', 'blue'] - const text = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'] - - const value = Math.round(Math.random() * 100) - lcdLineOne.setDisplay(value + text[value % 12]!) - lcdLineOne.setOptions({ - color: colors[value % 5], - elementPadding: 4, - }) - screen.render() -}, 1500) - -let pct = 0.00 - -function updateDonut() { - if (pct > 0.99) pct = 0.00 - let color = 'green' - if (pct >= 0.25) color = 'cyan' - if (pct >= 0.5) color = 'yellow' - if (pct >= 0.75) color = 'red' - donut.setData([ - {percent: parseFloat(((pct + 0.00) % 1) as any).toFixed(2), label: 'storage', 'color': color}, - ]) - pct += 0.01 -} - -setInterval(function() { - updateDonut() - screen.render() -}, 500) - -function setLineData(mockData: any, line: any) { - for (let i = 0; i < mockData.length; i++) { - const last = mockData[i].y[mockData[i].y.length - 1] - mockData[i].y.shift() - const num = Math.max(last + Math.round(Math.random() * 10) - 5, 10) - mockData[i].y.push(num) - } - - line.setData(mockData) -} - -screen.key(['escape', 'q', 'C-c'], function(ch: string, key: unknown) { - console.log(ch, key) - return process.exit(0) -}) - -// fixes https://github.com/yaronn/blessed-contrib/issues/10 -screen.on('resize', function() { - donut.emit('attach') - gauge.emit('attach') - gaugeTwo.emit('attach') - sparkline.emit('attach') - bar.emit('attach') - table.emit('attach') - lcdLineOne.emit('attach') - errorsLine.emit('attach') - boyConsole.emit('attach') - girlConsole.emit('attach') - log.emit('attach') -}) - -screen.render() - -// setInterval(() => { -// boyConsole.log('boy') -// girlConsole.log('girl') -// console.log('zixia') -// }, 500) - -/** - * - * - * - * Wechaty multi instance support example: - * boy & girl twins - * - * - * - */ -const boy = WechatyBuilder.build({ name: 'boy' }) -const girl = WechatyBuilder.build({ name: 'girl' }) - -startBot(boy, boyConsole) -startBot(girl, girlConsole) - -function startBot(bot: Wechaty, logElement: any) { - // logElement.log('Initing...') - bot - .on('logout' , user => logElement.log(`${user.name()} logouted`)) - .on('login' , user => { - logElement.setContent('') - logElement.log(`${user.name()} login`) - bot.say('Wechaty login').catch(console.error) - logElement.setLabel(logElement._label.content + ' - ' + user.name()) - }) - .on('scan', (qrcode) => { - generate( - qrcode, - { - small: true, - }, - (asciiart: string) => logElement.setContent(asciiart), - ) - }) - .on('message', async m => { - logElement.log(m.toString()) - }) - - bot.start() - .catch(async e => { - logElement.log(`start() fail: ${e}`) - await bot.stop() - process.exit(-1) - }) - - bot.on('error', async e => { - logElement.log(`error: ${e}`) - if (bot.isLoggedIn) { - await bot.say('Wechaty error: ' + e.message).catch(console.error) - } - // await bot.stop() - }) -} diff --git a/examples/professional/ctrl-c-signal-bot.ts b/examples/professional/ctrl-c-signal-bot.ts deleted file mode 100755 index 7fd637c..0000000 --- a/examples/professional/ctrl-c-signal-bot.ts +++ /dev/null @@ -1,162 +0,0 @@ -#!/usr/bin/env node -/** - * Wechaty - https://github.com/chatie/wechaty - * - * @copyright 2016-2018 Huan LI - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -/* tslint:disable:variable-name */ -import { generate } from 'qrcode-terminal' -import { finis } from 'finis' - -import { - WechatyBuilder, - log, - qrcodeValueToImageUrl, -} from 'wechaty' - -const bot = WechatyBuilder.build() - -const welcome = ` -| __ __ _ _ -| \\ \\ / /__ ___| |__ __ _| |_ _ _ -| \\ \\ /\\ / / _ \\/ __| '_ \\ / _\` | __| | | | -| \\ V V / __/ (__| | | | (_| | |_| |_| | -| \\_/\\_/ \\___|\\___|_| |_|\\__,_|\\__|\\__, | -| |___/ - -=============== Powered by Wechaty =============== --------- https://github.com/chatie/wechaty -------- - Version: ${bot.version()} - -I'm a bot, my superpower is: - - Send message to myself before I die. - (When you press Ctrl+C, or kill me with a signal) -__________________________________________________ - -Hope you like it, and you are very welcome to -upgrade me to more superpowers! - -Please wait... I'm trying to login in... - -` - -console.log(welcome) - -bot -.on('login' , user => { - log.info('Bot', `${user.name()} login`) - bot.say('Wechaty login').catch(console.error) -}) -.on('scan', (qrcode, status, data) => { - generate(qrcode, { small: true }) - if (data) { - console.log(data) - } - console.log(qrcodeValueToImageUrl(qrcode)) - console.log('^^^ Online QR Code Image URL ^^^ ') - console.log(`[${status}] ${qrcode} Scan QR Code above url to log in: `) -}) -.on('message', async msg => { - console.log(msg.toString()) - console.log('Please press Ctrl+C to kill me!') - console.log(`Then I'll send my last word to myself, check it out on your Wechat!`) -}) - -bot.on('error', async e => { - log.error('Bot', 'error: %s', e) - if (bot.isLoggedIn) { - await bot.say('Wechaty error: ' + e.message).catch(console.error) - } -}) - -let killChrome: ((signal: 'SIGINT') => void) | undefined - -bot.start() -.then(() => { - const listenerList = process.listeners('SIGINT') - for (const listener of listenerList) { - if (listener.name === 'killChrome') { - process.removeListener('SIGINT', listener) - killChrome = listener - } - } -}) -.catch(async e => { - log.error('Bot', 'start() fail: %s', e) - await bot.stop() - process.exit(-1) -}) - -let quiting = false -finis(async (code, signal) => { - log.info('Bot', 'finis(%s, %s)', code, signal) - - if (!bot.isLoggedIn) { - log.info('Bot', 'finis() bot had been already stopped') - doExit(code) - } - - if (quiting) { - log.warn('Bot', 'finis() already quiting... return and wait...') - return - } - - quiting = true - let done = false - // let checkNum = 0 - - const exitMsg = `Wechaty will exit ${code} because of ${signal} ` - - log.info('Bot', 'finis() broadcast quiting message for bot') - await bot.say(exitMsg) - // .then(() => bot.stop()) - .catch(e => log.error('Bot', 'finis() catch rejection: %s', e)) - .then(() => done = true) - - setImmediate(checkForExit) - - function checkForExit() { - // if (checkNum++ % 100 === 0) { - log.info('Bot', 'finis() checkForExit() checking done: %s', done) - // } - if (done) { - log.info('Bot', 'finis() checkForExit() done!') - setTimeout(() => doExit(code), 1000) // delay 1 second - return - } - // death loop to wait for `done` - // process.nextTick(checkForExit) - // setImmediate(checkForExit) - setTimeout(checkForExit, 100) - } -}) - -function doExit(code: number): void { - log.info('Bot', 'doExit(%d)', code) - if (killChrome) { - killChrome('SIGINT') - } - process.exit(code) -} - -// process.on('SIGINT', function() { -// console.log('Nice SIGINT-handler') -// const listeners = process.listeners('SIGINT') -// for (let i = 0; i < listeners.length; i++) { -// console.log(listeners[i].toString()) -// } -// }) diff --git a/examples/professional/send-link.ts b/examples/professional/send-link.ts deleted file mode 100755 index dbb49d2..0000000 --- a/examples/professional/send-link.ts +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env node -import { - WechatyBuilder, - impls, - type Message, -} from 'wechaty' - -import { PuppetPadchat } from 'wechaty-puppet-padchat' - -import { generate } from 'qrcode-terminal' - - -const puppet = new PuppetPadchat() - -export const wechatyBot = WechatyBuilder.build({ - puppet: puppet as never, -}) - -wechatyBot - .on('scan', async (qrcode) => { - generate(qrcode, {small: true}) - - }) - .on('login', async function (user) { - console.log(user) - }) - .on('error', async err => { - console.error('BOT ERROR:', `exit for ${JSON.stringify(err.message || '')}`) - }) - .on('message', async function (m: Message) { - if (m.text() === 'ding') { - const urlLink = new impls.UrlLinkImpl({ - description : 'WeChat Bot SDK for Individual Account, Powered by TypeScript, Docker, and Love', - thumbnailUrl: 'https://avatars0.githubusercontent.com/u/25162437?s=200&v=4', - title : 'Welcome to Wechaty', - url : 'https://github.com/chatie/wechaty', - }) - m.say(urlLink) - } - }) - -wechatyBot.start() diff --git a/examples/professional/speech-to-text-bot.ts b/examples/professional/speech-to-text-bot.ts deleted file mode 100755 index 295d975..0000000 --- a/examples/professional/speech-to-text-bot.ts +++ /dev/null @@ -1,189 +0,0 @@ -#!/usr/bin/env node -/** - * Wechaty - https://github.com/chatie/wechaty - * - * @copyright 2016-2018 Huan LI - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -import { - createReadStream, -} from 'node:fs' -import { - PassThrough, - Readable, -} from 'node:stream' -import querystring from 'node:querystring' - -import request from 'request' -import Ffmpeg from 'fluent-ffmpeg' - -/* tslint:disable:variable-name */ -import qrcodeTerminal from 'qrcode-terminal' - -/** - * Change `import { ... } from '../.js'` - * to `import { ... } from 'wechaty'` - * when you are runing with Docker or NPM instead of Git Source. - */ -import { - WechatyBuilder, - types, -} from 'wechaty' - -const bot = WechatyBuilder.build({ name: 'speech-bot' }) - -bot -.on('scan', (qrcode, status) => { - qrcodeTerminal.generate(qrcode) - console.log(`${qrcode}\n[${status}] Scan QR Code in above url to login: `) -}) -.on('login' , user => console.log(`${user} logined`)) -.on('message', async function(msg) { - console.log(`RECV: ${msg}`) - - if (msg.type() !== types.Message.Audio) { - return // skip no-VOICE message - } - - // const mp3Stream = await msg.readyStream() - - const msgFile = await msg.toFileBox() - const filename = msgFile.name - msgFile.toFile(filename) - - const mp3Stream = createReadStream(filename) - const text = await speechToText(mp3Stream) - console.log('VOICE TO TEXT: ' + text) - - if (msg.self()) { - await bot.say(text) // send text to 'filehelper' - } else { - await msg.say(text) // to original sender - } - -}) - -bot - .start() - .catch(e => console.error('bot.start() error: ' + e)) - -async function speechToText(mp3Stream: Readable): Promise { - const wavStream = mp3ToWav(mp3Stream) - - // const textStream = wavToText(wavStream) - - // textStream.on('data', text => { - // console.log(text) - // }) - - try { - const text = await wavToText(wavStream) - return text - - } catch (e) { - console.log(e) - return '' - } -} - -function mp3ToWav(mp3Stream: Readable): NodeJS.ReadableStream { - const wavStream = new PassThrough() - - Ffmpeg(mp3Stream) - .fromFormat('mp3') - .toFormat('wav') - .pipe(wavStream as any) - - // .on('start', function(commandLine) { - // console.log('Spawned Ffmpeg with command: ' + commandLine); - // }) - // .on('codecData', function(data) { - // console.log('Input is ' + data.audio + ' audio ' + - // 'with ' + data.video + ' video'); - // }) - // .on('progress', progress => { - // console.log('Processing: ' + progress.percent + '% done'); - // }) - // .on('end', function() { - // console.log('Finished processing'); - // }) - .on('error', function(err: Error /*, stdout, stderr */) { - console.log('Cannot process video: ' + err.message) - }) - - return wavStream -} - -/** - * Baidu: - * export BAIDU_SPEECH_API_KEY=FK58sUlteAuAIXZl5dWzAHCT - * export BAIDU_SPEECH_SECRET_KEY=feaf24adcc5b8f02b147e7f7b1953030 - * curl "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=${BAIDU_SPEECH_API_KEY}&client_secret=${BAIDU_SPEECH_SECRET_KEY}" - * - * OAuth: http://developer.baidu.com/wiki/index.php?title=docs/oauth/overview - * ASR: http://yuyin.baidu.com/docs/asr/57 - */ - -/** - * YunZhiSheng: - * http://dev.hivoice.cn/download_file/USC_DevelGuide_WebAPI_audioTranscription.pdf - */ - -/** - * Google: - * http://blog.csdn.net/dlangu0393/article/details/7214728 - * http://elric2011.github.io/a/using_speech_recognize_service.html - */ -async function wavToText(wavStream: NodeJS.ReadableStream): Promise { - const params = { - 'cuid': 'wechaty', - 'lan': 'zh', - 'token': '24.8c6a25b5dcfb41af189a97d9e0b7c076.2592000.1482571685.282335-8943256', - } - - const apiUrl = 'http://vop.baidu.com/server_api?' - + querystring.stringify(params) - - const options = { - headers: { - 'Content-Type': 'audio/wav; rate=8000', - }, - } - - return new Promise((resolve, reject) => { - wavStream.pipe(request.post(apiUrl, options, (err, _ /* httpResponse */, body) => { - // "err_msg":"success.","err_no":0,"result":["这是一个测试测试语音转文字,"] - if (err) { - return reject(err) - } - try { - const obj = JSON.parse(body) - if (obj.err_no !== 0) { - throw new Error(obj.err_msg) - } - - const text = obj.result?.[0] - if (typeof text !== 'string') { - throw new Error('speech result was empty') - } - return resolve(text) - - } catch (err) { - return reject(err) - } - })) - }) -} diff --git a/examples/professional/telegram-roger-bot.ts b/examples/professional/telegram-roger-bot.ts deleted file mode 100755 index cb4d678..0000000 --- a/examples/professional/telegram-roger-bot.ts +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env node -/** - * Wechaty - https://github.com/chatie/wechaty - * - * @copyright 2016-2018 Huan LI - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -/** - * This is an example to show how a simple bot runs under - * both Telegram and WeChat and shares the same code. - * - * For more information: https://github.com/hczhcz/wechaty-telegram - */ - -import TelegramBot from 'node-telegram-bot-api' -import WechatyTelegramBot from 'wechaty-telegram' - -type ChatBot = typeof TelegramBot - -const initBot = (ChatBot: ChatBot, token: string) => { - const bot = new ChatBot(token, { - // the "polling" option applies for a Telegram bot - // for WeChat bot, "polling" and "webhook" works in the same way - polling: true, - // options for Wechaty and Wechaty Telegram Bot Adaptor - wechaty: { - // if you do not want your bot to add a friend automatically - autoFriend: false - } - }) - - let roger = 'roger' - - bot.on('message', msg => { - bot.sendMessage(msg.chat.id, roger) // send roger - }) - - // use regular expressions to detect commands - bot.onText(/^\/setroger (.*)$/, (_msg, match) => { - const next = match?.[1] - if (next) { - roger = next // set roger message from user's input - } - }) -} - -initBot(TelegramBot, '123456:TOKEN') // you may obtain a Telegram bot token -initBot(WechatyTelegramBot, 'mybot') // you can use your bot's name as a token here diff --git a/examples/professional/tuling123-bot.ts b/examples/professional/tuling123-bot.ts deleted file mode 100755 index 0bf1d4c..0000000 --- a/examples/professional/tuling123-bot.ts +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env node -import qrTerm from 'qrcode-terminal' -import Tuling123 from 'tuling123-client' - -import { - WechatyBuilder, - types, - type Contact, - type Message, - type ScanStatus, -} from 'wechaty' - -const welcome = ` -=============== Powered by Wechaty =============== --------- https://github.com/Chatie/wechaty -------- - -I can talk with you using Tuling123.com -Apply your own tuling123.com API_KEY -at: http://www.tuling123.com/html/doc/api.html - -__________________________________________________ - -Please wait... I'm trying to login in... -` - -console.log(welcome) - -/** - * - * Apply Your Own Tuling123 Developer API_KEY at: - * http://www.tuling123.com - * - */ -const TULING123_API_KEY = '18f25157e0446df58ade098479f74b21' -const tuling = new Tuling123(TULING123_API_KEY) - -const bot = WechatyBuilder.build() - -bot.on('scan', onScan) -bot.on('login', onLogin) -bot.on('logout', onLogout) -bot.on('message', onMessage) -bot.on('error', onError) - -bot.start() - .catch(console.error) - -function onScan (qrcode: string, _status: ScanStatus) { - qrTerm.generate(qrcode, { small: true }) // show qrcode on console -} - -function onLogin (user: Contact) { - console.log(`${user} login`) -} - -function onLogout (user: Contact) { - console.log(`${user} logout`) -} - -function onError (e: unknown) { - console.error(e) -} - -async function onMessage (msg: Message) { - const from = msg.from() - // Skip message from self, or inside a room - if (msg.self() || msg.room() || !from || from.name() === '微信团队' || msg.type() !== types.Message.Text) return - - console.log('Bot', 'talk: %s' , msg.text()) - - try { - const {text: reply} = await tuling.ask(msg.text(), {userid: from}) - console.log('Tuling123', 'Talker reply:"%s" for "%s" ', - reply, - msg.text(), - ) - await msg.say(reply) - } catch (e) { - const reason = e instanceof Error ? e.message : e - console.error('Bot', 'on message tuling.ask() exception: %s' , reason) - } -} diff --git a/package.json b/package.json index 10f6065..e099d6d 100644 --- a/package.json +++ b/package.json @@ -9,14 +9,15 @@ }, "scripts": { "build": "tsc", + "clean": "node -e \"import('node:fs').then(fs => fs.rmSync('dist', { recursive: true, force: true }))\"", "lint:biome": "biome lint examples tests", + "lint:md": "markdownlint README.md DEVELOPMENT.md examples/README.md", "lint:ts": "tsc --isolatedModules --noEmit", - "lint": "npm run lint:biome && npm run lint:ts", - "postinstall": "check-node-version --node \">=26\" --npm \">=10\"", + "lint": "npm run lint:biome && npm run lint:ts && npm run lint:md", "start": "node examples/ding-dong-bot.ts", "test": "npm run lint && npm run test:smoke", - "test:smoke": "node --test --test-force-exit --test-timeout=180000 \"tests/*.test.ts\"", - "test:unit:deno": "env -i PATH=\"$PATH\" HOME=\"$HOME\" CI=\"${CI:-}\" NODE_BINARY=\"${NODE_BINARY:-$(command -v node)}\" deno test --no-check --allow-read --allow-write --allow-env --allow-net --allow-run --allow-sys --allow-ffi=node_modules/leveldown/prebuilds --allow-ffi=node_modules/wechaty-puppet-neo/native tests" + "test:smoke": "node --test --test-timeout=180000 \"tests/*.test.ts\"", + "test:unit:deno": "env -i PATH=\"$PATH\" HOME=\"$HOME\" CI=\"${CI:-}\" NODE_BINARY=\"${NODE_BINARY:-$(command -v node)}\" deno test --no-check --allow-read=.,/tmp,/etc/alpine-release --allow-write=/tmp --allow-env --allow-net --allow-run --allow-sys=hostname,cpus,networkInterfaces --allow-ffi=node_modules/leveldown/prebuilds,node_modules/wechaty-puppet-neo/native tests" }, "repository": { "type": "git", @@ -41,7 +42,7 @@ "@types/node": "^26.6.6", "@types/qrcode-terminal": "^0.12.2", "@typescript/native": "npm:typescript@^7.0.2", - "check-node-version": "^4.2.1", + "markdownlint-cli": "^0.50.0", "wechaty-puppet-mock": "^1.19.4" } } diff --git a/tests/wechaty-puppet-mock.test.ts b/tests/wechaty-puppet-mock.test.ts index 81f4394..bbedd95 100755 --- a/tests/wechaty-puppet-mock.test.ts +++ b/tests/wechaty-puppet-mock.test.ts @@ -1,34 +1,37 @@ #!/usr/bin/env node +/** + * Smoke test for Wechaty with `wechaty-puppet-mock`. + * + * Verifies that `WechatyBuilder` starts a mocked bot, emits a `scan` event, + * and stops cleanly within the test timeout. + */ import assert from 'node:assert/strict' import { test } from 'node:test' import { WechatyBuilder } from 'wechaty' - import { mock, PuppetMock, } from 'wechaty-puppet-mock' -test('wechaty-puppet-mock', async () => { +test('wechaty-puppet-mock', { timeout: 120_000 }, async (t) => { const mocker = new mock.Mocker() mocker.use(mock.SimpleEnvironment()) const puppetMock = new PuppetMock({ mocker }) const bot = WechatyBuilder.build({ - puppet: puppetMock, + // wechaty-puppet-mock@1.x still bundles wechaty-puppet@1.x types + puppet: puppetMock as unknown as Exclude[0]>['puppet'], string | undefined>, }) - const timer = setTimeout(() => { - console.error('Smoke testing timeout after 2 minutes.') - process.exit(1) - }, 120 * 1000) + t.after(async () => { + await bot.stop().catch(() => undefined) + }) - const future = new Promise(resolve => bot.once('scan', resolve)) + const future = new Promise((resolve) => bot.once('scan', resolve)) await bot.start() await future - await bot.stop() - clearTimeout(timer) assert.ok(bot.puppet, `Puppet ${bot.puppet} v${bot.puppet.version()} smoke testing passed.`) }) diff --git a/tests/wechaty-puppet-neo.test.ts b/tests/wechaty-puppet-neo.test.ts index 9ddc7fc..bf5849b 100644 --- a/tests/wechaty-puppet-neo.test.ts +++ b/tests/wechaty-puppet-neo.test.ts @@ -1,4 +1,10 @@ #!/usr/bin/env node +/** + * Smoke test for Wechaty with `wechaty-puppet-neo`. + * + * Verifies that `WechatyBuilder` starts `PuppetNeo`, emits a `scan` QR code, + * and stops cleanly without leaking unhandled rejection listeners. + */ import assert from 'node:assert/strict' import { test } from 'node:test' @@ -6,21 +12,26 @@ import { test } from 'node:test' import { WechatyBuilder } from 'wechaty' import { PuppetNeo } from 'wechaty-puppet-neo' -test('wechaty-puppet-neo', { timeout: 120_000 }, async () => { +test('wechaty-puppet-neo', { timeout: 120_000 }, async (t) => { const puppet = new PuppetNeo() const bot = WechatyBuilder.build({ - puppet, + // wechaty-puppet-neo@0.1.1 still bundles wechaty-puppet@1.x types + puppet: puppet as unknown as Exclude[0]>['puppet'], string | undefined>, }) let sawScan = false - // Neo rejects the background login when nobody scans the QR code. - // node:test fails the run on that rejection. Once a scan has arrived, - // the smoke test has done its job, so leave with success. - process.on('unhandledRejection', (reason) => { + // Neo rejects its background login promise when stopped before a QR scan. + // Register a scoped listener and remove it in t.after() so it never leaks. + const onUnhandledRejection = (reason: unknown) => { if (!sawScan) return console.error('Neo login was not completed after the QR code was shown.') console.error(reason) - process.exit(0) + } + process.on('unhandledRejection', onUnhandledRejection) + + t.after(async () => { + process.off('unhandledRejection', onUnhandledRejection) + await bot.stop().catch(() => undefined) }) const future = new Promise((resolve, reject) => { @@ -31,11 +42,7 @@ test('wechaty-puppet-neo', { timeout: 120_000 }, async () => { bot.once('error', reject) }) - try { - await bot.start() - await future - assert.ok(bot.puppet, `Puppet ${bot.puppet} v${bot.puppet.version()} smoke testing passed.`) - } finally { - await bot.stop().catch(() => undefined) - } + await bot.start() + await future + assert.ok(bot.puppet, `Puppet ${bot.puppet} v${bot.puppet.version()} smoke testing passed.`) }) diff --git a/tsconfig.json b/tsconfig.json index 237e9ff..212ddfb 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -14,8 +14,6 @@ "sourceMap": true, "skipLibCheck": true, "esModuleInterop": true, - "experimentalDecorators": true, - "emitDecoratorMetadata": true, "strict": true, "noEmitOnError": true, "noUnusedLocals": true,