百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
C

chatter

> 编程语言
开源

用于创建交互式聊天机器人的一系列有用原语。

197 stars0 点赞3 次浏览
访问官网GitHub

工具介绍

用于创建交互式聊天机器人的一系列有用原语。

chatter

A collection of useful primitives for creating interactive chat bots. [normalizeMessage]: #normalizeMessage [node]: https://nodejs.org/en/download/

Usage

bash
npm install --save chatter

Tested in [Node][node] 4.x and 6.x.

Note: If the following code example syntax looks unfamiliar, don't worry, it's just JavaScript! Read a detailed overview of ECMAScript 2015 features to learn more.

What is a bot?

For the purposes of this documentation, a bot is an automated system that selectively responds to text messages with text responses. The bot may simply respond to messages, statelessly, or the bot may do more complex things, like keep track of ongoing conversations with users.

The most basic bot looks something like this (note, this is pseudocode):

javascript
// Import the chat service's library.
const ChatService = require('chat-service');

// Create a chat service instance with the relevant options.
const myChatService = new ChatService(options);

// When the chat service receives a message that it cares about, respond to it.
myChatService.on('message', message => {
  // This is the code you'll spend most of your time writing. Ie, the bot:
  if (doICareAbout(message)) {
    myChatService.send(response);
  }
});

// Actually connect to the chat service.
myChatService.connect();

Usually, all the behind-the-scenes work of connecting the bot to the remote service, handling reconnections, keeping track of state (what users the bot is currently talking to, what channels the bot is currently in) is done by a service-specific library.

So, what's left to do? Well, as shown in the previous example, you'll need to write the code that determines if a given message warrants a response, and to then deliver that response to the user.

This project aims to help with all that.

Message handlers

Since most bot code is centered around these two steps:

  1. Testing an incoming message to see if it should be handled
  2. Sending a response based on the incoming message

It makes sense to introduce a primitive that does these things. That primitive is called a "message handler."

The simplest message handler is a function that accepts a message argument and returns a response if it should respond, or false if it doesn't care about that message:

javascript
const lolHandler = message => {
  if (/lol/i.test(message)) {
    const newMessage = message.replace(/lol/ig, 'laugh out loud');
    return `More like "${newMessage}" amirite`;
  }
  return false;
};

lolHandler('what')     // false
lolHandler('lol what') // 'More like "laugh out loud what" amirite'

But what if a message handler needs to yield a response asynchronously, instead of returning a value immediately? It can, by returning a Promise:

javascript
const stuffHandler = message => {
  if (message === 'get stuff') {
    return db.query('SELECT * FROM STUFF').then(results => {
      const stuff = results.join(', ');
      return `Look at all the stuff: ${stuff}`;
    });
  }
  return false;
};

stuffHandler('huh')       // false
stuffHandler('get stuff') // Promise -> 'Look at all the stuff! ...'

But what do you do if you want to pass all messages through both lolHandler and stuffHandler? What if your bot needs to be able to respond to a dozen types of message in a dozen different ways?

Just create an array of message handlers:

javascript
const messageHandlers = [
  lolHandler,
  stuffHandler,
];

Now, you've undoubtedly realized that functions that return values or promises and arrays behave quite differently. Without a helper function that knows how to iterate over that array, or wait for a promise to resolve, or both of those things, this won't make your job any easier.

Fortunately, chatter gives you that helper function.

Processing messages

The processMessage function (that chatter exports) takes two arguments:

  1. A message handler
  2. A message

This function understands that a message handler might be a function or an array of functions like the ones described above (or a few other possible things, which will be explained later).

It takes the message handler and message you give it and intelligently processes them to produce a response (if any), and it returns a Promise that will be resolved with that response:

…

Of course, instead of logging the response, your bot would be sending it back to the user who said the message or the channel it was said in, using the chat service library. But you get the idea.

Message handlers, more specifically

As far as the processMessage function is concerned, a message handler is a function, an object with a handleMessage method, or an array of any combination of those things. That array may contain other arrays.

javascript
const functionMessageHandler = message => {
  if (condition) {
    return response;
  }
  return false;
};

const objectMessageHandler = {
  handleMessage(message) {
    if (condition) {
      return response;
    }
    return false;
  },
};

const arrayMessageHandler = [
  functionMessageHandler,
  objectMessageHandler,
];

A message handler function (or method) may return false or return a Promise that yields false to indicate that the message handler doesn't care about the message, and the next message handler (if any) should process the message.

javascript
const returnsFalseMessageHandler = function(message) {
  return false;
};

const yieldsFalseMessageHandler = function(message) {
  return Promise.resolve(false);
};

A message handler may return or yield any other value, and if so, iteration will be stopped immediately and that value will be yielded.

javascript
const returnsValueMessageHandler = function(message) {
  return 'hello';
};

const yieldsValueMessageHandler = function(message) {
  return Promise.resolve('world');
};

Also, a message handler may return another message handler (function, object or array) and those new message handlers will be processed in-line.

As you can see, message handlers may be very simple, but may be composed in very creative ways.

(See message-handlers for more examples)

A naive bot using message handlers and processMessage

Like the earlier What is a bot? example, this bot is pseudocode, but this time it uses message handlers and the processMessage helper function:

…

Additional included message handlers

Because there are a number of common things message handlers need to do, a few message handler "creator" functions have been included to make creating common message handlers easier.

createMatcher

The createMatcher function creates a new message handler that only calls the specified message handler if the message matches. It accepts a match option, which is a string, regex or function, to match against the message. If a string is specified, it matches the beginning of the message. If a message is matched, the remainder of the message will be passed into the specified message handler:

…

See the create-matcher example.

createParser

The createParser function creates a new message handler that calls the specified message handler, not with a message string, but with an object representing the "parsed" message. This is especially useful if you want to work with an array of words from the message, instead of just a string message.

javascript
const createParser = require('chatter').createParser;

// Reduce the array of parsed args into a sum.
const addHandler = createParser(parsed => {
  const args = parsed.args;
  const result = args.reduce((sum, num) => sum + Number(num), 0);
  return `${args.join(' + ')} = ${result}`;
});

processMessage(addHandler, '1 2 3')    // Promise -> 1 + 2 + 3 = 6
processMessage(addHandler, '4 five 6') // Promise -> 4 + five + 6 = NaN

When parseOptions is defined, any options in the message specified like option=value will be parsed and processed via the defined function, and made available in parsed.options (any non-options args will still be available in parsed.args). As you can see, options may be abbreviated!

javascript
const parsingHandler = createParser({
  parseOptions: {
    alpha: String,
    beta: Number,
  },
}, parsed => JSON.stringify(parsed.options));

processMessage(parsingHandler, 'a=1 b=2') // Promise -> {"alpha":"1","beta":2}

See the create-parser example.

createCommand

The createCommand function is meant to be used to create a nested tree of message handlers that each have a name, description and usage information, with an automatically-created help command and a fallback message handler.

Like with the createMatcher match option, the name will be used to match the message, with the remainder of the message being passed into the specified message handler. The name, description and usage options will be used to display contextual help and usage information.

Note that because the response from message handlers created with createCommand may return arrays, they should be normalized into a newline-joined string with the included [normalizeMessage] helper function.

…

See the create-command and create-command-namespaced examples.

createConversation

The createConversation function creates a new message handler that calls the specified message handler, doing nothing of note until that message handler returns an object with a dialog property, which should be a new message handler. At that point, the new message handler is stored and used instead of the originally-specified message handler to handle the next message. After that message, the message handler is reverted to the original, unless another dialog is specified, in which case that is used instead.

Conversations can be used to create an interactive sequence of message handlers, and must be be cached on a per-conversation basis (usually per-channel or per-direct message), because of the need to keep track of the current dialog.

…

See the bot-conversation example.

createArgsAdjuster

The createArgsAdjuster function creates a new message handler that calls the specified message handler with a different set of arguments than the message handler received. This is especially useful when you need to pass state from where a parent message handler is created into a child message handler.

…

See the create-args-adjuster and bot-stateful examples.

Creating a more robust bot

As with message handlers, bot behaviors can get a little complex. As shown in the preceding createConversation and createArgsAdjuster examples, message handlers may have state. Additionally, the previous bot examples don't handle errors in a useful way or do anything to normalize responses, which means your message handlers may need extra code to help format multi-line responses.

To that end, this pseudocode example bot is implemented using createBot:

…

See the bot-stateful and bot-conversation examples.

Creating a Slack bot

While the aforementioned Bot is generally useful, it's really meant to be a starting point from which other more specific bots may be derived. Which brings us to SlackBot.

SlackBot contains all of the functionality of Bot, with some useful additional features like passing channel, user and slack information into message handlers, alowing message handlers to be chosen dynamically based on channel, group or dm, and automatically connecting the bot to the slack rtm & web clients.

When you create a SlackBot, you pass in an instance of the Slack `RtmClie

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

JavaScript

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言