This commit is contained in:
nicemoe
2021-04-28 21:48:43 +08:00
parent 94c38aec47
commit f294e31679
18 changed files with 2120 additions and 0 deletions

View File

@ -0,0 +1,62 @@
# -*- coding: utf-8 -*
"""
@Software : PyCharm
@File : __init__.py
@Author : 梦影
@Time : 2021/04/27 22:22:42
"""
from plugin.wsclient.content import wsHandler
from plugin.common import bot
from nonebot.log import logger
import websockets
import asyncio
import json
@bot.on_startup
async def init():
asyncio.ensure_future(ws_connect())
async def ws_connect():
count = 0
while True:
try:
uri = "wss://socket.nicemoe.cn"
ws = await websockets.connect(uri)
logger.critical(f'WebSocket > 建立连接成功!')
setattr(bot, 'wsClient', ws)
asyncio.ensure_future(ws_task())
return
except ConnectionRefusedError as echo: # 捕获错误
logger.critical(f"WebSocket > [{count}] {echo}")
if count == 30: # 重连次数
return
count += 1
logger.critical(f"WebSocket < [{count}] 开始尝试向 WebSocket 服务端建立连接!")
await asyncio.sleep(5) # 重连间隔
async def ws_task(): # WebSocket 任务分发函数
handler = wsHandler()
hold = {
2001: handler.status,
2002: handler.news,
2003: handler.serendipity,
}
try:
while True:
data = await bot.wsClient.recv() # 循环接收
logger.debug(f"WebSocket > {data}")
data = json.loads(data)
if data['type'] not in hold.keys():
continue
asyncio.ensure_future(hold[data['type']](data)) # 创建任务
except (websockets.exceptions.ConnectionClosedError, websockets.exceptions.ConnectionClosedOK) as echo: # 捕获错误
if echo.code == 1006:
logger.error('WebSocket > 连接已断开!') # 服务端内部错误
asyncio.ensure_future(ws_connect()) # 重新连接
else:
logger.error('WebSocket > 连接被关闭!') # 服务端主动关闭

77
plugin/wsclient/config.py Normal file
View File

@ -0,0 +1,77 @@
# -*- coding: utf-8 -*
"""
@Software : PyCharm
@File : config.py
@Author : 梦影
@Time : 2021/04/27 22:23:04
"""
from plugin.common import robot, bot, common
import random
class extend:
@staticmethod
async def server(value): # 检查用户群已绑定服务器
sql = "SELECT * FROM main WHERE Value = %s"
data = await bot.client.query(sql, value)
if not data:
return None
data = await common.next(data)
return data['Main']
@staticmethod
async def serendipityList(name, dwTime, serendipity): # 奇遇播报发送格式
sendList = [
f"{name}{dwTime} 带着 {serendipity} 跑惹!",
f"{serendipity}{dwTime}{name} 抱走惹!",
f"{name} 带着 {serendipity}{dwTime} 跑惹!",
f"{serendipity}{name}{dwTime} 抱走惹!",
f"{dwTime} {serendipity}{name} 抱走惹!",
f"{name} 抱着 {serendipity}{dwTime} 走惹!",
f"{serendipity}{dwTime}{name} 抱走惹!",
f"{name}{dwTime} 触发了 {serendipity}",
f"{name}{dwTime} 带走了 {serendipity}",
f"{serendipity}{dwTime}{name} 触发了",
f"{serendipity}{dwTime} 卒于 {name}",
f"{serendipity}{dwTime} 跟着 {name} 跑惹",
]
return random.choice(sendList)
class send:
@staticmethod
async def status(value: int, server, message): # 发送开服信息 # 监控模块
group_list = await robot.group_list(self_id=value)
for group_data in group_list:
sever = await extend.server(group_data['group_id'])
if sever == server and not await common.token(group_data['group_id']):
await robot.group_send(self_id=value, group_id=group_data['group_id'], message=message)
@staticmethod
async def news(value, message):
group_list = await robot.group_list(self_id=value)
for group_data in group_list:
switch = await common.table('switch', 'Value', group_data['group_id'], 'news') # 读取开关
if switch and not await common.token(group_data['group_id']): # 如果开关打开且群已授权
await robot.group_send(self_id=value, group_id=group_data['group_id'], message=message)
@staticmethod
async def serendipity(value, server, name, dwTime, serendipity): # 解析奇遇播报数据
group_list = await robot.group_list(self_id=value)
for group_data in group_list:
switch = await common.table('switch', 'Value', group_data['group_id'], 'scheduler')
sever = await extend.server(group_data['group_id'])
if switch and sever == server and not await common.token(group_data['group_id']):
await robot.group_send(self_id=value, group_id=group_data['group_id'],
message=await extend.serendipityList(name, dwTime, serendipity))
@staticmethod
async def quake(value, message):
group_list = await robot.group_list(self_id=value)
for group_data in group_list:
switch = await common.table('switch', 'Value', group_data['group_id'], 'quake')
if switch and not await common.token(group_data['group_id']):
await robot.group_send(self_id=value, group_id=group_data['group_id'],
message=message)

View File

@ -0,0 +1,46 @@
# -*- coding: utf-8 -*
"""
@Software : PyCharm
@File : content.py
@Author : 梦影
@Time : 2021/04/27 22:23:08
"""
from plugin.wsclient.config import extend, send
from plugin.common import bot
from nonebot.log import logger
import asyncio
import time
class wsHandler:
@staticmethod
async def status(data):
data = data['data']
sql = "UPDATE `status` SET `status` = %s WHERE `server` = %s"
await bot.client.execute(sql, (data['status'], data['server']))
status = {0: "维护", 1: "开服"}
result = f"{data['server']}{time.strftime('%H:%M:%S', time.localtime(time.time()))} {status[data['status']]}惹!"
logger.info(result)
for value in bot.config.ROBOT_LIST:
asyncio.ensure_future(send.status(value, data['server'], result))
await asyncio.sleep(0.1)
@staticmethod
async def news(data):
data = data['data']
result = f"{data['type']}来惹\n标题:{data['title']}\n链接:{data['url']}\n日期:{data['date']}"
logger.info(result)
for value in bot.config.ROBOT_LIST:
asyncio.ensure_future(send.news(value, result))
await asyncio.sleep(0.1)
@staticmethod
async def serendipity(data):
data = data['data']
dwTime = time.strftime("%H:%M", time.localtime(data['time']))
logger.info(await extend.serendipityList(data['name'], dwTime, data['serendipity']))
for value in bot.config.ROBOT_LIST: # 开始发送消息
asyncio.ensure_future(send.serendipity(value, data['server'], data['name'], dwTime, data['serendipity']))
await asyncio.sleep(0.1)