tgbot加入扩展机制

pull/393/head
midoks 2 years ago
parent da90386816
commit c9927c3fb9
  1. 2
      plugins/tgbot/index.html
  2. 85
      plugins/tgbot/index.py
  3. 70
      plugins/tgbot/js/tgbot.js
  4. 14
      plugins/tgbot/startup/extend/receive_faq.py
  5. 69
      plugins/tgbot/startup/tgbot.py

@ -19,7 +19,7 @@
} }
</style> </style>
<script type="text/javascript"> <script type="text/javascript">
resetPluginWinHeight(300); resetPluginWinHeight(350);
$.getScript( "/plugins/file?name=tgbot&f=js/tgbot.js", function(){ $.getScript( "/plugins/file?name=tgbot&f=js/tgbot.js", function(){
pluginService('tgbot'); pluginService('tgbot');
}); });

@ -58,10 +58,7 @@ def getExtCfg():
def writeExtCfg(data): def writeExtCfg(data):
cfg_path = getServerDir() + "/extend.cfg" cfg_path = getServerDir() + "/extend.cfg"
if not os.path.exists(cfg_path): return mw.writeFile(cfg_path, json.dumps(data))
mw.writeFile(cfg_path, '{}')
t = mw.readFile(cfg_path)
return json.loads(t)
def getInitDTpl(): def getInitDTpl():
@ -147,9 +144,9 @@ def tbOp(method):
return data[1] return data[1]
data = mw.execShell(file + ' ' + method) data = mw.execShell(file + ' ' + method)
print(data) # print(data)
# if data[1] == '': if data[1] == '':
# return 'ok' return 'ok'
return 'ok' return 'ok'
@ -243,7 +240,21 @@ def uninstallPreInspection():
return "请手动删除<br/> rm -rf {}".format(getServerDir()) return "请手动删除<br/> rm -rf {}".format(getServerDir())
def getExtCfgByName(name):
elist = getExtCfg()
for x in elist:
if x['name'] == name:
return x
return None
def botExtList(): def botExtList():
args = getArgs()
data_args = checkArgs(args, ['p'])
if not data_args[0]:
return data_args[1]
ext_path = getServerDir() + '/extend' ext_path = getServerDir() + '/extend'
if not os.path.exists(ext_path): if not os.path.exists(ext_path):
return mw.returnJson(False, 'ok', []) return mw.returnJson(False, 'ok', [])
@ -254,9 +265,63 @@ def botExtList():
if e.endswith('py'): if e.endswith('py'):
elist.append(e) elist.append(e)
# extList = getExtCfg() page = int(args['p'])
page_size = 5
make_ext_list = []
for ex in elist:
tmp = {}
tmp['name'] = ex
edata = getExtCfgByName(ex)
if edata:
tmp['status'] = edata['status']
else:
tmp['status'] = 'stop'
tmp['tag'] = ex.split('_')[0]
make_ext_list.append(tmp)
writeExtCfg(make_ext_list)
dlist_sum = len(make_ext_list)
page_start = int((page - 1) * page_size)
page_end = page_start + page_size
if page_end >= dlist_sum:
ret_data = make_ext_list[page_start:]
else:
ret_data = make_ext_list[page_start:page_end]
data = {}
data['data'] = ret_data
data['args'] = args
data['list'] = mw.getPage(
{'count': dlist_sum, 'p': page, 'row': page_size, 'tojs': 'botExtListP'})
return mw.returnJson(True, 'ok', data)
def setExtStatus():
args = getArgs()
data_args = checkArgs(args, ['name', 'status'])
if not data_args[0]:
return data_args[1]
elist = getExtCfg()
name = args['name']
status = args['status']
for x in range(len(elist)):
if elist[x]['name'] == name:
elist[x]['status'] = status
break
writeExtCfg(elist)
action = '开启'
if status == 'stop':
action = '关闭'
print(elist) return mw.returnJson(True, action + '[' + name + ']扩展成功')
def runLog(): def runLog():
@ -292,6 +357,8 @@ if __name__ == "__main__":
print(setBotConf()) print(setBotConf())
elif func == 'bot_ext_list': elif func == 'bot_ext_list':
print(botExtList()) print(botExtList())
elif func == 'set_ext_status':
print(setExtStatus())
elif func == 'run_log': elif func == 'run_log':
print(runLog()) print(runLog())

@ -86,7 +86,6 @@ function botExtList(){
<th width="20">脚本</th>\ <th width="20">脚本</th>\
<th width="120">类型</th>\ <th width="120">类型</th>\
<th width="10">状态</th>\ <th width="10">状态</th>\
<th style="text-align: right;" width="50">操作</th>\
</tr>\ </tr>\
</thead>\ </thead>\
<tbody id="ext_list"></tbody>\ <tbody id="ext_list"></tbody>\
@ -96,55 +95,54 @@ function botExtList(){
</div>\ </div>\
</div>'; </div>';
$('.soft-man-con').html(body); $('.soft-man-con').html(body);
botExtListP(1);
}
function setBotExtStatus(name,status){
botExtListP(1) appPost('set_ext_status',{'name':name,'status':status}, function(rdata){
var rdata = $.parseJSON(rdata.data);
layer.msg(rdata['msg'],);
showMsg(rdata['msg'], function(){
botExtListP(1);
},{icon:rdata['status']?1:2,shade: [0.3, '#000']},2000);
});
} }
function botExtListP(p=1){ function botExtListP(p=1){
appPost('bot_ext_list',{'page':p}, function(rdata){ appPost('bot_ext_list',{'p':p}, function(rdata){
// console.log(rdata);
var rdata = $.parseJSON(rdata.data); var rdata = $.parseJSON(rdata.data);
// console.log(rdata);
var tBody = ''; var tBody = '';
if (rdata.data.length == 0 ){ if (!rdata.status && rdata.data.length == 0 ){
var tBody = '<tr><td colspan="4"><div style="text-align:center;">无数据</div></td></tr>'; var tBody = '<tr><td colspan="4"><div style="text-align:center;">无数据</div></td></tr>';
} } else{
var ldata = rdata.data.data;
var ldata = rdata.data;
for (var i = 0; i < ldata.length; i++) { for (var i = 0; i < ldata.length; i++) {
tBody += '<tr data-id="'+ldata[i]['name']+'">' tBody += '<tr data-name="'+ldata[i]['name']+'">'
tBody += '<td>'+ldata[i]['id']+'</td>';
tBody += '<td>'+ldata[i]['name']+'</td>'; tBody += '<td>'+ldata[i]['name']+'</td>';
tBody += '<td>'+ldata[i]['tag']+'</td>';
if (ldata[i]['status'] == 'start'){ if (ldata[i]['status'] == 'start'){
tBody += '<td><span style="color:#20a53a;cursor: pointer;" class="strategy_status glyphicon glyphicon-play"></span></td>'; tBody += '<td><span style="color:#20a53a;cursor: pointer;" class="ext_status glyphicon glyphicon-play"></span></td>';
} else{ } else{
tBody += '<td><span style="color:red;cursor: pointer;" class="strategy_status glyphicon glyphicon-pause"></span></td>'; tBody += '<td><span style="color:red;cursor: pointer;" class="ext_status glyphicon glyphicon-pause"></span></td>';
} }
tBody += "<td style='text-align: right;'><a class='btlink restart'>重启</a> | <a class='btlink edit'>编辑</a></td>";
tBody +='<tr>'; tBody +='<tr>';
}; }
}
$('#ext_list').html(tBody); $('#ext_list').html(tBody);
// $('#strategy_list_page').html(rdata.data.list); $('#ext_list_page').html(rdata.data.list);
$('#ext_list .ext_status').click(function(){
// $('#strategy_list .strategy_status').click(function(){ var name = $(this).parent().parent().data('name');
// var id = $(this).parent().parent().data('id'); var status = 'stop';
// var status = 'stop'; if ($(this).hasClass('glyphicon-pause')){
// if ($(this).hasClass('glyphicon-pause')){ status = 'start';
// status = 'start'; }
// } setBotExtStatus(name,status);
// setStrategyStatus(id,status); });
// });
// $('#strategy_list .restart').click(function(){
// var id = $(this).parent().parent().data('id');
// setStrategyRestart(id);
// });
// $('#strategy_list .edit').click(function(){
// var id = $(this).parent().parent().data('id');
// setStrategyEdit(id);
// });
}); });
} }

@ -0,0 +1,14 @@
import sys
import io
import os
import time
import re
import json
import base64
import threading
import telebot
def run(bot, message):
return bot

@ -28,6 +28,9 @@ def getServerDir():
return mw.getServerDir() + '/' + getPluginName() return mw.getServerDir() + '/' + getPluginName()
sys.path.append(getServerDir() + "/extend")
def getConfigData(): def getConfigData():
cfg_path = getServerDir() + "/data.cfg" cfg_path = getServerDir() + "/data.cfg"
if not os.path.exists(cfg_path): if not os.path.exists(cfg_path):
@ -42,6 +45,24 @@ def writeConf(data):
return True return True
def getExtCfg():
cfg_path = getServerDir() + "/extend.cfg"
if not os.path.exists(cfg_path):
mw.writeFile(cfg_path, '{}')
t = mw.readFile(cfg_path)
return json.loads(t)
def getStartExtCfgByTag(tag='push'):
# 获取开启的扩展
elist = getExtCfg()
rlist = []
for x in elist:
if x['tag'] == tag and x['status'] == 'start':
rlist.append(x)
return rlist
def writeLog(log_str): def writeLog(log_str):
if __name__ == "__main__": if __name__ == "__main__":
print(log_str) print(log_str)
@ -60,6 +81,7 @@ while True:
writeLog('等待输入配置,填写app_token') writeLog('等待输入配置,填写app_token')
time.sleep(3) time.sleep(3)
bot = telebot.TeleBot(cfg['bot']['app_token']) bot = telebot.TeleBot(cfg['bot']['app_token'])
@ -76,9 +98,6 @@ bot.set_my_commands(
telebot.types.BotCommand("start", "查看帮助信息"), telebot.types.BotCommand("start", "查看帮助信息"),
telebot.types.BotCommand("mw_chat_id", "查看群组ChatID") telebot.types.BotCommand("mw_chat_id", "查看群组ChatID")
], ],
# scope=telebot.types.BotCommandScopeChat(12345678) # use for personal command for users
# scope=telebot.types.BotCommandScopeAllPrivateChats() # use for all
# private chats
) )
@ -87,13 +106,8 @@ def hanle_start_help(message):
bot.reply_to(message, "hello world") bot.reply_to(message, "hello world")
@bot.message_handler(commands=['mw'])
def hanle_start_mw(message):
bot.reply_to(message, "我就是最靓的仔!")
@bot.message_handler(commands=['mw_echo']) @bot.message_handler(commands=['mw_echo'])
def hanle_start_help(message): def hanle_mw_echo(message):
bot.reply_to(message, message.text) bot.reply_to(message, message.text)
@ -103,9 +117,30 @@ def hanle_get_chat_id(message):
@bot.message_handler(func=lambda message: True) @bot.message_handler(func=lambda message: True)
def echo_message(message): def all_message(message):
print(message) rlist = getStartExtCfgByTag('receive')
# bot.reply_to(message, "拦截所有消息:" + message.text) for r in rlist:
try:
script = r['name'].split('.')[0]
__import__(script).run(bot, message)
except Exception as e:
pass
def runBotPushTask():
plist = getStartExtCfgByTag('push')
for p in plist:
try:
script = p['name'].split('.')[0]
__import__(script).run(bot)
except Exception as e:
pass
def botPush():
while True:
runBotPushTask()
time.sleep(3)
def setDaemon(t): def setDaemon(t):
@ -113,19 +148,13 @@ def setDaemon(t):
t.daemon = True t.daemon = True
else: else:
t.setDaemon(True) t.setDaemon(True)
return t
def botPush():
while True:
print('a')
time.sleep(3)
if __name__ == "__main__": if __name__ == "__main__":
# 机器人推送任务 # 机器人推送任务
botPushTask = threading.Thread(target=botPush) botPushTask = threading.Thread(target=botPush)
botPushTask = setDaemon(botPushTask) # print(botPushTask)
# botPushTask = setDaemon(botPushTask)
botPushTask.start() botPushTask.start()
writeLog('启动成功') writeLog('启动成功')

Loading…
Cancel
Save