auto-reply

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Auto-Reply - Complete API Reference

自动回复(Auto-Reply)- 完整API参考

Create rules for automatic responses based on patterns, keywords, and conditions.

基于匹配模式、关键词与条件创建自动回复规则。

Chat Commands

聊天命令

List Rules

列出规则

/autoreply list                             List all rules
/autoreply active                           Show active rules only
/autoreply stats                            Rule statistics
/autoreply list                             列出所有规则
/autoreply active                           仅显示启用的规则
/autoreply stats                            规则统计数据

Create Rules

创建规则

/autoreply add <pattern> <response>         Simple keyword match
/autoreply add-regex <regex> <response>     Regex pattern
/autoreply add-keywords <kw1,kw2> <resp>    Keyword rule
/autoreply add <pattern> <response>         简单关键词匹配
/autoreply add-regex <regex> <response>     正则表达式匹配
/autoreply add-keywords <kw1,kw2> <resp>    多关键词规则

Manage Rules

管理规则

/autoreply enable <id>                      Enable rule
/autoreply disable <id>                     Disable rule
/autoreply remove <id>                      Remove rule
/autoreply edit <id> <new-response>         Update response
/autoreply get <id>                         Rule details
/autoreply enable <id>                      启用规则
/autoreply disable <id>                     禁用规则
/autoreply remove <id>                      删除规则
/autoreply edit <id> <new-response>         更新回复内容
/autoreply get <id>                         查看规则详情

Testing

测试功能

/autoreply test <message>                   Test which rules match
/autoreply simulate <message>               Preview response
/autoreply test <message>                   测试哪些规则会匹配
/autoreply simulate <message>               预览回复内容

Advanced

高级功能

/autoreply cooldown <id> <seconds>          Set cooldown
/autoreply schedule <id> <start-end>        Active hours (e.g. 9-17)
/autoreply priority <id> <number>           Set priority (higher first)
/autoreply channel <id> <channel>           Restrict to channel
/autoreply clear-cooldowns                  Clear all cooldowns
/autoreply reload                           Reload rules from disk

/autoreply cooldown <id> <seconds>          设置冷却时间
/autoreply schedule <id> <start-end>        设置生效时段(例如 9-17)
/autoreply priority <id> <number>           设置优先级(数值越高越优先)
/autoreply channel <id> <channel>           限制规则仅在指定频道生效
/autoreply clear-cooldowns                  清除所有冷却时间
/autoreply reload                           从磁盘重新加载规则

TypeScript API Reference

TypeScript API参考

Create Auto-Reply Manager

创建自动回复管理器

typescript
import { createAutoReplyManager } from 'clodds/auto-reply';

const autoReply = createAutoReplyManager({
  // Storage
  storage: 'sqlite',
  dbPath: './auto-reply.db',

  // Defaults
  defaultCooldownMs: 0,
  defaultPriority: 0,

  // Limits
  maxRulesPerUser: 100,
  maxResponseLength: 2000,
});
typescript
import { createAutoReplyManager } from 'clodds/auto-reply';

const autoReply = createAutoReplyManager({
  // 存储配置
  storage: 'sqlite',
  dbPath: './auto-reply.db',

  // 默认设置
  defaultCooldownMs: 0,
  defaultPriority: 0,

  // 限制配置
  maxRulesPerUser: 100,
  maxResponseLength: 2000,
});

Add Simple Rule

添加简单规则

typescript
// Keyword match
await autoReply.addRule({
  name: 'greeting',
  pattern: {
    type: 'keyword',
    value: 'hello',
    caseSensitive: false,
  },
  response: 'Hi there! How can I help?',
});
typescript
// 关键词匹配
await autoReply.addRule({
  name: 'greeting',
  pattern: {
    type: 'keyword',
    value: 'hello',
    caseSensitive: false,
  },
  response: 'Hi there! How can I help?',
});

Add Regex Rule

添加正则规则

typescript
// Regex pattern
await autoReply.addRule({
  name: 'price-query',
  pattern: {
    type: 'regex',
    value: /price\s+(btc|eth|sol)/i,
  },
  response: async (match, ctx) => {
    const symbol = match[1].toUpperCase();
    const price = await getPrice(symbol);
    return `${symbol} price: $${price}`;
  },
});
typescript
// 正则表达式匹配
await autoReply.addRule({
  name: 'price-query',
  pattern: {
    type: 'regex',
    value: /price\s+(btc|eth|sol)/i,
  },
  response: async (match, ctx) => {
    const symbol = match[1].toUpperCase();
    const price = await getPrice(symbol);
    return `${symbol} price: $${price}`;
  },
});

Add Conditional Rule

添加带条件的规则

typescript
// With conditions
await autoReply.addRule({
  name: 'trading-hours',
  pattern: {
    type: 'keyword',
    value: 'trade',
  },
  conditions: [
    // Only during market hours
    {
      type: 'time',
      start: '09:30',
      end: '16:00',
      timezone: 'America/New_York',
    },
    // Only on weekdays
    {
      type: 'day',
      days: ['mon', 'tue', 'wed', 'thu', 'fri'],
    },
    // Only for certain users
    {
      type: 'user',
      userIds: ['user-123', 'user-456'],
    },
  ],
  response: 'Markets are open! What would you like to trade?',
  elseResponse: 'Markets are closed. Try again during trading hours.',
});
typescript
// 带生效条件的规则
await autoReply.addRule({
  name: 'trading-hours',
  pattern: {
    type: 'keyword',
    value: 'trade',
  },
  conditions: [
    // 仅在交易时段生效
    {
      type: 'time',
      start: '09:30',
      end: '16:00',
      timezone: 'America/New_York',
    },
    // 仅在工作日生效
    {
      type: 'day',
      days: ['mon', 'tue', 'wed', 'thu', 'fri'],
    },
    // 仅对指定用户生效
    {
      type: 'user',
      userIds: ['user-123', 'user-456'],
    },
  ],
  response: '市场已开放!您想要交易什么?',
  elseResponse: '市场已休市,请在交易时段尝试。',
});

Add Cooldown

添加冷却限制

typescript
// Prevent spam
await autoReply.addRule({
  name: 'faq',
  pattern: {
    type: 'keyword',
    value: 'faq',
  },
  response: 'Check our FAQ at https://...',
  cooldown: {
    perUser: 60000,    // 60s per user
    perChannel: 10000, // 10s per channel
    global: 5000,      // 5s global
  },
});
typescript
// 防止重复触发(垃圾消息)
await autoReply.addRule({
  name: 'faq',
  pattern: {
    type: 'keyword',
    value: 'faq',
  },
  response: '查看我们的FAQ:https://...',
  cooldown: {
    perUser: 60000,    // 每个用户60秒冷却
    perChannel: 10000, // 每个频道10秒冷却
    global: 5000,      // 全局5秒冷却
  },
});

Dynamic Responses

动态回复内容

typescript
// Response with variables
await autoReply.addRule({
  name: 'welcome',
  pattern: {
    type: 'exact',
    value: '!welcome',
  },
  response: 'Welcome {{user.name}}! You joined {{user.joinDate}}.',
  variables: {
    'user.name': (ctx) => ctx.user.displayName,
    'user.joinDate': (ctx) => ctx.user.createdAt.toDateString(),
  },
});

// Response with API call
await autoReply.addRule({
  name: 'portfolio',
  pattern: {
    type: 'keyword',
    value: 'portfolio',
  },
  response: async (match, ctx) => {
    const portfolio = await getPortfolio(ctx.user.id);
    return `Your portfolio: $${portfolio.totalValue.toFixed(2)}`;
  },
});
typescript
// 带变量的回复
await autoReply.addRule({
  name: 'welcome',
  pattern: {
    type: 'exact',
    value: '!welcome',
  },
  response: '欢迎 {{user.name}}!您于 {{user.joinDate}} 加入。',
  variables: {
    'user.name': (ctx) => ctx.user.displayName,
    'user.joinDate': (ctx) => ctx.user.createdAt.toDateString(),
  },
});

// 调用API生成回复
await autoReply.addRule({
  name: 'portfolio',
  pattern: {
    type: 'keyword',
    value: 'portfolio',
  },
  response: async (match, ctx) => {
    const portfolio = await getPortfolio(ctx.user.id);
    return `您的资产组合总价值:$${portfolio.totalValue.toFixed(2)}`;
  },
});

List Rules

列出规则

typescript
const rules = await autoReply.listRules();

for (const rule of rules) {
  console.log(`${rule.id}: ${rule.name}`);
  console.log(`  Pattern: ${rule.pattern.value}`);
  console.log(`  Enabled: ${rule.enabled}`);
  console.log(`  Triggers: ${rule.triggerCount}`);
}
typescript
const rules = await autoReply.listRules();

for (const rule of rules) {
  console.log(`${rule.id}: ${rule.name}`);
  console.log(`  匹配模式: ${rule.pattern.value}`);
  console.log(`  启用状态: ${rule.enabled}`);
  console.log(`  触发次数: ${rule.triggerCount}`);
}

Test Rule

测试规则

typescript
// Test which rules would match
const matches = await autoReply.test('hello world', {
  userId: 'user-123',
  channelId: 'telegram-456',
});

for (const match of matches) {
  console.log(`Rule: ${match.rule.name}`);
  console.log(`Response: ${match.response}`);
}
typescript
// 测试指定消息会匹配哪些规则
const matches = await autoReply.test('hello world', {
  userId: 'user-123',
  channelId: 'telegram-456',
});

for (const match of matches) {
  console.log(`匹配规则: ${match.rule.name}`);
  console.log(`回复内容: ${match.response}`);
}

Enable/Disable

启用/禁用规则

typescript
await autoReply.enable('rule-id');
await autoReply.disable('rule-id');
typescript
await autoReply.enable('rule-id');
await autoReply.disable('rule-id');

Delete Rule

删除规则

typescript
await autoReply.deleteRule('rule-id');

typescript
await autoReply.deleteRule('rule-id');

Pattern Types

匹配模式类型

TypeExampleDescription
keyword
hello
Contains keyword
exact
!help
Exact match only
regex
/price\s+\w+/i
Regular expression
startsWith
!
Starts with prefix
endsWith
?
Ends with suffix

类型示例说明
keyword
hello
消息包含指定关键词
exact
!help
消息与内容完全匹配
regex
/price\s+\w+/i
符合正则表达式规则
startsWith
!
消息以指定前缀开头
endsWith
?
消息以指定后缀结尾

Condition Types

条件类型

TypeDescription
time
Active during time window
day
Active on specific days
user
Only for specific users
channel
Only in specific channels
role
Only for users with role
custom
Custom function

类型说明
time
在指定时间窗口内生效
day
在指定日期生效
user
仅对指定用户生效
channel
仅在指定频道生效
role
仅对拥有指定角色的用户生效
custom
自定义生效条件函数

Response Variables

回复变量

VariableDescription
{{user.name}}
User display name
{{user.id}}
User ID
{{channel.name}}
Channel name
{{match[0]}}
Full regex match
{{match[1]}}
First capture group
{{date}}
Current date
{{time}}
Current time

变量说明
{{user.name}}
用户显示名称
{{user.id}}
用户ID
{{channel.name}}
频道名称
{{match[0]}}
正则表达式完整匹配内容
{{match[1]}}
正则表达式第一个捕获组内容
{{date}}
当前日期
{{time}}
当前时间

Best Practices

最佳实践

  1. Use priorities — Important rules first
  2. Set cooldowns — Prevent spam
  3. Test patterns — Verify before enabling
  4. Use conditions — Context-aware responses
  5. Monitor triggers — Check rule effectiveness
  1. 设置优先级 — 让重要规则优先触发
  2. 配置冷却时间 — 避免重复触发造成骚扰
  3. 测试匹配模式 — 启用前验证规则有效性
  4. 使用生效条件 — 实现上下文感知的智能回复
  5. 监控触发数据 — 检查规则的实际效果