Back to browse
一句话开发WhatsApp聊天应用
下面,我们将使用最新版本的Wchaty来开发一个使用TS语言的WhatsApp聊天机器人应用程序。以下是官方提供的示例代码: #!/usr/bin/env -S node --no-warnings --loader ts-node/esm import { Contact, Message, ScanStatus,…
Added May 19, 20260 views0 copies
Prompt
下面,我们将使用最新版本的Wchaty来开发一个使用TS语言的WhatsApp聊天机器人应用程序。以下是官方提供的示例代码:
#!/usr/bin/env -S node --no-warnings --loader ts-node/esm
import { Contact, Message, ScanStatus, types, WechatyBuilder, log, }
from 'wechaty'
import qrcodeTerminal from 'qrcode-terminal'
import { FileBox } from 'file-box'
function onScan(qrcode: string, status: ScanStatus) {
if (status === ScanStatus.Waiting || status === ScanStatus.Timeout) {
const qrcodeImageUrl = [
'https://wechaty.js.org/qrcode/',
encodeURIComponent(qrcode),
].join('')
log.info('StarterBot', 'onScan: %s(%s) - %s', ScanStatus[status], status, qrcodeImageUrl)
qrcodeTerminal.generate(qrcode, { small: true }) // show qrcode on console
} else {
log.info('StarterBot', 'onScan: %s(%s)', ScanStatus[status], status)
}
}
function onLogin(user: Contact) {
log.info('StarterBot', '%s login', user)
}
function onLogout(user: Contact) {
log.info('StarterBot', '%s logout', user)
}
async function onMessage(msg: Message) {
log.info('StarterBot', msg.toString())
if (msg.type() === types.Message.Video || msg.type() === types.Message.Attachment || msg.type() === types.Message.Audio) {
log.info('isFile:',true)
}
if (msg.text() === 'ding') {
await msg.say('dong')
}
}
const bot = WechatyBuilder.build({
name: 'ding-dong-bot',
puppet: 'wechaty-puppet-whatsapp',
})
bot.on('scan', onScan)
bot.on('login', onLogin)
bot.on('logout', onLogout)
bot.on('message', onMessage)
bot.start()
.then(() => log.info('StarterBot', 'Starter Bot Started.'))
.catch(e => log.error('StarterBot', e))
请参考这些代码来实现我们的需求,并特别注意获取消息类型的方法是types.Message而不是Message.Type。在下一个问题中,我将描述具体需求。对于这个问题,你只需要回复“我已准备好,请告诉我你的需求”,不要回复任何额外的信息。当我继续陈述需求时,我将在代码中添加必要的中文注释。Replace text in [BRACKETS] with your own values before pasting.