基于 Python 的 TikTok 直播间智能自动回复系统,集情感分析、关键词匹配、多轮对话记忆、 类人口语生成和反检测机制于一体。支持多种回复风格,让机器人的回复像真人一样自然。
六大模块协同工作,打造最自然的自动回复体验
基于词典的情感分析,支持中英文混合识别。检测积极/消极/中性情感,对程度副词加权处理,自动识别疑问句、感谢和告别语气。
SentimentAnalyzer30+ 精细意图分类,覆盖问候、赞美、关注、商务合作、年龄、位置、直播、告别等场景。按优先级排序,支持多意图同时匹配。
KeywordMatcherRedis 风格会话管理,支持自动过期和 LRU 淘汰。用户画像抽取(姓名、位置、年龄),保持上下文不失忆。说话越多,回复越精准。
ConversationMemory五种回复风格:日常/热情/呆萌/高冷/撒娇。同类话题至少 5 种回复模板。随机颜文字、语气词、填充词,让回复充满人性化。
HumanLikeReplyGenerator多层反机器人检测:随机类人延迟、打字错误模拟、纠正回复、时段活性模拟(深夜低概率回复)、消息频率限制、首次消息慢回复。
AntiDetectionEngine支持 warm / cute / cold / playful / shy 五种回复风格,根据情感极性自动调整。记住用户的偏好风格,下次优先使用。
Style System模块化流水线设计,每个环节精确可控
核心模块代码片段,展示设计思路与实现细节
class SentimentAnalyzer: """基于词典的情感分析器""" def __init__(self): self.positive_words = [ '喜欢', '爱', '开心', '棒', '漂亮', 'love', 'nice', 'good', 'great', 'amazing' ] self.negative_words = [ '讨厌', '生气', '垃圾', '差', 'hate', 'bad', 'terrible' ] self.intensifiers = [ '非常', '超级', '太', '特别', 'very', 'so', 'extremely' ] def analyze(self, text: str) -> Dict: """分析文本情感,返回情感得分和极性""" words = re.findall(r'[\u4e00-\u9fff\w]+', text.lower()) pos_score, neg_score = 0, 0 for i, word in enumerate(words): if word in self.positive_words: multiplier = 1.5 if i > 0 and words[i-1] in self.intensifiers else 1.0 pos_score += 1.0 * multiplier total = pos_score + neg_score if total == 0: polarity = 'neutral' else: score = (pos_score - neg_score) / total polarity = 'positive' if score > 0.3 else ( 'negative' if score < -0.3 else 'neutral') return { 'polarity': polarity, 'is_question': text.endswith('?') or '什么' in text, 'is_thanks': '谢谢' in text.lower() }
class ConversationMemory: """基于 Redis-style 的对话记忆管理""" def __init__(self, max_users: int = 1000, max_history: int = 20): self.max_users = max_users self.max_history = max_history self.sessions: Dict[str, Dict] = {} def add_message(self, username: str, message: str, is_bot: bool = False): uid = hashlib.md5(username.encode()).hexdigest()[:12] if uid not in self.sessions: self.sessions[uid] = { 'username': username, 'history': [], 'extracted_info': {}, 'last_seen': time.time(), 'message_count': 0 } self.sessions[uid]['last_seen'] = time.time() self.sessions[uid]['message_count'] += 1 self.sessions[uid]['history'].append({ 'role': 'bot' if is_bot else 'user', 'text': message, 'time': time.time() }) # 自动抽取用户信息 if not is_bot: self._extract_info(uid, message) def get_context(self, username: str) -> Dict: """获取用户的对话上下文(最后6条消息)""" uid = hashlib.md5(username.encode()).hexdigest()[:12] session = self.sessions.get(uid) return { 'history': session['history'][-6:] if session else [], 'info': session.get('extracted_info', {}) if session else {}, 'message_count': session.get('message_count', 0) if session else 0 }
class AntiDetectionEngine: """TikTok 反机器人检测机制""" def __init__(self): # 各时段响应概率(0-23时) self.hour_probability = { 0: 0.05, 3: 0.01, 6: 0.05, 9: 0.40, 12: 0.60, 15: 0.40, 18: 0.60, 20: 0.80, 22: 0.70 } # 回复延迟范围 self.delay_ranges = { 'first_message': (5.0, 15.0), # 首次慢回 'normal': (1.0, 5.0), 'slow': (8.0, 25.0), # 深夜 } # 打字错误映射 self.typo_patterns = [ ('的', '滴'), ('了', '啦'), ('吗', '嘛'), ('好', '嗷'), ('是', '系'), ('我', '偶'), ] def get_delay(self, message_count: int, hour=None) -> float: """计算类人回复延迟""" if message_count <= 1: delay_range = self.delay_ranges['first_message'] elif hour is not None and hour < 7: delay_range = self.delay_ranges['slow'] else: delay_range = self.delay_ranges['normal'] return round(random.uniform(*delay_range), 2) def apply_typo(self, text: str, prob=0.08) -> str: """模拟打字错误(8%概率)""" if random.random() > prob: return text for correct, typo in self.typo_patterns: if correct in text: return text.replace(correct, typo, 1) return text def apply_correction(self, text: str, prob=0.05) -> str: """模拟发现打错字纠正(5%概率)""" if random.random() > prob: return text corrections = ['啊打错了', '手滑了…', '哎呀打错了'] return text.rstrip() + '\n' + random.choice(corrections)
class HumanLikeReplyGenerator: """自然语言回复生成器 - 多种风格""" def __init__(self): self.kaomoji = [ '(。>ㅅ<。)', '(´•ω•\`)', '(≧▽≦)', '(◕‿◕✿)', '(。♥‿♥。)', '(人´∀\`)♪', '(●´ω`●)', '(✧ω✧)', '(๑˃ᴗ˂)ﻭ' ] self.reply_templates = { 'greeting': { 'warm': [ '哈喽~ 你来啦!{kaomoji}', '你好呀!等你好久了~{kaomoji}', 'hello hello!好久不见呀~' ], 'cute': [ '呜哇!来人了!欢迎欢迎~{kaomoji}', '叮!捕捉到一只活的小可爱!{kaomoji}' ] }, 'compliment': { 'shy': [ '真的吗?好害羞~不要这样夸人家啦~{kaomoji}', '哪有你说的那么好啦~不过还是谢谢!' ], 'playful': [ '那必须的!每天照镜子都被自己美醒~', '嘻嘻~给你个特权,以后多夸夸我!' ] } } def generate(self, text, sentiment, matched_intents, context, style='warm'): """根据情感、意图和上下文生成回复""" polarity = sentiment.get('polarity', 'neutral') # 根据情感调整风格 if polarity == 'negative': style = 'warm' elif polarity == 'positive' and random.random() < 0.3: style = 'cute' # 选择模板并填充 primary_intent = matched_intents[0]['category'] if matched_intents else 'default' templates = self.reply_templates.get(primary_intent, {}) template_list = templates.get(style, templates.get('warm', [])) reply = random.choice(template_list) if template_list else '' # 添加自然语言元素 if random.random() < 0.15: filler = random.choice(['嗯…', '那个…', '就是说…']) reply = filler + reply return reply.replace('{kaomoji}', random.choice(self.kaomoji))
class TikTokAutoReplySystem: """TikTok 智能自动回复系统主控制器""" def __init__(self): self.sentiment = SentimentAnalyzer() self.keyword_matcher = KeywordMatcher() self.memory = ConversationMemory() self.reply_gen = HumanLikeReplyGenerator() self.anti_detection = AntiDetectionEngine() self.stats = { 'start_time': time.time(), 'total_responses': 0, 'responded_users': set() } def process_message(self, username: str, text: str) -> Optional[str]: """处理单条消息的完整流水线""" now = datetime.now() # 1. 反检测 - 判断是否回复 if not self.anti_detection.should_respond(now.hour): return None # 2. 情感分析 sentiment = self.sentiment.analyze(text) # 3. 关键词匹配 matched_intents = self.keyword_matcher.match(text) # 4. 获取对话上下文 context = self.memory.get_context(username) # 5. 存储消息 self.memory.add_message(username, text, is_bot=False) # 6. 计算延迟 delay = self.anti_detection.get_delay( context['message_count'], now.hour) time.sleep(delay) # 7. 生成回复 reply = self.reply_gen.generate( text, sentiment, matched_intents, context) # 8-9. 打字错误 + 纠正 reply = self.anti_detection.apply_typo(reply) reply = self.anti_detection.apply_correction(reply) # 10. 存储回复 self.memory.add_message(username, reply, is_bot=True) self.stats['total_responses'] += 1 self.stats['responded_users'].add(username) return reply def chat(self, username='guest'): """交互式聊天模式""" print(f'\n🎀 欢迎 {username}!开始聊天吧!\n') while True: text = input('你: ').strip() if text.lower() in ('q', 'quit', 'exit'): break reply = self.process_message(username, text) print(f'Bot: {reply}' if reply else '(已读不回模式)')
完整源码已打包为 ZIP 格式,包含全部核心模块和示例代码。即刻下载,马上使用!
解压后直接运行 python3 tiktok_bot_v3.py 即可体验
网络语料采集 · 特征提取 · 长期记忆 · 类人回复
覆盖抖音、B站、微博、小红书、贴吧、知乎6大平台的经典流行语和语录
自动分析文本中的精神小妹元素:感叹号密度、Emoji浓度、流行语使用频率、语气词结尾等
基于 pickle 的持久化记忆,记住用户偏好、学习新流行语、管理短语时间线
7大对话场景(问候/打气/自嘲/撩人/生气/鼓励/调侃)自动匹配最合适的口吻
0-100分打分制:🏆纯正精神小妹 → 有内味儿了 → 开始上道了 → 需要再冲一点
模拟从各社交媒体平台提取最新网络用语,保持语料库与时俱进
完整源码包含:语料库管理系统、特征提取引擎、长期记忆存储、场景化回复生成器,开箱即用!
解压后运行 python3 sister_spirit_learning.py 开冲!