diff --git a/.github/workflows/node.js.yml b/.github/workflows/node.js.yml index 0254b0a6..678c0887 100644 --- a/.github/workflows/node.js.yml +++ b/.github/workflows/node.js.yml @@ -16,13 +16,13 @@ jobs: strategy: matrix: os: + # macos-latest is Apple Silicon, which matches Neo's macOS addon. + # ubuntu-latest is Linux x64 and windows-latest is Windows x64. - macos-latest - windows-latest - ubuntu-latest node-version: - # Node 16 is EOL. 22 is the newest LTS line this Wechaty 1.x toolchain - # (ts-node 10 and the current puppet dependencies) is verified on. - - 22 + - 26 runs-on: ${{ matrix.os }} steps: @@ -38,4 +38,3 @@ jobs: - run: npm test env: CI: true - WECHATY_PUPPET_SERVICE_TOKEN: ${{ secrets.WECHATY_PUPPET_SERVICE_TOKEN }} diff --git a/.gitpod.dockerfile b/.gitpod.dockerfile deleted file mode 100644 index 701dd05e..00000000 --- a/.gitpod.dockerfile +++ /dev/null @@ -1,8 +0,0 @@ -FROM wechaty/wechaty:next -LABEL maintainer="Huan " - -RUN cd /tmp \ - && wget https://github.com/yudai/gotty/releases/download/v2.0.0-alpha.3/gotty_2.0.0-alpha.3_linux_amd64.tar.gz \ - && tar zxvf ./gotty*.tar.gz \ - && rm -f gotty*.tar.gz \ - && mv gotty* /usr/local/bin diff --git a/.gitpod.yml b/.gitpod.yml deleted file mode 100644 index 1e4877f6..00000000 --- a/.gitpod.yml +++ /dev/null @@ -1,47 +0,0 @@ -image: - file: .gitpod.dockerfile - -# List the ports you want to expose and what to do when they are served. See https://www.gitpod.io/docs/config-ports/ -# https://www.gitpod.io/docs/config-ports/ -ports: - - port: 8080 - onOpen: open-preview - -# List the start up tasks. You can start them in parallel in multiple terminals. See https://www.gitpod.io/docs/config-start-tasks/ -# https://www.gitpod.io/docs/config-start-tasks/ -tasks: - - name: Wechaty ding-dong BOT - openIn: main - openMode: split-right - # - # Huan(202002): `npm install` will fail the gitpod loading in browser - # https://github.com/wechaty/getting-started/issues/160 - # - init: | - echo '`npm install` will fail the gitpod loading in browser' - echo 'See: https://github.com/wechaty/getting-started/issues/160' - command: | - npm install - # WECHATY_PUPPET_SERVICE_TOKEN=XXX npm run start:puppet:service - # WECHATY_PUPPET_PADLOCAL_TOKEN=XXX npm run start:wechat:padlocal - # npm run start:whatsapp:web - npm run start:wechat:web - -github: - prebuilds: - # enable for the master/default branch (defaults to true) - master: true - # enable for all branches in this repo (defaults to false) - branches: false - # enable for pull requests coming from this repo (defaults to true) - pullRequests: true - # enable for pull requests coming from forks (defaults to false) - pullRequestsFromForks: false - # add a "Review in Gitpod" button as a comment to pull requests (defaults to true) - addComment: true - # add a "Review in Gitpod" button to pull requests (defaults to false) - addBadge: false - # add a label once the prebuild is ready to pull requests (defaults to false) - addLabel: false - # add a check to pull requests (defaults to true) - addCheck: true diff --git a/.vscode/settings.json b/.vscode/settings.json index 58854375..57a6d44f 100755 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -72,7 +72,6 @@ ], "cSpell.words": [ "KUBERNETES", - "gitpod", "gotty", "prebuild", "prebuilds" diff --git a/README.md b/README.md index 192f1b7d..73c42410 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # Wechaty Getting Started [![Powered by Wechaty](https://img.shields.io/badge/Powered%20By-Wechaty-brightgreen.svg)](https://wechaty.js.org) [![Node.js CI](https://github.com/wechaty/getting-started/workflows/Node.js%20CI/badge.svg)](https://github.com/wechaty/getting-started/actions?query=workflow%3A%22Node.js+CI%22) -![Node.js v16](https://img.shields.io/badge/node-%3E%3D16-green.svg) -[![TypeScript](https://img.shields.io/badge/%3C%2F%3E-TypeScript-blue.svg)](https://www.typescriptlang.org/) +![Node.js v26](https://img.shields.io/badge/node-%3E%3D26-green.svg) +[![TypeScript](https://img.shields.io/badge/TypeScript-7-blue.svg)](https://www.typescriptlang.org/) [![ES Modules](https://img.shields.io/badge/ES-Modules-brightgreen)](https://github.com/Chatie/tsconfig/issues/16) ## About Wechaty @@ -13,18 +13,18 @@ As a developer, you can use Wechaty to easily build your bot, effectively manage ## About Wechaty Getting Started Project -If you are a total beginner to Wechaty, this project is the best starting point for you. You can run it on a Cloud IDE in a couple of steps or on a local setup on your machine as described in the sections below. +If you are a total beginner to Wechaty, this project is the best starting point for you. You can run it on Google Cloud Shell or on a local setup on your machine as described in the sections below. If you encounter difficulties or have any questions, you are welcome to ask for help in our Discord Community at . -Notice: the current active version of Wechaty is v1.x which is not compatible with most of the v0.x modules. +This repository tracks Wechaty 2. It needs Node.js 26 or newer and TypeScript 7. - **`wechaty@0.x`** - To use the Wechaty v0.x, please visit the [Wechaty Getting Started v0.x](https://github.com/wechaty/getting-started/tree/v0.x) branch. ### Features of Wechaty Getting Started project -1. It works out of the box on Linux, Mac or Windows. -1. Supports all puppets like Web, Pad, Windows, and Mac. +1. It runs on Linux x64 and arm64 (glibc 2.38 or newer), macOS on Apple Silicon, and Windows x64. +1. The starter bot uses [Wechaty Puppet Neo](https://www.npmjs.com/package/wechaty-puppet-neo). 1. It replies with a `dong` message when it receives a `ding` message. ### Wechaty Getting Started video tutorial @@ -33,24 +33,10 @@ Notice: the current active version of Wechaty is v1.x which is not compatible wi -Above is a short run-through of deploying the ding-dong-bot using WeChat, WhatsApp, and WeCom. +Above is a short run-through of the ding-dong bot. ### Running Wechaty Getting Started Project on a cloud based IDE -The fastest way to getting started with Wechaty is to use a Cloud based IDE for running the Wechaty Getting Started Project. You can either use Gitpod or Google Cloud Shell. - -If you are a total beginner, then we recommed Gitpod. - -#### Using [Gitpod ❤️ Wechaty](docs/gitpod.md) - -Gitpod is an online and open source platform for automated and ready-to-code development environments. You can click the button below to access a complete setup of [Wechaty Getting Started ding-dong BOT](examples/ding-dong-bot.ts) project on gitpod. If you have never used gitpod before, you will be required to log in using your GitHub account. - -[![GitPod Ready-to-Code][gitpod_img]][gitpod_link] - -You can learn more about [Gitpod ❤️ Wechaty](docs/gitpod.md) from our blog: [Getting Started Without Leaving Your Browser: Wechaty ❤️ Gitpod, @huan, Feb 06, 2021](https://wechaty.js.org/2021/02/06/wechaty-getting-started-without-leave-your-browser/) - -#### Using Google Cloud Shell - Google Cloud Shell is an online development and operations environment accessible anywhere with your browser. You can run this project on Google Cloud Shell by clicking the button below. [![Open in Cloud Shell][shell_img]][shell_link] @@ -65,15 +51,25 @@ Learn more about running this project on Google Cloud Shell from our blog: [Goog #### Prerequisites -For you to run this project on your local machine, you need to: +For you to run this project on your local machine, you need [Node.js](https://nodejs.dev/) v26 or newer and npm 10 or newer. Run `node -v` and `npm -v` to check. A current Node.js 26 release looks like `v26.13.1`. + +Install Node.js from the links below when it is missing or older than 26: + +- [Windows](https://nodejs.org/en/download/package-manager/#windows) +- [Linux(Debian/Ubuntu)](https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions) +- [macOS](https://nodejs.org/en/download/package-manager/#macos) + +> Node.js for other platforms can be found at + +Puppet Neo publishes prebuilt native addons for: -1. Have [Node.js](https://nodejs.dev/) v16+ installed on your machine. You can run the command `node -v` on the terminal to check whether you have `Node.js` installed. If you have it, you should be able to see the version printed on the terminal like `v16.13.0`. Your version might be different from `v16.13.0`. If it is not installed or your version is below 16, You need to install the latest version by following the links below: - - [Windows](https://nodejs.org/en/download/package-manager/#windows) - - [Linux(Debian/Ubuntu)](https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions) - - [macOS](https://nodejs.org/en/download/package-manager/#macos) - > Node.js for other platforms can be found at +| Platform | Node.js | +| :--- | :--- | +| Linux x64 and arm64 | glibc 2.38 or newer | +| macOS | Apple Silicon | +| Windows x64 | x64 Node.js, including Windows on ARM under x64 emulation | -2. Have [Wechaty Puppet Service TOKEN](https://wechaty.js.org/docs/puppet-services/) if you want to use RPA protocols other than Web +Run `node -p process.arch` on Windows on ARM. It needs to print `x64`. #### Step 1: Clone this Repository @@ -92,79 +88,46 @@ You need to install dependencies by running the command below. npm install ``` -#### Step 3: Run the Bot - -You can use `export` to set environment variables in Linux, and use `set` in Windows. If you run into errors while running this command, check the troubleshooting tips in step 4. +`npm install` selects the newest Wechaty 2 release, including a later alpha, a beta, or a stable 2.x. -##### Linux +#### Step 3: Run the Bot -```shell -export WECHATY_LOG=verbose -export WECHATY_PUPPET=wechaty-puppet-wechat +```sh npm start -# the above is equals to the below command: -# npx ts-node examples/ding-dong-bot.ts ``` -##### Windows +The same command works on Linux, macOS, and Windows. Node.js runs `examples/ding-dong-bot.ts` directly. The bot is built with `WechatyBuilder` and `new PuppetNeo()`. -```shell -set WECHATY_LOG=verbose -set WECHATY_PUPPET=wechaty-puppet-wechat -npm start -# the above is equals to the below command: -# npx ts-node examples/ding-dong-bot.ts -``` +A QR code is printed in the terminal. Scan it with WeChat. Neo keeps the login in memory, so every start prints a new QR code. + +After the bot logs in, send `ding` from another WeChat account, in a direct chat or in a group that includes this account. The bot replies `dong`. You are all set! #### Step 4: Troubleshooting -If you run into problems while following the above steps, try the options below. You are also welcome to ask questions in our [gitter chatroom](https://gitter.im/wechaty/wechaty). - -1. You might also need [windows-build-tool](https://www.npmjs.com/package/windows-build-tool) if you are using windows: - - ```sh - npm install windows-build-tools - ``` - -## Working with Different Puppets +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). -In our getting started example, the ding-dong BOT uses [wechaty-puppet-wechat4u](https://github.com/wechaty/wechaty-puppet-wechat4u) when `WECHATY_PUPPET` is not set, which is just for newcomer's convenience. +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. +1. `node -p process.arch` is `x64` on Linux x64 and Windows, or `arm64` on Linux arm64 and macOS Apple Silicon. -By default, Wechaty will use the [Puppet Service](https://wechaty.js.org/docs/puppet-services/) for logging in your bot. You can use other [Puppet Provider](https://github.com/wechaty/wechaty-puppet/wiki/Directory) like Whatsapp Web protocol( [wechaty-puppet-whatsapp](https://github.com/wechaty/wechaty-puppet-whatsapp)). +## Wechaty Puppet Neo -If you want to use a Wechaty Puppet Provider for a different protocol, then you need to specify a puppet service provider name (the same as its NPM name) by setting the `WECHATY_PUPPET` environment variable. +The ding-dong bot in this repository uses [wechaty-puppet-neo](https://www.npmjs.com/package/wechaty-puppet-neo) through `WechatyBuilder`. -Thanks to the great contributions from our community, there are many Wechaty Puppets which can be used by Wechaty. They have helped us use protocols like Web, Pad, Mac, and Windows. +| Provider | NPM | Login | +| :--- | :--- | :--- | +| Puppet Neo | `wechaty-puppet-neo` | In memory. A new QR code on every start. | -### Wechaty Puppets +```ts +import { WechatyBuilder } from 'wechaty' +import { PuppetNeo } from 'wechaty-puppet-neo' -| Protocol | NPM | -| :--- | :--- | -| Puppet Service | `wechaty-puppet-service` | -| Whatsapp Web | `wechaty-puppet-whatsapp` | -| WeChat Web | `wechaty-puppet-wechat` | -| WeChat Pad | `wechaty-puppet-padlocal` | - -> Visit our website to learn more about [Wechaty Puppet Service Providers](https://wechaty.js.org/docs/puppet-services/) - -For example, if you want to use the `padlocal` puppet, you should set `WECHATY_PUPPET=wechaty-puppet-padlocal` before you run `npm start`. You also need a TOKEN for `wechaty-puppet-padlocal` which you need to set to the `WECHATY_PUPPET_PADLOCAL_TOKEN` environment variable. You can apply for the PadLocal TOKEN from [here](https://wechaty.js.org/docs/puppet-services/padlocal/). The code snippets below illustrate what has been described above on Linux/ MacOS and on Windows. - -### On Linux / macOS - -```sh -export WECHATY_PUPPET=wechaty-puppet-padlocal -export WECHATY_PUPPET_PADLOCAL_TOKEN='puppet_padlocal_your-token-here' -npm start -``` - -### On Windows - -```sh -set WECHATY_PUPPET=wechaty-puppet-padlocal -set WECHATY_PUPPET_PADLOCAL_TOKEN='puppet_padlocal_your-token-here' -npm start +const bot = WechatyBuilder.build({ + name: 'ding-dong-bot', + puppet: new PuppetNeo(), +}) ``` Learn more about installing Wechaty on windows from this [blog post](https://wechaty.js.org/2018/07/24/wechaty-installation-in-windows-10/). @@ -185,6 +148,8 @@ Above is a 10 minute video tutorial. It is using version 0.14 or older versions - [Official Wechaty Examples Directory](https://github.com/wechaty/getting-started/tree/master/examples) +The files under `examples/` other than the two starter bots are v1-era samples. The root package does not install them. + ## API REFERENCE 1. Official API Docs: @@ -209,19 +174,15 @@ Above is a 10 minute video tutorial. It is using version 0.14 or older versions ## FAQ -### 1. I can not login with my Wechat account - -WeChat account registered after 2017 will not be able to login via Web API. Learn more about it at +### 1. How do I log in -Solution: You can use Wechaty support protocols other than Web API, such as pad. Learn more at +`npm start` prints a QR code. Scan it with WeChat and confirm the login on the phone. Neo stores that login in memory, so stopping the process and starting it again prints a new QR code. ### 2. What is a `Puppet` in Wechaty -The term [Puppet](https://github.com/Chatie/wechaty/wiki/Puppet) in Wechaty is an Abstract Class for implementing protocol plugins. The plugins are the components that help Wechaty to control Wechat and that's the reason why we call it puppet. +The term [Puppet](https://github.com/wechaty/wechaty/wiki/Puppet) in Wechaty is an abstract class for implementing protocol plugins. The plugins are the components that help Wechaty control a chat service, which is why they are called puppets. -The plugins are named `PuppetXXX`, for example [PuppetWeChat](https://github.com/Chatie/wechaty-puppet-wechat) is using the [google puppeteer](https://github.com/GoogleChrome/puppeteer) to control the [WeChat Web API](https://wx.qq.com) via a chrome browser, [PuppetPadchat](https://github.com/lijiarui/wechaty-puppet-padchat) uses the WebSocket protocol to connect with a Protocol Server for controlling the iPad Wechat program. For more details you can go to [Puppet in wiki](https://github.com/Chatie/wechaty/wiki/Puppet). - -Learn more about Wechaty Puppet from our documentation at [Wechaty Puppet](https://wechaty.js.org/docs/specifications/puppet) +This repository uses [PuppetNeo](https://www.npmjs.com/package/wechaty-puppet-neo). Learn more from the documentation at [Wechaty Puppet](https://wechaty.js.org/docs/specifications/puppet). ## Wechaty Getting Started in Multiple Languages @@ -242,6 +203,10 @@ Learn more about Wechaty Puppet from our documentation at [Wechaty Puppet](https ## History +### main (Wechaty 2) + +Node.js 26, TypeScript 7, and [wechaty-puppet-neo](https://www.npmjs.com/package/wechaty-puppet-neo). The starter bot uses `WechatyBuilder` and `new PuppetNeo()`. + ### main v1.18 (Mar 14, 2022) Add CQRS Wechaty examples. @@ -258,12 +223,6 @@ Branch: [v1.11](https://github.com/wechaty/getting-started/tree/v1.11): release Using Google Cloud Shell for a quick setup! -### v0.6 (Feb 11, 2021) - -[![GitPod Ready-to-Code][gitpod_img]][gitpod_link] - -Using Gitpod for a quick setup! - ### v0.0.1 (Jan 12, 2017) Init version @@ -289,8 +248,5 @@ Init version - Code released under the Apache-2.0 License - Docs released under Creative Commons -[gitpod_img]: https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod -[gitpod_link]: https://gitpod.io/#https://github.com/wechaty/getting-started - [shell_img]: https://gstatic.com/cloudssh/images/open-btn.svg [shell_link]: https://ssh.cloud.google.com/cloudshell/editor?cloudshell_git_repo=https%3A%2F%2Fgithub.com%2Fwechaty%2Fgetting-started&cloudshell_open_in_editor=examples/ding-dong-bot.ts&cloudshell_workspace=.&cloudshell_tutorial=examples/tutorials/google-cloud-shell-tutorial.md diff --git a/docs/gitpod.md b/docs/gitpod.md deleted file mode 100644 index 851010f3..00000000 --- a/docs/gitpod.md +++ /dev/null @@ -1,53 +0,0 @@ -# 👇 **Click me** - -[![GitPod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/wechaty/getting-started) - -Click the ☝️ above `[Gitpod | Ready-to-Code]` button to launch Gitpod with Wechaty Getting Started ding-dong BOT instantly inside your favorite browser. - -The button will take you to this link: - -GitHub links: - -- Repo: -- Pages - -## Screenshot - -You can [join our Gitter](https://gitter.im/wechaty/wechaty) network if you aren’t already a member. - -[![GitPod Wechaty Getting Started](images/gitpod-wechaty.webp)](https://gitpod.io/#https://github.com/wechaty/getting-started) - -> Wechaty ❤️ Gitpod - -## What is Gitpod - -> Gitpod is an online IDE which can be launched from any GitHub page. Simply prefix any GitHub-URL with “” or use our browser extension that adds a button to GitHub pages. -> -> Within seconds, Gitpod provides you with a fully working development environment, including a VS Code-powered IDE and a cloud-based Linux container configured specifically for the project at hand. -> -> — [Gitpod — Online IDE For GitHub](https://medium.com/gitpod/gitpod-gitpod-online-ide-for-github-6296b907a886) - -[Here](https://stackoverflow.com/a/63595356/1123955) has a Stackoverflow answer from Gitpod co-founder Moriz Eysholdt. - -## What is Wechaty - -[Wechaty](https://github.com/wechaty/wechaty/) is a Conversational RPA SDK for Chatbot Makers. It's well designed with an easy to use API, supports all OSs including Linux, OSX, Win32, Docker, and lots of IMs including WeChat, WeCom, Whatsapp, Lark, Gitter, etc. - -## What is Wechaty Getting Started - -[Wechaty Getting Started](https://github.com/wechaty/getting-started) is a repository that work out-of-the-box, which is the best start point for Wechaty beginners. - -As a developer, you can use Wechaty to easily build your bot, effectively manage message sending/receiving, room creating/inviting, contact friendship, and delightful add artificial intelligence between users and your bot. - -- GitHub: -- `ding-dong-bot.ts`: - -## Maintainers - -[@wechaty/contributors](https://github.com/orgs/wechaty/teams/contributors/members) - -## Copyright & License - -- Code & Docs © 2018-now Huan and Wechaty Community Contributors () -- Code released under the Apache-2.0 License -- Docs released under Creative Commons diff --git a/docs/images/gitpod-wechaty.webp b/docs/images/gitpod-wechaty.webp deleted file mode 100644 index 132279c4..00000000 Binary files a/docs/images/gitpod-wechaty.webp and /dev/null differ diff --git a/examples/README.md b/examples/README.md index 14d10ea6..d410cff0 100644 --- a/examples/README.md +++ b/examples/README.md @@ -2,6 +2,8 @@ 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.js](basic/ding-dong-bot.js), the best starter template for you. +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. + | Filename | Description | 描述 | | --- | --- | --- | | ding-dong-bot.ts | The Best Starter Template for You | | diff --git a/examples/basic/ding-dong-bot.js b/examples/basic/ding-dong-bot.js index beace1a2..97c760ad 100644 --- a/examples/basic/ding-dong-bot.js +++ b/examples/basic/ding-dong-bot.js @@ -18,11 +18,12 @@ */ import 'dotenv/config.js' - import { +import { WechatyBuilder, ScanStatus, log, } from 'wechaty' +import { PuppetNeo } from 'wechaty-puppet-neo' import qrcodeTerminal from 'qrcode-terminal' function onScan (qrcode, status) { @@ -57,21 +58,13 @@ async function onMessage (msg) { } } +/** + * Puppet Neo keeps the login in memory and prints a new QR code on every start. + * Scan that code with WeChat. + */ const bot = WechatyBuilder.build({ name: 'ding-dong-bot', - /** - * How to set Wechaty Puppet Provider: - * - * 1. Specify a `puppet` option when instantiating Wechaty. (like `{ puppet: 'wechaty-puppet-padlocal' }`, see below) - * 1. Set the `WECHATY_PUPPET` environment variable to the puppet NPM module name. (like `wechaty-puppet-padlocal`) - * - * You can use the following providers: - * - wechaty-puppet-wechat (no token required) - * - wechaty-puppet-padlocal (token required) - * - wechaty-puppet-service (token required, see: ) - * - etc. see: - */ - // puppet: 'wechaty-puppet-wechat', + puppet: new PuppetNeo(), }) bot.on('scan', onScan) diff --git a/examples/ding-dong-bot.ts b/examples/ding-dong-bot.ts index 5c17e0f7..2d375d28 100755 --- a/examples/ding-dong-bot.ts +++ b/examples/ding-dong-bot.ts @@ -1,4 +1,4 @@ -#!/usr/bin/env -S node --no-warnings --loader ts-node/esm +#!/usr/bin/env node /** * Wechaty - Conversational RPA SDK for Chatbot Makers. * - https://github.com/wechaty/wechaty @@ -8,12 +8,13 @@ import 'dotenv/config.js' import { - Contact, - Message, ScanStatus, WechatyBuilder, log, + type Contact, + type Message, } from 'wechaty' +import { PuppetNeo } from 'wechaty-puppet-neo' import qrcodeTerminal from 'qrcode-terminal' @@ -48,40 +49,13 @@ async function onMessage (msg: Message) { } } +/** + * Puppet Neo keeps the login in memory and prints a new QR code on every start. + * Scan that code with WeChat. + */ const bot = WechatyBuilder.build({ name: 'ding-dong-bot', - /** - * You can specific `puppet` and `puppetOptions` here with hard coding: - * - puppet: 'wechaty-puppet-wechat', - puppetOptions: { - uos: true, - }, - */ - /** - * How to set Wechaty Puppet Provider: - * - * 1. Specify a `puppet` option when instantiating Wechaty. (like `{ puppet: 'wechaty-puppet-whatsapp' }`, see below) - * 1. Set the `WECHATY_PUPPET` environment variable to the puppet NPM module name. (like `wechaty-puppet-whatsapp`) - * - * You can use the following providers locally: - * - wechaty-puppet-wechat (web protocol, no token required) - * - wechaty-puppet-whatsapp (web protocol, no token required) - * - wechaty-puppet-padlocal (pad protocol, token required) - * - etc. see: - */ - // puppet: 'wechaty-puppet-whatsapp' - - /** - * You can use wechaty puppet provider 'wechaty-puppet-service' - * which can connect to remote Wechaty Puppet Services - * for using more powerful protocol. - * Learn more about services (and TOKEN) from https://wechaty.js.org/docs/puppet-services/ - */ - // puppet: 'wechaty-puppet-service' - // puppetOptions: { - // token: 'xxx', - // } + puppet: new PuppetNeo(), }) bot.on('scan', onScan) diff --git a/examples/professional/chatgpt-bot/README.md b/examples/professional/chatgpt-bot/README.md deleted file mode 100644 index b3f55291..00000000 --- a/examples/professional/chatgpt-bot/README.md +++ /dev/null @@ -1,22 +0,0 @@ -# Wechaty ChatGPT - -This is a wechaty implementation of ChatBot powered by OpenAI ChatGPT - -## Setup - -Modify `dotenv` file to add your openai_api_key as well as the service_token -``` -OPENAI_API_KEY="" -WECHATY_PUPPET_SERVICE_TOKEN="" -``` - -```shell -npm install -mv dotenv .env -``` - -## Run - -```shell -npm run start -``` diff --git a/examples/professional/chatgpt-bot/bot.ts b/examples/professional/chatgpt-bot/bot.ts deleted file mode 100644 index e13cb79d..00000000 --- a/examples/professional/chatgpt-bot/bot.ts +++ /dev/null @@ -1,49 +0,0 @@ -// Importing the Wechaty npm package -import { Wechaty,WechatyBuilder, Contact, Message, ScanStatus, log } from "wechaty"; -import { Configuration, OpenAIApi, ChatCompletionRequestMessage } from "openai"; -import { PuppetPadlocal } from "wechaty-puppet-padlocal"; -import { onScan, onLogin, onLogout, onMessage, onFriendship } from "./utils"; -import dotenv from "dotenv"; - -dotenv.config(); -console.log(process.env.OPENAI_API_KEY) - - -export function createBot(): Wechaty { - const token: string = process.env.WECHATY_PUPPET_SERVICE_TOKEN! - const puppet = new PuppetPadlocal({ - token, - }); - - return WechatyBuilder.build({ - name: "chatgpt-bot", - puppet, - }); -} - - -// config openAI -const configuration = new Configuration({ - apiKey: process.env.OPENAI_API_KEY, -}); -export const openai = new OpenAIApi(configuration); - -// Initializing the bot -export const bot = createBot(); - -// Keep the conversation state -export const initState: Array = new Array({ "role": "system", "content": "You are a helpful assistant." }) - -bot.on('scan', onScan) -bot.on('login', onLogin) -bot.on('logout', onLogout) -bot.on('message', onMessage) -bot.on('friendship', onFriendship) - -bot.start() - .then(() => log.info('StarterBot', 'Starter Bot Started.')) - .catch(e => log.error('StarterBot', e)) - -bot.ready() - .then(() => log.info('StarterBot', 'Starter Bot Ready.')) - .catch(e => log.error('StarterBot', e)) \ No newline at end of file diff --git a/examples/professional/chatgpt-bot/dotenv b/examples/professional/chatgpt-bot/dotenv deleted file mode 100644 index 1434f102..00000000 --- a/examples/professional/chatgpt-bot/dotenv +++ /dev/null @@ -1,2 +0,0 @@ -OPENAI_API_KEY="" -WECHATY_PUPPET_SERVICE_TOKEN="" diff --git a/examples/professional/chatgpt-bot/package.json b/examples/professional/chatgpt-bot/package.json deleted file mode 100644 index da622e43..00000000 --- a/examples/professional/chatgpt-bot/package.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "wechaty-chatgpt", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "start": "npx ts-node bot.ts", - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "dotenv": "^16.0.3", - "file-box": "^1.5.5", - "markdown-it": "^13.0.1", - "node-html-to-image": "^3.3.0", - "openai": "^3.2.1", - "qrcode-terminal": "^0.12.0", - "ts-node": "^10.9.1", - "wechaty": "^1.20.2", - "wechaty-puppet-padlocal": "^1.20.1", - "wechaty-puppet-service": "^1.19.9", - "wechaty-puppet-wechat": "^1.18.4" - }, - "devDependencies": { - "@types/markdown-it": "^12.2.3", - "@types/qrcode-terminal": "^0.12.0" - } -} diff --git a/examples/professional/chatgpt-bot/run.sh b/examples/professional/chatgpt-bot/run.sh deleted file mode 100755 index 4aa1329f..00000000 --- a/examples/professional/chatgpt-bot/run.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash - -export WECHATY_LOG=verbose -export WECHATY_PUPPET=wechaty-puppet-service - -npm run start diff --git a/examples/professional/chatgpt-bot/utils.ts b/examples/professional/chatgpt-bot/utils.ts deleted file mode 100644 index 5ff2d5bd..00000000 --- a/examples/professional/chatgpt-bot/utils.ts +++ /dev/null @@ -1,157 +0,0 @@ -import { Contact, Message, ScanStatus, log, Friendship } from "wechaty"; -import { bot, openai, initState } from "./bot"; -import markdownIt from 'markdown-it'; -import { ChatCompletionRequestMessage } from "openai"; -import { FileBox } from "file-box"; -import qrTerm from "qrcode-terminal"; -import nodeHtmlToImage from 'node-html-to-image'; - -const MEMORY_LIMIT = 50; // max memory -let conversation: Array = new Array(); -conversation.forEach(val => initState.push(Object.assign({}, val))); - -function convertMarkdownToHtml(markdown: string): string { - const md = new markdownIt(); - return md.render(markdown); -} - -export function onScan (qrcode: string, status: ScanStatus) { - if (status === ScanStatus.Waiting || status === ScanStatus.Timeout) { - qrTerm.generate(qrcode, { small: true }) // show qrcode on console - - const qrcodeImageUrl = [ - 'https://wechaty.js.org/qrcode/', - encodeURIComponent(qrcode), - ].join('') - - log.info('StarterBot', 'onScan: %s(%s) - %s', ScanStatus[status], status, qrcodeImageUrl) - } else { - log.info('StarterBot', 'onScan: %s(%s)', ScanStatus[status], status) - } - } - -export function onLogin(user: Contact) { - log.info('StarterBot', '%s login', user) -} - -export function onLogout(user: Contact) { - log.info('StarterBot', '%s logout', user) -} - -export async function onMessage(msg: Message) { - log.info('StarterBot', msg.toString()) - - const contact = msg.talker(); - const content = msg.text(); - const isText = msg.type() === bot.Message.Type.Text; - if (msg.self() || !isText) { // msg.self() check if the message is sent from the bot itself - return; - } - if (content === 'ding') { - await contact.say('dong'); - } - // return image - if (content.startsWith("/img ")) { - if (conversation.length === MEMORY_LIMIT) { - // reset to initial state when reach the memory limit - log.info("Resetting memory"); - conversation = new Array(); - conversation.forEach(val => initState.push(Object.assign({}, val))); - } - conversation.push({ "role": "user", "content": content.replace("/i", "") }) - const response = await openai.createChatCompletion({ - model: "gpt-3.5-turbo", - messages: conversation, - }); - - try { - const replyContent = response.data.choices[0].message!.content! - const html = convertMarkdownToHtml(replyContent); - await nodeHtmlToImage({ - output: './output.png', - html: html - }) - - log.info('The image was created successfully!') - const fileBox = FileBox.fromFile("./output.png"); - await contact.say(fileBox) - - // record reply - const reply: ChatCompletionRequestMessage = { "role": "assistant", "content": replyContent }; - conversation.push(reply); - } catch (e) { - console.error(e) - } - } else { - // return text if no slash command is specified - if (conversation.length === MEMORY_LIMIT) { - // reset to initial state when reach the memory limit - log.info("Resetting memory"); - conversation = new Array(); - conversation.forEach(val => initState.push(Object.assign({}, val))); - } - conversation.push({ "role": "user", "content": content.replace("/t", "") }) - const response = await openai.createChatCompletion({ - model: "gpt-3.5-turbo", - messages: conversation, - }); - - try { - const replyContent = response.data.choices[0].message!.content! - await contact.say(replyContent); - - // record reply - const reply: ChatCompletionRequestMessage = { "role": "assistant", "content": replyContent }; - conversation.push(reply); - } catch (e) { - console.error(e); - } - } -} - -export async function onFriendship(friendship: Friendship) { - let logMsg; - - try { - logMsg = "received `friend` event from " + friendship.contact().name(); - log.info(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 bot.Friendship.Type.Receive: - logMsg = 'accepted automatically'; - log.info("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(`Hi ${friendship.contact().name()} from FreeChatGPT, I am your person asistant!\n你好 ${friendship.contact().name()} 我是你的私人助理FreeChatGPT!`); - console.log("after accept"); - break; - - /** - * - * 2. Friend Ship Confirmed - * - */ - case bot.Friendship.Type.Confirm: - logMsg = "friendship confirmed with " + friendship.contact().name(); - break; - - default: - break; - } - } catch (e) { - console.error(e); - logMsg = "Friendship try catch failed"; - } - - log.info(logMsg); -} \ No newline at end of file diff --git a/examples/third-parties/codesandbox/.gitignore b/examples/third-parties/codesandbox/.gitignore deleted file mode 100644 index ac820ce7..00000000 --- a/examples/third-parties/codesandbox/.gitignore +++ /dev/null @@ -1 +0,0 @@ -gotty diff --git a/examples/third-parties/codesandbox/README.md b/examples/third-parties/codesandbox/README.md deleted file mode 100644 index cba81426..00000000 --- a/examples/third-parties/codesandbox/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# CodeSandBox Wechaty Getting Started - -See: diff --git a/examples/third-parties/codesandbox/ding-dong-bot.ts b/examples/third-parties/codesandbox/ding-dong-bot.ts deleted file mode 100644 index 7c23d7f7..00000000 --- a/examples/third-parties/codesandbox/ding-dong-bot.ts +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Wechaty - WeChat Bot SDK for Personal Account, Powered by TypeScript, Docker, and 💖 - * - https://github.com/wechaty/wechaty - */ -import { - Contact, - Message, - ScanStatus, - WechatyBuilder, - log, -} from 'wechaty' - -import qrTerm from 'qrcode-terminal' - -function onScan (qrcode: string, status: ScanStatus) { - if (status === ScanStatus.Waiting || status === ScanStatus.Timeout) { - qrTerm.generate(qrcode, { small: true }) // show qrcode on console - - const qrcodeImageUrl = [ - 'https://wechaty.js.org/qrcode/', - encodeURIComponent(qrcode), - ].join('') - - log.info('StarterBot', 'onScan: %s(%s) - %s', ScanStatus[status], status, qrcodeImageUrl) - } else { - log.info('StarterBot', 'onScan: %s(%s)', ScanStatus[status], status) - } -} - -function onLogin (user: Contact) { - log.info('StarterBot', '%s login', user) -} - -function onLogout (user: Contact) { - log.info('StarterBot', '%s logout', user) -} - -async function onMessage (msg: Message) { - log.info('StarterBot', msg.toString()) - - if (msg.text() === 'ding') { - await msg.say('dong') - } -} - -const bot = WechatyBuilder.build({ - name: 'ding-dong-bot', - /** - * Specify a `puppet` for a specific protocol (Web/Pad/Mac/Windows, etc). - * - * You can use the following providers: - * - wechaty-puppet-hostie - * - wechaty-puppet-wechat - * - wechaty-puppet-padplus - * - etc. - * - * Learn more about Wechaty Puppet Providers at: - * https://github.com/wechaty/wechaty-puppet/wiki/Directory - */ - - // puppet: 'wechaty-puppet-hostie', - puppet: 'wechaty-puppet-wechat4u', - -}) - -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)) diff --git a/examples/third-parties/codesandbox/install-gotty.sh b/examples/third-parties/codesandbox/install-gotty.sh deleted file mode 100755 index f76aa7eb..00000000 --- a/examples/third-parties/codesandbox/install-gotty.sh +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env bash - -[ -e gotty ] || { - wget https://github.com/yudai/gotty/releases/download/v2.0.0-alpha.3/gotty_2.0.0-alpha.3_linux_amd64.tar.gz - tar zxvf ./gotty*.tar.gz - rm -f gotty*.tar.gz -} diff --git a/examples/third-parties/codesandbox/package.json b/examples/third-parties/codesandbox/package.json deleted file mode 100644 index 4a8b9658..00000000 --- a/examples/third-parties/codesandbox/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "codesandbox-wechaty-getting-started", - "version": "0.5.1", - "description": "Wechaty is a Conversational SDK for Chatbot Makers", - "type": "module", - "engines": { - "node": ">=16" - }, - "scripts": { - "gotty": "bash -x install-gotty.sh", - "start": "npm install && npm run gotty && pwd && ls -l && npm ls nodemon && ./gotty --ws-origin '.*' npm run bot", - "bot": "cross-env NODE_OPTIONS=\"--no-warnings --loader=ts-node/esm\" WECHATY_LOG=verbose nodemon -w ding-dong-bot.ts ding-dong-bot.ts" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/wechaty/getting-started.git" - }, - "keywords": [], - "author": "Huan LI ", - "license": "Apache-2.0", - "bugs": { - "url": "https://github.com/wechaty/getting-started/issues" - }, - "homepage": "https://github.com/wechaty/getting-started#readme", - "dependencies": { - "@chatie/tsconfig": "^0.20.2", - "cross-env": "^7.0.3", - "nodemon": "^2.0.12", - "qrcode-terminal": "^0.12.0", - "wechaty": "^0.69.47", - "wechaty-puppet-mock": "^0.28.3", - "wechaty-puppet-wechat4u": "^0.19.2" - } -} diff --git a/examples/third-parties/codesandbox/sandbox.config.json b/examples/third-parties/codesandbox/sandbox.config.json deleted file mode 100644 index 0da04c0c..00000000 --- a/examples/third-parties/codesandbox/sandbox.config.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "container": { - "node": "16" - } -} diff --git a/examples/third-parties/codesandbox/tsconfig.json b/examples/third-parties/codesandbox/tsconfig.json deleted file mode 100644 index 1c23b7c6..00000000 --- a/examples/third-parties/codesandbox/tsconfig.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "extends": "@chatie/tsconfig", - "compilerOptions": { - "outDir": "dist" - }, - "exclude": [ - "node_modules/", - "dist/", - "tests/fixtures/" - ], - "include": [ - "app/**/*.ts", - "bin/*.ts", - "bot/**/*.ts", - "examples/**/*.ts", - "scripts/**/*.ts", - "src/**/*.ts", - "tests/**/*.spec.ts" - ] -} diff --git a/examples/third-parties/maodou/README.md b/examples/third-parties/maodou/README.md deleted file mode 100644 index 82446f3d..00000000 --- a/examples/third-parties/maodou/README.md +++ /dev/null @@ -1,39 +0,0 @@ -## Instructions for maodou-ketang-bot - -This is a third-party bot built using wechaty and [maodouketang courses API](https://api.maodouketang.com). - -* To see a preview demo of this bot, you need - - simply add "毛豆课堂小助手" as your wechat friend and send msg to her. - -* To run a bot of yourself, you need - - ```git clone``` this repo and ```cd wechaty-getting-started/examples/third-party/maodou``` - - Within this directory, type ```npm install``` and ```npm start``` and you are good to go! - - ```npm run dev``` if you want to see all debug logs and debug your own code - -To get your own authorization in fetchMaodouAPI, you need to follow these 3 steps: -1. Search a mini-program in wechat -> discover named "毛豆课堂", click it and login with your phone number. -2. Re-Login using your phone number in web page [kid.maodouketang.com](https://kid.maodouketang.com). -3. Find your auth_token in your browser->Application->Local Storage and replace authorization with auth_token value. - -You can also use maodouketang api to create your own reminders for your and your kid's classtime alert. - -Want to do more with this reminder bot? Please read this [maodou api spec](https://maodoukidclass.docs.apiary.io/). - -## Speical Thanks to -* [xiaoli news API](https://xiaoli.ai) from which comes this original code boilerplate -* [Zixia](https://zixia.net) who inspires me to opensource this code and re-do coding after 15+ years - -## Some useful referrences -* [@microsoft/recognizers-text-suite](https://github.com/microsoft/Recognizers-Text) I use this nlp api now to parse for time - - [@microsoft/recognizers-text-suite](https://www.npmjs.com/package/@microsoft/recognizers-text-suite) - - [@microsoft/recognizers-text-date-time](https://www.npmjs.com/package/@microsoft/recognizers-text-date-time) -* [bosonnlp](https://bosonnlp.com) I also use this nlp api to parse for title and location - - [BosonNLP NER](http://docs.bosonnlp.com/ner.html) this api is what I only find to get location, anyone knows other good solution? -* [Time-NLP](https://github.com/shinyke/Time-NLP) -* [ChiTimeNLP](https://github.com/JohnnieFucker/ChiTimeNLP) I used these two packages before switching to microsoft - - [chi-time-nlp npm package](https://www.npmjs.com/package/chi-time-nlp) v1.0.4 - - [chi-time-nlp-after npm package](https://www.npmjs.com/package/chi-time-nlp-after) v1.0.5 improved version - -## Contact -* http://maodou.io This is the company I work for -* Wechat ID: limingth, which is also [my personal github](https://github.com/limingth) ID \ No newline at end of file diff --git a/examples/third-parties/maodou/maodou-classes-bot.js b/examples/third-parties/maodou/maodou-classes-bot.js deleted file mode 100644 index 37f9662e..00000000 --- a/examples/third-parties/maodou/maodou-classes-bot.js +++ /dev/null @@ -1,168 +0,0 @@ -#!/usr/bin/env node -/** - * Powered by Wechaty - https://github.com/chatie/wechaty - * - * @author limingth - * - * This is a maodouketang reminder wechat bot. - * It can alert you when your class time is up. - * You can get alert by 4 ways: sms, call, email and wxmsg(wechat-miniapp-msg) - */ -import { - Wechaty, - Message, - config, -} from 'wechaty' -import qrTerm from 'qrcode-terminal' - -// import Debug from 'debug' -// const debug = Debug('maodou:api/utils/agenda.js') -import debug from 'debug' -import createCourse from './maodou-course-api.js' -/* - * Declare the Bot - * - */ - -const bot = WechatyBuilder.build({ - //profile: config.default.DEFAULT_PROFILE, - profile: 'maodou', -}) - -/** - * - * Register event handlers for Bot - * - */ -bot - .on('logout', onLogout) - .on('login', onLogin) - .on('scan', onScan) - .on('error', onError) - .on('message', onMessage) - -/** - * - * Start the bot! - * - */ -// getDaily() -bot.start() - .catch(async e => { - console.error('Bot start() fail:', e); - await bot.stop(); - process.exit(-1) - }) - -/** - * - * Define Event Handler Functions for: - * `scan`, `login`, `logout`, `error`, and `message` - * - */ -function onScan(qrcode, status) { - //qrTerm.generate(qrcode, {small: true}) - qrTerm.generate(qrcode) - - // 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: `) -} - -async function onLogin(user) { - console.log(`${user.name()} login`) -} - -function onLogout(user) { - console.log(`${user.name()} logouted`) -} - -function onError(e) { - console.error('Bot error:', e) -} - -function makeReport(course) { - let news = '[课程创建成功通知]\n' - - let title = '\n标题: ' + course.title + '\n' - let time = '时间: ' + new Date(course.start_time).toLocaleString() + '\n' - let location = '地点: ' + course.location + '\n' - let notes = '\n消息原文: \n' + course.notes + '\n' - - let url = '\n课程链接: https://kid.maodouketang.com/course/' + course._id + '\n' - let report = news + title + time + location + notes + url + '\n- microsoft nlp powered' - - return report -} - -/** - * send a report - */ -async function sendReportToRoom(report, room_topic) { - const room = await bot.Room.find({topic: room_topic}) //get the room by topic - if (room) - console.log('Sending Report to room ', room_topic, 'id:', room.id) - else - console.log('room_topic ', room_topic, '不存在') - - debug('report', report) - room.say(report) -} - -/** - * - * Dealing with Messages - * - */ -async function onMessage(msg) { - const room = msg.room() - const from = msg.from() - - if (!from) { - return - } - - console.log((room ? '[' + await room.topic() + ']' : '') - + '<' + from.name() + '>' - + ':' + msg, - ) - - if (msg.type() !== bot.Message.Type.Text) { - console.log('[Bot] ==> Message discarded because it is not a text message') - return - } - - // Skip message from self - if (msg.self() || from.name() === '微信团队' || from.name() === '毛豆课堂小助手' ) { - console.log('[Bot] ==> Message discarded because it is from self or 毛豆课堂小助手') - return - } - - // Now we begin to parse this msg - let msgText = msg.text() - debug('[original]', {msgText}) - - const room_topic = room ? await room.topic() : null - - // create course using msgText, and send report to wechat admin group - createCourse(msgText, function(newCourse) { - debug("[newCourse]", newCourse) - // get report from newCourse - var report = makeReport(newCourse) - console.log("[New course report]", report) - - // only these 2 admin groups will receive report - if (room_topic === '毛豆少儿课堂产品开发组' || room_topic === 'Wechaty LiLiLi') - sendReportToRoom(report, room_topic) - - // if this message is from a single chatter, just send report back to this chatter - if (!room_topic) - msg.say(report) - }) -} - diff --git a/examples/third-parties/maodou/maodou-course-api.js b/examples/third-parties/maodou/maodou-course-api.js deleted file mode 100644 index f3c413e7..00000000 --- a/examples/third-parties/maodou/maodou-course-api.js +++ /dev/null @@ -1,110 +0,0 @@ -import { parseTime, parseTitleAndLocation } from './maodou-nlp.js' - -import debug from 'debug' -import fetch from 'node-fetch' - -function createCourse(originalText, createCallback) { - // get rid of html tags like in case someone use emoji input - var msgText = originalText.replace(/<[^>]*>?/gm, '') - debug("[-emoji]", {msgText}) - - // get rid of blank space in the left - msgText = msgText.replace(/(^\s*)/g, '') - debug("[-space]", {msgText}) - - const time = parseTime(msgText) - console.log('[parser] ==> Time: ', {time}) - - // now we have 'time', next we use bosonnlp to parse for 'title' and 'location' - if (time) { - parseTitleAndLocation(msgText, function(title, location) { - console.log('[parser] ==> Title: ', {title}) - console.log('[parser] ==> Location: ', {location}) - - // title, start_time, location, notes is 4 params to create a new maodou course - const start_time = time - const notes = originalText - createMaodouCourse(title, start_time, location, notes, createCallback) - }) - } -} - -/** - * query Maodou api to create a new course - * @param title: required - * @param start_time, location, notes: options - */ -async function createMaodouCourse(title, start_time, location, notes, createMaodouCourseCallback) { - debug('createCourse params:', {title}, {start_time}, {location}, {notes}) - - let path = '/courses' - let postBody = { - "title": title, - "start_time": start_time, - "location": location, - "duration": 3600, - "count": 1, - "freq": "NONE", - "alerts": [ - // { - // at: -3600, //单位s - // by: 'sms', - // }, - { - at: -1800, - by: 'wxmsg', - }, - { - at: -900, - by: 'call', - }, - ], - "notes": notes - } - - // call maodou api - await fetchMaodouAPI(path, postBody, createMaodouCourseCallback) - return -} - -/** - * Fetch response from Maodou API - * @param URL - * @param postBody - * @param fetchCallback: covert json to msg text when fetch succeeds - */ -async function fetchMaodouAPI(path, postBody, fetchCallback) { - let resText = null - const url = 'https://api.maodouketang.com/api/v1' + path - const options = { - method: "POST", - body: JSON.stringify(postBody), // put keywords and token in the body - // If you want to get alert by your own phone, replace with your own 'authorization' - // To get your own 'authorization', please see it in README.md - headers: { - 'Content-Type': 'application/json', - 'authorization': "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1ZDA5ZjcxYTQyOTg4YjAwMTI2ZmYxYmMiLCJvcGVuSWQiOiJvRHprWTBUTjlfTmNLdXZCYVo1SzhzeE1NZHNzIiwiaWF0IjoxNTYwOTM0MTcwLCJleHAiOjE1NjYxMTgxNzB9.-NtfK62Y1S_EHAkA2Y0j5BW4qtb7IdH2mpq85NUqPuA" - } - } - debug('fetchMaodouAPI: ', {url}, {options}) - - try { - let resp = await fetch( url, options ) - let resp_json = await resp.json() - if (resp.ok) { - // status code = 200, we got it! - debug('[resp_json.data]', resp_json['data']) - resText = fetchCallback(resp_json['data']) - } else { - // status code = 4XX/5XX, sth wrong with API - debug('[resp_json.msg]', resp_json['msg']) - resText = 'API ERROR: ' + resp_json['msg'] - } - } catch (err) { - debug('[err]', err) - resText = 'NETWORK ERROR: ' + err - } - return resText -} - -module.exports = createCourse diff --git a/examples/third-parties/maodou/maodou-nlp.js b/examples/third-parties/maodou/maodou-nlp.js deleted file mode 100644 index 232e7592..00000000 --- a/examples/third-parties/maodou/maodou-nlp.js +++ /dev/null @@ -1,165 +0,0 @@ -import debug from 'debug' -import bosonnlp from 'bosonnlp' - -import Recognizers from '@microsoft/recognizers-text-suite' - -const defaultCulture = Recognizers.Culture.Chinese; - -//import NLP from 'chi-time-nlp' -// var nlp = new NLP() - -var b_nlp = new bosonnlp.BosonNLP('6wXvIkZk.35344.lbaaVKiTzyh6') - -function getTimeInResults(results) { - debug('getTimeInResult()', {results}) - var result - var date - var time - var datetime - - // if results have date and time, just return value - result = results.find(x => x.typeName === 'datetimeV2.datetime') - if (result) { - if (result.resolution.values[1]) - datetime = new Date(result.resolution.values[1].value) - else - datetime = new Date(result.resolution.values[0].value) - - return datetime - } - - // first deal with time - time = results.find(x => x.typeName === 'datetimeV2.time') - var timeStr - if (time) { - timeStr = time.resolution.values[0].value - if (time.resolution.values[1]) // we prefer the later time for kid's class - timeStr = time.resolution.values[1].value - } else { - time = results.find(x => x.typeName === 'datetimeV2.timerange') - if (time) { - timeStr = time.resolution.values[0].start - } else { - // do nothing with timeStr - } - } - debug({timeStr}) - - if (!timeStr) { - // if results have date and time range, we return start - result = results.find(x => x.typeName === 'datetimeV2.datetimerange') - if (result) { - datetime = new Date(result.resolution.values[0].start) - return datetime - } else - return // undefined - } - - // then deal with date - date = results.find(x => x.typeName === 'datetimeV2.date') - var dateStr - if (date) { - dateStr = date.resolution.values[0].value - } else { - date = results.find(x => x.typeName === 'datetimeV2.daterange') - if (date) { - dateStr = date.resolution.values[0].start - } else { - dateStr = new Date().toDateString() - } - } - debug({dateStr}) - - datetime = new Date(dateStr + ' ' + timeStr) - return datetime -} - -function parseTime(input) { - // no longer using ChiTimeNlp - //const time = nlp.parse(input) - //return time - - var results = Recognizers.recognizeDateTime(input, defaultCulture) - var time = null - - if (results.length > 0) { - // show details in results, we can not use one line to print due to values[] inside - results.forEach(function (result) { - debug(JSON.stringify(result, null, "\t")); - }); - - // we only pick up those item which has datetime or time - //results = results.filter(r => r.typeName === 'datetimeV2.date' || r.typeName === 'datetimeV2.datetime' || r.typeName === 'datetimeV2.time' || r.typeName === 'datetimeV2.timerange' || r.typeName === 'datetimeV2.datetimerange') - //debug('results after filter', results) - - if (results.length > 0) { - time = getTimeInResults(results) - debug('time: ', time && time.toLocaleString()) - } - } - return time -} - -function parseTitleAndLocation(input, callback) { - var title = input.substring(0, 16) - var location = 'beijing' - - b_nlp.ner(input, function (result) { - debug('result:', result); - - var b_result = JSON.parse(result) - debug('result[0]:', b_result[0]); - if (b_result[0]) { - const length = b_result[0]["word"].length - for (var i = 0; i < length; i++) - debug('[index, word, tag] -> ', i, b_result[0]["word"][i], b_result[0]["tag"][i]) - - //debug('result[0]["word"]', b_result[0]["word"]) - title = b_result[0]["word"].filter((x,index) => - b_result[0]["tag"][index] === 'n' || - b_result[0]["tag"][index] === 'nl' || - b_result[0]["tag"][index] === 'nz' || - b_result[0]["tag"][index] === 'v' || - b_result[0]["tag"][index] === 'vi' || - b_result[0]["tag"][index] === 's') - .slice(0, 3) - .join('') - - location = b_result[0]["word"].filter((x,index) => - b_result[0]["tag"][index] === 'ns' || - b_result[0]["tag"][index] === 'nt' || - b_result[0]["tag"][index] === 'nz' || - b_result[0]["tag"][index] === 'an' || - b_result[0]["tag"][index] === 'n' || - b_result[0]["tag"][index] === 'm' || - b_result[0]["tag"][index] === 'q' || - b_result[0]["tag"][index] === 's') - .slice(0, 5) - .join('') - - // [2, 9, "location"] - var location_array = b_result[0].entity.filter(item => item.indexOf("location")>=0) - - if (location_array.length > 0) { - // clear the old location value - location = "" - - for (var i = 0; i < location_array.length; i++) { - const from = location_array[i][0] - const to = location_array[i][1] - //debug({from}, {to}) - - const l = b_result[0]["word"].slice(from, to).join('') - //debug(l) - - // make the new location value - location += l - } - } - - callback(title, location) - } - }); -} - -module.exports = { parseTime, parseTitleAndLocation } diff --git a/examples/third-parties/maodou/package.json b/examples/third-parties/maodou/package.json deleted file mode 100644 index 3cd6f5e5..00000000 --- a/examples/third-parties/maodou/package.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "maodou-classes-bot", - "version": "0.1.0", - "description": "maodou-classes-bot is a class reminder bot based on wechaty", - "main": "index.js", - "engines": { - "node": ">= 10" - }, - "scripts": { - "postinstall": "check-node-version --node \">= 10\"", - "start": "node maodou-classes-bot.js", - "dev": "DEBUG=maodou* node maodou-classes-bot.js" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/maodouio/wechaty-getting-started.git" - }, - "keywords": [], - "author": "", - "license": "ISC", - "bugs": { - "url": "https://github.com/maodouio/wechaty-getting-started/issues" - }, - "homepage": "https://github.com/maodouio/wechaty-getting-started#readme", - "dependencies": { - "@microsoft/recognizers-text-suite": "^1.1.4", - "bosonnlp": "^0.1.0", - "chi-time-nlp": "^1.0.4", - "node-fetch": "^2.6.0", - "qrcode-terminal": "^0.12.0", - "wechaty": "^0.26.1", - "wechaty-puppet": "^0.14.1", - "wechaty-puppet-wechat": "^0.26" - }, - "devDependencies": { - } -} diff --git a/examples/third-parties/xiaoli/README.md b/examples/third-parties/xiaoli/README.md deleted file mode 100644 index 3b12f112..00000000 --- a/examples/third-parties/xiaoli/README.md +++ /dev/null @@ -1,7 +0,0 @@ -## Instructions for xiaoli-news-bot - -This is a third-party bot built using wechaty and [xiaoli news API](https://xiaoli.ai). - -Within this directory, type ```npm install``` and ```npm start``` and you are good to go! - -For more information about this news bot read [this blog](https://blog.chatie.io/wechaty-xiaoli/). diff --git a/examples/third-parties/xiaoli/package.json b/examples/third-parties/xiaoli/package.json deleted file mode 100644 index 9eb8721b..00000000 --- a/examples/third-parties/xiaoli/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "wechaty-getting-started", - "version": "0.1.0", - "description": "Wechaty is a Wechat Bot SDK for Personal Account in Node.js", - "main": "index.js", - "engines": { - "node": ">= 10" - }, - "scripts": { - "postinstall": "check-node-version --node \">= 10\"", - "start": "node xiaoli-news-bot.js" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/Chatie/wechaty-getting-started.git" - }, - "keywords": [], - "author": "", - "license": "ISC", - "bugs": { - "url": "https://github.com/Chatie/wechaty-getting-started/issues" - }, - "homepage": "https://github.com/Chatie/wechaty-getting-started#readme", - "dependencies": { - "qrcode-terminal": "^0.12.0", - "wechaty": "^0.19.137", - "node-fetch": "^2.2.0", - "node-schedule": "^1.3.0" - }, - "devDependencies": { - } -} diff --git a/examples/third-parties/xiaoli/xiaoli-news-bot.js b/examples/third-parties/xiaoli/xiaoli-news-bot.js deleted file mode 100644 index cc20ea3f..00000000 --- a/examples/third-parties/xiaoli/xiaoli-news-bot.js +++ /dev/null @@ -1,225 +0,0 @@ -#!/usr/bin/env node -/** - * Powered by Wechaty - https://github.com/chatie/wechaty - * - * @author judaschrist - * - * This is a simple news wechat bot. - * It can tell you the latest news about anything you're interested in. - * It can also send you news briefings on a daily basis. - * Read more about this bot in https://blog.chatie.io/wechaty-xiaoli/ - * The bot is implemented using Wechaty and xiaoli news API - https://xiaoli.ai - */ -import { - Wechaty, - config, -} from 'wechaty' -import qrTerm from 'qrcode-terminal' -import fetch from 'node-fetch' -import schedule from 'node-schedule' - -/** - * - * Declare the Bot - * - */ -const bot = WechatyBuilder.build({ - profile: config.default.DEFAULT_PROFILE, -}) - -/** - * - * Register event handlers for Bot - * - */ -bot - .on('logout', onLogout) - .on('login', onLogin) - .on('scan', onScan) - .on('error', onError) - .on('message', onMessage) - -/** - * - * Start the bot! - * - */ -// getDaily() -bot.start() - .catch(async e => { - console.error('Bot start() fail:', e); - await bot.stop(); - process.exit(-1) - }) - -/** - * - * Define Event Handler Functions for: - * `scan`, `login`, `logout`, `error`, and `message` - * - */ -function onScan(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: `) -} - -async function onLogin(user) { - console.log(`${user.name()} login`) - schedule.scheduleJob('40 50 16 * * 1-5', sendDaily); //send daily on 16:50:40 every weekday -} - -function onLogout(user) { - console.log(`${user.name()} logouted`) -} - -function onError(e) { - console.error('Bot error:', e) -} - -/** - * send a daily - */ -async function sendDaily() { - const room = await bot.Room.find({topic: '小桔和小理'}) //get the room by topic - console.log('Sending daily to room ' + room.id) - let dailyText = await getDaily() - room.say(dailyText) -} - - -/** - * list of the news details - * @type {Array} - */ -let preNewsList = [] -/** - * - * Dealing with Messages - * - */ -async function onMessage(msg) { - console.log(msg.toString()) - - if (msg.type() !== bot.Message.Type.Text) { - console.log('Message discarded because it is not a text message') - return - } - - let msgText = msg.text() - - // A super naive implementation of intent detection for news query - if (msgText.endsWith("最新消息") && msgText.length > 4) { - respText = await searchNews(msgText.substring(0, msgText.length-4)) - await msg.say(respText) - } - - // query for news details - if (msgText.startsWith('#')) { - newsNum = parseInt((msgText.substring(1)), 10) - 1 - if (newsNum < preNewsList.length && newsNum >= 0) { - await msg.say(preNewsList[newsNum]) - } - } - -} - -/** - * query xiaoli's api for news related to the keyword - * @param keyword: search keyword - */ -async function searchNews(keyword) { - let searchURL = 'https://api.xiaoli.ai/v1/api/search/basic' - let postBody = { - "keywords": [keyword], - "token": "45d898b459b4a739474175657556249a" - } - let okCallback = makeSearchResponseText - let resText = await fetchXiaoliAPI(searchURL, postBody, okCallback) - return resText -} - -/** - * parse the returned json for a list of news titles - */ -function makeSearchResponseText(json_obj) { - preNewsList = [] - let newsList = json_obj.contents - if (newsList.length === 0) { - return "暂无相关新闻" - } - let newsText = '' - for (let i = 0; i < newsList.length; i++) { - newsText += (i+1) + '. ' + newsList[i].title + '\n' - preNewsList.push(newsList[i].news_abstract) // Save the news details for later queries - } - newsText += "\n回复\"#+数字\"(例如\"#1\")看详情" - return newsText -} - -/** - * query xiaoli's api for a daily news brief - */ -async function getDaily() { - const dailyUuid = 'e02e6f14-3212-4d44-9f3d-1d79538c38f6' - let dailyURL = 'https://api.xiaoli.ai/v1/api/briefing/' + dailyUuid - let postBody = { - "token": "45d898b459b4a739474175657556249a" - } - let okCallback = makeDailyResponseText - let resText = await fetchXiaoliAPI(dailyURL, postBody, okCallback) - return resText -} - - -function makeDailyResponseText(json_obj) { - let secList = json_obj.sections - let newsText = '今日' + json_obj.title + '\n\n' - for (let i = 0; i < Math.min(secList.length, 5); i++) { - newsText += secList[i].title + '\n' - let newsList = secList[i].contents - for (let j = 0; j < Math.min(newsList.length, 3); j++) { - newsText += (j+1) + '. ' + newsList[j].title + '\n' - } - newsText += '\n' - } - return newsText -} - - -/** - * Fetch response from xiaoli API - * @param URL - * @param postBody - * @param okCallback: covert json to msg text when fetch succeeds - */ -async function fetchXiaoliAPI(URL, postBody, okCallback) { - let resText = null - try { - let resp = await fetch( - URL, - { - method: "POST", - body: JSON.stringify(postBody), // put keywords and token in the body - } - ) - let resp_json = await resp.json() - if (resp.ok) { - // status code = 200, we got it! - resText = okCallback(resp_json['data']) - } else { - // status code = 4XX/5XX, sth wrong with API - resText = 'API ERROR: ' + resp_json['msg'] - } - } catch (err) { - resText = 'NETWORK ERROR: ' + err - } - return resText -} diff --git a/examples/tutorials/google-cloud-shell-tutorial.md b/examples/tutorials/google-cloud-shell-tutorial.md index 4f3a05f6..b613837f 100644 --- a/examples/tutorials/google-cloud-shell-tutorial.md +++ b/examples/tutorials/google-cloud-shell-tutorial.md @@ -22,7 +22,7 @@ Click the **Start** button to move to the next step. Before you get started, let's briefly go over what Wechaty can do. -Wechaty is a Conversatioanl RPA SDK for Chatbot Makers. It's well designed with an easy to use API, supports all OSs including Linux, OSX, Win32, Docker, and lots of IMs including WeChat, Whatsapp, WeCom, Lark, Gitter, etc. +Wechaty is a Conversational RPA SDK for Chatbot Makers. It's well designed with an easy to use API, supports all OSs including Linux, OSX, Win32, Docker, and lots of IMs including WeChat, Whatsapp, WeCom, Lark, Gitter, etc. ![Wechaty][wechaty_flyer_url] @@ -30,40 +30,32 @@ Wechaty is a Conversatioanl RPA SDK for Chatbot Makers. It's well designed with As a developer, you can use Wechaty to easily build your bot, effectively manage message sending/receiving, room creating/inviting, contact friendship, and delightful add artificial intelligence between users and your bot. -This repository should work out-of-the-box, and is the best start point for Wechaty beginners. +This repository should work out-of-the-box, and is the best start point for Wechaty beginners. The starter bot uses Wechaty 2 with Puppet Neo. Continue on to the **Next** step to start setting up your chatbot. ## Setting up developing environments -1. Install [Node.js](https://nodejs.org) v16+ +1. Install [Node.js](https://nodejs.org) v26+ 1. Git clone [wechaty/getting-started](https://github.com/wechaty/getting-started) repo -1. Install system dependency packages ### 1. Install Node.js Node.js has been pre-installed in Google Cloud Shell. -However, we need to upgrade Node.js to version 16+ +This repository needs Node.js 26 or newer and npm 10 or newer: ```sh -nvm install 16 +nvm install 26 ``` -You should get a `v16.13.0` output by running command `node --version` +`node --version` should print v26 or newer, for example `v26.13.1`. `npm --version` should print 10 or newer. ### 2. Git clone `wechaty/getting-started` repo -Git Repo has been already cloned in Google Cloud Shell already. +The git repository has already been cloned in Google Cloud Shell. -### 3. Install system dependency packages - -The `puppeteer` needs `libgbm1` and `libatk-bridge2.0` to be presented in the system, we need to install it first, run: - -```sh -sudo apt install -y libgbm1 libxkbcommon-x11-0 -sudo apt-get install -y libatk-bridge2.0-0 -``` +Puppet Neo ships a prebuilt native addon. On Linux that addon needs glibc 2.38 or newer, which the current Google Cloud Shell image provides. ## NPM Install @@ -73,7 +65,7 @@ Let's install NPM packages, run: npm install ``` -The NPM system should help you to install all the dependencies by Wechaty, it will take 1 - 3 minutes. +npm installs the newest Wechaty 2 release and `wechaty-puppet-neo`. It takes a few minutes. After all dependencies have been resolved, we will be able to start our ding-dong BOT. @@ -81,41 +73,25 @@ Click **Next**. ## NPM Start -Let's start our ding-dong BOT, it's source code [examples/ding-dong-bot.ts] should have already opened in the editor. +Let's start our ding-dong BOT. Its source code [examples/ding-dong-bot.ts] should have already opened in the editor. If it's not opened yet, click Open to open it now. -Our `npm start` script is defined as `ts-node examples/ding-dong-bot.ts`. (`ts-node` is the `node` for TypeScript) - -### 1. Get a Whatsapp login QR Code +`npm start` runs `examples/ding-dong-bot.ts` with Node.js. The bot is built with `WechatyBuilder` and `new PuppetNeo()`. -To start our bot with Whatsapp, we need to define `WECHATY_PUPPET` as `wechaty-puppet-whatsapp`, run: +### 1. Get a WeChat login QR code ```sh -export WECHATY_PUPPET=wechaty-puppet-whatsapp npm start ``` -You should see our bot start generating logs and after a while, a QR Code will be printed. +The bot prints logs and then a QR code. Scan it with WeChat and confirm the login on your phone. -You can use your Whatsapp to scan it to login your bot now. +Neo keeps the login in memory, so the next start prints a new QR code. -### 2. Get a WeChat login QR Code - -To start our bot with WeChat, we can define `WECHATY_PUPPET` as `wechaty-puppet-wechat`, run: - -```sh -export WECHATY_PUPPET=wechaty-puppet-wechat -npm start -``` +### 2. Play with your bot -You should see our bot start generating logs and after a while, a QR Code will be printed. - -You can use your WeChat app to scan it to login your bot now. - -### 3. Play with your bot - -Please play with your bot for a while now. **Next** we will add our first new feature to the bot. +Send `ding` to the bot from another WeChat account. The bot replies `dong`. **Next** we will add a new feature to the bot. ## Add a new feature @@ -125,11 +101,9 @@ _“reply `dongdong` for `dingding`”_ ### 1. Requirement analysis -If you have finished the previous step, and login-ed successfully, then your bot will be able to reply a `dong` for any message send it as a `ding`, no matter which IM(Whatsapp or WeChat) your bot are working with. +After you log in, the bot replies `dong` when it receives `ding`. -Now we get a new feature request from our client: reply `dongdong` for `dingding`. - -It will be a hard work but we will make it! +The new request is to reply `dongdong` for `dingding`. ### 2. Code explaination @@ -149,7 +123,7 @@ Let's start working on it now. ### 3. Developing new code -We need to check the `msg.text()` for `dingding` when receiving messages, and use `msg.say('dongdong')` to replay! +We need to check the `msg.text()` for `dingding` when receiving messages, and use `msg.say('dongdong')` to reply: ```ts if (msg.text() === 'dingding') { @@ -157,11 +131,9 @@ if (msg.text() === 'dingding') { } ``` -It looks great! - ### 4. Final `onMessage` function -Let's put out new code into the `onMessage` function: +Let's put our new code into the `onMessage` function: ```ts async function onMessage (msg: Message) { @@ -176,30 +148,21 @@ async function onMessage (msg: Message) { } ``` -That's it! We have added 3 lines of code to implment our new feature. Do not forget to save the file changes to the disk. +That's it. We have added 3 lines of code to implement our new feature. Save the file. -**Next** up, starting our braning new ding-dong BOT! +**Next** up, starting our ding-dong BOT again. ## Test new feature We will start our ding-dong BOT again. -### 1. Select puppet to use by WCHATY_PUPPET - -You can set `WECHATY_PUPPET` to either `wechaty-puppet-whatapp` or `wechaty-puppet-wechat`, depends where you want to test the bot. - -### 2. Run - -If you decide to use Whatsapp, run: +### 1. Run ```sh -export WECHATY_PUPPET=wechaty-puppet-whatsapp npm start ``` -The ding-dong BOT should start outputing log messages, after a while shows you a QR Code for login. - -Scan it on your phone, and then try to send `dingding` to the bot, you should receive `dongdong` instantly! +The bot prints logs and a new QR code. Scan it with WeChat, then send `dingding` to the bot. You should receive `dongdong`. Enjoy your bot, and click **Next** when you like. @@ -209,7 +172,7 @@ Enjoy your bot, and click **Next** when you like. You're all set! -You have finished the Wechaty Getting Started Tutorial, and be able to run Wechaty in TypeScript, receiving and replying messages on Whatsapp and WeChat! +You have finished the Wechaty Getting Started Tutorial. You can run Wechaty in TypeScript, with Puppet Neo, and receive and reply to WeChat messages. Congratulations to be a Wechaty developer now! @@ -223,4 +186,4 @@ Done! Learn more about Wechaty from our [docs](https://wechaty.js.org/docs/) and [blog](https://wechaty.js.org/blog/), and [join our Gitter](https://gitter.im/wechaty/wechaty) network if you aren’t already a member! -Wechaty © 2016 - 2021 +Wechaty © 2016 - 2026 diff --git a/package.json b/package.json index ec55e925..f0785446 100644 --- a/package.json +++ b/package.json @@ -4,23 +4,17 @@ "description": "Wechaty conversational SDK getting start template & examples", "type": "module", "engines": { - "node": ">=16", - "npm": ">=7" + "node": ">=26", + "npm": ">=10" }, "scripts": { "build": "tsc", - "lint": "eslint \"examples/*.ts\" \"tests/*.ts\"", - "postinstall": "check-node-version --node \">=16\" --npm \">=7\"", - "cqrs": "cross-env NODE_OPTIONS=\"--no-warnings --loader=ts-node/esm\" node examples/cqrs/ding-dong-bot.ts ", - "start": "cross-env NODE_OPTIONS=\"--no-warnings --loader=ts-node/esm\" node examples/ding-dong-bot.ts", - "start:js": "node examples/ding-dong-bot.js", - "start:walnut": "cross-env WECHATY_LOG=verbose WECHATY_PUPPET=wechaty-puppet-walnut npm start", - "start:service": "cross-env WECHATY_LOG=verbose WECHATY_PUPPET=wechaty-puppet-service npm start", - "start:wechat:web": "cross-env WECHATY_LOG=verbose WECHATY_PUPPET=wechaty-puppet-wechat npm start", - "start:wechat:padlocal": "cross-env WECHATY_LOG=verbose WECHATY_PUPPET=wechaty-puppet-padlocal npm start", - "start:whatsapp:web": "cross-env WECHATY_LOG=verbose WECHATY_PUPPET=wechaty-puppet-whatsapp npm start", + "lint": "tsc --noEmit", + "postinstall": "check-node-version --node \">=26\" --npm \">=10\"", + "start": "node examples/ding-dong-bot.ts", + "start:js": "node examples/basic/ding-dong-bot.js", "test": "npm-run-all lint test:smoke", - "test:smoke": "cross-env NODE_OPTIONS=\"--no-warnings --loader=ts-node/esm\" tap --timeout=150 \"tests/**/*.spec.ts\"" + "test:smoke": "tap --timeout=150 \"tests/**/*.spec.ts\"" }, "repository": { "type": "git", @@ -37,27 +31,23 @@ "dotenv": "^18.0.10", "npm-run-all": "^4.1.5", "qrcode-terminal": "^0.12.0", - "wechaty": "^1.20.2", - "wechaty-cqrs": "^0.7.5", + "wechaty": ">=2.0.0-0 <3", "wechaty-plugin-contrib": "^1.12.2", - "wechaty-puppet-oicq": "^1.10.2", - "wechaty-puppet-walnut": "^1.18.8", - "wechaty-puppet-wechat": "^1.18.4", - "wechaty-puppet-wechat4u": "~1.11.1", - "wechaty-puppet-whatsapp": "^1.19.16" + "wechaty-puppet-neo": "^0.1.1" }, "devDependencies": { "@chatie/eslint-config": "^1.4.1", "@chatie/git-scripts": "^0.6.2", - "@chatie/tsconfig": "^4.9.2", + "@types/qrcode-terminal": "^0.12.2", "check-node-version": "^4.2.1", "is-pr": "^2.0.0", - "ts-node": "^10.9.2", - "typescript": "~5.9.3", - "wechaty-puppet-mock": "^1.18.2" + "tap": "~16.3.10", + "tstest": "^1.2.8", + "typescript": "^7.0.2", + "wechaty-puppet-mock": "^1.19.4" }, "overrides": { - "typescript": "~5.9.3" + "typescript": "^7.0.2" }, "git": { "scripts": { diff --git a/tests/wechaty-puppet-mock.spec.ts b/tests/wechaty-puppet-mock.spec.ts index db43e798..04c13b76 100755 --- a/tests/wechaty-puppet-mock.spec.ts +++ b/tests/wechaty-puppet-mock.spec.ts @@ -1,4 +1,4 @@ -#!/usr/bin/env -S node --no-warnings --loader ts-node/esm +#!/usr/bin/env node import { test } from 'tstest' import { WechatyBuilder } from 'wechaty' diff --git a/tests/wechaty-puppet-neo.spec.ts b/tests/wechaty-puppet-neo.spec.ts new file mode 100644 index 00000000..3a218902 --- /dev/null +++ b/tests/wechaty-puppet-neo.spec.ts @@ -0,0 +1,51 @@ +#!/usr/bin/env node + +import { test } from 'tstest' +import { WechatyBuilder } from 'wechaty' +import { PuppetNeo } from 'wechaty-puppet-neo' + +test('wechaty-puppet-neo', async t => { + const puppet = new PuppetNeo() + const bot = WechatyBuilder.build({ + puppet, + }) + + const timer = setTimeout(() => { + console.error('Smoke testing timeout after 2 minutes.') + process.exit(1) + }, 120 * 1000) + + let sawScan = false + // A failed login rejects the background session. Exit then, unless a QR + // scan event has already arrived. + process.once('unhandledRejection', reason => { + if (sawScan) return + console.error(reason) + clearTimeout(timer) + process.exit(1) + }) + + const future = new Promise((resolve, reject) => { + bot.once('scan', () => { + sawScan = true + resolve(undefined) + }) + bot.once('error', reject) + }) + + try { + await bot.start() + await future + await bot.stop() + } catch (error) { + clearTimeout(timer) + await bot.stop().catch(() => undefined) + throw error + } + + clearTimeout(timer) + t.pass(`Puppet ${bot.puppet} v${bot.puppet.version()} smoke testing passed.`) + // A successful smoke test can leave sockets open. Exit so tap does not + // wait until its timeout and then fail the run. + t.teardown(() => process.exit(0)) +}) diff --git a/tests/wechaty-puppet-service.spec.ts b/tests/wechaty-puppet-service.spec.ts deleted file mode 100755 index d5ba72ca..00000000 --- a/tests/wechaty-puppet-service.spec.ts +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env -S node --no-warnings --loader ts-node/esm - -import https from 'node:https' - -import { test } from 'tstest' -import { WechatyBuilder } from 'wechaty' - -import 'dotenv/config.js' - -const token = process.env['WECHATY_PUPPET_SERVICE_TOKEN'] - -/** - * api.chatie.io is an external dependency. A 503 or a rejected token - * makes puppet startup throw inside wechaty-token and fail this job. - */ -const discoveryIsReady = (serviceToken: string): Promise => { - const url = `https://api.chatie.io/v0/hosties/${encodeURIComponent(serviceToken)}` - return new Promise(resolve => { - const req = https.get(url, res => { - res.resume() - const status = res.statusCode ?? 0 - resolve(status >= 200 && status < 300) - }) - req.setTimeout(15_000, () => { - req.destroy() - resolve(false) - }) - req.on('error', () => resolve(false)) - }) -} - -test('wechaty-puppet-service', { - skip: token ? false : 'WECHATY_PUPPET_SERVICE_TOKEN is not set', -}, async t => { - if (!token || !await discoveryIsReady(token)) { - t.pass('Puppet service discovery is unavailable, so the live smoke test was not run.') - return - } - - const bot = WechatyBuilder.build({ - puppet: 'wechaty-puppet-service', - /** - * Huan(202108): our puppet service token is no-TLS for now. - * FIXME: enable TLS in the future - */ - puppetOptions: { tls: { disable: true } }, - }) - - const timer = setTimeout(() => { - console.error('Smoke testing timeout after 2 minutes.') - process.exit(1) - }, 120 * 1000) - - const future = new Promise(resolve => bot.once('scan', resolve)) - await bot.start() - await future - await bot.stop() - - clearTimeout(timer) - t.pass(`Puppet ${bot.puppet} v${bot.puppet.version()} smoke testing passed.`) - // A successful smoke test can leave sockets open. Exit so tap does not - // wait until its timeout and then fail the run. - t.teardown(() => process.exit(0)) -}) diff --git a/tests/wechaty-puppet-wechat.spec.ts b/tests/wechaty-puppet-wechat.spec.ts deleted file mode 100755 index f6c30d62..00000000 --- a/tests/wechaty-puppet-wechat.spec.ts +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env -S node --no-warnings --loader ts-node/esm - -import { test } from 'tstest' -import { WechatyBuilder } from 'wechaty' - -test('wechaty-puppet-wechat', async t => { - const optionsWeChat = { - puppet: 'wechaty-puppet-wechat', - puppetOptions: { - launchOptions: { - ignoreDefaultArgs: [ '--disable-extensions' ], - }, - }, - } as const - - const bot = WechatyBuilder.build(optionsWeChat) - - const describeError = (payload: unknown): string => { - if (payload instanceof Error) return payload.message - if (typeof payload === 'string') return payload - try { - return JSON.stringify(payload) - } catch { - return String(payload) - } - } - - /** - * Puppeteer 13 ships Chromium r982053. Current macOS arm64 runners - * cannot connect to that browser, and the smoke test used to exit 1 - * after two minutes. A scan event is still required when the browser - * does launch. - */ - const sawScan = new Promise(resolve => { - const timer = setTimeout(() => resolve(false), 100 * 1000) - const finish = (ready: boolean) => { - clearTimeout(timer) - resolve(ready) - } - bot.once('scan', () => finish(true)) - bot.on('error', (payload: unknown) => { - const message = describeError(payload) - if (/connect to the browser|Failed to launch the browser|Only Chrome at revision/.test(message)) { - console.error('Web WeChat browser did not launch: %s', message) - finish(false) - } - }) - }) - - await bot.start() - if (!await sawScan) { - t.pass('Web WeChat browser did not launch on this runner, so the live smoke test was not completed.') - t.teardown(() => process.exit(0)) - return - } - - await bot.stop() - t.pass(`Puppet ${bot.puppet} v${bot.puppet.version()} smoke testing passed.`) - // Chromium stays running after puppet.stop(). Exit so tap does not - // wait until its timeout and then fail the run. - t.teardown(() => process.exit(0)) -}) diff --git a/tests/wechaty-puppet-wechat4u.spec.ts b/tests/wechaty-puppet-wechat4u.spec.ts deleted file mode 100755 index 9ceffe73..00000000 --- a/tests/wechaty-puppet-wechat4u.spec.ts +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/env -S node --no-warnings --loader ts-node/esm - -import { test } from 'tstest' -import { WechatyBuilder } from 'wechaty' - -test('wechaty-puppet-wechat4u', async t => { - const bot = WechatyBuilder.build({ puppet: 'wechaty-puppet-wechat4u' }) - - const timer = setTimeout(() => { - console.error('Smoke testing timeout after 2 minutes.') - process.exit(1) - }, 120 * 1000) - - const future = new Promise(resolve => bot.once('scan', resolve)) - await bot.start() - await future - await bot.stop() - - clearTimeout(timer) - t.pass(`Puppet ${bot.puppet} v${bot.puppet.version()} smoke testing passed.`) - // A successful smoke test can leave sockets open. Exit so tap does not - // wait until its timeout and then fail the run. - t.teardown(() => process.exit(0)) -}) diff --git a/tsconfig.json b/tsconfig.json index fd1e8df1..81ca8be3 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,7 +1,30 @@ { - "extends": "@chatie/tsconfig", "compilerOptions": { - "outDir": "dist" + "target": "esnext", + "module": "nodenext", + "moduleResolution": "nodenext", + "verbatimModuleSyntax": true, + "isolatedModules": true, + "outDir": "dist", + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "skipLibCheck": true, + "esModuleInterop": true, + "experimentalDecorators": true, + "emitDecoratorMetadata": true, + "lib": [ + "esnext" + ], + "strict": true, + "noEmitOnError": true, + "noUnusedLocals": true, + "noImplicitReturns": true, + "noImplicitOverride": true, + "noUncheckedIndexedAccess": true, + "noPropertyAccessFromIndexSignature": true, + "noFallthroughCasesInSwitch": true, + "forceConsistentCasingInFileNames": true }, "exclude": [ "node_modules/", @@ -13,5 +36,5 @@ "scripts/**/*.ts", "src/**/*.ts", "tests/**/*.ts" - ], + ] }