代码仅供参考,请根据自身业务情况修改
#!/usr/bin/python3 | |
#-*- encoding:utf-8 -*- | |
''' | |
pip3 install -r requirements.txt | |
pip3 install requests_toolbelt | |
pip3 install pymysql | |
pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple matplotlib | |
pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple numpy | |
pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple openpyxl | |
pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple xlsxwriter | |
''' | |
import requests | |
import json | |
from requests_toolbelt import MultipartEncoder | |
from PIL import Image | |
import re | |
## | |
import pymysql | |
import sys | |
import time | |
import datetime | |
# | |
import os | |
import numpy as np | |
import matplotlib.pyplot as plt | |
import matplotlib | |
#from matplotlib import font_manager | |
import random | |
import shutil | |
import datetime | |
import pandas as pd | |
import xlrd | |
import openpyxl | |
# import xlsxwriter | |
# from openpyxl.workbook import Workbook | |
# from openpyxl.writer.excel import ExcelWriter | |
# from openpyxl.drawing.image import Image | |
class DBUtil(object): | |
host = "10.8.0.1" | |
port = 3306 | |
user = "root" | |
password = "pwd@123456." | |
db = "mysql" | |
charset = "utf8" | |
conn = None | |
def __init__(self,db='mysql',host='10.8.0.1',port=3306,user='root',password='123456',charset='utf8'): | |
self.db = db | |
self.host = host | |
self.port = port | |
self.user = user | |
self.password = password | |
self.charset = charset | |
pass | |
def db_connect(self): | |
try: | |
#self.db = db_name | |
#print(self.db) | |
self.conn = pymysql.connect(host=self.host,port=self.port,user=self.user,password=self.password,db=self.db,charset=self.charset) | |
cursor = self.conn.cursor() | |
except Exception as e: | |
print(e) | |
else: | |
print('Connect Success:%s' % cursor) | |
def db_sql(self,command,sql): | |
""" | |
查询数据库数据 | |
:param command: | |
:param sql: | |
:return: | |
""" | |
if not self.conn: | |
print("no connect db") | |
sys.exit() | |
cursor = self.conn.cursor() | |
if command in ('SELECT', 'select'): | |
# 如果为查询指令 | |
sql = sql.encode('utf-8') | |
try: | |
cursor.execute(sql) | |
result = cursor.fetchall() | |
return result | |
except Exception as e: | |
print(e) | |
finally: | |
self.conn.close() | |
elif command in ('delete', 'DELETE', 'update', 'UPDATE', 'insert', 'INSERT'): | |
# 如果为增删改 | |
sql = sql.encode('utf-8') | |
try: | |
cursor.execute(sql) | |
self.conn.commit() | |
except Exception as e: | |
# 如果失败则回滚 | |
self.conn.rollback() | |
print(e) | |
finally: | |
self.conn.close() | |
else: | |
print('Command Error!') | |
class qywx: | |
# 部门ID | |
''' | |
22 [{"id":14,"name":"总经理办公室","parentid":1,"order":100001000,"department_leader":["XingYe"]},{"id":19,"name":"策划","parentid":18,"order":100000000,"department_leader":[]},{"id":22,"name":"程序","parentid":18,"order":99997000,"department_leader":[]},{"id":24,"name":"商务","parentid":5,"order":99995000,"department_leader":[]},{"id":25,"name":"市场","parentid":5,"order":99994000,"department_leader":[]}] | |
''' | |
# | |
corpid = 'ww953722a35a02111a' #步骤1-3中的企业id | |
app_list = [ | |
(1000002, '-iKikad01lHeFVaZ_2G01F3sZg5T0TV6l3OUXtf2Xr0') #此处将步骤1-2中的AgentId 和 Secret分别填入,多个应用逗号隔开 | |
] | |
def __init__(self, app_id): #app_id 按app_list顺序编号 | |
self.agentid, self.corpsecret = qywx.app_list[app_id] | |
# 上传临时文件素材接口,图片也可使用此接口,20M上限 | |
def post_file(self, filepath, filename): | |
response = requests.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={corpsecret}".format(corpid=qywx.corpid, corpsecret=self.corpsecret)) | |
data = json.loads(response.text) | |
access_token = data['access_token'] | |
post_file_url = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={access_token}&type=file".format(access_token=access_token) | |
m = MultipartEncoder( | |
fields={'file': (filename, open(filepath + filename, 'rb'), 'multipart/form-data')}, | |
) | |
r = requests.post(url=post_file_url, data=m, headers={'Content-Type': m.content_type}) | |
js = json.loads(r.text) | |
print("upload " + js['errmsg']) | |
if js['errmsg'] != 'ok': | |
return None | |
return js['media_id'] | |
# 向应用发送图片接口,_message为上传临时素材后返回的media_id | |
def send_img(self, _message, useridlist = ['name1|name2'],toparty=None): | |
useridstr = "|".join(useridlist) | |
response = requests.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={corpsecret}".format(corpid=qywx.corpid, corpsecret=self.corpsecret)) | |
data = json.loads(response.text) | |
access_token = data['access_token'] | |
json_dict = { | |
"touser" : useridstr, | |
"msgtype" : "image", | |
"agentid" : self.agentid, | |
"image" : { | |
"media_id" : _message, | |
}, | |
"safe": 0, | |
"enable_id_trans": 1, | |
"enable_duplicate_check": 0, | |
"duplicate_check_interval": 1800 | |
} | |
if not toparty: | |
print("use default") | |
else: | |
del json_dict['touser'] | |
json_dict['toparty'] = toparty | |
json_str = json.dumps(json_dict) | |
response_send = requests.post("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}".format(access_token=access_token), data=json_str) | |
print("send to " + useridstr + ' ' + json.loads(response_send.text)['errmsg']) | |
return json.loads(response_send.text)['errmsg'] == 'ok' | |
# 向应用发送文字消息接口,_message为字符串 | |
def send_text(self, _message, useridlist = ['name1|name2'],toparty=None): | |
useridstr = "|".join(useridlist) # userid 在企业微信-通讯录-成员-账号 | |
response = requests.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={corpsecret}".format(corpid=qywx.corpid, corpsecret=self.corpsecret)) | |
data = json.loads(response.text) | |
access_token = data['access_token'] | |
json_dict = { | |
"touser" : useridstr, | |
"msgtype" : "text", | |
"agentid" : self.agentid, | |
"text" : { | |
"content" : _message | |
}, | |
"safe": 0, | |
"enable_id_trans": 1, | |
"enable_duplicate_check": 0, | |
"duplicate_check_interval": 1800 | |
} | |
if not toparty: | |
print("use default") | |
else: | |
del json_dict['touser'] | |
json_dict['toparty'] = toparty | |
json_str = json.dumps(json_dict) | |
response_send = requests.post("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}".format(access_token=access_token), data=json_str) | |
print("send to " + useridstr + ' ' + json.loads(response_send.text)['errmsg']) | |
return json.loads(response_send.text)['errmsg'] == 'ok' | |
# 向应用发送markdown消息接口,_message为字符串 | |
def send_markdown(self, _message, useridlist = ['name1|name2'],toparty=None): | |
useridstr = "|".join(useridlist) # userid 在企业微信-通讯录-成员-账号 | |
response = requests.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={corpsecret}".format(corpid=qywx.corpid, corpsecret=self.corpsecret)) | |
data = json.loads(response.text) | |
access_token = data['access_token'] | |
json_dict = { | |
"touser" : useridstr, | |
"msgtype" : "markdown", | |
"agentid" : self.agentid, | |
"markdown" : { | |
"content" : _message | |
}, | |
"safe": 0, | |
"enable_id_trans": 1, | |
"enable_duplicate_check": 0, | |
"duplicate_check_interval": 1800 | |
} | |
if not toparty: | |
print("use default") | |
else: | |
del json_dict['touser'] | |
json_dict['toparty'] = toparty | |
json_str = json.dumps(json_dict) | |
response_send = requests.post("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}".format(access_token=access_token), data=json_str) | |
print("send to " + useridstr + ' ' + json.loads(response_send.text)['errmsg']) | |
return json.loads(response_send.text)['errmsg'] == 'ok' | |
# 向应用发送file消息接口,_message为上传临时素材后返回的media_id | |
def send_file(self, _message, useridlist = ['name1|name2'],toparty=None): | |
useridstr = "|".join(useridlist) # userid 在企业微信-通讯录-成员-账号 | |
response = requests.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={corpsecret}".format(corpid=qywx.corpid, corpsecret=self.corpsecret)) | |
data = json.loads(response.text) | |
access_token = data['access_token'] | |
json_dict = { | |
"touser" : useridstr, | |
"msgtype" : "file", | |
"agentid" : self.agentid, | |
"file" : { | |
"media_id" : _message | |
}, | |
"safe": 0, | |
"enable_id_trans": 1, | |
"enable_duplicate_check": 0, | |
"duplicate_check_interval": 1800 | |
} | |
if not toparty: | |
print("use default") | |
else: | |
del json_dict['touser'] | |
json_dict['toparty'] = toparty | |
json_str = json.dumps(json_dict) | |
response_send = requests.post("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}".format(access_token=access_token), data=json_str) | |
print("send to " + useridstr + ' ' + json.loads(response_send.text)['errmsg']) | |
return json.loads(response_send.text)['errmsg'] == 'ok' | |
def get_login_count(): | |
unit = 3600 | |
cur_time = int(time.time()) | |
hour_stamp = cur_time - ( cur_time % unit ) | |
prev_stamp = hour_stamp - 3600 | |
prev_time_struct = time.localtime(prev_stamp) | |
print(prev_stamp) | |
prev_date_string = time.strftime("%Y-%m-%d %H:%M:%S", prev_time_struct) | |
cur_time_struct = time.localtime(hour_stamp) | |
cur_date_string = time.strftime("%Y-%m-%d %H:%M:%S", cur_time_struct) | |
date_int_string = time.strftime("%Y%m%d",prev_time_struct) | |
db = DBUtil("db_authen_log") | |
sql = "SELECT COUNT(DISTINCT a_uid) as login FROM tb_authen_log_{} WHERE a_login_time>={} AND a_login_time<{} ;".format(date_int_string, prev_stamp, hour_stamp); | |
print("{} - {} : sql:{}".format(prev_date_string,cur_date_string, sql)) | |
db.db_connect() | |
data = db.db_sql('SELECT',sql) | |
count_login = 0 | |
for i in data: | |
count_login = i[0] | |
target = {"key":"login_count","name":"登录人数(全渠道)","value":count_login,"start_time":prev_date_string, "end_time":cur_date_string,"sql":sql} | |
return target | |
def get_pay_sum(): | |
unit = 3600 | |
cur_time = int(time.time()) | |
hour_stamp = cur_time - ( cur_time % unit ) | |
prev_stamp = hour_stamp - 3600 | |
prev_time_struct = time.localtime(prev_stamp) | |
print(prev_stamp) | |
prev_date_string = time.strftime("%Y-%m-%d %H:%M:%S", prev_time_struct) | |
cur_time_struct = time.localtime(hour_stamp) | |
cur_date_string = time.strftime("%Y-%m-%d %H:%M:%S", cur_time_struct) | |
date_int_string = time.strftime("%Y%m%d",prev_time_struct) | |
db = DBUtil(db="db_pay_log") | |
sql = "SELECT SUM(p_price) FROM tb_pay_log_{} WHERE p_status = 0 AND p_finishTime >= {} AND p_finishTime < {} ;".format(date_int_string, prev_stamp, hour_stamp); | |
print("{} - {} : sql:{}".format(prev_date_string,cur_date_string, sql)) | |
db.db_connect() | |
data = db.db_sql('SELECT',sql) | |
sum_data = 0 | |
for i in data: | |
sum_data = i[0] | |
target = {"key":"pay_sum","name":"充值金额(全渠道)","value":sum_data,"start_time":prev_date_string, "end_time":cur_date_string,"sql":sql} | |
return target | |
def get_login_count_hour(): | |
unit = 3600 | |
cur_time = int(time.time()) | |
hour_stamp = cur_time - ( cur_time % unit ) | |
prev_stamp = hour_stamp - 3600 | |
prev_time_struct = time.localtime(prev_stamp) | |
print(prev_stamp) | |
prev_date_string = time.strftime("%Y-%m-%d %H:%M:%S", prev_time_struct) | |
cur_time_struct = time.localtime(hour_stamp) | |
cur_date_string = time.strftime("%Y-%m-%d %H:%M:%S", cur_time_struct) | |
date_int_string = time.strftime("%Y%m%d",prev_time_struct) | |
db = DBUtil(db="db_authen_log") | |
sql = "select FROM_UNIXTIME(a_login_time, '%H') AS time, COUNT(1) from tb_authen_log_{} GROUP BY time;".format(date_int_string); | |
db.db_connect() | |
data = db.db_sql('SELECT',sql) | |
target = {"key":"login_count_hour","name":"登录人数(每小时)","value":data,"sql":sql} | |
return target | |
def get_pay_sum_hour(): | |
unit = 3600 | |
cur_time = int(time.time()) | |
hour_stamp = cur_time - ( cur_time % unit ) | |
prev_stamp = hour_stamp - 3600 | |
prev_time_struct = time.localtime(prev_stamp) | |
print(prev_stamp) | |
prev_date_string = time.strftime("%Y-%m-%d %H:%M:%S", prev_time_struct) | |
cur_time_struct = time.localtime(hour_stamp) | |
cur_date_string = time.strftime("%Y-%m-%d %H:%M:%S", cur_time_struct) | |
date_int_string = time.strftime("%Y%m%d",prev_time_struct) | |
db = DBUtil(db="db_pay_log") | |
sql = "select FROM_UNIXTIME(p_finishTime, '%H') AS time, SUM(p_price) from tb_pay_log_{} GROUP BY time;".format(date_int_string); | |
db.db_connect() | |
data = db.db_sql('SELECT',sql) | |
target = {"key":"pay_sum_hour","name":"充值概况(每小时)","value":data,"sql":sql} | |
return target | |
def get_pay_order_hour(): | |
unit = 3600 | |
cur_time = int(time.time()) | |
hour_stamp = cur_time - ( cur_time % unit ) | |
cur_time_struct = time.localtime(hour_stamp) | |
prev_stamp = hour_stamp - 3600 | |
prev_time_struct = time.localtime(prev_stamp) | |
date_int_string = time.strftime("%Y%m%d",prev_time_struct) | |
db = DBUtil(db="db_pay_log") | |
sql = "select FROM_UNIXTIME(p_finishTime, '%H') AS time, COUNT(1) from tb_pay_log_{} GROUP BY time;".format(date_int_string); | |
db.db_connect() | |
data = db.db_sql('SELECT',sql) | |
target = {"key":"pay_sum_hour","name":"充值订单数(每小时)","value":data,"sql":sql} | |
return target | |
def create_plt_data(x,y,title,xlabel,ylabel,filename): | |
# 准备数据 | |
x_data = x #[f"{i}" for i in range(1, 25)] | |
y_data = y #[random.randint(100, 300) for i in range(24)] | |
print("titile:{} ,x:{} ,y:{}".format(title,x,y)) | |
# print(matplotlib.matplotlib_fname()) | |
plt.clf() | |
# 正确显示中文和负号 | |
plt.rcParams["font.sans-serif"] = ["SimHei"] | |
plt.rcParams["axes.unicode_minus"] = False | |
# 画图,plt.bar()可以画柱状图 | |
for i in range(len(x_data)): | |
plt.bar(x_data[i], y_data[i]) | |
# 设置图片名称 | |
plt.title(title) | |
# 设置x轴标签名 | |
plt.xlabel(xlabel) | |
# 设置y轴标签名 | |
plt.ylabel(ylabel) | |
save_dir = "/tmp/" | |
out = None | |
if not os.path.exists(save_dir): | |
print("[warning] file save dir not exists") | |
else: | |
filepath = save_dir+filename | |
print("[info] will save file to:",filepath) | |
plt.savefig(filepath) | |
out = filepath | |
# plt.show() | |
# plt.savefig(path+'scatter.jpg')#保存图片 | |
# plt.savefig(path+'plot.jpg')#保存图片\n", | |
return {'out':out,'dir':save_dir,'filename':filename} | |
def create_plt_duiji_data(x,y1,y2,title,xlabel,ylabel,y2label,filename): | |
plt.clf() | |
plt.rcParams["font.sans-serif"] = ["SimHei"] | |
plt.rcParams["axes.unicode_minus"] = False | |
plt.bar(x,y2,width=0.4,color='#dddddd',zorder=5,label=y2label) | |
plt.bar(x,y1,width=0.4,bottom=y2,color='#d62728',zorder=5,label=ylabel) | |
c=np.mean(y1) | |
plt.axhline(y=c,color="black",linestyle=':') | |
plt.title(title) | |
plt.xlabel(xlabel) | |
plt.tick_params(axis='x',length=0) | |
plt.grid(axis='y',alpha=0.5,ls='--') | |
plt.legend(frameon=False) | |
plt.tight_layout() | |
#plt.ylabel(ylabel) | |
save_dir = "/tmp/" | |
out = None | |
if not os.path.exists(save_dir): | |
print("[warning] file save dir not exists") | |
else: | |
filepath = save_dir+filename | |
print("[info] will save file to:",filepath) | |
plt.savefig(filepath) | |
out = filepath | |
return {'out':out,'dir':save_dir,'filename':filename} | |
def create_plt_line(x,y,title,xlabel,ylabel,filename): | |
# 准备数据 | |
x_data = x #[f"{i}" for i in range(1, 25)] | |
y_data = y #[random.randint(100, 300) for i in range(24)] | |
print("titile:{} ,x:{} ,y:{}".format(title,x,y)) | |
# print(matplotlib.matplotlib_fname()) | |
plt.clf() | |
# 正确显示中文和负号 | |
plt.rcParams["font.sans-serif"] = ["SimHei"] | |
plt.rcParams["axes.unicode_minus"] = False | |
#x_ticks_label=["{}:00".format(i) for i in x] | |
#rotation表示旋转角度 | |
#设置x坐标 | |
#plt.xticks(x,x_ticks_label,rotation=45) | |
#y_ticks_label=['{}'.format(i) for i in range(min(y),max(y)+1)] | |
#设置y坐标 | |
#plt.yticks(range(min(y),max(y)+1),y_ticks_label) | |
plt.plot(x,y,color='blue',alpha=0.8,marker='*',linestyle='--',linewidth=1) | |
#plt.plot(x,y,color='blue',ls='-',lw=1,marker='*',markevery=20) | |
# 设置图片名称 | |
plt.title(title,color='black') | |
# 设置x轴标签名 | |
plt.xlabel(xlabel) | |
# 设置y轴标签名 | |
plt.ylabel(ylabel) | |
save_dir = "/tmp/" | |
out = None | |
if not os.path.exists(save_dir): | |
print("[warning] file save dir not exists") | |
else: | |
filepath = save_dir+filename | |
print("[info] will save file to:",filepath) | |
plt.savefig(filepath) | |
out = filepath | |
# plt.show() | |
# plt.savefig(path+'scatter.jpg')#保存图片 | |
# plt.savefig(path+'plot.jpg')#保存图片\n", | |
return {'out':out,'dir':save_dir,'filename':filename} | |
def totalGameOnline(urls,filter_keys=None): | |
data = {} | |
for url in urls: | |
response = requests.get(url) | |
# regex = r'^haproxy_backend_current_sessions\{backend="(.*?)"\} (\d+)$' | |
lines = response.text.split('\n') | |
for line in lines: | |
if not line.startswith('haproxy_backend_current_sessions'): | |
continue | |
result = re.match(r'^haproxy_backend_current_sessions\{backend="(.*?)"\} (\d+)$', line) | |
if result: | |
service_name = result.group(1) | |
online_size = int(result.group(2)) | |
if filter_keys and service_name in filter_keys: | |
continue | |
if service_name in data: | |
# data[service_name] += data[service_name]+online_size | |
# print(online_size) | |
if online_size > 0: | |
data[service_name] = (data[service_name]+online_size) | |
else: | |
data[service_name] = online_size | |
return data | |
online_metrics_urls=[ | |
"http://127.0.0.1:9912/metrics", | |
"http://127.0.0.1:9913/metrics", | |
"http://127.0.0.1:9914/metrics", | |
"http://127.0.0.1:9915/metrics", | |
"http://127.0.0.1:9916/metrics" | |
] | |
game_tag_with_name={ | |
"game-gate" : "游戏大厅", | |
"game-ddz-bs" : "斗地主比赛场[id 401-450]", | |
"game-ddz4-pt" : "四斗普通场[id 61-65]", | |
"game-ddz4-bxp" : "四斗不洗牌场[id 127-180]", | |
"game-ddz4-hb" : "四斗红包场[id 68]", | |
"game-ddz3-pt" : "三斗普通场[id 71-74]", | |
"game-ddz3-bxp" : "三斗不洗牌[id 124-126]", | |
"game-ddz3-hb" : "三斗红包场[id 76]", | |
"game-ddz2-pt" : "二斗普通场[id 81-84]", | |
"game-ddz2-yl" : "二斗娱乐场[id 69]", | |
"game-ddz2-hf" : "二斗话费场[id 118]", | |
"game-dyj-pt" : "大赢家(拼三张)[id 77-80]", | |
"game-jpfc-pt" : "极品飞车(奔驰宝马)[id 100-106]", | |
"game-brdp-pt" : "百人斗牌(牛牛)[id 90-91]", | |
"game-sgj-pt" : "水果机[id 107]", | |
"game-yyl-pt":"摇摇乐[id 105]", | |
"game-jkby-pt":"杰克捕鱼[id 109|112|113|120]", | |
"game-shz-pt":"水浒传[id 121-123]", | |
"game-ermj-pt":"二人麻将[id 130-133]", | |
"game-xlmj-pt":"血流麻将[id 139-142]", | |
"game-guandan-pt":"掼蛋[id 143-147]", | |
"game-xmbd-pt" : "消灭病毒[id 160]", | |
"game-bdzc-pt" : "病毒战场[id 170]", | |
"game-sldj-pt" : "首领对决[id 175]", | |
"game-lzddz4-pt" : "连炸斗地主[id 51-54]" | |
} | |
tag_xxyx=["game-lzddz4-pt","game-guandan-pt","game-ermj-pt","game-xlmj-pt","game-ddz-bs","game-ddz4-pt","game-ddz4-bxp","game-ddz4-hb","game-ddz3-pt","game-ddz3-bxp","game-ddz3-hb","game-ddz2-pt","game-ddz2-yl","game-ddz2-hf"] | |
def getOnlineStr(): | |
data = totalGameOnline(online_metrics_urls,["admin_stats","game-chat"]) | |
gate = data['game-gate'] | |
del data['game-gate'] | |
val = sum(data.values()) | |
online_info = "\n\n## 在线人数(实时) ##\n" | |
online_info += "\n游戏大厅: {} 人\n".format(gate) | |
online_info += "\n游戏局内: {} 人\n".format(val) | |
dict= sorted(data.items(), key=lambda d:d[1], reverse = True) | |
for index, item in enumerate(dict): | |
tag = item[0] | |
name = game_tag_with_name[tag] | |
online = data[tag] | |
rate = (round(online/val,4)*100.0) | |
online_info += "\n{}. {}: {}人({:.2f}%)\n".format((index+1),name,online,rate) | |
# print(f'{name}:{online} \n') | |
return online_info | |
def getOnlineStrSimple(): | |
data = totalGameOnline(online_metrics_urls,["admin_stats","game-chat"]) | |
gate = data['game-gate'] | |
del data['game-gate'] | |
val = sum(data.values()) | |
online_info = "\n\n##在线人数(实时采样)##\n" | |
online_info += "\n游戏大厅: {} 人\n".format(gate) | |
online_info += "\n游戏局内: {} 人\n".format(val) | |
xxyx_online=0 | |
xyx_online=0 | |
print(tag_xxyx) | |
for tag in data: | |
print(tag) | |
if tag in tag_xxyx: | |
xxyx_online += data[tag] | |
else: | |
xyx_online += data[tag] | |
online_info += "\n休闲游戏: {}人({:.2f}%)\n".format(xxyx_online,(round(xxyx_online/val,4)*100.00)) | |
online_info += "\n小游戏: {}人({:.2f}%)\n".format(xyx_online,(round(xyx_online/val,4)*100.00)) | |
#online_info += "\n小游戏: {}人({:.2f}%)\n".format(xyx_online,(round(xyx_online/val,4)*100.00)) | |
# print(f'{name}:{online} \n') | |
return online_info | |
def getOnlineMap(): | |
data = totalGameOnline(online_metrics_urls,["admin_stats","game-chat"]) | |
gate = data['game-gate'] | |
del data['game-gate'] | |
val = sum(data.values()) | |
xxyx_online=0 | |
xyx_online=0 | |
print(tag_xxyx) | |
for tag in data: | |
print(tag) | |
if tag in tag_xxyx: | |
xxyx_online += data[tag] | |
else: | |
xyx_online += data[tag] | |
online_dict = {} | |
online_dict["gate"] = gate | |
online_dict["game"] = val | |
online_dict['xxyx'] = xxyx_online | |
online_dict['xxyx_rate'] = "{:.2f}%".format((round(xxyx_online/val,4)*100.00)) | |
online_dict['xyx'] = xyx_online | |
online_dict['xyx_rate'] = "{:.2f}%".format((round(xyx_online/val,4)*100.00)) | |
return online_dict | |
def zhibiao(): | |
send_wechat1 = False | |
send_wechat2 = False | |
send_wechat3 = True | |
qy = qywx(0) | |
m_login = get_login_count() | |
m_pay = get_pay_sum() | |
date_time = time.strftime("%Y-%m-%d", time.localtime()) | |
date_time_hour = time.strftime("%Y%m%d%H", time.localtime()) | |
weekList = ["星期一","星期二","星期三","星期四","星期五","星期六","星期日"] | |
week = weekList[datetime.datetime.now().weekday()] | |
msg_login = "## 指标统计 ##\n\n起始时间:{} \n\n截止时间:{}\n\n指标名称:{} \n\n指标数值:{}人".format(m_login["start_time"],m_login["end_time"],m_login["name"],m_login["value"]); | |
msg_pay = "## 指标统计 ##\n\n起始时间:{} \n\n截止时间:{}\n\n指标名称:{} \n\n指标数值:{}元".format(m_pay["start_time"],m_pay["end_time"],m_pay["name"],m_pay["value"]); | |
# 发送文本消息 | |
msg_wechat = msg_login+"\n\n"+msg_pay | |
online_map = getOnlineMap() | |
msg_tongji = "### 业务指标\n>**<font color=\"info\">整点播报</font>**\n >起始: {}\n >截至: {}\n >登陆人数: {} 人\n >充值金额: {} 元\n >\n\n >**<font color=\"warning\">在线人数(实时采样)</font>**\n >大厅在线: {} 人\n >游戏局内: {} 人\n >休闲游戏: {} 人({})\n >小游戏: {} 人({})\n ".format(m_login["start_time"],m_login["end_time"],m_login["value"],m_pay["value"],online_map['gate'],online_map['game'],online_map['xxyx'],online_map['xxyx_rate'],online_map['xyx'],online_map['xyx_rate']) | |
#print(msg_tongji) | |
#if msg_tongji: | |
# sys.exit() | |
#### | |
d1 = get_login_count_hour() | |
print(d1) | |
login_hour_val = d1["value"] | |
login_title = d1["name"] | |
login_file_name = "login_hour_{}.jpg".format(int(time.time())) | |
login_x = [] | |
login_y = [] | |
for i in login_hour_val: | |
login_x.append(i[0]) | |
login_y.append(i[1]) | |
x_label = "日期:{}({})".format(date_time,week) | |
login_out = create_plt_line(login_x,login_y,login_title,x_label,"登录人数",login_file_name) | |
login_save_dir = login_out['dir'] | |
if send_wechat1: | |
media_id = qy.post_file(login_save_dir, login_file_name) | |
online_str = getOnlineStrSimple() | |
msg_login += online_str | |
qy.send_text(msg_login, ['@all']) | |
qy.send_img(media_id, ['@all']) | |
#### | |
d2 = get_pay_sum_hour() | |
order_detail = get_pay_order_hour() | |
order_val = order_detail["value"] | |
print(d2) | |
pay_hour_val = d2["value"] | |
pay_title = d2["name"] | |
pay_file_name = "pay_hour_{}.jpg".format(int(time.time())) | |
pay_x = [] | |
pay_y = [] | |
for i in pay_hour_val: | |
pay_x.append(i[0]) | |
pay_y.append(i[1]) | |
orders = [] | |
for order in order_val: | |
orders.append(order[1]) | |
pay_sum = sum(pay_y) | |
y_label = "充值额" | |
y2_label = "订单数" | |
x_title = "{} ,∑ = {}".format(x_label,pay_sum) | |
print(y_label) | |
#pay_out = create_plt_data(pay_x,pay_y,pay_title,x_label,y_label,pay_file_name) | |
pay_out = create_plt_duiji_data(pay_x,pay_y,orders,pay_title,x_title,y_label,y2_label,pay_file_name) | |
pay_save_dir = pay_out['dir'] | |
l_filename = login_save_dir+login_file_name | |
p_filename = pay_save_dir+pay_file_name | |
onepic_filename = "tongji_hour_{}.jpg".format(int(time.time())) | |
onepic = image_Splicing(l_filename,p_filename,"y",onepic_filename) | |
print(msg_wechat) | |
print(onepic) | |
if send_wechat3: | |
media_id = qy.post_file("/tmp/",onepic_filename) | |
#qy.send_text(msg_wechat,['@all']) | |
qy.send_markdown(msg_tongji,['@all']) | |
qy.send_img(media_id,['@all']) | |
if send_wechat2: | |
media_id = qy.post_file(pay_save_dir, pay_file_name) | |
qy.send_text(msg_pay, ['@all']) | |
qy.send_img(media_id, ['@all']) | |
def liuyan(): | |
sql = "SELECT COUNT(1) FROM tb_feedback WHERE fb_status = 0 AND DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= FROM_UNIXTIME(`fb_timestamp`);" | |
db = DBUtil(db="db_common_info",host="10.8.18.108") | |
db.db_connect() | |
data = db.db_sql('SELECT',sql) | |
count_message = 0 | |
for i in data: | |
count_message = i[0] | |
# target = {"key":"liuyan","name":"用户留言数量(最近一周)","value":data,"sql":sql} | |
# return target | |
if count_message > 0: | |
qy = qywx(0) | |
#msg_unread = "## 用户反馈 ##\n\n您有新的留言,请注意查收!\n\n未处理数量:{}条 (近一周) \n\n登录后台管理->玩家数据->玩家咨询 进行处理".format(count_message); | |
#msg_unread = "### 用户反馈 \n\n > 您有的:**{}**条留言未处理, 请注意查收!\n\n > 登录后台管理-玩家数据-玩家咨询 [进行处理](http://o.manage.zhuoyigame.com:9090/)".format(count_message) | |
#qy.send_text(msg_unread, ['@all']) | |
msg_unread = '### 用户反馈 \n\n > 您有 {} 条留言未处理, 请注意查收!\n\n > 登录 后台管理-玩家数据-玩家咨询 [进行处理](http://o.manage.zhuoyigame.com:9090/)'.format(count_message) | |
qy.send_markdown(msg_unread,['@all']) | |
else: | |
print("no message need process") | |
# print("you have a message") | |
def ribao(): | |
date_time = time.strftime("%Y-%m-%d", time.localtime()) | |
#inotice_msg = '## 每日总结 \n\n > <font color=\"info\">每一天提醒自己,不要忘记理想,不要忘记目标;每一天提醒自己,不要忘记学习,不要忘记看书。每一天提醒自我不要忘记快乐,成为更好的自己</font>\n\n > <font color=\"warning\">今天工作辛苦了,感谢您的付出, 别忘了对今天的自己进行下评价、小结,是否距离小目标更进一步了? </font> \n\n > 明天的你一定会感谢今天努力的自己,加油!' | |
#notice_msg = '## hello world \n\n > <font color=\"info\"> This is a Test </font>' | |
notice_msg = '## 每日总结 \n\n > <font color=\"warning\">感谢您的付出,工作一天辛苦了! 别忘了对今天的自己进行下评价、小结,是否距离小目标更近一步了? </font> \n\n > 明天的你一定会感谢今天努力的自己,加油! \n\n ' | |
target = ["@all"] | |
#toparty = "22" | |
file_dir = '/root/' | |
src_file = "/root/workday.xlsx" | |
to_file_name = "工作日报"+"-"+date_time+".xlsx" | |
to_file = file_dir + to_file_name | |
if os.path.exists(to_file): | |
print("already exists") | |
else: | |
print("copy file ") | |
#shutil.copyfile(src_file,to_file) | |
qy = qywx(0) | |
qy.send_markdown(notice_msg,target) | |
#media_id = qy.post_file(file_dir,to_file_name) | |
#qy.send_file(media_id,target) | |
############# | |
def plt_pannel_graph_duiji(pannel,x,y1,y2,title,xlabel,ylabel,y2label): | |
pannel.bar(x,y2,width=0.4,color='#dddddd',zorder=5,label=y2label) | |
pannel.bar(x,y1,width=0.4,bottom=y2,color='#d62728',zorder=5,label=ylabel) | |
c=np.mean(y1) | |
pannel.axhline(y=c,color="black",linestyle=':') | |
#pannel.title(title) | |
#pannel.xlabel(xlabel) | |
pannel.tick_params(axis='x',length=0) | |
pannel.grid(axis='x',ls='-.') | |
pannel.grid(axis='y',alpha=0.5,ls='--') | |
pannel.yaxis.tick_right() # 将y轴的数值显示在右边 | |
pannel.legend(frameon=False) | |
for label in pannel.xaxis.get_ticklabels(): # 设置x轴标签的字体大小 | |
label.set_fontsize(30) | |
for label in pannel.yaxis.get_ticklabels(): # 设置y轴标签的字体大小 | |
label.set_fontsize(45) | |
# pannel.tight_layout() | |
def plt_pannel_graph_line(pannel,x,y,title,xlabel,ylabel): | |
pannel.plot(x,y,color='blue',alpha=0.8,marker='*',linestyle='--',linewidth=1) | |
#plt.plot(x,y,color='blue',ls='-',lw=1,marker='*',markevery=20) | |
# 设置图片名称 | |
# pannel.title(title,color='black') | |
# 设置x轴标签名 | |
# pannel.xlabel(xlabel) | |
# 设置y轴标签名 | |
# pannel.ylabel(ylabel) | |
pannel.grid(axis='x', linestyle='-.') # 添加x轴方向的网格 | |
pannel.grid(axis='y', linestyle='-.') # 添加y轴方向的网格 | |
pannel.yaxis.tick_right() # 将y轴的数值显示在右边 | |
for label in pannel.xaxis.get_ticklabels(): # 设置x轴标签的字体大小 | |
label.set_fontsize(30) | |
for label in pannel.yaxis.get_ticklabels(): # 设置y轴标签的字体大小 | |
label.set_fontsize(45) | |
def plt_pannel_text(pannel,text_content,font_size): | |
pannel.text(0.01, 0.5, text_content, | |
ha="left", va='center', fontsize=font_size) | |
for label in pannel.xaxis.get_ticklabels(): | |
label.set_visible(False) | |
for label in pannel.yaxis.get_ticklabels(): | |
label.set_visible(False) | |
def plt_pannel_table(pannel, text_content, table_labels,table_font_size, table_scale): | |
# yeji_list = ['单季度营收', '03-31', '06-30', '09-30', '12-31', '单季度净利润', '03-31', '06-30', '09-30', '12-31', '12-31'] | |
yeji_table = pannel.table( | |
cellText=text_content, # 表格中内容 | |
colLabels=table_labels, # 表格的列标签 | |
cellLoc='left', # 单元格对齐方式 | |
loc='center', | |
fontsize=30) # 表格中字体大小 | |
yeji_table.auto_set_font_size(False) | |
yeji_table.set_fontsize(table_font_size) | |
yeji_table.scale(1, table_scale) # 调整表格行高 | |
for label in pannel.xaxis.get_ticklabels(): | |
label.set_visible(False) | |
for label in pannel.yaxis.get_ticklabels(): | |
label.set_visible(False) | |
def image_Splicing(img_1, img_2, flag='y',filename=None): | |
img1 = Image.open(img_1) | |
img2 = Image.open(img_2) | |
size1, size2 = img1.size, img2.size | |
if flag == 'x': | |
joint = Image.new("RGB", (size1[0] + size2[0], size1[1])) | |
loc1, loc2 = (0, 0), (size1[0], 0) | |
else: | |
joint = Image.new("RGB", (size1[0], size2[1]+size1[1])) | |
loc1, loc2 = (0, 0), (0, size1[1]) | |
joint.paste(img1, loc1) | |
joint.paste(img2, loc2) | |
if filename: | |
save_path="/tmp/"+filename | |
joint.save(save_path) | |
return save_path | |
return None | |
def onepice(): | |
plt.clf() | |
# 正确显示中文和负号 | |
plt.rcParams["font.sans-serif"] = ["SimHei"] | |
plt.rcParams["axes.unicode_minus"] = False | |
fig = plt.figure( # 添加fig对象 | |
figsize=(16, 9), # 设置fig大小,长和宽,单位为英寸 | |
dpi=50, # 每英寸的像素点数 | |
facecolor="white") | |
gs = fig.add_gridspec( | |
3, 1, # 9行1列的网格 | |
left=0.01, right=0.96, bottom=0.03, top=0.99, # 设置页边距 | |
wspace=0.02, hspace=0.12, # 设置行与行之间的距离,列与列之间的距离 | |
height_ratios=[0.3, 0.45,0.15]) # 这边是9行,设置每行占的高度的比例 | |
# 添加文字说明 | |
pannel1 = fig.add_subplot(gs[0, 0]) | |
plt_pannel_text(pannel1, "title:\n\nhello world", 50) | |
# 添加表格 | |
pannel2 = fig.add_subplot(gs[1, 0]) | |
plt_pannel_table(pannel2, [["xxx","1%",123],["xxx","2%",423],["xxx","2%",523]],["前十用户充值排名(当日)","占比(当日)","金额(元)"], 46,9.5) | |
# # 添加登录汇总 | |
# pannel2 = fig.add_subplot(gs[1, 0]) | |
# login_hour_data = get_login_count_hour() | |
# login_hour_val = login_hour_data["value"] | |
# login_title = login_hour_data["name"] | |
# login_x = [] | |
# login_y = [] | |
# for i in login_hour_val: | |
# login_x.append(i[0]) | |
# login_y.append(i[1]) | |
# x_label = "日期:{}".format("2023-06-06") | |
# plt_pannel_graph_line(pannel2, login_x,login_y,login_title,x_label,"登录人数") | |
# # 添加充值汇总 | |
# pannel3 = fig.add_subplot(gs[2, 0]) | |
# order_detail = get_pay_order_hour() | |
# order_val = order_detail["value"] | |
# pay_hour_val = order_detail["value"] | |
# pay_title = order_detail["name"] | |
# pay_x = [] | |
# pay_y = [] | |
# for i in pay_hour_val: | |
# pay_x.append(i[0]) | |
# pay_y.append(i[1]) | |
# orders = [] | |
# for order in order_val: | |
# orders.append(order[1]) | |
# pay_sum = sum(pay_y) | |
# y_label = "充值额" | |
# y2_label = "订单数" | |
# x_title = "{} ,∑ = {}".format(x_label,pay_sum) | |
# plt_pannel_graph_duiji(pannel3, pay_x,pay_y,orders,pay_title,x_title,y_label,y2_label) | |
# 8、留白,待后续补充 | |
pannel_empty = fig.add_subplot(gs[1, 0]) | |
pannel_empty.text(0.01, 0.5, '====', | |
ha="left", va='center', fontsize='100') | |
filename="huizong.jpg" | |
save_dir = "/tmp/" | |
out = None | |
if not os.path.exists(save_dir): | |
print("[warning] file save dir not exists") | |
else: | |
filepath = save_dir + filename | |
print("[info] will save file to:",filepath) | |
plt.savefig(filepath) | |
out = filepath | |
plt.close() | |
return {'out':out,'dir':save_dir,'filename':filename} | |
def zhoubao(): | |
date_time = time.strftime("%Y-%m-%d", time.localtime()) | |
notice_msg = '## 每周总结 \n\n > 今天是周五,笑容多灿烂。亲人天天盼,相伴周末玩。工作抓紧干,效率翻一番' | |
#toparty = "22" | |
file_dir = '/root/' | |
src_file = "/root/workweek.xlsx" | |
to_file_name = "工作周报"+"-"+date_time+".xlsx" | |
to_file = file_dir + to_file_name | |
if os.path.exists(to_file): | |
print("already exists") | |
else: | |
print("copy file ") | |
#shutil.copyfile(src_file,to_file) | |
target = ["@all"] | |
qy = qywx(0) | |
qy.send_markdown(notice_msg,target) | |
#media_id = qy.post_file(file_dir,to_file_name) | |
#qy.send_file(media_id,target) | |
''' | |
查询应用信息 | |
''' | |
def get_app_info(app_ids): | |
ids = ','.join(str(i) for i in app_ids) | |
sql = "SELECT a_appid,a_pn,a_appname,a_channel from tb_app where a_appid in ({});".format(ids) | |
db = DBUtil(db="db_common_info",host="10.8.18.108") | |
db.db_connect() | |
data = db.db_sql('SELECT',sql) | |
return data | |
''' | |
5个日新增超过100的渠道,异常情况监测,及时了解渠道下架或不外显 | |
任意渠道2个小时内新增 = 0 | |
''' | |
def userRegisterException(minNum): | |
app_ids = [386,413,429,407,365] | |
app_data_list = get_app_info(app_ids) | |
exception_list = [] | |
for app_data in app_data_list: | |
app_id = app_data[0] | |
app_pn = app_data[1] | |
app_name = app_data[2] | |
app_channel = app_data[3] | |
querySql = "SELECT COUNT(1) as num FROM tb_account WHERE regDate>=UNIX_TIMESTAMP(NOW())-7200 AND channel={};".format(app_channel) | |
db = DBUtil(db="zhuoyigame",host="10.8.18.108") | |
db.db_connect() | |
data = db.db_sql('SELECT',querySql) | |
count_num = 0 | |
for i in data: | |
count_num = i[0] | |
if count_num <= minNum : | |
# 添加到数组异常数组中 | |
notice = "*** 应用ID:{} 应用名称:{} 指标值:{} \n".format(app_id,app_name,count_num) | |
exception_list.append(notice) | |
return exception_list | |
''' | |
7个日活超过1000的渠道,登录异常情况监测(除维护),与现有短信提醒机制不同,防止某个渠道长时间无法登录 | |
''' | |
def userLoginException(minNum): | |
app_ids = [386,413,429,407,365,385,351] | |
app_data_list = get_app_info(app_ids) | |
exception_list = [] | |
for app_data in app_data_list: | |
app_id = app_data[0] | |
app_pn = app_data[1] | |
app_name = app_data[2] | |
app_channel = app_data[3] | |
querySql = "SELECT COUNT(1) as num FROM tb_account WHERE lastLogin>=UNIX_TIMESTAMP(NOW())-1800 AND channel={};".format(app_channel) | |
db = DBUtil(db="zhuoyigame",host="10.8.18.108") | |
db.db_connect() | |
data = db.db_sql('SELECT',querySql) | |
count_num = 0 | |
for i in data: | |
count_num = i[0] | |
if count_num <= minNum : | |
# 添加到数组异常数组中 | |
notice = "*** 应用ID:{} 应用名称:{} 指标值:{} \n".format(app_id,app_name,count_num) | |
exception_list.append(notice) | |
return exception_list | |
''' | |
充值异常情况监测,防止长时间无法充值 | |
30分钟内充值成功金额 = 0 | |
''' | |
def userPayException(): | |
# pay_notice = "" | |
querySql = "SELECT COUNT(1) as num FROM tb_account WHERE lastPayTime>=UNIX_TIMESTAMP(NOW())-1800;" | |
db = DBUtil(db="zhuoyigame",host="10.8.18.108") | |
db.db_connect() | |
data = db.db_sql('SELECT',querySql) | |
count_num = 0 | |
for i in data: | |
count_num = i[0] | |
# if count_num <=0 : | |
# pay_notice = "充值异常" | |
return count_num | |
''' | |
获取三人斗地主和四人斗地主的在线人数 | |
''' | |
def getOnlineDDZ3And4(): | |
data = totalGameOnline(online_metrics_urls,["admin_stats","game-chat"]) | |
target = ["game-lzddz4-pt","game-ddz-bs","game-ddz4-pt","game-ddz4-bxp","game-ddz4-hb","game-ddz3-pt","game-ddz3-bxp","game-ddz3-hb"] | |
online = 0 | |
for name in data: | |
if name in target: | |
online = online + data[name] | |
return online | |
''' | |
后台“平台管理 - 注册权重管理”,包含的全部设备号或IP | |
2小时内,有新注册账号 | |
''' | |
def getManageNewUser(): | |
queryIPSQL = "SELECT fb_obj from tb_forbid_weight WHERE fb_type = 1;" | |
queryIMEISQL = "SELECT fb_obj from tb_forbid_weight WHERE fb_type = 2;" | |
common_db = DBUtil(db="db_common_info",host="10.8.18.108") | |
common_db.db_connect() | |
dataIps = common_db.db_sql('SELECT', queryIPSQL) | |
common_db.db_connect() | |
dataImeis = common_db.db_sql('SELECT', queryIMEISQL) | |
listIps = [] | |
listImeis = [] | |
# count_num = 0 | |
for dataIp in dataIps: | |
listIps.append(dataIp[0]) | |
for dataImei in dataImeis: | |
listImeis.append(dataImei[0]) | |
authen_db = DBUtil(db="db_authen_zy",host="10.8.18.108") | |
newAccountIdsFromLimitIp = [] | |
newAccountidsFromImei = [] | |
if len(listIps) > 0 : | |
limitData = ",".join("\"{}\"".format(i) for i in listIps) | |
sql = "SELECT a_uid FROM `db_authen_zy`.`tb_account` WHERE a_login_ip in ({}) AND a_reg_time >= UNIX_TIMESTAMP(NOW())-7200;".format(limitData) | |
authen_db.db_connect() | |
res = authen_db.db_sql('SELECT',sql) | |
for uinfo in res: | |
newAccountIdsFromLimitIp.append(uinfo[0]) | |
if len(listImeis) > 0 : | |
limitData = ",".join("\"{}\"".format(i) for i in listImeis) | |
sql = "SELECT a_uid FROM `db_authen_zy`.`tb_account` WHERE a_imei in ({}) AND a_reg_time >= UNIX_TIMESTAMP(NOW())-2592000;".format(limitData) | |
authen_db.db_connect() | |
authen_db.db_sql('SELECT',sql) | |
for uinfo in res: | |
newAccountidsFromImei.append(uinfo[0]) | |
return (newAccountIdsFromLimitIp,newAccountidsFromImei) | |
def bizReg(): | |
target = ["@all"] | |
val = 1 | |
datalist = userRegisterException(val) | |
if len(datalist) > 0: | |
qy = qywx(0) | |
msg = "## 业务异常 ## \n\n" | |
msg = msg + "渠道新增异常 <= {} \n\n".format(val) | |
msg = msg + '\n'.join(datalist) | |
qy.send_text(msg,target) | |
def bizLogin(): | |
# print(userLoginException(100)) | |
target = ["@all"] | |
val = 1 | |
datalist = userLoginException(val) | |
if len(datalist) > 0: | |
qy = qywx(0) | |
msg = "## 业务异常 ## \n\n" | |
msg = msg + "渠道登陆异常 <={} \n\n".format(val) | |
msg = msg + '\n'.join(datalist) | |
qy.send_text(msg,target) | |
def bizPay(): | |
payuserSize = userPayException() | |
target = ["@all"] | |
val = 1 | |
if payuserSize <= val: | |
qy = qywx(0) | |
msg = "## 业务异常 ## \n\n" | |
msg = msg + "平台充值异常 充值人数: {} <= {}".format(payuserSize, val) | |
qy.send_text(msg,target) | |
def bizDdz(): | |
gameUserOnlineSize = getOnlineDDZ3And4() | |
target = ["@all"] | |
val = 10 | |
if gameUserOnlineSize <= val: | |
qy = qywx(0) | |
msg = "## 业务异常 ## \n\n" | |
msg = msg + "游戏场次异常 人数: {} <= {}".format(gameUserOnlineSize, val) | |
qy.send_text(msg,target) | |
def bizGlyh(): | |
manageUsers = getManageNewUser() | |
manageUserIp = manageUsers[0] | |
manageUserImei = manageUsers[1] | |
target = ["@all"] | |
# target = ["22"] | |
msg = "## 业务关注 ## \n\n" | |
ipUsers = len(manageUserIp) | |
imeiUsers = len(manageUserImei) | |
if ipUsers > 0: | |
uids = "\n".join(str(i) for i in manageUserIp) | |
msg = "{} 后台监控IP有新注册账号:\n {} \n".format(msg, uids) | |
if imeiUsers > 0: | |
uids = "\n".join(str(i) for i in manageUserImei) | |
msg = "{} 后台监控设备号有新注册账号:\n {} \n".format(msg, uids) | |
if (ipUsers + imeiUsers) > 0: | |
qy = qywx(0) | |
qy.send_text(msg,target,"22") | |
#生成xlsx文件的函数 | |
def retxls(ret,dt,title): | |
dir="/root/query/" | |
basename = dt + datetime.datetime.now().strftime("%Y%m%d%H%M")+ ".xlsx" | |
filename = dir + basename | |
dret = pd.DataFrame.from_records(list(ret)) | |
dret.style.set_properties(**{'border': '1px solid black'}) | |
###z注意openpyxl这个库可能在生成xls的时候出错,pip install openpyxls==1.8.6,其他版本似乎与pandas有点冲突,安装1.8.6的即可 | |
dret.to_excel(filename,"Sheet1",engine="openpyxl",header=title,index=False) | |
print ("Ok!!! the file in",filename) | |
return basename | |
''' | |
屏蔽字异常报警 | |
''' | |
def bizPbz(): | |
#targetKeyWords=["毛泽东","朱德","周恩来","刘少奇","任弼时","陈云","宋庆龄","李济深","张澜","高岗","邓小平","林彪","董必武","陶铸","陈伯达","康生","李富春","王洪文","叶剑英","李德生","张春桥","华国锋","李先念","汪东兴","赵紫阳","胡耀邦","乌兰夫","彭真","邓颖超","乔石","胡启立","姚依林","杨尚昆","万里","李鹏","王震","江泽民","宋平","李瑞环","朱镕基","刘华清","胡锦涛","荣毅仁","尉健行","李岚清","吴邦国","温家宝","贾庆林","曾庆红","黄菊","吴官正","李长春","罗干","贺国强","周永康","习近平","李克强","张德江","俞正声","刘云山","王岐山","张高丽","栗战书","汪洋","王沪宁","赵乐际","韩正"] | |
sql = "SELECT * FROM tb_pbz_record WHERE timestamp >= UNIX_TIMESTAMP(NOW())-1800 and level>=1;" | |
db = DBUtil(db="db_common_info",host="10.8.18.108") | |
db.db_connect() | |
data = db.db_sql('SELECT',sql) | |
if len(data)>0: | |
title = ("序号","应用名称","公司名称","用户昵称","UID","拦截测试样本","场景(评论、昵称等)","发布时间","最近一次登录日志(含源端口号)","应用登录方式"); | |
matrix = list(data) | |
retsLevel1 = [] | |
retsLevel2 = [] | |
for item in matrix: | |
# print(item) | |
dbkey=item[0] | |
uid=item[1] | |
#content=item[2] | |
content="******" | |
timestamp=item[4] | |
username=item[5] | |
sceneType=item[6] | |
loginSource=item[7] | |
loginType=item[8] | |
level=item[9] | |
scene=sceneType | |
# print(scene) | |
if not loginSource: | |
loginSource = "Unknown" | |
if not loginType: | |
loginType = "Unknown" | |
timeArray = time.localtime(timestamp) | |
sendTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) | |
if sceneType=="sign": | |
scene = "修改签名" | |
if sceneType=="changeName": | |
scene = "修改昵称" | |
if loginType == "user": | |
loginType = "渠道账号" | |
if loginType == "third": | |
loginType = "联运账号" | |
if loginType == "mobile": | |
loginType = "手机号码" | |
if loginType == "wechat": | |
loginType = "微信号" | |
# print(level) | |
tupleItem=(dbkey,"卓毅四人斗地主","卓毅(上海)网络技术有限公司",username,uid,content,scene,sendTime,loginSource,loginType) | |
#target = ["22"] | |
target = ["@all"] | |
if level==1 : | |
retsLevel1.append(tupleItem) | |
if level==2 : | |
retsLevel2.append(tupleItem) | |
ret1=tuple(retsLevel1) | |
ret2=tuple(retsLevel2) | |
qy = qywx(0) | |
if len(ret1) > 0: | |
print(ret1) | |
main_file = retxls(ret1,"一级屏蔽字",title); | |
media_id = qy.post_file("/root/query/",main_file) | |
qy.send_file(media_id,target) | |
if len(ret2) > 0: | |
print(ret2) | |
main_file = retxls(ret2,"二级屏蔽字",title); | |
media_id = qy.post_file("/root/query/",main_file) | |
qy.send_file(media_id,target) | |
# qy = qywx(0) | |
# qy.send_text("触发二级屏蔽字",target,"22") | |
pass | |
now = datetime.datetime.now() | |
weekday = now.weekday() | |
week_val = weekday + 1 | |
# 调用示例 | |
if __name__ == '__main__': | |
argc = len( sys.argv ); | |
if argc < 2: | |
print("not exists args") | |
sys.exit() | |
command = sys.argv[1]; | |
if command == "zhibiao": | |
zhibiao() | |
elif command == "liuyan": | |
liuyan() | |
elif command == "online": | |
print(getOnlineStrSimple()) | |
elif command == "online2": | |
print(getOnlineStr()) | |
elif command == "one": | |
print(onepice()) | |
elif command == "hetu": | |
print(image_Splicing("/tmp/login_hour_1685646002.jpg","/tmp/pay_hour_1685350803.jpg","y","hetu.jpg")) | |
elif command == "ribao": | |
if week_val == 5: | |
zhoubao() | |
else: | |
ribao() | |
elif command == "bizReg" : | |
bizReg() | |
elif command == "bizLogin" : | |
bizLogin() | |
elif command == "bizPay" : | |
bizPay() | |
elif command == "bizDdz" : | |
bizDdz() | |
elif command == "bizGlyh" : | |
bizGlyh() | |
elif command == "bizPbz" : | |
bizPbz() | |
else: | |
print(f"\n[ Error] 未知参数:{command},请检查。") |
正文完