Running locally
For running Ding Dong Bot, you can setup your own server for running locally. Just follow the steps below:
- Getting Started
- Clone the Ding Dong Bot repository
- Install dependencies
- Run the bot
Try out the 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
- Node.js v16+
- Wechaty Puppet Service TOKEN (if you want to use RPA protocols other than Web)
Usage
- TypeScript
- JavaScript
- Python
- Go
- Java
- PHP
- Scala
- C#
- Rust
- OpenAPI
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)
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)
from wechaty import Wechaty
import asyncio
async def main():
bot = Wechaty()
bot.on('scan', lambda status, qrcode, data: print('Scan QR Code to login: {}\nhttps://wechaty.js.org/qrcode/{}'.format(status, qrcode)))
bot.on('login', lambda user: print('User {} logged in'.format(user)))
bot.on('message', lambda message: print('Message: {}'.format(message)))
await bot.start()
asyncio.run(main())
package main
import (
"fmt"
"github.com/wechaty/go-wechaty/wechaty"
)
func main() {
_ = wechaty.NewWechaty().
OnScan(func(qrCode, status string) {
fmt.Printf("Scan QR Code to login: %s\nhttps://wechaty.js.org/qrcode/%s\n", status, qrCode)
}).
OnLogin(func(user string) { fmt.Printf("User %s logged in\n", user) }).
OnMessage(func(message string) { fmt.Printf("Message: %s\n", message) }).
Start()
}
package io.github.wechaty;
class Bot{
public static void main(String args[]){
Wechaty bot = Wechaty.instance()
.onScan((qrcode, statusScanStatus, data) -> System.out.println(QrcodeUtils.getQr(qrcode)))
.onLogin(user -> System.out.println("User logged in :" + user))
.onMessage(message -> System.out.println("Message:" + message))
.start(true);
}
}
$wechaty = \IO\Github\Wechaty\Wechaty::getInstance($token, $endPoint);
$wechaty->onScan(function($qrcode, $status, $data) {
$qr = \IO\Github\Wechaty\Util\QrcodeUtils::getQr($qrcode);
echo "$qr\n\nOnline Image: https://wechaty.js.org/qrcode/$qrcode\n";
})->onLogin(function(\IO\Github\Wechaty\User\ContactSelf $user) {
})->onMessage(function(\IO\Github\Wechaty\User\Message $message) {
$message->say("hello from PHP7.4");
})->start();
package wechaty
object DingDongBot {
def main(args: Array[String]): Unit = {
Wechaty.instance()
.onScan(payload => { println("Scan QR Code to login: %s\nhttps://wechaty.js.org/qrcode/%s\n".format(payload.status, payload.qrcode)) })
.onLogin(payload => { println("User %s logged in\n".format(payload.id)) })
.onMessage(message => { println(message) })
.start()
Thread.currentThread().join()
}
}
var wechaty = new Wechaty(options, logger).onScan((qrcode, status) => {
Console.WriteLine($"Scan QR Code to login: {status} https://wechaty.js.org/qrcode/{(qrcode)}`");
}).OnLogin( user => {
Console.WriteLine("User {user} logined");
}).OnMessage( message => {
Console.WriteLine($"Message: {message}");
}).Start();
let bot = Wechaty::new(PuppetService::new(options).await.unwrap());
bot.on_scan(handle_scan)
.on_login(handle_login)
.on_logout(handle_logout)
.on_message(handle_message)
.start()
.await;
# To be add: curl ...
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:
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:
- Linux
- macOS
- Windows
sudo apt install build-essential
brew install make
choco install make
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:
- Linux
- macOS
- Windows
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
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
set WECHATY_LOG=verbose
set 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:
- wechaty: Official Wechaty package
- qrcode-terminal: Displays the QR code
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):
If you want to use WhatsApp, install
wechaty-puppet-whatsapp
:npm install wechaty-puppet-whatsapp
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.
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:
- Linux
- macOS
- Windows
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"
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"
set WECHATY_LOG=verbose
set WECHATY_PUPPET=wechaty-puppet-wechat
# For using WhatsApp:
# set WECHATY_PUPPET=wechaty-puppet-whatsapp
# For using WeCom:
# set WECHATY_PUPPET=wechaty-puppet-service
# set 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:
Scan it using your WeChat/WhatsApp as per the puppet you have selected, and you are ready to play with the bot!
Bot demonstration
Conclusion
You have learnt to make a ding dong bot.