initial commit. It works!

This commit is contained in:
jerry
2018-04-28 16:20:44 +08:00
parent 04b6c2b648
commit e1abed776c
14 changed files with 445 additions and 232 deletions

View File

@@ -6,13 +6,6 @@
* Time: 10:43 * Time: 10:43
*/ */
namespace cqbot;
use cqbot\mods\ModBase;
use cqbot\utils\Buffer;
use cqbot\utils\CQUtil;
class CQBot class CQBot
{ {
/** @var Framework */ /** @var Framework */
@@ -41,33 +34,26 @@ class CQBot
CQUtil::errorLog("请求执行任务时异常\n" . $e->getMessage()); CQUtil::errorLog("请求执行任务时异常\n" . $e->getMessage());
CQUtil::sendDebugMsg("引起异常的消息:\n" . $it["message"]); CQUtil::sendDebugMsg("引起异常的消息:\n" . $it["message"]);
} }
$msg_arr = explode("&&amp", $this->replace($it["message"], $it));
foreach ($msg_arr as $item) {
$msg = trim($item);
$msg = explode(" ", $msg);
$this->checkFunction($msg, $it);
} }
} }
}
public function checkFunction($msgCut, $it){
$cmdList = Buffer::get("commands");
if (isset($cmdList[$msgCut[0]])) {
Console::debug("Call CQFunction:" . $msgCut[0]);
$temp = $cmdList[$msgCut[0]];
/** @var ModBase $class */
$class = new $temp($this, $it);
$class->execute($msgCut);
return true;
}
Console::debug("未找到指令:[" . $msgCut[0] . "]");
return false;
}
public function callTask($it){ public function callTask($it){
if ($this->data["post_type"] == "message") { if ($this->data["post_type"] == "message") {
foreach(Buffer::get("mod_task") as $v){ foreach(Buffer::get("mods") as $v){
new $v($this, $this->data); Console::info("Activating module ".$v);
/** @var ModBase $w */
$w = new $v($this, $this->data);
if($w->call_task === false){
$msg = trim($this->data["message"]);
$msg = explode(" ", $msg);
$prefix = Buffer::get("cmd_prefix");
if($prefix != ""){
if(mb_substr($msg[0],0,mb_strlen($prefix)) == $prefix){
$msg[0] = mb_substr($msg[0], mb_strlen($prefix));
}
}
$w->execute($msg);
}
} }
} }
} }

View File

@@ -6,13 +6,9 @@
* Time: 11:16 * Time: 11:16
*/ */
namespace cqbot;
use cqbot\utils\Buffer;
use cqbot\utils\CQUtil;
class Framework class Framework
{ {
public static $super_user;
private $host = "127.0.0.1"; private $host = "127.0.0.1";
private $api_port = 10000; private $api_port = 10000;
private $event_port = 20000; private $event_port = 20000;
@@ -22,13 +18,14 @@ class Framework
public static $obj = null; public static $obj = null;
private $run_time; public $run_time;
public static $admin_group; public static $admin_group;
public $info_level = 1; public $info_level = 1;
/** @var \swoole_http_client $api */ /** @var \swoole_http_client $api */
public $api; public $api;
private $log_file; private $log_file;
public $tick_time;
public function __construct(){ } public function __construct(){ }
@@ -69,16 +66,17 @@ class Framework
return self::$obj; return self::$obj;
} }
public function init(){ public function init($option = null){
self::$super_user = ($option !== null ? $option : "");
self::$obj = $this; self::$obj = $this;
Console::put("CQBot Framework starting..."); Console::info("CQBot Framework starting...");
$this->event = new \swoole_websocket_server($this->host, $this->event_port); $this->event = new \swoole_websocket_server($this->host, $this->event_port);
Buffer::$log_file = CONFIG_DIR . "log/swoole.log"; Buffer::$log_file = CONFIG_DIR . "log/swoole.log";
Console::put("Current log file: " . Buffer::$log_file); Console::info("Current log file: " . Buffer::$log_file);
$worker_num = 1; $worker_num = 1;
Console::put("Current worker count: " . $worker_num); Console::info("Current worker count: " . $worker_num);
$dispatch_mode = 2; $dispatch_mode = 2;
Console::put("Current dispatch mode: " . $dispatch_mode); Console::info("Current dispatch mode: " . $dispatch_mode);
$this->checkFiles(); $this->checkFiles();
$this->event->set([ $this->event->set([
"log_file" => Buffer::$log_file, "log_file" => Buffer::$log_file,
@@ -87,8 +85,13 @@ class Framework
]); ]);
$this->event->on('WorkerStart', [$this, 'onWorkerStart']); $this->event->on('WorkerStart', [$this, 'onWorkerStart']);
$this->event->on('message', [$this, 'onEventMessage']); $this->event->on('message', [$this, 'onEventMessage']);
$this->event->on('open', [$this, 'onConnect']); //$this->event->on('open', [$this, 'onConnect']);
$this->event->on('open', function ($server, $request){
Console::put("EVENT connection established", "lightblue");
});
$this->event->on("request", [$this, "onRequest"]);
$this->event->on('close', function ($serv, $fd){ $this->event->on('close', function ($serv, $fd){
Console::info(Console::setColor("EVENT connection closed","red"));
//put your connection close method here. //put your connection close method here.
}); });
Buffer::$in_count = new \swoole_atomic(1); Buffer::$in_count = new \swoole_atomic(1);
@@ -98,7 +101,7 @@ class Framework
} }
public function checkFiles(){ public function checkFiles(){
@mkdir(WORKING_DIR."log/", 0777, true); @mkdir(CONFIG_DIR."log/", 0777, true);
if(!is_file(CONFIG_DIR."log/last_error.log")) if(!is_file(CONFIG_DIR."log/last_error.log"))
file_put_contents(CONFIG_DIR."log/last_error.log", ""); file_put_contents(CONFIG_DIR."log/last_error.log", "");
if(!is_file(CONFIG_DIR."log/error_flag")) if(!is_file(CONFIG_DIR."log/error_flag"))
@@ -115,18 +118,17 @@ class Framework
*/ */
public function onWorkerStart(\swoole_server $server, $worker_id){ public function onWorkerStart(\swoole_server $server, $worker_id){
$this->run_time = time(); $this->run_time = time();
Console::info("Starting worker " . $worker_id); Buffer::set("info_level", $this->info_level);//设置info等级
Console::info("Loading source code..."); Console::info("Starting worker: " . $worker_id);
require_once(WORKING_DIR . "src/cqbot/loader.php"); require_once(WORKING_DIR . "src/cqbot/loader.php");
CQUtil::loadAllFiles(); CQUtil::loadAllFiles();
Buffer::set("info_level", $this->info_level);//设置info等级
foreach (get_included_files() as $file) foreach (get_included_files() as $file)
Console::debug("Loaded " . $file); Console::debug("Loaded " . $file);
echo("\n");
//计时器ms //计时器ms
$server->tick(1000, [$this, "processTick"]); $server->tick(1000, [$this, "processTick"]);
//API连接部分
$this->api = new \swoole_http_client($this->host, $this->api_port); $this->api = new \swoole_http_client($this->host, $this->api_port);
$this->api->set(['websocket_mask' => true]); $this->api->set(['websocket_mask' => true]);
$this->api->on('message', [$this, "onApiMessage"]); $this->api->on('message', [$this, "onApiMessage"]);
@@ -137,18 +139,18 @@ class Framework
Console::debug("master_pid = " . $server->master_pid); Console::debug("master_pid = " . $server->master_pid);
Console::debug("worker_id = " . $worker_id); Console::debug("worker_id = " . $worker_id);
Console::put("\n====================\n"); Console::put("\n==========STARTUP DONE==========\n");
} }
public function onUpgrade($cli){ public function onUpgrade($cli){
Console::info("Upgraded API websocket"); Console::info("Upgraded API websocket");
Buffer::$api = $this->api; Buffer::$api = $this->api;
Buffer::$event = $this->event; Buffer::$event = $this->event;
if ($data = file(CONFIG_DIR . "last_error.log")) { if ($data = file(CONFIG_DIR . "log/last_error.log")) {
$last_time = file_get_contents(CONFIG_DIR . "error_flag"); $last_time = file_get_contents(CONFIG_DIR . "log/error_flag");
if (time() - $last_time < 2) { if (time() - $last_time < 2) {
CQUtil::sendDebugMsg("检测到重复引起异常,停止服务器", 0); CQUtil::sendDebugMsg("检测到重复引起异常,停止服务器", 0);
file_put_contents(CONFIG_DIR."last_error.log", ""); file_put_contents(CONFIG_DIR."log/last_error.log", "");
$this->event->shutdown(); $this->event->shutdown();
return; return;
} }
@@ -166,4 +168,121 @@ class Framework
CQUtil::sendDebugMsg("[CQBot] 成功开启!", 0); CQUtil::sendDebugMsg("[CQBot] 成功开启!", 0);
} }
} }
/**
* 回调函数当HTTP插件发来json包后激活此函数
* @param swoole_websocket_server $server
* @param $frame
*/
public function onEventMessage($server, $frame){
$in_count = Buffer::$in_count->get();
Buffer::$in_count->add(1);
$req = json_decode($frame->data, true);
if (Buffer::$data["info_level"] == 2) {
Console::put("************EVENT RECEIVED***********");
Console::put("msg_id = " . $in_count);
Console::put("worker_id = " . $server->worker_id);
}
if (Buffer::$data["info_level"] >= 1) {
$type = $req["post_type"] == "message" ? ($req["message_type"] == "group" ? "GROUP_MSG:" . $req["group_id"] : ($req["message_type"] == "private" ? "PRIVATE_MSG" : "DISCUSS_MSG:" . $req["discuss_id"])) : strtoupper($req["post_type"]);
Console::put(Console::setColor(date("H:i:s"), "green") . Console::setColor(" [$in_count]" . $type, "lightlightblue") . Console::setColor(" " . $req["user_id"], "yellow") . Console::setColor(" > ", "gray") . ($req["post_type"] == "message" ? $req["message"] : Console::setColor($this->executeType($req), "gold")));
}
//传入业务逻辑CQBot
try {
$c = new CQBot($this);
$c->execute($req);
$c->endtime = microtime(true);
$value = $c->endtime - $c->starttime;
Console::debug("Using time: ".$value);
if(Buffer::get("time_send") === true)
CQUtil::sendDebugMsg("Using time: ".$value);
} catch (Exception $e) {
CQUtil::errorlog("处理消息时异常,消息处理中断\n" . $e->getMessage() . "\n" . $e->getTraceAsString());
CQUtil::sendDebugMsg("引起异常的消息:\n" . var_export($req, true));
}
}
/******************* 微信HTTP 响应 ******************
* @param swoole_http_request $request
* @param swoole_http_response $response
*/
public function onRequest($request, $response){
$response->end("Hello world");
}
/******************* API 响应 ******************
* @param swoole_http_client $client
* @param $frame
*/
public function onApiMessage($client, $frame){
}
/***************** 计时器 ******************
* @param $id
*/
public function processTick($id){
$this->tick_time = time();
new TickTask($this, $id);
}
/**
* 此函数用于解析其他非消息类型事件显示在log里
* @param $req
* @return string
*/
public function executeType($req){
switch($req["post_type"]){
case "message":
return "消息";
case "event":
switch($req["event"]){
case "group_upload":
return "群[".$req["group_id"]."] 文件上传:".$req["file"]["name"]."".intval($req["file"]["size"] / 1024)."kb";
case "group_admin":
switch($req["sub_type"]){
case "set":
return "群[".$req["group_id"]."] 设置管理员:".$req["user_id"];
case "unset":
return "群[".$req["group_id"]."] 取消管理员:".$req["user_id"];
default:
return "unknown_group_admin_type";
}
case "group_decrease":
switch($req["sub_type"]){
case "leave":
return "群[".$req["group_id"]."] 成员主动退群:".$req["user_id"];
case "kick":
return "群[".$req["group_id"]."] 管理员[".$req["operator_id"]."]踢出了:".$req["user_id"];
case "kick_me":
return "群[".$req["group_id"]."] 本账号被踢出";
default:
return "unknown_group_decrease_type";
}
case "group_increase":
return "群[".$req["group_id"]."] ".$req["operator_id"]." 同意 ".$req["user_id"]." 加入了群";
default:
return "unknown_event";
}
case "request":
switch($req["request_type"]){
case "friend":
return "加好友请求:".$req["user_id"].",验证信息:".$req["message"];
case "group":
switch($req["sub_type"]){
case "add":
return "加群[".$req["group_id"]."] 请求:".$req["user_id"].",请求信息:".$req["message"];
case "invite":
return "用户".$req["user_id"]."邀请机器人进入群:".$req["group_id"];
default:
return "unknown_group_type";
}
default:
return "unknown_request_type";
}
default:
return "unknown_post_type";
}
}
} }

View File

@@ -6,10 +6,7 @@
* Time: 13:29 * Time: 13:29
*/ */
namespace cqbot; use DataProvider as DP;
use cqbot\utils\Buffer;
use cqbot\utils\DataProvider as DP;
class User class User
{ {

View File

@@ -15,6 +15,7 @@ function loadAllClass($dir){
else { else {
if (count($taskFileName) < 2 || $taskFileName[1] != "php") continue; if (count($taskFileName) < 2 || $taskFileName[1] != "php") continue;
require_once($dir . $m); require_once($dir . $m);
Console::debug("Loading PHP file ".$dir.$m);
} }
} }
} }

View File

@@ -6,36 +6,51 @@
* Time: 14:55 * Time: 14:55
*/ */
namespace cqbot\mods;
use cqbot\CQBot;
use cqbot\utils\CQUtil;
class Admin extends ModBase class Admin extends ModBase
{ {
protected $cmds; protected $cmds;
public function __construct(CQBot $main, $data){ public function __construct(CQBot $main, $data){
//这里放置你的本模块的新加的指令,写入后系统会自动添加到指令列表 parent::__construct($main, $data);
$cmds = [
"add-cmd"
];
parent::__construct($main, $data, $cmds);
} }
public function execute($it){ public function execute($it){
if (!$this->main->isAdmin($this->getUserId())) return false; if (!$this->main->isAdmin($this->getUserId())) return false;
switch ($it[0]) { switch ($it[0]) {
case "add-cmd": case "reload":
if (count($it) < 3) { $this->reply("正在重新启动...");
$this->reply("用法add-cmd 指令 模块名"); if (file_get_contents("/home/ubuntu/CrazyBotFramework/src/Framework.php") != Buffer::get("res_code"))
$this->reply("检测到改变了Framework文件的内容如需完全重载请重启完整进程");
CQUtil::reload();
return true;
case "stop":
$this->reply("正在停止服务器...");
CQUtil::stop();
return true;
case "set-prefix":
if(count($it) < 2) return $this->sendDefaultHelp($it[0],["set-prefix","新前缀/空"],"设置新的前缀或设置不需要前缀(不需要前缀输入\"\"即可)");
$prefix = $it[1];
if(mb_strlen($prefix) > 2){
$this->reply("指令前缀最长为两个字符");
return true; return true;
} }
if(!CQUtil::isModExists($it[2])){ Buffer::set("cmd_prefix", $prefix);
$this->reply("对不起,模块 ".$it[2]." 不存在!"); $this->reply("成功设置新前缀!\n下次输入指令时需前面带 ".$prefix);
return true;
case "op":
$user = $it[1];
Buffer::append("su", $user);
$this->reply("added operator $user");
return true;
case "deop":
$user = $it[1];
if(Buffer::in_array("su", $user)) Buffer::unsetByValue("su", $user);
$this->reply("removed operator $user");
return true;
case "test":
$this->reply("Hello world");
return true; return true;
} }
} return false;
} }
} }

View File

@@ -6,17 +6,12 @@
* Time: 10:39 * Time: 10:39
*/ */
namespace cqbot\mods;
use cqbot\CQBot;
use cqbot\utils\CQUtil;
abstract class ModBase abstract class ModBase
{ {
protected $main; protected $main;
protected $data; protected $data;
protected $cmds; protected $cmds;
public $call_task = false;
public function __construct(CQBot $main, $data, $mod_cmd = false){ public function __construct(CQBot $main, $data, $mod_cmd = false){
$this->main = $main; $this->main = $main;
@@ -41,4 +36,17 @@ abstract class ModBase
public function getMessageType(){ return $this->data["message_type"]; } public function getMessageType(){ return $this->data["message_type"]; }
public function getCommands(){ return $this->cmds; } public function getCommands(){ return $this->cmds; }
public function sendDefaultHelp($cmd, $args = [], $help = ""){
$msg = "".$cmd."使用帮助」";
$msg .= "\n用法:".Buffer::get("cmd_prefix").$cmd;
if($args != []){
$msg .= " ".implode(" ", $args);
}
if($help != ""){
$msg .= "".$help;
}
$this->reply($msg);
return true;
}
} }

View File

@@ -0,0 +1,17 @@
<?php
/**
* Created by PhpStorm.
* User: jerry
* Date: 2018/4/28
* Time: 下午4:00
*/
class TickTask
{
public function __construct(Framework $framework, $timer_id) {
$interval = ($framework->tick_time - $framework->run_time);
if ($interval % 900 == 0) CQUtil::saveAllFiles();//15分钟存一次数据
//这里可以放置你的定时器内执行的功能,自由扩展
}
}

View File

@@ -0,0 +1,12 @@
<?php
/**
* Created by PhpStorm.
* User: jerry
* Date: 2018/4/26
* Time: 下午1:42
*/
class APIHandler
{
}

View File

@@ -6,8 +6,6 @@
* Time: 11:30 * Time: 11:30
*/ */
namespace cqbot\utils;
class Buffer class Buffer
{ {
@@ -28,7 +26,7 @@ class Buffer
/** @var \swoole_atomic $out_count */ /** @var \swoole_atomic $out_count */
static $api_id;//API调用ID static $api_id;//API调用ID
static function get($name){ return self::$data[$name]; } static function get($name){ return self::$data[$name] ?? null; }
static function set($name, $value){ self::$data[$name] = $value; } static function set($name, $value){ self::$data[$name] = $value; }
@@ -46,4 +44,9 @@ class Buffer
static function isset($name){ return isset(self::$data[$name]); } static function isset($name){ return isset(self::$data[$name]); }
static function array_key_exists($name, $key){ return isset(self::$data[$name][$key]); } static function array_key_exists($name, $key){ return isset(self::$data[$name][$key]); }
static function in_array($name, $value){
if(!is_array((self::$data[$name] ?? 1))) return false;
return in_array($value, self::$data[$name]);
}
} }

View File

@@ -6,22 +6,39 @@
* Time: 10:39 * Time: 10:39
*/ */
namespace cqbot\utils; use DataProvider as DP;
use cqbot\Console;
use function cqbot\CQMsg;
use cqbot\Framework;
use cqbot\User;
use cqbot\utils\DataProvider as DP;
class CQUtil class CQUtil
{ {
public static function loadAllFiles() { public static function loadAllFiles() {
Console::debug("loading configs...");
Buffer::set("su", DP::getJsonData("su.json"));//超级管理员用户列表 Buffer::set("su", DP::getJsonData("su.json"));//超级管理员用户列表
Buffer::set("commands", DP::getJsonData("commands.json"));//非实时激活类指令对应模块列表 if (count(Buffer::get("su")) < 1 && Framework::$super_user !== "") {
Console::info("Added super user");
Buffer::set("su", [Framework::$super_user]);
}
Buffer::set("mods", self::getMods());//加载模块列表
Buffer::set("user", []);//清空用户列表
Buffer::set("time_send", false);//发送Timing数据到管理群
Buffer::set("cmd_prefix", DP::getJsonData("config.json")["cmd_prefix"] ?? "");//设置指令的前缀符号
Buffer::set("res_code", file_get_contents(WORKING_DIR."src/cqbot/Framework.php"));
}
//TODO: load all config files to memory public static function saveAllFiles() {
Console::info("Saving files...");
DP::setJsonData("su.json", Buffer::get("su"));//保存超级管理员的QQ列表
//保存cmd_prefix指令前缀
$config = DP::getJsonData("config.json");
$config["cmd_prefix"] = Buffer::get("cmd_prefix");
DP::setJsonData("config.json", $config);
//保存用户数据
foreach (self::getAllUsers() as $k => $v) {
$serial = serialize($v);
file_put_contents(DP::getUserFolder() . $k . ".dat", $serial);
}
Console::info("Saved files");
} }
/** /**
@@ -37,8 +54,7 @@ class CQUtil
file_put_contents(DP::getDataFolder() . "log_error.txt", $msg, FILE_APPEND); file_put_contents(DP::getDataFolder() . "log_error.txt", $msg, FILE_APPEND);
if (self::checkAPIConnection() === -1) { if (self::checkAPIConnection() === -1) {
file_put_contents(DP::getDataFolder() . "last_error.log", $msg, FILE_APPEND); file_put_contents(DP::getDataFolder() . "last_error.log", $msg, FILE_APPEND);
} } else {
else {
if ($send_debug_message) if ($send_debug_message)
self::sendDebugMsg($msg, 0); self::sendDebugMsg($msg, 0);
} }
@@ -104,6 +120,9 @@ class CQUtil
return true; return true;
} }
/**
* 延迟推送在API连接断开后收到的消息函数
*/
static function APIPushDelayMsg() { static function APIPushDelayMsg() {
$delay_push_list = Buffer::get("delay_push"); $delay_push_list = Buffer::get("delay_push");
$cur_time = time(); $cur_time = time();
@@ -197,8 +216,7 @@ class CQUtil
if (is_array($address)) { if (is_array($address)) {
foreach ($address as $item) foreach ($address as $item)
$mail->addAddress($item); $mail->addAddress($item);
} } else {
else {
$mail->addAddress($address); $mail->addAddress($address);
} }
//Content //Content
@@ -230,22 +248,19 @@ class CQUtil
if (intval($time_len / 86400) > 0) { if (intval($time_len / 86400) > 0) {
$run_time[0] = intval($time_len / 86400); $run_time[0] = intval($time_len / 86400);
$time_len = $time_len % 86400; $time_len = $time_len % 86400;
} } else {
else {
$run_time[0] = 0; $run_time[0] = 0;
} }
if (intval($time_len / 3600) > 0) { if (intval($time_len / 3600) > 0) {
$run_time[1] = intval($time_len / 3600); $run_time[1] = intval($time_len / 3600);
$time_len = $time_len % 3600; $time_len = $time_len % 3600;
} } else {
else {
$run_time[1] = 0; $run_time[1] = 0;
} }
if (intval($time_len / 60) > 0) { if (intval($time_len / 60) > 0) {
$run_time[2] = intval($time_len / 60); $run_time[2] = intval($time_len / 60);
$time_len = $time_len % 60; $time_len = $time_len % 60;
} } else {
else {
$run_time[2] = 0; $run_time[2] = 0;
} }
$run_time[3] = $time_len; $run_time[3] = $time_len;
@@ -418,8 +433,7 @@ class CQUtil
if (!is_array($data)) { if (!is_array($data)) {
$api = []; $api = [];
$api["action"] = $data; $api["action"] = $data;
} } else {
else {
$api = $data; $api = $data;
} }
$api["echo"] = $echo; $api["echo"] = $echo;
@@ -471,6 +485,7 @@ class CQUtil
if ($v != "ModBase.php" && (strstr($v, ".php") !== false)) { if ($v != "ModBase.php" && (strstr($v, ".php") !== false)) {
$name = substr($v, 0, -4); $name = substr($v, 0, -4);
$ls[] = $name; $ls[] = $name;
Console::debug("loading mod: " . $name);
} }
} }
return $ls; return $ls;
@@ -485,4 +500,23 @@ class CQUtil
$ls = self::getMods(); $ls = self::getMods();
return in_array($mod_name, $ls); return in_array($mod_name, $ls);
} }
/**
* 重启框架,此服务重启为全自动的
*/
static function reload(){
Console::info("Reloading server");
self::saveAllFiles();
Buffer::$event->reload();
}
/**
* 停止运行框架需要用shell再次开启才能启动
*/
static function stop(){
Console::info("Stopping server...");
self::saveAllFiles();
Buffer::$api->close();
Buffer::$event->shutdown();
}
} }

View File

@@ -6,11 +6,6 @@
* Time: 11:32 * Time: 11:32
*/ */
namespace cqbot;
use cqbot\utils\Buffer;
class Console class Console
{ {
static function setColor($string, $color = ""){ static function setColor($string, $color = ""){

View File

@@ -6,9 +6,6 @@
* Time: 12:54 * Time: 12:54
*/ */
namespace cqbot\utils;
class DataProvider class DataProvider
{ {
/** /**

View File

@@ -6,9 +6,6 @@
* Time: 11:31 * Time: 11:31
*/ */
namespace cqbot\utils;
class ErrorStatus class ErrorStatus
{ {
static $error = [ static $error = [

View File

@@ -6,11 +6,6 @@
* Time: 11:13 * Time: 11:13
*/ */
namespace {
}
namespace cqbot {
date_default_timezone_set("Asia/Shanghai"); date_default_timezone_set("Asia/Shanghai");
define("WORKING_DIR", __DIR__ . "/"); define("WORKING_DIR", __DIR__ . "/");
define("CONFIG_DIR", WORKING_DIR . "config/"); define("CONFIG_DIR", WORKING_DIR . "config/");
@@ -19,7 +14,6 @@ namespace cqbot {
@mkdir(CONFIG_DIR, 0777, true); @mkdir(CONFIG_DIR, 0777, true);
@mkdir(USER_DIR, 0777, true); @mkdir(USER_DIR, 0777, true);
register_shutdown_function('handleFatal'); register_shutdown_function('handleFatal');
function handleFatal() { function handleFatal() {
$error = error_get_last(); $error = error_get_last();
if (isset($error['type'])) { if (isset($error['type'])) {
@@ -65,36 +59,74 @@ namespace cqbot {
$reply["echo"] = $reply; $reply["echo"] = $reply;
$reply["echo"]["time"] = time(); $reply["echo"]["time"] = time();
$reply = json_encode($reply); $reply = json_encode($reply);
} } else if ($type === "private") {
else if ($type === "private") {
$reply = ["action" => "send_private_msg", "params" => ["user_id" => $id, "message" => $msg]]; $reply = ["action" => "send_private_msg", "params" => ["user_id" => $id, "message" => $msg]];
$reply["echo"] = $reply; $reply["echo"] = $reply;
$reply["echo"]["time"] = time(); $reply["echo"]["time"] = time();
$reply = json_encode($reply); $reply = json_encode($reply);
} } else if ($type === "discuss") {
else if ($type === "discuss") {
$reply = ["action" => "send_discuss_msg", "params" => ["discuss_id" => $id, "message" => $msg]]; $reply = ["action" => "send_discuss_msg", "params" => ["discuss_id" => $id, "message" => $msg]];
$reply["echo"] = $reply; $reply["echo"] = $reply;
$reply["echo"]["time"] = time(); $reply["echo"]["time"] = time();
$reply = json_encode($reply); $reply = json_encode($reply);
} } else {
else {
$reply = false; $reply = false;
} }
return $reply; return $reply;
} }
$host = "0.0.0.0";
$api_port = 10000;
$event_port = 20000;
$admin_group = "";
$info_level = 1;
$super_user = "";
//check argv option.
if(count($argv) >= 3){
echo "detected options.\n";
//var_dump($argv);
array_shift($argv);
for($i = 0; $i < count($argv); $i++){
if(substr($argv[$i],0,2) == '--'){
$option = substr($argv[$i],2);
if(isset($argv[$i+1])){
switch($option){
case "host":
$host = $argv[$i+1];
break;
case "api-port":
$api_port = $argv[$i+1];
break;
case "event-port":
$event_port = $argv[$i+1];
break;
case "admin-group":
$admin_group = $argv[$i+1];
break;
case "info-level":
$info_level = $argv[$i+1];
break;
case "super-user":
$super_user = $argv[$i+1];
break;
default:
break;
}
}
}
}
}
//loading projects //loading projects
require(WORKING_DIR . "src/cqbot/Framework.php"); require(WORKING_DIR . "src/cqbot/Framework.php");
require(WORKING_DIR . "src/cqbot/utils/Buffer.php"); require(WORKING_DIR . "src/cqbot/utils/Buffer.php");
require(WORKING_DIR . "src/cqbot/utils/ErrorStatus.php"); require(WORKING_DIR . "src/cqbot/utils/ErrorStatus.php");
require(WORKING_DIR . "src/cqbot/utils/Console.php"); require(WORKING_DIR . "src/cqbot/utils/Console.php");
$cqbot = new Framework(); $cqbot = new Framework();
$cqbot->setHost("127.0.0.1"); $cqbot->setHost($host);
$cqbot->setApiPort("10000"); $cqbot->setApiPort($api_port);
$cqbot->setEventPort("20000"); $cqbot->setEventPort($event_port);
$cqbot->setAdminGroup(""); $cqbot->setAdminGroup($admin_group);
$cqbot->setInfoLevel(1); $cqbot->setInfoLevel($info_level);
$cqbot->init(); $cqbot->init($super_user);
$cqbot->eventServerStart(); $cqbot->eventServerStart();
}