Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ You are welcome to send your plugin to our contrib by creating a Pull Request!
| 8 | RoomInviter | @huan | Invite user to rooms by keyword |
| 9 | EventHotHandler | @huan | Hot reloading event handler module files |
| 10 | RoomInvitationAccepter | @huan | Automatically accepting any room invitations |
| 11 | MessageAwaiter | @ssine | Wait for a particular message using `await` syntax |

### 1 DingDong

Expand Down Expand Up @@ -240,6 +241,29 @@ import { RoomInvitationAccepter } from 'wechaty-plugin-contrib'
wechaty.use(RoomInvitationAccepter())
```

### 11 MessageAwaiter

- Description: Wait for a particular message using `await` syntax (`await bot.waitForMessage(...)`).
- Author: @ssine

```ts
import { MessageAwaiter } from 'wechaty-plugin-contrib'
wechaty.use(MessageAwaiter())

wechaty.on('message' async (message) => {
if (message.text() === 'whatever triggers the dialog') {
await message.say('hint message')

// wait for the reply from the same sender
let reply = await wechaty.waitForMessage({ contactId: msg.from()?.id, roomId: msg.room()?.id })

// do anything you want...
}
})
```

Other arguments include `regex` which is tested on the message and `timeoutSecond` which automatically rejects the dialog after specified seconds.

## Wechaty Plugin Directory

The Wechaty Plugin Contrib will only accept simple plugins which does not dependence very heavy NPM modules, and the SLOC (Source Line Of Code) is no more than 100.
Expand Down
65 changes: 65 additions & 0 deletions examples/message-awaiter-bot.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/**
* Wechaty - https://github.com/wechaty/wechaty
*
* @copyright 2016-now Huan LI <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import { Wechaty } from 'wechaty'

import {
DingDong,
EventLogger,
QRCodeTerminal,
MessageAwaiter,
} from '../src' // from 'wechaty-plugin-contrib'

const bot = new Wechaty({
name: 'message-awaiter-bot',
})

bot.use(
QRCodeTerminal(),
DingDong(),
EventLogger(),
MessageAwaiter()
)

bot.on('message', async (msg) => {
if (msg.text() === 'repeat me') {

await msg.say('what to repeat?')
let repeatMsg = await bot.waitForMessage({ contactId: msg.from()?.id, roomId: msg.room()?.id })
await repeatMsg.say(repeatMsg.text())

} else if (msg.text() === 'test') {

await msg.say('please reply a message with digits in a minute')
try {
let repeatMsg = await bot.waitForMessage({
contactId: msg.from()?.id,
regex: /\d/,
roomId: msg.room()?.id,
timeoutSecond: 60,
})
await repeatMsg.say(repeatMsg.text())
} catch (err) {
await msg.say(String(err))
}

}
})

bot.start()
.catch(console.error)
64 changes: 64 additions & 0 deletions src/contrib/message-awaiter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/**
* Author: Siyao Liu https://github.com/ssine
* Date: June 2020
*/
import {
Wechaty,
WechatyPlugin,
Message,
log,
} from 'wechaty'

type MessageAwaiterArgs = {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The wechaty-plugin-contrib has standard helper functions/interfaces to deal with those parameters.

Please read the related code and keep this part consistent with other plugins.

+ import * as matchers from '../matcher/mod'

type MessageAwaiterArgs = {
-  contactId?: string,
+  contact?: matchers.ContactMatcherOptions,
-  roomId?: string,
+  room?: matchers.RoomMatcherOptions,
-  regex?: RegExp,
+  text?: matchers.StringMatcherOptions,
  timeoutSecond?: number
}

contactId?: string,
roomId?: string,
regex?: RegExp,
timeoutSecond?: number
}

declare module 'wechaty' {
class Wechaty {

waitForMessage(args: MessageAwaiterArgs): Promise<Message>

}
}

export function MessageAwaiter (): WechatyPlugin {
log.verbose('WechatyPluginContrib', 'MessageAwaiter')

return function MessageAwaiterPlugin (wechaty: Wechaty) {
log.verbose('WechatyPluginContrib', 'MessageAwaiter installing on %s ...', wechaty)

wechaty.waitForMessage = async (args: MessageAwaiterArgs): Promise<Message> => {
let { contactId, roomId, regex, timeoutSecond } = args
let waitTime = new Date()

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can create the matchers helper functions from the options (demonstrated as the following code):

const matchContact = matchers.contactMatcher(args.contact)
const matchRoom = matchers.roomMatcher(args.room)
const matchString = matchers.stringMatcher(args.text)

return new Promise<Message>((resolve, reject) => {

let callback = async (message: Message) => {
let messageFrom = message.from()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Then we can use the matchers helper functions like this:

if (!matchContact(message.from)) { return }
if (!matchRoom(message.room()) { return }
if (!matchString(message.text()) { return }

let messageRoom = message.room()
if (message.date() < waitTime) return
if (contactId && messageFrom?.id !== contactId) return
if (roomId && messageRoom?.id !== roomId) return
if (regex && !regex.test(message.text())) return
wechaty.off('message', callback)
resolve(message)
}

wechaty.on('message', callback)

if (timeoutSecond) {
setTimeout(() => {
wechaty.off('message', callback)
reject(Error('timed out'))
}, timeoutSecond * 1000)
}

log.verbose('begin waiting for message from %s', contactId)
})
}
}

}
4 changes: 4 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,7 @@ export {
export {
RoomInvitationAccepter,
} from './contrib/room-invitation-accepter'

export {
MessageAwaiter,
} from './contrib/message-awaiter'