自动回复特定消息的脚本

wen 实用脚本 3

本文目录导读:

自动回复特定消息的脚本

  1. Python 版本(通用型)
  2. 基于配置文件的版本(更灵活)
  3. 简单版(适用于QQ/微信机器人)
  4. Telegram Bot 示例(需要安装 python-telegram-bot)
  5. 如何选择?
  6. 使用建议:

我来帮你创建几个不同场景下自动回复特定消息的脚本,请根据你的具体需求选择:

Python 版本(通用型)

import re
import time
from datetime import datetime
class AutoReplyBot:
    def __init__(self):
        # 定义回复规则:关键词 -> 回复内容
        self.rules = {
            '你好': '你好!有什么可以帮助您的吗?',
            '再见': '再见,祝您愉快!',
            '帮助': '我可以回复特定的消息,请发送测试消息。',
            '价格': '请咨询客服获取最新价格信息。'
        }
        # 使用正则表达式的规则
        self.regex_rules = [
            (r'联系|电话|手机', '客服热线:400-123-4567'),
            (r'邮箱|邮件', '客服邮箱:support@example.com'),
            (r'(早上|下午|晚上)好', '您好!感谢您的问候!')
        ]
    def get_reply(self, message):
        """生成回复"""
        # 检查精确匹配规则
        for keyword, reply in self.rules.items():
            if keyword in message:
                return reply
        # 检查正则规则
        for pattern, reply in self.regex_rules:
            if re.search(pattern, message):
                return reply
        return None  # 没有匹配的回复
    def process_message(self, sender, message):
        """处理单条消息"""
        print(f"[{datetime.now().strftime('%H:%M:%S')}] 收到来自 {sender} 的消息: {message}")
        reply = self.get_reply(message)
        if reply:
            print(f"-> 自动回复: {reply}")
            return reply
        else:
            print("-> 无匹配回复")
            return None
# 使用示例
if __name__ == "__main__":
    bot = AutoReplyBot()
    # 模拟消息处理
    test_messages = [
        ("用户A", "你好"),
        ("用户B", "请问价格是多少?"),
        ("用户C", "我的邮箱是test@test.com"),
        ("用户D", "下午好"),
        ("用户E", "再见")
    ]
    for sender, msg in test_messages:
        bot.process_message(sender, msg)
        time.sleep(0.5)

基于配置文件的版本(更灵活)

# config.json
import json
CONFIG = {
    "rules": {
        "你好": "你好!很高兴为您服务!",
        "再见": "再见,期待下次联系!",
        "谢谢": "不客气,这是我们应该做的!",
        "投诉": "抱歉给您带来不便,请拨打投诉专线:400-999-8888",
        "人工": "正在为您转接人工客服,请稍候..."
    },
    "regex_rules": [
        ["[1-9]\d{10}", "您提到的号码我们已经记录,稍后会有专人与您联系。"],
        ["\d{17}[\dXx]", "身份证信息已收到,请注意保护个人隐私。"],
        ["(付款|支付|转账)", "请通过官方渠道进行支付,谨防诈骗。"]
    ],
    "default_reply": "您好,您的消息已收到,我们将尽快处理。"
}
# 使用配置的自动回复器
class ConfigBasedAutoReply:
    def __init__(self, config_file='config.json'):
        self.config = CONFIG  # 实际应用中可以加载配置文件
    def get_reply(self, message):
        import re
        # 检查关键词规则
        for keyword, reply in self.config['rules'].items():
            if keyword in message:
                return reply
        # 检查正则规则
        for pattern, reply in self.config['regex_rules']:
            if re.search(pattern, message):
                return reply
        # 返回默认回复
        return self.config['default_reply']

简单版(适用于QQ/微信机器人)

# 简单直接的关键词回复
def auto_reply(message):
    """最简单的关键词回复函数"""
    replies = {
        '你好': '你好呀!',
        '在吗': '在的,有什么可以帮您?',
        '早安': '早安!新的一天加油!',
        '晚安': '晚安,好梦!',
        'help': '可用命令:1.你好 2.再见 3.帮助',
        '帮助': '可用命令:1.你好 2.再见 3.帮助',
        '版本': '当前版本:1.0.0',
        '时间': __import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    }
    for keyword, reply in replies.items():
        if keyword in message:
            return reply
    return None  # 不回复
# 批量处理
test_msgs = ['你好', '在吗?', '我想知道版本', '时间现在']
for msg in test_msgs:
    response = auto_reply(msg)
    if response:
        print(f"收到: {msg} -> 回复: {response}")

Telegram Bot 示例(需要安装 python-telegram-bot)

from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters
import re
# 定义回复规则
REPLY_RULES = {
    'hello': 'Hello! Welcome!',
    'help': 'Available commands: /start, /help',
}
async def handle_message(update: Update, context):
    """处理收到的消息"""
    message = update.message.text.lower()
    user = update.effective_user.first_name
    # 检查关键词
    for keyword, reply in REPLY_RULES.items():
        if keyword in message:
            await update.message.reply_text(reply)
            return
    # 正则匹配
    if re.search(r'\d{11}', message):  # 匹配手机号
        await update.message.reply_text("您的手机号已收到,我们会保护您的隐私。")
    elif re.search(r'你好|你好', message):
        await update.message.reply_text(f"你好 {user}!很高兴见到你!")
    else:
        await update.message.reply_text("收到您的消息,但我们无法自动回复,稍后会有客服联系您。")
# 主函数
def main():
    # 替换为你的 Bot Token
    application = Application.builder().token("YOUR_BOT_TOKEN").build()
    # 添加消息处理器
    application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
    # 启动 Bot
    application.run_polling()
if __name__ == '__main__':
    main()

如何选择?

需求场景 推荐版本
简单关键词回复 简单版(版本3)
需要正则匹配 Python通用版(版本1)
多人使用,需要配置文件 配置文件版(版本2)
Telegram Bot Telegram版(版本4)

使用建议:

  1. 增加重试机制:防止网络问题导致回复失败
  2. 添加日志记录:记录所有自动回复记录
  3. 设置频率限制:防止被刷屏
  4. 加入人工转接:当无法处理时转接人工

需要我针对特定平台(如微信、QQ、Telegram、Discord等)或特定场景(如客服、游戏、自动化测试等)提供更详细的方案吗?

抱歉,评论功能暂时关闭!