pull/405/head
midoks 2 years ago
parent 5ff0a0bfbc
commit 0b7b48ab23
  1. BIN
      mdioks.session
  2. BIN
      mdioks.session-journal
  3. 2
      plugins/tgbot/info.json
  4. 1
      plugins/tgbot/startup/tgbot.py
  5. BIN
      plugins/tgclient/ico.png
  6. 26
      plugins/tgclient/index.html
  7. 367
      plugins/tgclient/index.py
  8. 20
      plugins/tgclient/info.json
  9. 14
      plugins/tgclient/init.d/tgclient.service.tpl
  10. 86
      plugins/tgclient/init.d/tgclient.tpl
  11. 58
      plugins/tgclient/install.sh
  12. 154
      plugins/tgclient/js/tgclient.js
  13. 106
      plugins/tgclient/startup/extend/push_notice_msg.py
  14. 1
      plugins/tgclient/startup/extend/readme.md
  15. 220
      plugins/tgclient/startup/extend/receive_faq.py
  16. 87
      plugins/tgclient/startup/tgclient.py

Binary file not shown.

Binary file not shown.

@ -11,7 +11,7 @@
"install_pre_inspection":true,
"uninstall_pre_inspection":true,
"display": 1,
"author": "midokos",
"author": "midoks",
"date": "2023-03-06",
"home": "https://core.telegram.org/bots/api",
"depend_doc1":"https://github.com/eternnoir/pyTelegramBotAPI",

@ -1,4 +1,3 @@
# coding:utf-8
import sys

Binary file not shown.

After

Width:  |  Height:  |  Size: 974 B

@ -0,0 +1,26 @@
<div class="bt-form">
<div class='plugin_version'></div>
<div class="bt-w-main">
<div class="bt-w-menu">
<p class="bgw" onclick="pluginService('tgclient');">服务</p>
<p onclick="pluginInitD('tgclient');">自启动</p>
<p onclick="clientConf();">配置</p>
<p onclick="botExtList();">扩展列表</p>
<p onclick="pluginLogs('tgclient','','run_log');">日志</p>
</div>
<div class="bt-w-con pd15">
<div class="soft-man-con"></div>
</div>
</div>
</div>
<style>
.conf_p span{
width: 70px;
}
</style>
<script type="text/javascript">
resetPluginWinHeight(350);
$.getScript( "/plugins/file?name=tgclient&f=js/tgclient.js", function(){
pluginService('tgclient');
});
</script>

@ -0,0 +1,367 @@
# coding:utf-8
import sys
import io
import os
import time
import re
import json
import base64
sys.path.append(os.getcwd() + "/class/core")
import mw
app_debug = False
if mw.isAppleSystem():
app_debug = True
def getPluginName():
return 'tgclient'
def getPluginDir():
return mw.getPluginDir() + '/' + getPluginName()
def getServerDir():
return mw.getServerDir() + '/' + getPluginName()
def getInitDFile():
if app_debug:
return '/tmp/' + getPluginName()
return '/etc/init.d/' + getPluginName()
def getConfigData():
cfg_path = getServerDir() + "/data.cfg"
if not os.path.exists(cfg_path):
mw.writeFile(cfg_path, '{}')
t = mw.readFile(cfg_path)
return json.loads(t)
def writeConf(data):
cfg_path = getServerDir() + "/data.cfg"
mw.writeFile(cfg_path, json.dumps(data))
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 writeExtCfg(data):
cfg_path = getServerDir() + "/extend.cfg"
return mw.writeFile(cfg_path, json.dumps(data))
def getInitDTpl():
path = getPluginDir() + "/init.d/" + getPluginName() + ".tpl"
return path
def getArgs():
args = sys.argv[2:]
tmp = {}
args_len = len(args)
if args_len == 1:
t = args[0].strip('{').strip('}')
if t.strip() == '':
tmp = []
else:
t = t.split(':')
tmp[t[0]] = t[1]
tmp[t[0]] = t[1]
elif args_len > 1:
for i in range(len(args)):
t = args[i].split(':')
tmp[t[0]] = t[1]
return tmp
def checkArgs(data, ck=[]):
for i in range(len(ck)):
if not ck[i] in data:
return (False, mw.returnJson(False, '参数:(' + ck[i] + ')没有!'))
return (True, mw.returnJson(True, 'ok'))
def status():
data = mw.execShell(
"ps -ef|grep tgclient |grep -v grep | grep -v mdserver-web | awk '{print $2}'")
if data[0] == '':
return 'stop'
return 'start'
def initDreplace():
file_tpl = getInitDTpl()
service_path = mw.getServerDir()
app_path = service_path + '/' + getPluginName()
initD_path = getServerDir() + '/init.d'
if not os.path.exists(initD_path):
os.mkdir(initD_path)
file_bin = initD_path + '/' + getPluginName()
# initd replace
# if not os.path.exists(file_bin):
content = mw.readFile(file_tpl)
content = content.replace('{$SERVER_PATH}', service_path + '/mdserver-web')
content = content.replace('{$APP_PATH}', app_path)
mw.writeFile(file_bin, content)
mw.execShell('chmod +x ' + file_bin)
# systemd
systemDir = mw.systemdCfgDir()
systemService = systemDir + '/tgclient.service'
systemServiceTpl = getPluginDir() + '/init.d/tgclient.service.tpl'
if os.path.exists(systemDir) and not os.path.exists(systemService):
service_path = mw.getServerDir()
se_content = mw.readFile(systemServiceTpl)
se_content = se_content.replace('{$APP_PATH}', app_path)
mw.writeFile(systemService, se_content)
mw.execShell('systemctl daemon-reload')
return file_bin
def tbOp(method):
file = initDreplace()
if not mw.isAppleSystem():
data = mw.execShell('systemctl ' + method + ' ' + getPluginName())
if data[1] == '':
return 'ok'
return data[1]
data = mw.execShell(file + ' ' + method)
# print(data)
if data[1] == '':
return 'ok'
return 'ok'
def start():
return tbOp('start')
def stop():
return tbOp('stop')
def restart():
status = tbOp('restart')
return status
def reload():
tgbot_tpl = getPluginDir() + '/startup/tgclient.py'
tgbot_dst = getServerDir() + '/tgclient.py'
content = mw.readFile(tgbot_tpl)
mw.writeFile(tgbot_dst, content)
ext_src = getPluginDir() + '/startup/extend'
ext_dst = getServerDir()
mw.execShell('cp -rf ' + ext_src + ' ' + ext_dst)
return tbOp('restart')
def initdStatus():
if mw.isAppleSystem():
return "Apple Computer does not support"
shell_cmd = 'systemctl status ' + \
getPluginName() + ' | grep loaded | grep "enabled;"'
data = mw.execShell(shell_cmd)
if data[0] == '':
return 'fail'
return 'ok'
def initdInstall():
if mw.isAppleSystem():
return "Apple Computer does not support"
mw.execShell('systemctl enable ' + getPluginName())
return 'ok'
def initdUinstall():
if mw.isAppleSystem():
return "Apple Computer does not support"
mw.execShell('systemctl disable ' + getPluginName())
return 'ok'
def getClientConf():
data = getConfigData()
if 'bot' in data:
return mw.returnJson(True, 'ok', data['bot'])
return mw.returnJson(False, 'ok', {})
def setClientConf():
args = getArgs()
data_args = checkArgs(args, ['api_id', 'api_hash'])
if not data_args[0]:
return data_args[1]
data = getConfigData()
args['api_id'] = base64.b64decode(args['api_id']).decode('ascii')
args['api_hash'] = base64.b64decode(args['api_hash']).decode('ascii')
data['bot'] = args
writeConf(data)
return mw.returnJson(True, '保存成功!', [])
def installPreInspection():
i = sys.version_info
if i[0] < 3 or i[1] < 7:
return "telebot在python小于3.7无法正常使用"
return 'ok'
def uninstallPreInspection():
stop()
return "请手动删除<br/> rm -rf {}".format(getServerDir())
def getExtCfgByName(name):
elist = getExtCfg()
for x in elist:
if x['name'] == name:
return x
return None
def clientExtList():
args = getArgs()
data_args = checkArgs(args, ['p'])
if not data_args[0]:
return data_args[1]
ext_path = getServerDir() + '/extend'
if not os.path.exists(ext_path):
return mw.returnJson(False, 'ok', [])
elist_source = os.listdir(ext_path)
elist = []
for e in elist_source:
if e.endswith('py'):
elist.append(e)
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 = '关闭'
return mw.returnJson(True, action + '[' + name + ']扩展成功')
def runLog():
p = getServerDir() + '/task.log'
return p
if __name__ == "__main__":
func = sys.argv[1]
if func == 'status':
print(status())
elif func == 'start':
print(start())
elif func == 'stop':
print(stop())
elif func == 'restart':
print(restart())
elif func == 'reload':
print(reload())
elif func == 'initd_status':
print(initdStatus())
elif func == 'initd_install':
print(initdInstall())
elif func == 'initd_uninstall':
print(initdUinstall())
elif func == 'install_pre_inspection':
print(installPreInspection())
elif func == 'uninstall_pre_inspection':
print(uninstallPreInspection())
elif func == 'get_client_conf':
print(getClientConf())
elif func == 'set_client_conf':
print(setClientConf())
elif func == 'client_ext_list':
print(clientExtList())
elif func == 'set_ext_status':
print(setExtStatus())
elif func == 'run_log':
print(runLog())
else:
print('error')

@ -0,0 +1,20 @@
{
"sort": 7,
"ps": "简单Telegram客服端管理",
"name": "tgclient",
"title": "tgclient",
"shell": "install.sh",
"versions":["1.0"],
"tip": "soft",
"checks": "server/tgclient",
"path": "server/tgclient",
"install_pre_inspection":true,
"uninstall_pre_inspection":true,
"display": 1,
"author": "midoks",
"date": "2023-03-06",
"home": "https://my.telegram.org/apps",
"depend_doc1":"https://docs.telethon.dev/en/stable/basic/installation.html",
"type": 0,
"pid": "5"
}

@ -0,0 +1,14 @@
[Unit]
Description=Tgbot Service
After=network.target
[Service]
Type=forking
ExecStart={$APP_PATH}/init.d/tgclient start
ExecStop={$APP_PATH}/init.d/tgclient stop
ExecReload={$APP_PATH}/init.d/tgclient reload
KillMode=process
Restart=on-failure
[Install]
WantedBy=multi-user.target

@ -0,0 +1,86 @@
#!/bin/sh
# chkconfig: 2345 55 25
# description: Tgbot Service
### BEGIN INIT INFO
# Provides: Tgbot
# Required-Start: $all
# Required-Stop: $all
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: starts Tgbot
# Description: starts the MDW-Web
### END INIT INFO
# Simple Tgbot init.d script conceived to work on Linux systems
# as it does use of the /proc filesystem.
PATH=/usr/local/bin:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export LANG=en_US.UTF-8
mw_path={$SERVER_PATH}
PATH=$PATH:$mw_path/bin
if [ -f $mw_path/bin/activate ];then
source $mw_path/bin/activate
fi
tg_start(){
isStart=`ps -ef|grep 'tgclient.py' |grep -v grep | awk '{print $2}'`
if [ "$isStart" == '' ];then
echo -e "starting tgclient... \c"
cd $mw_path
echo "python3 {$APP_PATH}/tgclient.py"
python3 {$APP_PATH}/tgclient.py >> {$APP_PATH}/task.log &
isStart=""
while [[ "$isStart" == "" ]];
do
echo -e ".\c"
sleep 0.5
isStart=`ps -ef|grep 'tgclient.py' |grep -v grep | awk '{print $2}'`
let n+=1
if [ $n -gt 20 ];then
break;
fi
done
if [ "$isStart" == '' ];then
echo -e "\033[31mfailed\033[0m"
echo -e "\033[31mError: tgclient service startup failed.\033[0m"
return;
fi
echo -e "\033[32mdone\033[0m"
else
echo "starting tgclient...(pid $(echo $isStart)) already running"
fi
}
tg_stop(){
echo -e "stopping tgclient ... \c";
arr=`ps aux|grep 'tgclient.py'|grep -v grep|awk '{print $2}'`
for p in ${arr[@]}
do
kill -9 $p > /dev/null 2>&1
done
echo -e "\033[32mdone\033[0m"
}
case "$1" in
start)
tg_start
;;
stop)
tg_stop
;;
restart|reload)
tg_stop
sleep 0.3
tg_start
;;
*)
echo "Please use start or stop as first argument"
;;
esac

@ -0,0 +1,58 @@
#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
curPath=`pwd`
rootPath=$(dirname "$curPath")
rootPath=$(dirname "$rootPath")
serverPath=$(dirname "$rootPath")
install_tmp=${rootPath}/tmp/mw_install.pl
VERSION=$2
# pip3 install ccxt
if [ -f ${rootPath}/bin/activate ];then
source ${rootPath}/bin/activate
fi
pip3 install telethon
Install_App()
{
echo '正在安装脚本文件...' > $install_tmp
mkdir -p $serverPath/source
mkdir -p $serverPath/tgclient
echo "${VERSION}" > $serverPath/tgclient/version.pl
cp -rf ${rootPath}/plugins/tgclient/startup/* $serverPath/tgclient
cd ${rootPath} && python3 ${rootPath}/plugins/tgclient/index.py start
cd ${rootPath} && python3 ${rootPath}/plugins/tgclient/index.py initd_install
echo '安装完成' > $install_tmp
}
Uninstall_App()
{
if [ -f /usr/lib/systemd/system/tgclient.service ];then
systemctl stop tgclient
systemctl disable tgclient
rm -rf /usr/lib/systemd/system/tgclient.service
systemctl daemon-reload
fi
if [ -f $serverPath/tgclient/initd/tgclient ];then
$serverPath/tgclient/initd/tgclient stop
fi
rm -rf $serverPath/tgclient
echo "Uninstall_redis" > $install_tmp
}
action=$1
if [ "${1}" == 'install' ];then
Install_App
else
Uninstall_App
fi

@ -0,0 +1,154 @@
function appPost(method, args,callback){
var loadT = layer.msg('正在获取...', { icon: 16, time: 0, shade: 0.3 });
var req_data = {};
req_data['name'] = 'tgclient';
req_data['func'] = method;
if (typeof(args) == 'string'){
req_data['args'] = JSON.stringify(toArrayObject(args));
} else {
req_data['args'] = JSON.stringify(args);
}
$.post('/plugins/run', req_data, function(data) {
layer.close(loadT);
if(typeof(callback) == 'function'){
callback(data);
}
},'json');
}
function appPostCallbak(method, args,callback){
var loadT = layer.msg('正在获取...', { icon: 16, time: 0, shade: 0.3 });
var req_data = {};
req_data['name'] = 'tgclient';
req_data['func'] = method;
if (typeof(args) == 'string'){
req_data['args'] = JSON.stringify(toArrayObject(args));
} else {
req_data['args'] = JSON.stringify(args);
}
$.post('/plugins/callback', req_data, function(data) {
layer.close(loadT);
if (!data.status){
layer.msg(data.msg,{icon:0,time:2000,shade: [0.3, '#000']});
return;
}
if(typeof(callback) == 'function'){
callback(data);
}
},'json');
}
function clientConf(){
appPost('get_client_conf','',function(data){
var rdata = $.parseJSON(data.data);
var api_id = 'api_id';
var api_hash = 'api_hash';
if(rdata['status']){
db_data = rdata['data'];
// api_id, api_hash
api_id = db_data['api_id'];
api_hash = db_data['api_hash'];
}
var mlist = '';
mlist += '<p><span>api_id</span><input style="width: 250px;" class="bt-input-text mr5" name="api_id" value="'+api_id+'" type="text"><font>必填写</font></p>';
mlist += '<p><span>api_hash</span><input style="width: 250px;" class="bt-input-text mr5" name="api_hash" value="'+api_hash+'" type="text"><font>必填写</font></p>';
var option = '<style>.conf_p p{margin-bottom: 2px}</style>\
<div class="conf_p" style="margin-bottom:0">\
' + mlist + '\
<div style="margin-top:10px; padding-right:15px" class="text-right">\
<button class="btn btn-success btn-sm" onclick="submitBotConf()">保存</button>\
</div>\
</div>';
$(".soft-man-con").html(option);
});
}
function submitBotConf(){
var pull_data = {};
pull_data['api_id'] = base64_encode($('input[name="api_id"]').val());
pull_data['api_hash'] = base64_encode($('input[name="api_hash"]').val());
appPost('set_client_conf',pull_data,function(data){
var rdata = $.parseJSON(data.data);
layer.msg(rdata['msg'],{icon:rdata['status']?1:2,time:2000,shade: [0.3, '#000']});
});
}
function botExtList(){
var body = '<div class="divtable mtb10">\
<table class="table table-hover" width="100%" cellspacing="0" cellpadding="0" border="0">\
<thead>\
<tr>\
<th width="20">脚本</th>\
<th width="120">类型</th>\
<th width="10">状态</th>\
</tr>\
</thead>\
<tbody id="ext_list"></tbody>\
</table>\
<div class="dataTables_paginate paging_bootstrap pagination">\
<ul id="ext_list_page" class="page"></ul>\
</div>\
</div>';
$('.soft-man-con').html(body);
botExtListP(1);
}
function setBotExtStatus(name,status){
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){
appPost('client_ext_list',{'p':p}, function(rdata){
// console.log(rdata);
var rdata = $.parseJSON(rdata.data);
// console.log(rdata);
var tBody = '';
if (!rdata.status && rdata.data.length == 0 ){
var tBody = '<tr><td colspan="4"><div style="text-align:center;">无数据</div></td></tr>';
} else{
var ldata = rdata.data.data;
for (var i = 0; i < ldata.length; i++) {
tBody += '<tr data-name="'+ldata[i]['name']+'">'
tBody += '<td>'+ldata[i]['name']+'</td>';
tBody += '<td>'+ldata[i]['tag']+'</td>';
if (ldata[i]['status'] == 'start'){
tBody += '<td><span style="color:#20a53a;cursor: pointer;" class="ext_status glyphicon glyphicon-play"></span></td>';
} else{
tBody += '<td><span style="color:red;cursor: pointer;" class="ext_status glyphicon glyphicon-pause"></span></td>';
}
tBody +='<tr>';
}
}
$('#ext_list').html(tBody);
$('#ext_list_page').html(rdata.data.list);
$('#ext_list .ext_status').click(function(){
var name = $(this).parent().parent().data('name');
var status = 'stop';
if ($(this).hasClass('glyphicon-pause')){
status = 'start';
}
setBotExtStatus(name,status);
});
});
}

@ -0,0 +1,106 @@
# coding:utf-8
import sys
import io
import os
import time
import re
import json
import base64
import threading
sys.path.append(os.getcwd() + "/class/core")
import mw
import telebot
from telebot import types
from telebot.util import quick_markup
# 轮播实例
chat_id = -1001578009023
# chat_id = 5568699210
def send_msg(bot, tag='ad', trigger_time=300):
# 信号只在一个周期内执行一次|start
lock_file = mw.getServerDir() + '/tgbot/lock.json'
if not os.path.exists(lock_file):
mw.writeFile(lock_file, '{}')
lock_data = json.loads(mw.readFile(lock_file))
if tag in lock_data:
diff_time = time.time() - lock_data[tag]['do_time']
if diff_time >= trigger_time:
lock_data[tag]['do_time'] = time.time()
else:
return False, 0, 0
else:
lock_data[tag] = {'do_time': time.time()}
mw.writeFile(lock_file, json.dumps(lock_data))
# 信号只在一个周期内执行一次|end
# https://t.me/gjgzs2022 | 19/m
# ♻CMS导航网♻/💰流量变现💰 | 28/m
# CK资源采集 |29/m
# 高防服务器CDN请联系玥玥 |3/m
keyboard = [
[
types.InlineKeyboardButton(
text="海外服务器高防CDN请联系玥玥", url='https://t.me/CDNYUEYUE')
],
[
types.InlineKeyboardButton(
text="CK资源采集", url='https://ckzy1.com/')
],
[
types.InlineKeyboardButton(
text="CMS导航网♻", url='https://t.me/maccms_jccms')
],
[
types.InlineKeyboardButton(
text="💰流量变现💰", url='https://t.me/taohaozhan')
],
[
types.InlineKeyboardButton(
text="🙎代实名🙍过人脸🅾国际阿里云腾讯云(赞助商)", url='https://t.me/gjgzs2022')
],
[
types.InlineKeyboardButton(
text="倩倩CDN服务器", url='https://t.me/KLT_12'),
types.InlineKeyboardButton(
text="💎DigitalVirt(赞助商)", url='https://digitalvirt.com/aff.php?aff=154')
],
[
types.InlineKeyboardButton(
text="论坛", url='https://bbs.midoks.me'),
types.InlineKeyboardButton(
text="搜索", url='https://bbs.midoks.me/search.php'),
types.InlineKeyboardButton(
text="@ME", url='tg://user?id=5568699210'),
types.InlineKeyboardButton(
text="100RMB/M", url='tg://user?id=5568699210')
]
]
markup = types.InlineKeyboardMarkup(keyboard)
msg_notice = "由于在解决的问题的时候,不给信息,无法了解情况。以后不再群里回答技术问题。全部去论坛提问。在解决问题的过程中,可能需要面板信息,和SSH信息,如无法提供请不要提问。为了让群里都知晓。轮播一年!\n"
msg_notice += "为了不打扰双方,私聊解决问题先转100U,否则无视!\n"
msg = bot.send_message(chat_id, msg_notice, reply_markup=markup)
# print(msg.message_id)
time.sleep(90)
try:
bot.delete_message(
chat_id=chat_id, message_id=msg.message_id)
except Exception as e:
pass
def run(bot):
try:
send_msg(bot, 'notice_msg', 180)
except Exception as e:
writeLog('-----push_notice_msg error start -------')
print(mw.getTracebackInfo())
writeLog('-----push_notice_msg error start -------')

@ -0,0 +1 @@
push_*.py 识别为推送插件

@ -0,0 +1,220 @@
import sys
import io
import os
import time
import re
import json
import base64
import threading
sys.path.append(os.getcwd() + "/class/core")
import mw
import telebot
from telebot import types
from telebot.util import quick_markup
def isThisCmd(cmd, msg):
clen = len(cmd)
msg_len = len(msg)
if msg_len < clen:
return False
check_msg = msg[0:clen]
if cmd == check_msg:
return True
return False
def getReadCmd(cmd, msg):
clen = len(cmd)
msg_len = len(msg)
real_msg = msg[clen:]
return real_msg
def getFaqKw(cmd):
matchObj = re.match(r'寻找【(.*?)】问题如下', cmd, re.M | re.I)
data = matchObj.groups()
if len(data) > 0:
return True, data[0]
return False, ''
def searchHttpPage(kw='', p=1, size=1):
import urllib
kw = kw.strip()
kw = urllib.parse.quote_plus(kw)
api = 'https://bbs.midoks.me/plugin.php?id=external_api&f=bbs_search&q=' + kw + \
'&size=' + str(size) + '&p=' + str(p)
# print('url', api)
data = mw.httpGet(api)
# print(data)
data = json.loads(data)
# print(data)
if data['code'] > -1:
alist = data['data']['list']
r = []
for x in alist:
tmp = {}
tmp['tid'] = x['tid']
tmp['subject'] = x['subject']
tmp['url'] = 'https://bbs.midoks.me/thread-' + \
x['tid'] + '-1-1.html'
r.append(tmp)
data['data']['list'] = r
return data
def searchFaq(bot, message, cmd_text):
# cmd_text = 'mw'
data = searchHttpPage(cmd_text, 1, 5)
if data['code'] == 0 and len(data['data']['list']) > 0:
keyboard = []
dlist = data['data']['list']
for x in dlist:
keyboard.append([types.InlineKeyboardButton(
text=x['subject'], url=x['url'])])
keyboard.append([
types.InlineKeyboardButton(
text="下一页", callback_data='bbs_next_page_2'),
types.InlineKeyboardButton(
text="" + str(data['data']['p']) + "页,共" + str(data['data']['page_num']) + "", callback_data='bbs_page_total')
])
keyboard.append([types.InlineKeyboardButton(
text="关闭消息", callback_data='bbs_search_close')])
# print(keyboard)
markup = types.InlineKeyboardMarkup(keyboard)
bot.send_message(message.chat.id, "寻找【" +
cmd_text.strip() + "】问题如下:", reply_markup=markup)
else:
keyboard = [
[
types.InlineKeyboardButton(
text="论坛", url='https://bbs.midoks.me'),
types.InlineKeyboardButton(
text="搜索", url='https://bbs.midoks.me/search.php')
],
[
types.InlineKeyboardButton(
text="关闭消息", callback_data='bbs_search_close')
]
]
markup = types.InlineKeyboardMarkup(keyboard)
bot.send_message(
message.chat.id, "未找到合适内容,请在官方论坛[bbs.midoks.me]提问!", reply_markup=markup)
return True
def searchDebug(bot, message, cmd_text):
searchFaq(bot, message, cmd_text)
return True
def answer_callback_query(bot, call):
keyword = call.data
if keyword == 'bbs_search_close':
bot.delete_message(chat_id=call.message.chat.id,
message_id=call.message.message_id)
return
is_bbs_page = False
p = 1
if keyword.startswith('bbs_next_page'):
is_bbs_page = True
p = keyword.replace('bbs_next_page_', '')
if keyword.startswith('bbs_pre_page'):
is_bbs_page = True
p = keyword.replace('bbs_pre_page_', '')
# print("p", p)
if is_bbs_page:
is_match, cmd_text = getFaqKw(call.message.text)
if not is_match:
bot.edit_message_text(
chat_id=call.message.chat.id, message_id=call.message.message_id, text="出现错误!")
return
data = searchHttpPage(cmd_text, int(p), 5)
dlist = data['data']['list']
# print(data)
keyboard = []
for x in dlist:
keyboard.append([types.InlineKeyboardButton(
text=x['subject'], url=x['url'])])
page_nav = []
if int(data['data']['p']) > 1:
page_nav.append(types.InlineKeyboardButton(
text="上一页", callback_data='bbs_pre_page_' + str(int(p) - 1)))
if data['data']['page_num'] != data['data']['p']:
page_nav.append(types.InlineKeyboardButton(
text="下一页", callback_data='bbs_next_page_' + str(int(p) + 1)))
page_nav.append(types.InlineKeyboardButton(
text="" + str(data['data']['p']) + "页,共" + str(data['data']['page_num']) + "", callback_data='bbs_page_total'))
keyboard.append(page_nav)
keyboard.append([types.InlineKeyboardButton(
text="关闭消息", callback_data='bbs_search_close')])
markup = types.InlineKeyboardMarkup(keyboard)
bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id,
text=call.message.text, reply_markup=markup)
def run(bot, message):
text_body = message.text
# 过滤URL
is_has_url = re.search(
'(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]', text_body)
if is_has_url:
return bot
# print(text_body)
if isThisCmd('/faq:', text_body):
cmd_text = getReadCmd('/faq:', text_body)
return searchFaq(bot, message, cmd_text)
# if isThisCmd('/debug', text_body):
# cmd_text = getReadCmd('/debug', text_body)
# return searchDebug(bot, message, cmd_text)
if text_body.find('?') > -1 or text_body.find('') > -1:
return_msg = "你似乎在寻找【" + text_body + "】答案:\n"
return_msg += "/faq:开始寻找你的问题\n"
keyboard = [
[
types.InlineKeyboardButton(
text="如未找到,可以在论坛补充你的提问!", url='https://bbs.midoks.me'),
]
]
markup = types.InlineKeyboardMarkup(keyboard)
bot.reply_to(message, return_msg, reply_markup=markup)
return bot
if __name__ == "__main__":
# print(isThisCmd('/?:', '/?:如何在安装面板'))
# print(getReadCmd('/?:', '/?:如何在安装面板'))
# print(searchHttpPage('mw'))
print(getFaqKw('寻找【mw】问题如下:'))

@ -0,0 +1,87 @@
# coding:utf-8
# python /Users/midoks/Desktop/mwdev/server/tgclient/tgclient.py
from telethon import TelegramClient
sys.path.append(os.getcwd() + "/class/core")
import mw
sys.path.append(getServerDir() + "/extend")
def getPluginName():
return 'tgclient'
def getPluginDir():
return mw.getPluginDir() + '/' + getPluginName()
def getServerDir():
return mw.getServerDir() + '/' + getPluginName()
def getConfigData():
cfg_path = getServerDir() + "/data.cfg"
if not os.path.exists(cfg_path):
mw.writeFile(cfg_path, '{}')
t = mw.readFile(cfg_path)
return json.loads(t)
def writeConf(data):
cfg_path = getServerDir() + "/data.cfg"
mw.writeFile(cfg_path, json.dumps(data))
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):
if __name__ == "__main__":
print(log_str)
now = mw.getDateFromNow()
log_file = getServerDir() + '/task.log'
mw.writeFileLog(now + ':' + log_str, log_file, limit_size=5 * 1024)
return True
# start tgbot
cfg = getConfigData()
while True:
cfg = getConfigData()
if 'bot' in cfg and 'app_id' in cfg['bot']:
if cfg['bot']['app_id'] != '' and cfg['bot']['app_id'] != 'app_id':
break
if cfg['bot']['app_hash'] != '' and cfg['bot']['app_hash'] != 'app_hash':
break
writeLog('等待输入配置,填写app_token')
time.sleep(3)
client = TelegramClient('mdioks', cfg['bot']['api_id'], cfg['bot']['api_hash'])
async def main():
# Now you can use all client methods listed below, like for example...
await client.send_message('me', 'Hello to myself!')
with client:
client.loop.run_until_complete(main())
Loading…
Cancel
Save