[MD]
---
Powered by Sukairain X ChatGPT o3-mini X Deepseek
在你的xenForo论坛使用请遵守MIT的开源规则
### **一、服务器环境准备**
```bash
# 1. SSH 登录服务器
ssh your_username@your_server_ip -p 22
# 2. 进入 XenForo 安装目录(根据实际情况调整)
cd /var/www/html/your_forum
# 3. 确认目录结构(应有 src、_output 等目录)
ls -al
```
---
### **二、创建机器人账户**
1. 访问后台:`https://yourforum.com/admin.php`
2. **用户管理 → 添加用户**
3. 填写信息:
- 用户名:`DeepSeekBot`
- 邮箱:`[email protected]`
- 密码:`生成强密码并保存`
4. **用户组权限设置**:
- 主用户组:注册用户
- 辅助用户组:添加至有发帖权限的组
5. **版块权限验证**:
- 访问 `论坛节点 → 选择目标版块 → 权限`
- 确认注册用户组有:
- 查看节点
- 发新主题
- 回复主题
---
### **三、创建插件文件结构**
```bash
# 1. 创建插件主目录
mkdir -p src/addons/DeepSeek/Bot/CronEntry
# 2. 创建插件描述文件
nano src/addons/DeepSeek/Bot/addon.json
```
**文件内容**:
```json
{
"legacy_addon_id": "DeepSeekBot",
"title": "DeepSeek Bot Pro",
"version_id": 1000030,
"version_string": "3.0.0",
"dev": "Your Company",
"description": "Advanced DeepSeek integration with random thread selection",
"icon": "fa-robot"
}
```
---
### **四、编写核心代码**
#### 1. 基础框架文件
```bash
nano src/addons/DeepSeek/Bot/Setup.php
```
**内容**:
```php
<?php
namespace DeepSeek\Bot;
use XF\AddOn\AbstractSetup;
class Setup extends AbstractSetup {
public function install(array $stepParams = []) {
// 安装时自动设置默认配置
\XF::db()->query("
REPLACE INTO xf_option (option_id, option_value)
VALUES
('deepSeekBotApiKey', ''),
('deepSeekBotUserId', '0')
");
}
public function upgrade(array $stepParams = []) {}
public function uninstall(array $stepParams = []) {
// 卸载时清理配置
\XF::db()->query("
DELETE FROM xf_option
WHERE option_id IN ('deepSeekBotApiKey', 'deepSeekBotUserId')
");
}
}
```
#### 2. 主逻辑文件
```bash
nano src/addons/DeepSeek/Bot/CronEntry/DeepSeekPost.php
```
**完整代码**:
```php
<?php
namespace DeepSeek\Bot\CronEntry;
use XF\Entity\Post;
use XF\Mvc\Entity\Finder;
class DeepSeekPost
{
const MAX_RETRIES = 3; // 失败重试次数
public static function run()
{
$app = \XF::app();
$startTime = microtime(true);
try {
// 获取基础配置
$botUserId = (int)$app->options()->deepSeekBotUserId;
$apiKey = $app->options()->deepSeekBotApiKey;
// 验证配置有效性
if (!$botUserId || !$apiKey) {
throw new \Exception("未配置机器人用户ID或API密钥");
}
// 频率控制检查
if (!self::checkPostFrequency()) {
\XF::logDebug('DeepSeekBot: 频率控制阻止本次执行');
return;
}
// 随机选择主帖
$thread = self::findRandomThread();
if (!$thread) {
throw new \Exception("没有符合条件的可用主帖");
}
// 生成回复内容
$response = self::generateResponse($apiKey, $thread);
// 创建回复
$post = $app->repository('XF
ost')->createPost($thread, [
'message' => $response,
'user_id' => $botUserId
]);
$post->save();
// 记录成功日志
$execTime = round(microtime(true) - $startTime, 3);
\XF::logDebug("DeepSeekBot 成功回复:线程 {$thread->thread_id} (耗时 {$execTime}s)");
} catch (\Exception $e) {
\XF::logError("DeepSeekBot 错误: " . $e->getMessage());
}
}
private static function checkPostFrequency(): bool
{
$app = \XF::app();
$lastPost = $app->finder('XF
ost')
->where('user_id', $app->options()->deepSeekBotUserId)
->order('post_date', 'DESC')
->fetchOne();
// 随机间隔机制:1-6小时
$minInterval = 3600; // 1小时
$maxInterval = 21600; // 6小时
$nextAllowed = $lastPost ? ($lastPost->post_date + rand($minInterval, $maxInterval)) : 0;
return time() >= $nextAllowed;
}
private static function findRandomThread()
{
$app = \XF::app();
return $app->finder('XF:Thread')
->where('discussion_state', 'visible')
->where('discussion_open', 1)
->where('reply_count', '>', 0) // 排除零回复帖子
->where('post_date', '>', time() - 2592000) // 仅最近30天的帖子
->orderRandom()
->fetchOne();
}
private static function generateResponse(string $apiKey, \XF\Entity\Thread $thread): string
{
$client = \XF::app()->http()->client();
$retryCount = 0;
do {
try {
$prompt = "你是一个论坛助手,请根据以下主题生成自然回复:\n\n";
$prompt .= "主题标题:{$thread->title}\n";
$prompt .= "主题内容:".strip_tags($thread->FirstPost->message)."\n\n";
$prompt .= "请用口语化中文回复,长度在50-100字之间";
$response = $client->post('https://api.deepseek.com/v1/chat/completions', [
'headers' => [
'Authorization' => 'Bearer ' . $apiKey,
'Accept' => 'application/json',
],
'json' => [
'model' => 'deepseek-chat',
'messages' => [['role' => 'user', 'content' => $prompt]],
'temperature' => 0.7,
'max_tokens' => 150
],
'timeout' => 15
]);
$data = json_decode($response->getBody(), true);
$content = trim($data['choices'][0]['message']['content'] ?? '');
// 内容过滤
if (strlen($content) < 10 || preg_match('/[<>]/', $content)) {
throw new \Exception("生成内容不符合安全规范");
}
return $content;
} catch (\GuzzleHttp\Exception\RequestException $e) {
if ($e->getCode() == 429 && $retryCount < self::MAX_RETRIES) {
sleep(2);
$retryCount++;
continue;
}
throw new \Exception("API调用失败: " . $e->getMessage());
}
} while ($retryCount < self::MAX_RETRIES);
return "【系统提示】当前无法生成回复,请稍后再试";
}
}
```
---
### **五、配置系统参数**
```bash
nano src/config.php
```
**在文件末尾添加**:
```php
// DeepSeek 机器人配置
$options->deepSeekBotApiKey = 'your_api_key_here'; // 替换为真实密钥
$options->deepSeekBotUserId = 2; // 替换为机器人用户ID
// 高级配置(可选)
$options->deepSeekBotMinInterval = 3600; // 最小间隔(秒)
$options->deepSeekBotMaxInterval = 21600; // 最大间隔(秒)
$options->deepSeekBotMaxRetries = 3; // API失败重试次数
```
---
### **六、定时任务配置**
#### 1. 创建执行脚本
```bash
nano _output/cron_deepseek.php
```
**内容**:
```php
<?php
$start = microtime(true);
require(__DIR__ . '/../src/XF.php');
XF::startApp();
// 添加随机延迟(0-300秒)避免多服务器同时执行
sleep(random_int(0, 300));
\DeepSeek\Bot\CronEntry\DeepSeekPost::run();
// 记录执行时长
$time = round(microtime(true) - $start, 3);
file_put_contents('cron_deepseek.log', date('Y-m-d H:i:s')." - {$time}s\n", FILE_APPEND);
```
#### 2. 设置Cron Job
```bash
crontab -e
```
**添加以下内容**:
```bash
# 每10分钟触发检查,实际执行由频率控制逻辑决定
*/10 * * * * /usr/bin/php /path/to/your_forum/_output/cron_deepseek.php >/dev/null 2>&1
```
#### 3. 设置文件权限
```bash
chmod 755 _output/cron_deepseek.php
chown www-data:www-data _output/cron_deepseek.php
```
---
### **七、安装与激活插件**
1. 访问后台:`https://yourforum.com/admin.php`
2. 进入 **插件与扩展**
3. 找到 "DeepSeek Bot Pro" 点击 **安装**
4. 完成安装后点击 **重新构建**
---
### **八、验证与测试**
#### 1. 手动测试
```bash
php _output/cron_deepseek.php
```
#### 2. 检查日志
```bash
# 实时查看错误日志
tail -f src/XF/logs/error.log
# 查看定时任务日志
tail -f _output/cron_deepseek.log
```
#### 3. 数据库验证
```sql
-- 查看最近的机器人发帖
SELECT * FROM xf_post
WHERE user_id = BOT_USER_ID
ORDER BY post_date DESC
LIMIT 5;
```
---
### **九、高级安全配置(可选)**
#### 1. 使用环境变量
```bash
nano /etc/environment
```
添加:
```ini
DEEPSEEK_API_KEY=your_actual_key_here
```
修改代码中的获取方式:
```php
// 替换原来的 $apiKey = ...
$apiKey = getenv('DEEPSEEK_API_KEY');
```
#### 2. IP白名单限制
```bash
nano _output/cron_deepseek.php
```
在文件开头添加:
```php
if ($_SERVER['REMOTE_ADDR'] !== '127.0.0.1') {
die('Access Denied');
}
```
---
### **十、故障排除指南**
| 现象 | 排查步骤 | 解决方案 |
|------|---------|---------|
| 无任何回复 | 1. 检查 error.log<br>2. 手动执行脚本<br>3. 验证API密钥 | 确保:<br>- 密钥有效<br>- 用户有权限<br>- 存在开放帖子 |
| 回复内容异常 | 1. 查看API响应日志<br>2. 测试API调用 | 调整生成提示词<br>添加内容过滤规则 |
| 频率过高 | 1. 检查 crontab 配置<br>2. 验证时间间隔逻辑 | 调整 cron 执行频率<br>修改 $min/$maxInterval |
| 权限拒绝 | 1. 检查文件所有者<br>2. 验证用户组权限 | 运行:<br>`chown -R www-data:www-data src/addons` |
---
### **十一、维护与更新**
#### 1. 更新插件
```bash
# 备份旧版本
cp -r src/addons/DeepSeek/Bot DeepSeekBot_backup
# 上传新文件后重新构建
php cmd.php xf-addon:build DeepSeek/Bot
```
#### 2. 监控资源使用
```bash
# 查看内存使用
watch -n 60 'ps aux | grep cron_deepseek.php'
# 监控API调用次数
grep 'DeepSeek API调用' src/XF/logs/error.log | wc -l
```
---
### **十二、完整部署检查清单**
1. [ ] 机器人账户已创建并验证权限
2. [ ] 插件文件已正确放置
3. [ ] 配置参数已正确设置
4. [ ] 定时任务已添加至 crontab
5. [ ] 文件权限已正确设置
6. [ ] 完成手动测试验证
7. [ ] 错误日志监控已设置
8. [ ] 安全配置(HTTPS/防火墙)已实施
---
通过以上完整流程,您的 XenForo 论坛将拥有一个:
- 每小时随机间隔(1-6小时)
- 自动选择随机主帖
- 生成自然语言回复
- 具备完善错误处理
- 符合安全规范的 DeepSeek 机器人
建议在正式环境部署前,先于测试环境验证所有功能。部署后前48小时建议保持密切监控,根据实际流量调整频率参数。
[/MD]
---
Powered by Sukairain X ChatGPT o3-mini X Deepseek
在你的xenForo论坛使用请遵守MIT的开源规则
### **一、服务器环境准备**
```bash
# 1. SSH 登录服务器
ssh your_username@your_server_ip -p 22
# 2. 进入 XenForo 安装目录(根据实际情况调整)
cd /var/www/html/your_forum
# 3. 确认目录结构(应有 src、_output 等目录)
ls -al
```
---
### **二、创建机器人账户**
1. 访问后台:`https://yourforum.com/admin.php`
2. **用户管理 → 添加用户**
3. 填写信息:
- 用户名:`DeepSeekBot`
- 邮箱:`[email protected]`
- 密码:`生成强密码并保存`
4. **用户组权限设置**:
- 主用户组:注册用户
- 辅助用户组:添加至有发帖权限的组
5. **版块权限验证**:
- 访问 `论坛节点 → 选择目标版块 → 权限`
- 确认注册用户组有:
- 查看节点
- 发新主题
- 回复主题
---
### **三、创建插件文件结构**
```bash
# 1. 创建插件主目录
mkdir -p src/addons/DeepSeek/Bot/CronEntry
# 2. 创建插件描述文件
nano src/addons/DeepSeek/Bot/addon.json
```
**文件内容**:
```json
{
"legacy_addon_id": "DeepSeekBot",
"title": "DeepSeek Bot Pro",
"version_id": 1000030,
"version_string": "3.0.0",
"dev": "Your Company",
"description": "Advanced DeepSeek integration with random thread selection",
"icon": "fa-robot"
}
```
---
### **四、编写核心代码**
#### 1. 基础框架文件
```bash
nano src/addons/DeepSeek/Bot/Setup.php
```
**内容**:
```php
<?php
namespace DeepSeek\Bot;
use XF\AddOn\AbstractSetup;
class Setup extends AbstractSetup {
public function install(array $stepParams = []) {
// 安装时自动设置默认配置
\XF::db()->query("
REPLACE INTO xf_option (option_id, option_value)
VALUES
('deepSeekBotApiKey', ''),
('deepSeekBotUserId', '0')
");
}
public function upgrade(array $stepParams = []) {}
public function uninstall(array $stepParams = []) {
// 卸载时清理配置
\XF::db()->query("
DELETE FROM xf_option
WHERE option_id IN ('deepSeekBotApiKey', 'deepSeekBotUserId')
");
}
}
```
#### 2. 主逻辑文件
```bash
nano src/addons/DeepSeek/Bot/CronEntry/DeepSeekPost.php
```
**完整代码**:
```php
<?php
namespace DeepSeek\Bot\CronEntry;
use XF\Entity\Post;
use XF\Mvc\Entity\Finder;
class DeepSeekPost
{
const MAX_RETRIES = 3; // 失败重试次数
public static function run()
{
$app = \XF::app();
$startTime = microtime(true);
try {
// 获取基础配置
$botUserId = (int)$app->options()->deepSeekBotUserId;
$apiKey = $app->options()->deepSeekBotApiKey;
// 验证配置有效性
if (!$botUserId || !$apiKey) {
throw new \Exception("未配置机器人用户ID或API密钥");
}
// 频率控制检查
if (!self::checkPostFrequency()) {
\XF::logDebug('DeepSeekBot: 频率控制阻止本次执行');
return;
}
// 随机选择主帖
$thread = self::findRandomThread();
if (!$thread) {
throw new \Exception("没有符合条件的可用主帖");
}
// 生成回复内容
$response = self::generateResponse($apiKey, $thread);
// 创建回复
$post = $app->repository('XF

'message' => $response,
'user_id' => $botUserId
]);
$post->save();
// 记录成功日志
$execTime = round(microtime(true) - $startTime, 3);
\XF::logDebug("DeepSeekBot 成功回复:线程 {$thread->thread_id} (耗时 {$execTime}s)");
} catch (\Exception $e) {
\XF::logError("DeepSeekBot 错误: " . $e->getMessage());
}
}
private static function checkPostFrequency(): bool
{
$app = \XF::app();
$lastPost = $app->finder('XF

->where('user_id', $app->options()->deepSeekBotUserId)
->order('post_date', 'DESC')
->fetchOne();
// 随机间隔机制:1-6小时
$minInterval = 3600; // 1小时
$maxInterval = 21600; // 6小时
$nextAllowed = $lastPost ? ($lastPost->post_date + rand($minInterval, $maxInterval)) : 0;
return time() >= $nextAllowed;
}
private static function findRandomThread()
{
$app = \XF::app();
return $app->finder('XF:Thread')
->where('discussion_state', 'visible')
->where('discussion_open', 1)
->where('reply_count', '>', 0) // 排除零回复帖子
->where('post_date', '>', time() - 2592000) // 仅最近30天的帖子
->orderRandom()
->fetchOne();
}
private static function generateResponse(string $apiKey, \XF\Entity\Thread $thread): string
{
$client = \XF::app()->http()->client();
$retryCount = 0;
do {
try {
$prompt = "你是一个论坛助手,请根据以下主题生成自然回复:\n\n";
$prompt .= "主题标题:{$thread->title}\n";
$prompt .= "主题内容:".strip_tags($thread->FirstPost->message)."\n\n";
$prompt .= "请用口语化中文回复,长度在50-100字之间";
$response = $client->post('https://api.deepseek.com/v1/chat/completions', [
'headers' => [
'Authorization' => 'Bearer ' . $apiKey,
'Accept' => 'application/json',
],
'json' => [
'model' => 'deepseek-chat',
'messages' => [['role' => 'user', 'content' => $prompt]],
'temperature' => 0.7,
'max_tokens' => 150
],
'timeout' => 15
]);
$data = json_decode($response->getBody(), true);
$content = trim($data['choices'][0]['message']['content'] ?? '');
// 内容过滤
if (strlen($content) < 10 || preg_match('/[<>]/', $content)) {
throw new \Exception("生成内容不符合安全规范");
}
return $content;
} catch (\GuzzleHttp\Exception\RequestException $e) {
if ($e->getCode() == 429 && $retryCount < self::MAX_RETRIES) {
sleep(2);
$retryCount++;
continue;
}
throw new \Exception("API调用失败: " . $e->getMessage());
}
} while ($retryCount < self::MAX_RETRIES);
return "【系统提示】当前无法生成回复,请稍后再试";
}
}
```
---
### **五、配置系统参数**
```bash
nano src/config.php
```
**在文件末尾添加**:
```php
// DeepSeek 机器人配置
$options->deepSeekBotApiKey = 'your_api_key_here'; // 替换为真实密钥
$options->deepSeekBotUserId = 2; // 替换为机器人用户ID
// 高级配置(可选)
$options->deepSeekBotMinInterval = 3600; // 最小间隔(秒)
$options->deepSeekBotMaxInterval = 21600; // 最大间隔(秒)
$options->deepSeekBotMaxRetries = 3; // API失败重试次数
```
---
### **六、定时任务配置**
#### 1. 创建执行脚本
```bash
nano _output/cron_deepseek.php
```
**内容**:
```php
<?php
$start = microtime(true);
require(__DIR__ . '/../src/XF.php');
XF::startApp();
// 添加随机延迟(0-300秒)避免多服务器同时执行
sleep(random_int(0, 300));
\DeepSeek\Bot\CronEntry\DeepSeekPost::run();
// 记录执行时长
$time = round(microtime(true) - $start, 3);
file_put_contents('cron_deepseek.log', date('Y-m-d H:i:s')." - {$time}s\n", FILE_APPEND);
```
#### 2. 设置Cron Job
```bash
crontab -e
```
**添加以下内容**:
```bash
# 每10分钟触发检查,实际执行由频率控制逻辑决定
*/10 * * * * /usr/bin/php /path/to/your_forum/_output/cron_deepseek.php >/dev/null 2>&1
```
#### 3. 设置文件权限
```bash
chmod 755 _output/cron_deepseek.php
chown www-data:www-data _output/cron_deepseek.php
```
---
### **七、安装与激活插件**
1. 访问后台:`https://yourforum.com/admin.php`
2. 进入 **插件与扩展**
3. 找到 "DeepSeek Bot Pro" 点击 **安装**
4. 完成安装后点击 **重新构建**
---
### **八、验证与测试**
#### 1. 手动测试
```bash
php _output/cron_deepseek.php
```
#### 2. 检查日志
```bash
# 实时查看错误日志
tail -f src/XF/logs/error.log
# 查看定时任务日志
tail -f _output/cron_deepseek.log
```
#### 3. 数据库验证
```sql
-- 查看最近的机器人发帖
SELECT * FROM xf_post
WHERE user_id = BOT_USER_ID
ORDER BY post_date DESC
LIMIT 5;
```
---
### **九、高级安全配置(可选)**
#### 1. 使用环境变量
```bash
nano /etc/environment
```
添加:
```ini
DEEPSEEK_API_KEY=your_actual_key_here
```
修改代码中的获取方式:
```php
// 替换原来的 $apiKey = ...
$apiKey = getenv('DEEPSEEK_API_KEY');
```
#### 2. IP白名单限制
```bash
nano _output/cron_deepseek.php
```
在文件开头添加:
```php
if ($_SERVER['REMOTE_ADDR'] !== '127.0.0.1') {
die('Access Denied');
}
```
---
### **十、故障排除指南**
| 现象 | 排查步骤 | 解决方案 |
|------|---------|---------|
| 无任何回复 | 1. 检查 error.log<br>2. 手动执行脚本<br>3. 验证API密钥 | 确保:<br>- 密钥有效<br>- 用户有权限<br>- 存在开放帖子 |
| 回复内容异常 | 1. 查看API响应日志<br>2. 测试API调用 | 调整生成提示词<br>添加内容过滤规则 |
| 频率过高 | 1. 检查 crontab 配置<br>2. 验证时间间隔逻辑 | 调整 cron 执行频率<br>修改 $min/$maxInterval |
| 权限拒绝 | 1. 检查文件所有者<br>2. 验证用户组权限 | 运行:<br>`chown -R www-data:www-data src/addons` |
---
### **十一、维护与更新**
#### 1. 更新插件
```bash
# 备份旧版本
cp -r src/addons/DeepSeek/Bot DeepSeekBot_backup
# 上传新文件后重新构建
php cmd.php xf-addon:build DeepSeek/Bot
```
#### 2. 监控资源使用
```bash
# 查看内存使用
watch -n 60 'ps aux | grep cron_deepseek.php'
# 监控API调用次数
grep 'DeepSeek API调用' src/XF/logs/error.log | wc -l
```
---
### **十二、完整部署检查清单**
1. [ ] 机器人账户已创建并验证权限
2. [ ] 插件文件已正确放置
3. [ ] 配置参数已正确设置
4. [ ] 定时任务已添加至 crontab
5. [ ] 文件权限已正确设置
6. [ ] 完成手动测试验证
7. [ ] 错误日志监控已设置
8. [ ] 安全配置(HTTPS/防火墙)已实施
---
通过以上完整流程,您的 XenForo 论坛将拥有一个:
- 每小时随机间隔(1-6小时)
- 自动选择随机主帖
- 生成自然语言回复
- 具备完善错误处理
- 符合安全规范的 DeepSeek 机器人
建议在正式环境部署前,先于测试环境验证所有功能。部署后前48小时建议保持密切监控,根据实际流量调整频率参数。
[/MD]
领取红包用户


