|
| 1 | +/** |
| 2 | + * Wechaty - https://github.com/chatie/wechaty |
| 3 | + * |
| 4 | + * @copyright 2016-2018 Huan LI <[email protected]> |
| 5 | + * |
| 6 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | + * you may not use this file except in compliance with the License. |
| 8 | + * You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, software |
| 13 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | + * See the License for the specific language governing permissions and |
| 16 | + * limitations under the License. |
| 17 | + * |
| 18 | + */ |
| 19 | +import { |
| 20 | + Wechaty, |
| 21 | +} from 'wechaty' |
| 22 | + |
| 23 | +import { generate } from 'qrcode-terminal' |
| 24 | + |
| 25 | +/** |
| 26 | + * |
| 27 | + * 1. Declare your Bot! |
| 28 | + * |
| 29 | + */ |
| 30 | +const bot = new Wechaty({ |
| 31 | + name : 'javascript-es6', |
| 32 | +}) |
| 33 | + |
| 34 | +/** |
| 35 | + * |
| 36 | + * 2. Register event handlers for Bot |
| 37 | + * |
| 38 | + */ |
| 39 | +bot |
| 40 | +.on('login', onLogin) |
| 41 | +.on('scan', onScan) |
| 42 | +.on('error', onError) |
| 43 | +.on('message', onMessage) |
| 44 | + |
| 45 | +/** |
| 46 | + * |
| 47 | + * 3. Start the bot! |
| 48 | + * |
| 49 | + */ |
| 50 | +bot.start() |
| 51 | +.catch(async e => { |
| 52 | + console.error('Bot start() fail:', e) |
| 53 | + await bot.stop() |
| 54 | + process.exit(-1) |
| 55 | +}) |
| 56 | + |
| 57 | +/** |
| 58 | + * |
| 59 | + * 4. You are all set. ;-] |
| 60 | + * |
| 61 | + */ |
| 62 | + |
| 63 | +/** |
| 64 | + * |
| 65 | + * 5. Define Event Handler Functions for: |
| 66 | + * `scan`, `login`, `logout`, `error`, and `message` |
| 67 | + * |
| 68 | + */ |
| 69 | +function onScan (qrcode, status) { |
| 70 | + generate(qrcode, { small: true }) |
| 71 | + |
| 72 | + // Generate a QR Code online via |
| 73 | + // http://goqr.me/api/doc/create-qr-code/ |
| 74 | + const qrcodeImageUrl = [ |
| 75 | + 'https://api.qrserver.com/v1/create-qr-code/?data=', |
| 76 | + encodeURIComponent(qrcode), |
| 77 | + ].join('') |
| 78 | + |
| 79 | + console.log(`[${status}] ${qrcodeImageUrl}\nScan QR Code above to log in: `) |
| 80 | +} |
| 81 | + |
| 82 | +function onLogin (user) { |
| 83 | + console.log(`${user.name()} login`) |
| 84 | + bot.say('Wechaty login').catch(console.error) |
| 85 | +} |
| 86 | + |
| 87 | +function onError (e) { |
| 88 | + console.error('Bot error:', e) |
| 89 | +} |
| 90 | + |
| 91 | +/** |
| 92 | + * |
| 93 | + * 6. The most important handler is for: |
| 94 | + * dealing with Messages. |
| 95 | + * |
| 96 | + */ |
| 97 | +async function onMessage (msg) { |
| 98 | + console.log(msg.toString()) |
| 99 | +} |
0 commit comments