Giter Club home page Giter Club logo

plugin-contrib's Introduction

wechaty-plugin-contrib Wechaty Plugin Contrib

NPM Version NPM ES Modules

Wechaty Plugin Contrib Package for the Community

Wechaty Plugin

Image Credit: What is Plugin

Powered by Wechaty TypeScript

Introduction

When you find yourself writing repetitive code, it's time to extract it into a plugin.

Wechaty has a great support for using Plugins by calling Wechaty.use(WechatyPlugin()). A Wechaty Plugin is a JavaScript function that returns a function which accepts a Wechaty instance.

The first Wechaty Plugin system was design by our core team developer @gcaufy from issue #1939(Wechaty Plugin Support with Kick out Example) to PR #1946(feat: added wechaty plugin).

This package is for publishing the Wechaty Plugins that are very common used by the core developer team.

Requirements

  1. Wechaty v0.40 or above versions

Plugins Contrib

You are welcome to send your plugin to our contrib by creating a Pull Request!

# Plugin Author Feature
1 DingDong @huan Reply dong if bot receives a ding message.
2 EventLogger @huan Log Wechaty Events for 'scan' | 'login' | 'message' ... etc.
3 QRCodeTerminal @huan Show QR Code for Scan in Terminal
4 Heartbeat @huan Send emoji periodically
5 ChatOps @huan Forward DM & Mention messages to a room
6 RoomConnector @huan Connect rooms together with 1:N, M:1, and M:N modes
7 FriendshipAccepter @huan Accept friendship automatically, and say/do something for greeting.
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 #13

1 DingDong

  • Description: Reply dong if bot receives a ding message.
  • Author: @huan
import { DingDong } from 'wechaty-plugin-contrib'

const config = {
  mention : true,    // default: true - Response to Mention Self (@/at) Message in Room
  contact : true,    // default: true - Response to Direct Message
  room    : true,    // default: true - Response to Rooms Message
  self    : true,    // default: true - Response to Message that send from the bot itself
}

wechaty.use(DingDong(config))

config as a Function

config can also be a function which receives a message: Message and returns a boolean result to decide whether response a ding message.

Config: (message: Message) => boolean | Promise<boolean>

2 EventLogger

  • Description: Log Wechaty Events: "dong" | "message" | "error" | "friendship" | "heartbeat" | "login" | "logout" | "ready" | "reset" | "room-invite" | "room-join" | "room-leave" | "room-topic" | "scan"
  • Author: @huan
import { EventLogger } from 'wechaty-plugin-contrib'
const config = ['login', 'ready', 'message']
// Do not provide an config will log all events.
wechaty.use(EventLogger(config))

3 QR Code Terminal

  • Description: Show QR Code for Scan in Terminal
  • Author: @huan
import { QRCodeTerminal } from 'wechaty-plugin-contrib'
const config = {
  small: false,   // default: false - the size of the printed QR Code in terminal
}
wechaty.use(QRCodeTerminal(config))

4 Heartbeat

  • Description: Send emoji periodically
  • Author: @huan
import { Heartbeat } from 'wechaty-plugin-contrib'
const config = {
  contact: 'filehelper',    // default: filehelper - Contact id who will receive the emoji
  emoji: {
    heartbeat: '[爱心]',    // default: [爱心] - Heartbeat emoji
  },
  intervalSeconds: 60 * 60, // Default: 1 hour - Send emoji for every 1 hour
}
wechaty.use(Heartbeat(config))

5 ChatOps

  • Description: Forward DM & Mention messages to a ChatOps room for logging.
  • Author: @huan
import { ChatOps } from 'wechaty-plugin-contrib'

const config = {
  room : 'xxx@chatroom',      // required: room id for ChatOps
  mention?  : true,                // default: true - Response to Mention Self (@/at) Message in Room
  contact?  : true,                // default: true - Response to Direct Message
  whitelist?: ChatOpsFilter,  // whitelist for messages that allow to send to ChatOps Room
  blacklist?: ChatOpsFilter,  // blacklist for messages that forbidden to send to ChatOps Room
}

wechaty.use(ChatOps(config))

6 RoomConnector(s)

Connect rooms together, it supports three modes:

  1. 1:N - OneToManyRoomConnector can broadcast the messages in one room to others.
  2. M:1 - ManyToOneRoomConnector can summary messages from rooms into one room.
  3. M:M - ManyToManyRoomConnector will broadcast every message between rooms.
  4. M:N - SourceToTargetRoomConnector will broadcast every message from source room(s) to target room(s).

The difference between SourceToTargetRoomConnector and ManyToManyRoomConnector is that:

  1. SourceToTargetRoomConnector have two options to specify:
    1. source: use RoomMatcherOptions to specify the source rooms
    2. target: use RoomFinderOptions to specify the target rooms
  2. ManyToManyRoomConnector have one option to specify:
    1. many: use string[] as list of room ids to broadcast to

6.1 OneToManyRoomConnector()

import { OneToManyRoomConnector, OneToManyRoomConnectorConfig } from 'wechaty-plugin-contrib'
const config: OneToManyRoomConnectorConfig = {
  blacklist: [ async () => true ],
  many: [
    '20049383519@chatroom',     // 小句子测试
    '5611663299@chatroom',      // 'ChatOps - Mike BO'
  ],
  map: async message => message.talker().name() + '(one to many): ' + message.text(),
  one: '17237607145@chatroom',  // PreAngel 动态
  whitelist: [ async message => message.type() === Message.Type.Text ],
}
wechaty.use(OneToManyRoomConnector(config))

6.2 ManyToOneRoomConnector()

import { ManyToOneRoomConnector, ManyToOneRoomConnectorConfig } from 'wechaty-plugin-contrib'
const config: ManyToOneRoomConnectorConfig = {
  blacklist: [ async () => true ],
  many: [
    '20049383519@chatroom',     // 小句子测试
    '5611663299@chatroom',      // 'ChatOps - Mike BO'
  ],
  map: async message => message.talker().name() + '(many to one): ' + message.text(),
  one: '17237607145@chatroom',  // PreAngel 动态
  whitelist: [ async message => message.type() === Message.Type.Text ],
}
wechaty.use(ManyToOneRoomConnector(config))

6.3 ManyToManyRoomConnector()

import { ManyToManyRoomConnector, ManyToManyRoomConnectorConfig } from 'wechaty-plugin-contrib'
const config: ManyToManyRoomConnectorConfig = {
  blacklist: [ async () => true ],
  many: [
    '20049383519@chatroom',     // 小句子测试
    '5611663299@chatroom',      // 'ChatOps - Mike BO'
  ],
  map: async message => message.talker().name() + '(many to many): ' + message.text(),
  whitelist: [ async message => message.type() === Message.Type.Text ],
}
wechaty.use(ManyToManyRoomConnector(config))

6.4 SourceToTargetRoomConnector()

import { SourceToTargetRoomConnector, SourceToTargetRoomConnectorConfig } from 'wechaty-plugin-contrib'
const config: SourceToTargetRoomConnectorConfig = {
  blacklist: [ async () => true ],
  source: [
    '5611663299@chatroom',
    /source room topic/i,
  ],
  target: [
    '20049383519@chatroom',
    /target room topic/i,
  ],

  map: async message => message.talker().name() + '(source to target): ' + message.text(),
  whitelist: [ async message => message.type() === Message.Type.Text ],
}
wechaty.use(SourceToTargetRoomConnector(config))

7 FriendshipAccepter

Accept friendship automatically, and say/do something for greeting.

import { FriendshipAccepter, FriendshipAccepterConfig } from 'wechaty-plugin-contrib'
const config: FriendshipAccepterConfig = {
  greeting: 'we are friends now!',
  keyword: '42',
}
wechaty.use(FriendshipAccepter(config))
  1. greeting will be sent after the friendship has been accepted.
  2. keyword if set, the friendship must match the keyword text.

8 RoomInviter

Invite a contact to the room with password, welcome(public message), and rule(private message) options supported.

import { RoomInviter, RoomInviterConfig } from 'wechaty-plugin-contrib'
const config: RoomInviterConfig = {
  password : 'wechaty',
  room     : '18171595067@chatroom',
  welcome  : 'Welcome to join the room!',
  rule     : 'Please be a good people',
  repeat   : 'You have already in our room',
}
wechaty.use(RoomInviter(config))

9 EventHotHandler DEPRECATED after v0.15

Hot reloading event handler module files.

import { EventHotHandler, EventHotHandlerConfig } from 'wechaty-plugin-contrib'
const config: EventHotHandlerConfig = {
  login: './handlers/on-login',
  logout: './handlers/on0-logout',
}
wechaty.use(EventHotHandler(config))

10 RoomInvitationAccepter

Automatically accepting any room invitations.

import { RoomInvitationAccepter } from 'wechaty-plugin-contrib'
wechaty.use(RoomInvitationAccepter())

11 messagePrompter

  • Description: Wait for a particular message using await syntax (await messagePrompter(message)(...)).
  • Author: @ssine (refactored by @huan)
import { messageAwaiter } from 'wechaty-plugin-contrib'

wechaty.on('message' async (message) => {
  const prompter = messagePrompter(message)

  const reply = prompter('Hello')
  if (reply) {
    await message.say('hint message')
    // do anything you want...
  }
})

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

Learn more from:

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.

There are many great Wechaty Plugins can not be included in the contrib because they are too powerful. They will be published as a NPM by itself.

We are listing those powerful Wechaty Plugins outside the contrib as in the following list, and you are welcome to add your plugin below if you have published any!

Wechaty Plugin Contrib

  1. VoteOut Plugin by @gcaufy - help you to have a vote and kick out feature for you room.
  2. Schedule by @gcaufy - easily schedule jobs for your Wechaty bots.
  3. GotKicked by @JesseWeb - monitor whether your bot got kicked out of group chat. Just few line of code to implement this instead fussy judging.
  4. WebPanel by @Leo_chen - help you quickly access the web panel
  5. Intercom by @huan - helps you to manage your customers/leads/users in the WeChat Room, with the power of the Intercom service.
  6. Wechaty Vorpal by @huan - CLI for Chatbot - Extensible Commands for ChatOps, Powered by Vorpal.
  7. Freshdesk by @huan - Managing Conversations in WeChat Rooms by Freshdesk.
  8. QnAMaker by @huan - Wechaty QnAMaker Plugin helps you to answer questions in WeChat with the power of https://QnAMaker.ai.
  9. Weixin OpenAI by @windmemory - Wechaty Weixin OpenAI Plugin helps you to answer questions in WeChat with the power of https://openai.weixin.qq.com.
  10. YouDao Translate by @Chs97 - Wechaty YouDao Translate Plugin helps you to translate word in WeChat with the power of https://ai.youdao.com/.
  11. Log Monitor by @ArchyWillHe - For log-related DevOps using only WeChat! Fully functional! Very loose coupling! Pretty much pure (other than side effects in I.O.)! Also contains features like QR Rescue (aka 掉线给码) for 2 Wechaties to rescue one another when one is disconnected from the grpc server.
  12. Wechaty Xyao by @watertao - Wechaty Xyao Plugin gives bot ability to execute instruction with distributed brain module.
  13. Wechaty-fanli by @Leo_chen - help you quickly access the rebate robot about taobao

History

master v1.0

  1. Add SourceToTargetRoomConnector to connect a source room to a target room by forward messages to target room.
  2. Support ES Modules
    1. Deprecated EventHotHandler due to ESM
  3. Change MessageAwaiter plugin to messagePrompter helper function. (#60)

v0.14 master

  1. Add types.SayableMessage and types.toSayableMessage
  2. Normalize config option:
    1. dm renamed to contact
    2. at renamed to mention

v0.10 (Jun 14, 2020)

  1. Export talkers.*, finders.*, and matchers.*
  2. Add Mustache template & view support for all talkers.
  3. Add mappers.messageMapper()
  4. Add matcher.languageMatcher()

v0.8 (Jun 13, 2020)

Add more helper utility functions.

  1. Matchers: RoomMatcher, ContactMatcher, MessageMatcher
  2. Talkers: RoomTalker, ContactTalker, MessageTalker
  3. Finders: RoomFinder, ContactFinder

v0.6 (Jun 9, 2020)

  1. New Plugins: OneToManyRoomConnector, ManyToOneRoomConnector, and ManyToManyRoomConnector.
  2. New Plugin: FriendshipAccepter for setting to accept friendship automatically.
  3. New Plugin: RoomInviter for invite user to rooms with password, rule, and welcome options support.
  4. New Plugin: EventHotHandler for hot reloading event handler module files.

v0.4 (May 2020)

  1. New plugin: ChatOps: forward all DM & Mention messages to a Room for logging.

v0.2 (May 2020)

Added the following Wechaty Plugins:

  1. DingDong
  2. EventLogger
  3. QRCodeTerminal
  4. Heartbeat

v0.0.1 (Apr 2020)

The wechaty-plugin-contrib project was kicked off by the issue Wechaty Plugin Support with Kickout Example #1939 and the PR feat: added wechaty plugin #1946.

Contributors

contributor contributor contributor contributor contributor contributor contributor contributor

Maintainers

Copyright & License

  • Code & Docs © 2020 Wechaty Contributors https://github.com/wechaty
  • Code released under the Apache-2.0 License
  • Docs released under Creative Commons

plugin-contrib's People

Contributors

archywillhe avatar atorber avatar chs97 avatar dependabot-preview[bot] avatar dependabot[bot] avatar gcaufy avatar huan avatar jesn avatar jesseweb avatar leochen-g avatar lijiarui avatar ssine avatar watertao avatar windmemory avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

plugin-contrib's Issues

New Plugin: Sync Between Multiple Rooms

Plugin Name

SyncRoom (?)

Plugin Options

type IdListFunction = (wechaty: Wechaty) => string | string[]
type IdOption = string | string[] | IdListFunction

interface Options {
  room: IdOption
  blackList: {
    contact: IdOption,
    messageType: Message.Type | Message.Type[],
  },
  whiteList: {
    contact: IdOption,
    messageType: Message.Type | Message.Type[],
  }
}

Description

If there's any new message in the rooms, the bot will say this message in the other rooms.

Cannot receive heartbeat msg

//     "wechaty-plugin-contrib": "0.19"
  bot.use(
    Heartbeat({
      contact: 'willinx',
      emoji: {
        heartbeat: '[爱心]',
        login: '[太阳]',
        logout: '[月亮]',
        ready: '[拳头]'
      },
      intervalSeconds: 5
    })
  );

image

Logs:

WECHATY_LOG=silly npx ts-node src/index.ts | grep Heartbeat
12:43:04 VERB WechatyPluginContrib Heartbeat("{"contact":"willinx","emoji":{"heartbeat":"[爱心]","login":"[太阳]","logout":"[月亮]","ready":"[拳头]"},"intervalSeconds":5}")
12:43:04 VERB WechatyPluginContrib Heartbeat installing on Wechaty#2ed9be83-1c86-4c46-a91c-13cb8d7b8d89<Puppet#1<PuppetPadlocal>(NONAME)>() ...
12:43:04 VERB WechatyPluginContrib Heartbeat setting `ready` event
12:43:04 VERB WechatyPluginContrib Heartbeat setting `logout` event
12:43:06 VERB WechatyPluginContrib Heartbeat wechaty.on(login)
12:43:06 VERB WechatyPluginContrib Heartbeat talkerList numbers: 1
12:43:06 VERB WechatyPluginContrib Heartbeat heart()...
12:43:06 SILL WechatyPluginContrib Heartbeat heart() new timer set
12:43:06 VERB WechatyPluginContrib Heartbeat sayEmoji(login)
12:43:06 VERB WechatyPluginContrib Heartbeat getEmoji(login)
12:43:07 SILL [LongLink] [43:8410] longlink stopHeartbeat
12:43:07 WARN [PadLocalClient] 
================================================================================
WARNING: Your token will be expired on: "2022/01/24". Please renew ASAP to avoid
                              service termination.
================================================================================

12:43:07 VERB WechatyPluginContrib Heartbeat sayEmoji(ready)

nenver got ready/heartbeat message

[feature request] Heartbeat health check

It'd be great to have a heartbeat health check plugin -- 验证heartbeat

就是如何验证自己的代码是否收不到更新消息了

前几天遇到过一次,不知道为什么,一条新消息都收不到了,可事实上是错过了好多

[Huan (李卓桓)]:

看来应该发布一个插件做这个验证 heartbeat 了呢
你去发一个 issue 提一个 feature request 吧,我可以把之前的代码封装一下

New Plugin: Message Awaiter

Plugin Name

Message Awaiter

Description

During my experience of developinng bots (telegram, coolq, and newly on wechaty), I find that all the frameworks provide a callback mechanism when message is received. However, this clear and simple api is indirect when developing dialogs with multiple message sending and receiving.

For example, I have a bot that asks what I've done and record it everyday. This happens every 11pm:

1. bot: what have you done today?
2. me : a/b/c
3. bot: give yourself a score?
4. me : 30
5. bot: events recorded.

so after message 1, 3 are sent, the bot begin to wait for my reply. Such dialog pattern is common and intuitive, but is indirect to implement in EventEmitter's api. To do this, we can make a state machine for each dialog, or pass subsequent logic into callback function, but neither of them matches the simplicity of await bot.newMessageFrom(...).

This plugin returns a Promise object that resolves when a new message that satisfies some condition (from whom, text pattern matching, timing) is received (and manages the lifecycle of the listener function), so that the dialog logic in code can continue uninterrupted. The code pattern would look like this:

async function dialog() {
  await bot.say(...)
  let reply = await bot.waitFor(...)
  // do something with reply
  await bot.say(...)
  reply = await bot.waitFor(...)
  // the pattern repeats or ends
}

NewPlugin: Crontab

Like the following code from our Friday BOT demonstrated: (original author: @qhduan )

import cron from 'node-cron'

interface CRONConfig {
  time: string,
  reply: string
}

const CRON_CONFIG: CRONConfig[] = [
  {
    reply: '星期一了,如果主席还没发活动总结的话要注意了',
    /**
     * 定时任务
     *     ┌─────────────── second (optional)
     *     │ ┌───────────── minute
     *     │ │ ┌─────────── hour
     *     │ │ │  ┌──────── day of month
     *     │ │ │  │ ┌────── month
     *     │ │ │  │ │ ┌──── day of week
     *     │ │ │  │ │ │
     *     │ │ │  │ │ │
     *     * * *  * * *      // */
    time: '0 0 19 * * 1',
  },
]

/**
 * TODO: Huan(202006)
 */
export async function crontab () {
  for (const cronConfig of CRON_CONFIG) {
    cron.schedule(cronConfig.time, async () => {
      // await Chatops.instance().say(cronConfig.reply)
    })
  }
}

See:

New Plugin: Make Rooms' Announcement

Plugin Name

RoomAnnouncer (?)

Plugin Options

type IdListFunction = (wechaty: Wechaty) => string | string[]
type IdOption = string | string[] | IdListFunction

interface Options {
  admin: {
    room: IdOption,
    at: boolean,
    command?: string,
    doubleCofirm: boolean,
    whitelist: {
      contact?: IdOption,
    },
    blacklist: {
      contact?: IdOption,
    }
  },
  room: string | string[] | RoomListFunction
}

Description

If there's a new message in the admin room, and it matches the options as a room announcement request, then the bot will set this message as the announcement in the room rooms.

New Plugin: Broadcast to Multiple Rooms

Plugin Name

RoomBroadcast (?)

Plugin Options

type IdListFunction = (wechaty: Wechaty) => string | string[]
type IdOption = string | string[] | IdListFunction

interface Options {
  source: {
    room: IdOption,
    blackList: {
      messageType: MessageType | MessageType[],
      contact: IdOption,
    }
  },
  target: {
    room: string | string[] | RoomListFunction
  }
}

Description

If there's any new message in the from rooms, the bot will say this message in the to rooms.

New Plugin: HotImport Handlers

to hotImport a wechaty event listener from a module file.

This plugin will replace the internal code from the Wechaty

Feature List

功能大全
入群欢迎
新人进群后27助手发送指定信息@并欢迎新人,增加仪式感及快速了解群规等

广告踢人
27助手自动检验群内发送的网址链接,小程序链接等内容对其进行禁言或踢除

批量拉人入群
可批量选择微信群内需要入群的好友,方便快捷的将好友拉入群众

好友添加回复
自动同意好友添加请求,并可自定义设置被添加后的自动回复话术引导用户入群

多群群发
可将需要在多群内发布的多条消息,按照时间循序同步发送出去,以达到直播效果

定时群发
支持在某一时间点推送消息,并可自定义发送周期

被@后回复
群内有人@时,会进行设定好消息的自动回复,以助于了解群规提醒私聊

图灵智能聊天
图灵机器人 聊天机器人可以在未触发关键词与群内用户智能聊天,提高群组活跃

清理僵尸粉
通过想27助手发送指令,0打扰清理僵尸粉,多少人已将你删除一目了然

多开聊天
支持多微信号同时登录聚合聊天

关键词回复
可设置多个关键词策略进行群和好友问题的自动回复

群邀请
可在群内发布群邀请任务,统计群成员邀请入群数量,提醒并奖励积分

防重复入群
禁止用户在指定群内多次出现

群成员查重
可检查清理重复入群人员

多群转播
可设置主讲人将消息群发转播至广播群内

See:

http://www.27wx.com/

please update @latest on npm repo to the real latest version

In the getting-started project, we have "wechaty-plugin-contrib": "^1.11.1". But if I initialize project with yarn add wechaty-plugin-contrib@latest, I got 1.0.18. It causes an import problem:

yarn run start
yarn run v1.22.19
$ cross-env WECHATY_LOG=verbose WECHATY_PUPPET=wechaty-puppet-wechat NODE_OPTIONS="--no-warnings --loader=ts-node/esm" node index.ts
file:///***/node_modules/wechaty-plugin-contrib/dist/esm/src/types/talker-message.js:1
import { type, log, } from 'wechaty';
         ^^^^
SyntaxError: The requested module 'wechaty' does not provide an export named 'type'
    at ModuleJob._instantiate (node:internal/modules/esm/module_job:128:21)
    at async ModuleJob.run (node:internal/modules/esm/module_job:194:5)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:385:24)
    at async loadESM (node:internal/process/esm_loader:88:5)
    at async handleMainPromise (node:internal/modules/run_main:61:12)
error Command failed with exit code 1.

The deps are:

  "dependencies": {
    "dotenv": "^16.0.1",
    "qrcode-terminal": "^0.12.0",
    "wechaty": "^1.20.2",
    "wechaty-plugin-contrib": "^1.0.18",
    "wechaty-puppet-wechat": "^1.18.4"
  },

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.