下载地址:www.pan38.com/dow/share.p… 提取密码:1133
这个项目包含四个主要模块:核心评论机器人、配置加载器、评论内容管理器和主程序入口。核心模块实现了签名生成、评论发布等核心功能,支持抖音、小红书和快手平台。使用时需要为每个平台准备配置文件,并准备好评论内容CSV文件。
import requests import json import time import random from urllib.parse import quote from hashlib import md5 import base64
class SocialCommentBot: def init(self, platform_config): self.platform = platform_config['platform'] self.base_url = platform_config['base_url'] self.headers = platform_config['headers'] self.session = requests.Session() self.session.headers.update(self.headers)
def generate_signature(self, params):
"""生成平台要求的签名"""
if self.platform == 'douyin':
params_str = '&'.join([f'{k}={v}' for k,v in sorted(params.items())])
return md5(params_str.encode()).hexdigest()
elif self.platform == 'xiaohongshu':
params_str = json.dumps(params, separators=(',', ':'))
return base64.b64encode(md5(params_str.encode()).hexdigest().encode()).decode()
else:
return ''
def post_comment(self, content, video_id, retry=3):
"""发布评论到指定视频"""
params = {
'video_id': video_id,
'content': content,
'timestamp': int(time.time()),
'platform': self.platform
}
params['sign'] = self.generate_signature(params)
for attempt in range(retry):
try:
response = self.session.post(
f"{self.base_url}/comment",
data=params,
timeout=10
)
if response.status_code == 200:
result = response.json()
if result.get('code') == 0:
return True, result.get('comment_id')
else:
time.sleep(random.uniform(1, 3))
else:
time.sleep(random.uniform(2, 5))
except Exception as e:
print(f"Attempt {attempt+1} failed: {str(e)}")
time.sleep(random.uniform(3, 6))
return False, None
def batch_comments(self, comments, video_ids):
"""批量发布评论到多个视频"""
results = []
for video_id in video_ids:
for comment in comments:
success, comment_id = self.post_comment(comment, video_id)
results.append({
'video_id': video_id,
'comment': comment,
'success': success,
'comment_id': comment_id
})
time.sleep(random.uniform(5, 15))
return results
import yaml import os
class ConfigLoader: @staticmethod def load_platform_config(platform_name): """加载指定平台的配置文件""" config_path = os.path.join('configs', f'{platform_name}.yaml') try: with open(config_path, 'r', encoding='utf-8') as f: config = yaml.safe_load(f) return config except Exception as e: print(f"Error loading config for {platform_name}: {str(e)}") return None
@staticmethod
def get_all_platforms():
"""获取所有支持的平台配置"""
platforms = []
config_dir = 'configs'
if os.path.exists(config_dir):
for file in os.listdir(config_dir):
if file.endswith('.yaml'):
platforms.append(file[:-5])
return platforms
pandas as pd import random
class CommentManager: def init(self, comment_file='comments.csv'): self.comments = [] self.load_comments(comment_file)
def load_comments(self, file_path):
"""从CSV文件加载评论内容"""
try:
df = pd.read_csv(file_path)
self.comments = df['content'].tolist()
except Exception as e:
print(f"Error loading comments: {str(e)}")
self.comments = []
def get_random_comment(self):
"""随机获取一条评论"""
if self.comments:
return random.choice(self.comments)
return "不错的视频!"
def get_comments_batch(self, count=5):
"""获取多条评论"""
if len(self.comments) >= count:
return random.sample(self.comments, count)
return self.comments * (count // len(self.comments)) + self.comments[:count % len(self.comments)]