Skip to content

Commit

Permalink
Merge pull request #1155 from sbis04/docs-tutorials-media-file-bot
Browse files Browse the repository at this point in the history
Add tutorial for Media File Bot
  • Loading branch information
Rohitesh-Kumar-Jain authored Aug 24, 2021
2 parents a0fce17 + 559fbaa commit 71cc7c3
Show file tree
Hide file tree
Showing 3 changed files with 384 additions and 4 deletions.
3 changes: 0 additions & 3 deletions docusaurus/docs/examples/advanced/media-file-bot.md

This file was deleted.

383 changes: 383 additions & 0 deletions docusaurus/docs/examples/advanced/media-file-bot.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,383 @@
---
title: Media File Bot
---

<!-- MDX import -->
import Tabs from '@theme/Tabs'
import TabItem from '@theme/TabItem'

import ShortestChatbots from '../../polyglot/transclusions/shortest-chatbots.mdx'

[![Powered by Wechaty](https://img.shields.io/badge/Powered%20By-Wechaty-brightgreen.svg)](https://github.com/Wechaty/wechaty)
[![JavaScript](https://img.shields.io/badge/%3C%2F%3E-JavaScript-blue.svg)](https://www.javascript.com/)

Wechaty **Media File Bot** helps in saving media attachments of messages to local files.

In this tutorial, you will get step-by-step instructions for building the Wechaty Media File Bot from scratch.

## Try out the bot

[![Edit wechaty-media-file-bot](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/github/sbis04/wechaty-media-file-bot/tree/main/?fontsize=14&hidenavigation=1&theme=dark)

You can try out the Wechaty Media File Bot using this interactive CodeSandbox.

Just scan the generated QR code with **WeChat** app, and you are ready to play with the bot!

<iframe
class="codesandbox"
src="https://codesandbox.io/embed/github/sbis04/wechaty-media-file-bot/tree/main/?fontsize=12&hidenavigation=1&module=%2Fmedia-file-bot.js&theme=dark"
title="media-file-bot"
sandbox="allow-forms allow-modals allow-popups allow-same-origin allow-scripts"
></iframe>

## Requirements

1. [Node.js](https://nodejs.org/en/download) v12+
2. [Wechaty](https://github.com/wechaty/wechaty) v0.40+

## Getting started

You should have `Node.js` 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:

:::note Node.js installation docs

* [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)

> Installation guide for `Node.js` on other platforms can be found [here](https://nodejs.org/en/download/package-manager/).
:::

You can head over to the [Building the bot](#building-the-bot) section to learn how to build the bot on your own.

Otherwise, if you just want to try out the bot on your local system, follow the steps below:

### 1. Clone the repository

Use the following commands to clone the [GitHub repository](https://github.com/wechaty/wechaty-getting-started) and navigate to the directory:

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

### 2. Install dependencies

You can install the `npm` packages required for running the bot, using this command:

```sh
npm install
```

### 3. Run the bot
You have to `export/set` the environment variables:

<Tabs
groupId="operating-systems"
defaultValue="linux"
values={[
{ label: 'Linux', value: 'linux', },
{ label: 'macOS', value: 'mac', },
{ label: 'Windows', value: 'windows', },
]
}>

<TabItem value="linux">

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

</TabItem>
<TabItem value="mac">

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

</TabItem>
<TabItem value="windows">

```bash
set WECHATY_LOG=verbose
set WECHATY_PUPPET=wechaty-puppet-wechat
```

</TabItem>
</Tabs>

> There are various **Wechaty puppets** available, you can know more about them [here](https://github.com/wechaty/wechaty-getting-started#working-with-different-puppets).
Run the bot by using the following command:

```bash
node examples/advanced/media-file-bot.js
```

It will generate a QR code, scan it using **WeChat** or **WhatsApp** (according to the puppet you have used), and you are ready to play with the bot.

## Building the bot

Let's get started with building the Wechaty Media File Bot using Wechaty.

### 1. Initialize project

Create a new folder called `media-file-bot` and move into that directory:

```bash
mkdir media-file-bot
cd media-file-bot
```

Use the following command to initialize an npm project:

```bash
npm init -y
```

This will generate the `package.json` file containing these:

```json
{
"name": "media-file-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

You will need the `wechaty` NPM package for building this bot & `qrcode-terminal` for displaying the QR code that can be scanned for using the bot. Install them using the following command:

```sh
npm install wechaty
npm install qrcode-terminal
```

You will also need to add dependencies for using any [Wechaty Puppet](https://wechaty.js.org/docs/puppet-providers/) which helps to integrate Wechaty with various **instant messaging (IM) systems** (such as WeChat, WhatsApp, and WeCom):

1. If you want to use **[WhatsApp](https://www.whatsapp.com/)**, install `wechaty-puppet-whatsapp`:

```bash
npm install wechaty-puppet-whatsapp
```

2. If you want to use **[WeChat](https://www.wechat.com/)**, you can try the following puppets:

* **Web Protocol:** Install `wechaty-puppet-wechat`:

```bash
npm install wechaty-puppet-wechat
```

* **iPad Protocol:**
* padlocal: Install `wechaty-puppet-padlocal`:

```bash
npm install wechaty-puppet-padlocal
```

Then get a token like `puppet_padlocal_XXX`, know more about puppet service padlocal [here](http://wechaty.js.org/docs/puppet-services/padlocal).

* paimon: Install `wechaty-puppet-service`:

```bash
npm install wechaty-puppet-service
```

Then get a token like `puppet_paimon_XXX`, know more about puppet service paimon [here](http://wechaty.js.org/docs/puppet-services/paimon).

3. If you want to use **[WeCom](https://work.weixin.qq.com/)**, install `wechaty-puppet-service`:

```bash
npm install wechaty-puppet-service
```

Then get a token like `puppet_wxwork_XXXXX`, more about puppet service wxwork [here](https://wechaty.js.org/docs/puppet-services/wxwork/).

> You can find more information about the puppets [here](https://wechaty.js.org/docs/puppet-providers/).
### 3. Write code for bot

Start by creating a new file `media-file-bot.js`. We will be writing the code here.

Let's import the required packages in the JavaScript file:

```js
const qrTerm = require("qrcode-terminal");
const { Wechaty, Message } = require("wechaty");
```

Specify some functions that you will require for handling different events returned by the Wechaty bot.

* **onScan**

This function will be used for generating the **QR code** for the puppet specified, and display it on the console.

```js
function onScan (qrcode, status) {
qrTerm.generate(qrcode, { small: true })
}
```

* **onLogin**

This will print a log message when a user logs in to the bot, and will call the `main()` function.

```js
function onLogin (user) {
console.log(`${user} login`)
main()
}
```

We'll look into the content of this `main()` function in a moment.

* **onLogout**

This will print a log message when a user logs out of the bot.

```js
function onLogout (user) {
console.log(`${user} logout`)
}
```

* **onError**

This is for printing an error message to the console.

```js
function onError (e) {
console.error(e)
}
```

* **onMessage**

This is for handling the messages and for determining if the messages contain any file attachments. If it contains then save the file locally.

```js
async function onMessage(msg) {
console.log(`RECV: ${msg}`);

if (msg.type() !== Message.Type.Text) {
const file = await msg.toFileBox();
const name = file.name;
console.log("Save file to: " + name);
file.toFile(name);
}
}
```

You have completed defining all the functions required for handling various bot events. Now, provide a name to initialize the Wechaty bot:

```js
const bot = new Wechaty({
name: "media-file-bot",
});
```

Assign proper function to call when an event is triggered by the bot:

```js
bot.on("scan", onScan);
bot.on("login", onLogin);
bot.on("logout", onLogout);
bot.on("message", onMessage);
bot.on("error", onError);
```

Use the following to start the bot:

```js
bot.start()
.catch(console.error)
```

## Running the bot

In order to run the bot, first you have to **export/set** an environment variable with the type of puppet to use:

<Tabs
groupId="operating-systems"
defaultValue="linux"
values={[
{ label: 'Linux', value: 'linux', },
{ label: 'macOS', value: 'mac', },
{ label: 'Windows', value: 'windows', },
]
}>

<TabItem value="linux">

```bash
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"
```

</TabItem>
<TabItem value="mac">

```bash
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"
```

</TabItem>
<TabItem value="windows">

```bash
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"
```

</TabItem>
</Tabs>

> If you are using WeCom, you can get token from [puppet service wxwork](http://wechaty.js.org/docs/puppet-services/wxwork).
Run the bot using the following command:

```bash
node media-file-bot.js
```

This will start the bot and generate a QR code.

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

## References

* [Wechaty Getting Started GitHub repository](https://github.com/wechaty/wechaty-getting-started)
2 changes: 1 addition & 1 deletion docusaurus/docs/tutorials/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ For better understanding we have classified the bots under three categories taki

- [Demo in tutorial](examples/advanced/demo-in-tutorial.md): The demo bot from tutorial
- [Busy bot](examples/advanced/busy-bot.mdx): Auto response `busy` message for you when you are busy
- [Media file bot](examples/advanced/media-file-bot.md): Save media attachment in message to local files
- [Media file bot](examples/advanced/media-file-bot.mdx): Save media attachment in message to local files
- [Room bot](examples/advanced/room-bot.mdx): Practical examples illustrating how to do room handling
- [Friend bot](examples/advanced/friend-bot.mdx): Practical example illustrating how to do friend handling
- [Gist bot](examples/advanced/gist-bot.md): Best template for bigger modules, with each handler in separated files
Expand Down

0 comments on commit 71cc7c3

Please sign in to comment.