Skip to main content

Running locally

Powered by Wechaty TypeScript

For running Ding Dong Bot, you can setup your own server for running locally. Just follow the steps below:

  1. Getting Started
  2. Clone the Ding Dong Bot repository
  3. Install dependencies
  4. Run the bot

Try out the bot

Edit wechaty-ding-dong-bot

You can try out Ding Dong Bot using this interactive CodeSandbox.

Just scan the generated QR code with WeChat app and you are ready to go.

Requirements

  1. Node.js v16+
  2. Wechaty Puppet Service TOKEN (if you want to use RPA protocols other than Web)

Usage

import { Wechaty } from 'wechaty'

async function main () {
const bot = new Wechaty()
bot
.on('scan', (qrcode, status) => console.log(`Scan QR Code to login: ${status}\nhttps://wechaty.js.org/qrcode/${encodeURIComponent(qrcode)}`))
.on('login', user => console.log(`User ${user} logged in`))
.on('message', message => console.log(`Message: ${message}`))
await bot.start()
}

main()
.catch(console.error)

Getting Started

In this tutorial you will learn to use Ding Dong bot which replies with a dong message when it receives a ding message.

Before getting started make sure you have Node installed on your system. If you do not have Node.js installed (or have a version below 12), then you need to install the latest version of Node.js by following the links below:

Node.js installation docs

Installation guide for Node.js in other platforms can be found here.

You can head over to Building the bot section to learn how to build the bot on your own.

If you just want to try out the bot on your local system, follow the steps below.

1. Install make

You will need make for running the Makefile, use the command below to install:

sudo apt install build-essential

2. Clone repository

You can clone the Ding Dong Bot repository by following the below command, and navigate to the directory:

git clone https://github.com/wechaty/wechaty-getting-started
cd wechaty-getting-started

3. Install dependencies

For installing the required npm dependencies run the following:

# npm install
make install

4. Run the bot

First, you have to export/set the environment variables, and then you can run the bot:

export WECHATY_LOG=verbose
export WECHATY_PUPPET=wechaty-puppet-wechat
make bot
# the above is equals to the below command:
# npm start
# or, npx ts-node examples/ding-dong-bot.ts

There are various Wechaty puppets available, you can know more about them here.

This will generate a QR code. Scan it using Wechat or WhatsApp depending upon the puppet used.

You are ready to play with the bot.

Building the bot

Let's get started with building the Ding Dong bot using Wechaty.

1. Initialize project

Create a new folder called ding-dong-bot and move into that directory.

mkdir ding-dong-bot
cd ding-dong-bot

Use the following command to initialize an npm project:

npm init -y

This will generate the package.json file containing these:

{
"name": "ding-dong-bot",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}

2. Install dependencies

For building the ding dong bot you will require these dependencies:

For installing these dependencies run the following commands:

  • For installing wechaty
npm install wechaty
  • For installing qrcode-terminal
npm install qrcode-terminal

You will also need to add dependencies for using any Wechaty Puppet which helps to integrate Wechaty with various instant messaging (IM) systems (such as WeChat, Whatsapp, and Gitter):

  1. If you want to use WhatsApp, install wechaty-puppet-whatsapp:

    npm install wechaty-puppet-whatsapp
  2. If you want to use WeChat, you can try the following puppets:

    • Web Protocol: Install wechaty-puppet-wechat:

      npm install wechaty-puppet-wechat
    • iPad Protocol:

      • padlocal: Install wechaty-puppet-padlocal:

        npm install wechaty-puppet-padlocal

        Then get a token like puppet_padlocal_XXX, know more about puppet service padlocal here.

      • paimon: Install wechaty-puppet-service:

        npm install wechaty-puppet-service

        Then get a token like puppet_paimon_XXX, know more about puppet service paimon here.

  3. If you want to use WeCom, install wechaty-puppet-service:

    npm install wechaty-puppet-service

    Then get a token like puppet_wxwork_XXXXX, more about puppet service wxwork here.

You can find more information about the puppets here.

Now, you are ready to write the main code for the bot.

3. Writing code for bot

Create a new file ding-dong-bot.ts. We will be writing the code here.

Let's import the required packages in this file:

import {
Contact,
Message,
ScanStatus,
WechatyBuilder,
log,
}from 'wechaty'

import { generate } from 'qrcode-terminal'

require('dotenv').config()

Now we will write some functions which will be required for handling different events returned by bot.

onScan

This function will be required for generating QR code for puppet specified and Displays it on console.

function onScan (qrcode: string, status: ScanStatus) {
if (status === ScanStatus.Waiting || status === ScanStatus.Timeout) {
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)
}
}

1. If status is Waiting or Timeout then function onScan will generate qrcode

2. qrcodeImageUrl is used for reading the generated qrcode. encodeURIComponent(qrcode) encodes a URI (string that refers to a resource ie. qrcode) by replacing each instance of certain characters by UTF-8 encoding of characters.

3. After reading the qrcode it return ScanStatus.

onLogin

This function will print message when a user logs into the bot.

function onLogin (user: Contact) {
log.info('StarterBot', '%s login', user)
}

onLogout

This will print message when a user logs out.

function onLogout (user: Contact) {
log.info('StarterBot', '%s logout', user)
}

onMessage

This will print a log message. If the message is ding then it will print dong.

async function onMessage (msg: Message) {
log.info('StarterBot', msg.toString())

if (msg.text() === 'ding') {
await msg.say('dong')
}
}

Now initializing the bot by providing a name.

const bot = WechatyBuilder.build({
name: 'ding-dong-bot'
})

Assigning proper functions to call when an event is triggered.

bot.on('scan',    onScan)
bot.on('login', onLogin)
bot.on('logout', onLogout)
bot.on('message', onMessage)

Finally for starting the bot

bot.start()
.then(() => log.info('StarterBot', 'Starter Bot Started.'))
.catch(e => log.error('StarterBot', 'Failed to start the bot:', e))

Running the bot

You have to export/set an environment variable with the type of puppet to use:

export WECHATY_LOG=verbose
export WECHATY_PUPPET=wechaty-puppet-wechat

# For using WhatsApp:
# export WECHATY_PUPPET=wechaty-puppet-whatsapp

# For using WeCom:
# export WECHATY_PUPPET=wechaty-puppet-service
# export WECHATY_PUPPET_SERVICE_TOKEN="puppet_wxwork_XXXXX"

If you are using WeCom, you can get token from puppet service wxwork.

Run the bot using the following command:

ts-node ding-dong-bot.ts

This will start bot and generate QR code like this:

hard-way

Scan it using your WeChat/WhatsApp as per the puppet you have selected, and you are ready to play with the bot!

Bot demonstration

bot-demo

Conclusion

You have learnt to make a ding dong bot.

References