nicemoe 4 years ago
parent 94c38aec47
commit f294e31679
  1. 23
      bot.py
  2. 47
      config.py
  3. 103
      plugin/admin.py
  4. 169
      plugin/common.py
  5. 316
      plugin/content/__init__.py
  6. 52
      plugin/content/config.py
  7. 667
      plugin/content/content.py
  8. 94
      plugin/database.py
  9. 120
      plugin/dict.py
  10. 43
      plugin/member.py
  11. 73
      plugin/random/__init__.py
  12. 29
      plugin/random/config.py
  13. 61
      plugin/random/content.py
  14. 30
      plugin/scheduler.py
  15. 108
      plugin/superuser.py
  16. 62
      plugin/wsclient/__init__.py
  17. 77
      plugin/wsclient/config.py
  18. 46
      plugin/wsclient/content.py

@ -0,0 +1,23 @@
# -*- coding: utf-8 -*
"""
@Software : PyCharm
@File : bot.py
@Author : 梦影
@Time : 2021/04/25 19:28:39
"""
from os import path
import nonebot
import config
nonebot.init(config)
nonebot.load_plugins(
path.join(path.dirname(__file__), 'plugin'),
'plugin'
)
bot = nonebot.get_bot()
app = bot.asgi
if __name__ == '__main__':
nonebot.run()

@ -0,0 +1,47 @@
# -*- coding: utf-8 -*
"""
@Software : PyCharm
@File : config.py
@Author : 梦影
@Time : 2021/04/25 19:28:51
"""
from nonebot.default_config import *
from datetime import timedelta
HOST = '0.0.0.0' # NoneBot 的 HTTP 和 WebSocket 服务端监听的 IP/主机名。
PORT = 1888 # NoneBot 的 HTTP 和 WebSocket 服务端监听的端口。
DEBUG = False # 是否以调试模式运行,生产环境需要设置为 False 以提高性能。
SUPERUSERS = {22282320, 3321056200} # 超级用户的 QQ 号,用于命令的权限检查。
NICKNAME = {'萌萌'} # 机器人的昵称,用于辨别用户是否在和机器人说话。
COMMAND_START = {'', '/', '!', '', ''} # 命令的起始标记,用于判断一条消息是不是命令。
ACCESS_TOKEN = '' # 需要和 CQHTTP 插件的配置中的 access_token 相同。
COMMAND_SEP = {'.'} # 命令的分隔标记,用于将文本形式的命令切分为元组(实际的命令名)。
SESSION_RUN_TIMEOUT = timedelta(seconds=10) # 命令会话的运行超时时长,超时后会话将被移除,命令处理函数会被异常所中断。此时用户可以调用新的命令,开启新的会话。None 表示不超时。
SHORT_MESSAGE_MAX_LENGTH = 50 # 短消息的最大长度。默认情况下(only_short_message 为 True),自然语言处理器只会响应消息中纯文本部分的长度总和小于等于此值的消息。
SESSION_RUNNING_EXPRESSION = '很抱歉,有故障惹!' # 当有命令会话正在运行时,给用户新消息的回复。
ROBOT_LIST = [15853655, 256865536, 1938255364, 536069770] # 已连接 NoneBot 的机器人 QQ 号,用于主动推送消息。
ROBOT_EXIT_TIME = 7 # 已授权 QQ群 到期后退群时间(天)。
RANDOM_MAX_VALUE = 2 # NoneBot 随机文字(骚话)、语音(骚话) 触发几率。
NLPCHAT_MAX_VALUE = 3 # NoneBot 随机聊天 触发几率。
SMS_PHONE = 18500000000 # BOT掉线后接收短信通知的号码
NLPCHAT_APPID = 1000000000 # 腾讯AI 开放平台 智能闲聊 的 APPID,请勿开启画像,用于智能聊天。(留空可能会报错)
NLPCHAT_APPKEY = '' # 腾讯AI 开放平台 智能闲聊 的 APPKEY,请勿开启画像,用于智能聊天。(留空可能会报错)
ALIYUN_APPKEY = '' # 阿里云 智能语音交互 的 APPKEY 用于语音合成(留空可能会报错)
ALIYUN_ACCESS = '' # 阿里云 智能语音交互 的 ACCESS 用于语音合成(留空可能会报错)
ALIYUN_SECRET = '' # 阿里云 智能语音交互 的 SECRET 用于语音合成(留空可能会报错)
DATA_DOMAIN = 'https://www.jx3api.com' # NoneBot 功能数据 API 地址
EXPLAIN_URL = 'https://docs.qq.com/doc/DTEhJTUZNeUJHY2Ni?pub=1&dver=2.1.0' # 使用说明链接,推荐腾讯在线文档
MYSQL_CONFIG = { # NoneBot 数据记录配置。
'host': '127.0.0.1', # 连接主机名。
'user': 'root', # 用户账号
'password': 'ret.content', # 用户密码
'db': 'nonebot', # 数据库名
'port': 3306, # 连接端口
'charset': 'utf8', # 数据编码
'minsize': 10, # 连接池最小值
'maxsize': 20, # 连接池最大值
'autocommit': True, # 自动提交模式
}

@ -0,0 +1,103 @@
# -*- coding: utf-8 -*
"""
@Software : PyCharm
@File : admin.py
@Author : 梦影
@Time : 2021/04/26 18:04:47
"""
from nonebot.permission import SUPERUSER, GROUP_OWNER, GROUP_ADMIN
from nonebot import CommandSession, on_command
from plugin.common import bot, common
from nonebot.log import logger
import time
@on_command('查询授权', aliases='查看授权', permission=SUPERUSER | GROUP_OWNER | GROUP_ADMIN, only_to_me=False)
async def authorization(session: CommandSession):
sql = "SELECT * FROM main WHERE Value = %s"
data = await bot.client.query(sql, (await common.value(session)))
if data:
data = await common.next(data)
dwTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(data['Relet']))
if data['Relet'] > time.time():
status = '正常'
else:
status = '过期'
result = f"{list(bot.config.NICKNAME)[0]}·查询授权\n群号:{await common.value(session)}\n过期:{dwTime}\n状态:{status}"
else:
result = "该群未被正式授权,请通过正规渠道购买使用!"
logger.info(result)
await session.send(result)
@on_command('设置欢迎语', permission=SUPERUSER | GROUP_OWNER | GROUP_ADMIN, only_to_me=False)
async def setup_welcome(session: CommandSession):
content = str(session.ctx['message'])[6:]
content = content.replace('[', '[').replace(']', ']')
if not await common.token(await common.value(session)):
if not content:
result = "请输入欢迎语!"
else:
sql = "UPDATE switch SET member = %s WHERE Value = %s;"
await bot.client.execute(sql, (content, await common.value(session)))
result = "设置欢迎语成功!"
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('删除欢迎语', permission=GROUP_OWNER | SUPERUSER | GROUP_ADMIN, only_to_me=False)
async def del_welcome(session: CommandSession):
if not await common.token(await common.value(session)):
sql = "SELECT * FROM switch WHERE value = %s"
data = await bot.client.query(sql, await common.value(session))
data = await common.next(data)
if not data['member']:
result = "本群未设置欢迎语!"
else:
sql = "UPDATE switch SET member = %s WHERE Value = %s"
await bot.client.execute(sql, (None, await common.value(session)))
result = "删除欢迎语成功!"
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
funcList = {'官方资讯': 'news', '撩人模式': 'random', '奇遇玩法': 'reward', '游戏功能': 'player', '自由聊天': 'nlpchat',
'奇遇播报': 'scheduler'}
@on_command('开启', permission=GROUP_OWNER | SUPERUSER | GROUP_ADMIN, only_to_me=False)
async def open_func(session: CommandSession):
content = await common.subtext(session)
if not await common.token(await common.value(session)):
if content[0] in funcList.keys():
sql = f"UPDATE switch SET {funcList[content[0]]} = %s WHERE Value = %s;"
await bot.client.execute(sql, (1, await common.value(session)))
result = f"{content[0]} 开启成功!"
else:
result = f"找不到 {content[0]} 的开关!"
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('关闭', permission=GROUP_OWNER | SUPERUSER | GROUP_ADMIN, only_to_me=False)
async def open_func(session: CommandSession):
content = await common.subtext(session)
if not await common.token(await common.value(session)):
if content[0] in funcList.keys():
sql = f"UPDATE switch SET {funcList[content[0]]} = %s WHERE Value = %s;"
await bot.client.execute(sql, (0, await common.value(session)))
result = f"{content[0]} 关闭成功!"
else:
result = f"找不到 {content[0]} 的开关!"
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)

@ -0,0 +1,169 @@
# -*- coding: utf-8 -*
"""
@Software : PyCharm
@File : common.py
@Author : 梦影
@Time : 2021/04/25 19:30:09
"""
from plugin.dict import serverList, flowerList, sectList, serendipityList
from aiocqhttp import ActionFailed, ApiNotAvailable
from plugin.database import MySql, MySqlInit
from aiocqhttp.message import Message
from aiohttp import ClientSession
from nonebot.log import logger
from nonebot import get_bot
import asyncio
import json
import time
bot = get_bot()
BOT = bot.config
class common:
@staticmethod
async def tencent(arg): # CQ:QQ # 公共模块
arg_as_msg = Message(arg)
return [s.data['qq'] for s in arg_as_msg if s.type == 'at']
@staticmethod
async def subtext(session): # 获取参数组
return session.current_arg_text.split()
@staticmethod
async def value(session): # 获取来源群号
return session.ctx['group_id']
@staticmethod
async def token(value): # 判断是否被授权
sql = 'SELECT * FROM `main` WHERE `Value` = %s'
data = await bot.client.query(sql, value)
if not data:
return "该群未被正式授权,请通过正常渠道购买使用!"
base = await common.next(data)
if base['Relet'] > int(time.time()):
result = False
else:
result = "该群已过期,请尽快续费恢复服务!"
return result
@staticmethod
async def next(data: list): # 下一条数据
for item in data:
return item
@staticmethod
async def table(Table, FieldName, FieldValue, Value): # 自定义查询数据库数据 # 公共模块
sql = f"SELECT * FROM `{Table}` WHERE `{FieldName}` = '{FieldValue}'"
data = await bot.client.query(sql)
if data:
data = await common.next(data)
return data[Value]
return None
# 网页访问
class submit:
@staticmethod
async def connect(url: str, data=None, headers=None, timeout=10): # POST
async with ClientSession() as session:
async with session.post(url=url, data=data, headers=headers, timeout=timeout) as data:
result = await data.text()
data.close()
return await submit.data(result)
@staticmethod
async def content(url: str, params=None, headers=None, timeout=10): # GET
async with ClientSession() as session:
async with session.get(url=url, params=params, headers=headers, timeout=timeout) as data:
result = await data.text()
data.close()
return await submit.data(result)
@staticmethod
async def sms(tencent: int): # 发送短信通知
data = {"phone": BOT.SMS_PHONE, "tencent": tencent}
result = await submit.connect(url=f"{bot.domain}/qcloud/app.php", data=data)
if not result['result']:
logger.info("发送短信成功!")
else:
logger.info("发送短信失败!")
bot.status[tencent] = 0
@staticmethod
async def data(text):
try:
result = json.loads(text)
except ValueError:
return text
return result
# 机器人操作
class robot:
@staticmethod
async def group_list(self_id: int): # 获取群列表
result = list()
try:
result = await bot.get_group_list(self_id=self_id)
if bot.status[self_id] == 0:
bot.status[self_id] = 1
except ApiNotAvailable:
logger.error(f"请求群信息'{self_id}'有问题惹!")
if bot.status[self_id] == 1:
asyncio.ensure_future(submit.sms(self_id)) # 发送短信
return result
@staticmethod
async def group_send(self_id: int, group_id, message): # 发送群消息
try:
await bot.send_group_msg(self_id=self_id, group_id=group_id, message=message)
except ActionFailed:
logger.error(f"发送群消息'{group_id}'有问题惹!")
@staticmethod
async def event(event, content): # 发送事件消息
try:
await bot.send(event, content)
except ActionFailed:
logger.error(f"发送群消息'{event['group_id']}有问题惹!")
@staticmethod
async def sender(session): # 发送人名称
if "sender" not in session.keys():
if not session.ctx['sender']['card']:
return session.ctx['sender']['nickname']
return session.ctx['sender']['card']
else:
if not session['sender']['card']:
return session['sender']['nickname']
return session['sender']['card']
class static:
@staticmethod
async def data(data, value): # 检索服务器,花价,心法,奇遇数据
if data == 0:
return value['Main']
m = {1: serverList, 2: flowerList, 3: sectList, 4: serendipityList}
result = None
for k, v in m[data].items():
if value in v:
result = k
return result
@bot.on_startup
async def init(): # 初始化
connect = MySql()
pool = await connect.initpool(BOT)
connect.pool = pool
setattr(bot, 'status', dict())
setattr(bot, 'client', connect)
setattr(bot, 'domain', BOT.DATA_DOMAIN)
for x in BOT.ROBOT_LIST:
bot.status[x] = 0
asyncio.ensure_future(MySqlInit(bot, serverList))

@ -0,0 +1,316 @@
# -*- coding: utf-8 -*
"""
@Software : PyCharm
@File : __init__.py
@Author : 梦影
@Time : 2021/04/26 20:21:12
"""
from nonebot.permission import SUPERUSER, GROUP_OWNER, GROUP_ADMIN, GROUP_MEMBER
from nonebot import on_command, CommandSession, aiocqhttp
from plugin.common import robot, bot, common
from plugin.content.content import seasun
from nonebot.log import logger
@on_command('日常', aliases=('日常查询', '查询日常'), permission=GROUP_MEMBER, only_to_me=False)
async def content(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.content(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('开服', aliases=('开服查询', '查询开服'), permission=GROUP_MEMBER, only_to_me=False)
async def status(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.status(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('金价', aliases=('金价查询', '查询金价'), permission=GROUP_MEMBER, only_to_me=False)
async def gold(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.gold(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('花价', aliases=('花价查询', '查询花价'), permission=GROUP_MEMBER, only_to_me=False)
async def flower(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.flower(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('沙盘', aliases=('沙盘查询', '查询沙盘'), permission=GROUP_MEMBER, only_to_me=False)
async def sand(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.sand(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('副本', aliases=('PVE', 'pve'), permission=GROUP_MEMBER, only_to_me=False)
async def pve(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.pve(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('竞技', aliases=('PVP', 'pvp'), permission=GROUP_MEMBER, only_to_me=False)
async def pvp(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.pvp(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('绝境', aliases=('绝境奇穴', '吃鸡', '吃鸡奇穴'), permission=GROUP_MEMBER, only_to_me=False)
async def plan(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.plan(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('战场', aliases=('战场奇穴', '奇穴', '查询奇穴'), permission=GROUP_MEMBER, only_to_me=False)
async def battle(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.battle(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('小药', aliases=('小药查询', '查询小药'), permission=GROUP_MEMBER, only_to_me=False)
async def heighten(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.heighten(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('', aliases=('宏命令', '云端宏'), permission=GROUP_MEMBER, only_to_me=False)
async def macro(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.macro(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@bot.on_message('group') # 格式:冰心宏
async def macros(event: aiocqhttp.Event):
message = str(event['message'])
if len(message) >= 3 and message[-1] == '':
if not await common.token(event['group_id']):
result = await seasun.macros(event)
else:
result = await common.token(event['group_id'])
logger.info(result)
await robot.event(event, result)
@on_command('物价', aliases=('物价查询', '查询物价'), permission=GROUP_MEMBER, only_to_me=False)
async def prices(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.prices(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('价格', aliases=('价格查询', '查询价格'), permission=GROUP_MEMBER, only_to_me=False)
async def price(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.price(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('条件', aliases=('条件查询', '查询条件'), permission=GROUP_MEMBER, only_to_me=False)
async def method(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.method(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('成就', aliases=('成就查询', '查询成就'), permission=GROUP_MEMBER, only_to_me=False)
async def achievement(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.achievement(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('科举', aliases=('科举查询', '查询科举'), permission=GROUP_MEMBER, only_to_me=False)
async def exam(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.exam(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('图谱', aliases=('器物谱', '查询器物谱'), permission=GROUP_MEMBER, only_to_me=False)
async def travel(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.travel(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('装饰', aliases=('装饰查询', '查询装饰'), permission=GROUP_MEMBER, only_to_me=False)
async def furniture(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.furniture(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('公告', aliases=('公告查询', '更新公告'), permission=GROUP_MEMBER, only_to_me=False)
async def announcement(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.announcement(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('奇遇', aliases=('奇遇查询', '查询奇遇'), permission=GROUP_MEMBER, only_to_me=False)
async def adventure(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.adventure(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('查询', aliases=('个人查询', '查询个人'), permission=GROUP_MEMBER, only_to_me=False)
async def personal(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.personal(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('点歌', aliases=('腾讯点歌', 'QQ点歌'), permission=GROUP_MEMBER, only_to_me=False)
async def music(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.music(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('网易', aliases=('网易点歌', '163点歌'), permission=GROUP_MEMBER, only_to_me=False)
async def netease(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.netease(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('世界', aliases=('骚话', '世界骚话'), permission=GROUP_MEMBER, only_to_me=False)
async def world(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.world(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('阵眼', aliases=('阵眼查询', '查询阵眼'), permission=GROUP_MEMBER, only_to_me=False)
async def gest(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.gest(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('挂件', aliases=('挂件查询', '查询挂件'), permission=GROUP_MEMBER, only_to_me=False)
async def pendant(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.pendant(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('日记', aliases=('舔狗', '舔狗日记'), permission=GROUP_MEMBER, only_to_me=False)
async def dog(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.dog(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('菜单', aliases=('功能', '帮助', '说明', '使用说明', '使用帮助'), permission=GROUP_MEMBER, only_to_me=False)
async def explain(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.explain(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)
@on_command('绑定', aliases=('绑定区服', '区服绑定'), permission=SUPERUSER | GROUP_OWNER | GROUP_ADMIN, only_to_me=False)
async def serverlock(session: CommandSession):
if not await common.token(await common.value(session)):
result = await seasun.lock(session)
else:
result = await common.token(await common.value(session))
logger.info(result)
await session.send(result)

@ -0,0 +1,52 @@
# -*- coding: utf-8 -*
"""
@Software : PyCharm
@File : config.py
@Author : 梦影
@Time : 2021/04/26 20:21:16
"""
from plugin.common import bot, common
import time
class extend:
@staticmethod
async def select(value): # 查询用户群数据
sql = 'SELECT * FROM `main` WHERE `Value` = %s'
data = await bot.client.query(sql, value)
result = await common.next(data)
return result
@staticmethod
async def update(value, name, number): # 更新用户群间隔数据
name = f"CD.{name}"
sql = f"UPDATE `main` SET `{name}` = {time.time() + number} WHERE `Value` = {value}"
await bot.client.execute(sql)
@staticmethod
async def week(date): # 指定时间星期几 # 查询模块
text = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期天"]
ret = date.weekday()
return text[ret]
@staticmethod
async def count(text): # 计算冷却时间 # 查询模块
result = text - int(time.time())
return f'模块冷却中({result})...'
@staticmethod
async def local(data, value): # 本地记录的时间戳
if not data:
return 0
if value == 1080:
result = time.time()
else:
result = data[f'CD.{value}']
return result
@staticmethod
async def lock(server, value): # 更新数据库数据
sql = 'UPDATE `main` SET `Main` = %s WHERE `Value` = %s'
await bot.client.execute(sql, (server, value))

@ -0,0 +1,667 @@
# -*- coding: utf-8 -*
"""
@Software : PyCharm
@File : content.py
@Author : 梦影
@Time : 2021/04/26 20:21:20
"""
from plugin.common import bot, submit, static, common
from plugin.content.config import extend
import datetime
import time
class seasun:
@staticmethod
async def content(session):
data = await extend.select(await common.value(session))
if await extend.local(data, 1001) <= await extend.local(data, 1080):
content = await common.subtext(session)
if not content:
server = await static.data(0, data)
else:
server = await static.data(1, content[0])
data = await submit.connect(url=f"{bot.domain}/app/getdaily", data={"server": server})
if data['code'] == 200:
dayDraw, data, result = "", data['data'], ""
if 'DayDraw' in data.keys():
dayDraw = f"美人画像:{data['DayDraw']}\n"
dayList = {
"": f"帮会跑商:阴山商路(10:00)\n阵营祭天:出征祭祀(19:00)\n",
"": f"阵营攻防:逐鹿中原(20:00)\n",
"": f"世界首领:少林·乱世,七秀·乱世(20:00)\n{dayDraw}",
"": f"阵营攻防:逐鹿中原(20:00)\n",
"": f"世界首领:藏剑·乱世,万花·乱世(20:00)\n{dayDraw}",
"": f"攻防前置:南屏山(12:00)\n阵营攻防:浩气盟(13:00,19:00)\n{dayDraw}",
"": f"攻防前置:昆仑(12:00)\n阵营攻防:恶人谷(13:00,19:00)\n{dayDraw}",
}
result = f"当前时间:{time.strftime('%Y年%m月%d', time.localtime())} {await extend.week(datetime.datetime.now())}\n秘境大战:{data['DayWar']}\n今日战场:{data['DayBattle']}\n公共任务:{data['DayCommon']}\n阵营任务:{data['DayCamp']}\n{dayList[data['Week']]}\n武林通鉴·公共任务\n{data['WeekCommon']}\n武林通鉴·秘境任务\n{data['WeekFive']}\n武林通鉴·团队秘境\n{data['WeekTeam']}"
await extend.update(await common.value(session), 1001, 30)
else:
result = "找不到相关信息!"
else:
result = await extend.count(await extend.local(data, 1001))
return result
@staticmethod
async def status(session):
data = await extend.select(await common.value(session))
if await extend.local(data, 1002) <= await extend.local(data, 1080):
content = await common.subtext(session)
if not content:
server = await static.data(0, data)
else:
server = await static.data(1, content[0])
if not server:
return "请输入正确的服务器!"
result = await common.table('status', 'server', server, 'status')
status = {1: '已开服', 0: '维护中'}
result = f"{server}{time.strftime('%H:%M:%S', time.localtime(time.time()))} 的状态 [{status[result]}]"
await extend.update(await common.value(session), 1002, 30)
else:
result = await extend.count(await extend.local(data, 1002))
return result
@staticmethod
async def gold(session):
data = await extend.select(await common.value(session))
content = await common.subtext(session)
if not content:
server = await static.data(0, data)
else:
server = await static.data(1, content[0])
if not server:
return "请输入正确的服务器!"
if await extend.local(data, 1003) <= await extend.local(data, 1080):
data = await submit.connect(url=f"{bot.domain}/app/getgold", data={"server": server})
if data['code'] == 200:
wanbaolou = data['data']['wanbaolou']
dd373 = data['data']['dd373']
uu898 = data['data']['uu898']
s7881 = data['data']['7881']
result = f"金价·{'%-5s' % server} {time.strftime('%m-%d %H:%M', time.localtime(time.time()))}\n官方平台:1元 = {wanbaolou}\n嘟嘟平台:1元 = {dd373}\n悠悠平台:1元 = {uu898}\n其他平台:1元 = {s7881}"
await extend.update(await common.value(session), 1003, 30)
else:
result = "找不到相关信息!"
else:
result = await extend.count(await extend.local(data, 1003))
return result
@staticmethod
async def flower(session):
data = await extend.select(await common.value(session))
content = await common.subtext(session)
if not content:
return 'https://jx3api.com/php/flower.php'
if len(content) == 1:
server = await static.data(0, data)
flower = await static.data(2, content[0])
else:
server = await static.data(1, content[0])
flower = await static.data(2, content[1])
if not server:
return "请输入正确的服务器!"
if not flower:
return "请输入正确的关键字!"
if await extend.local(data, 1004) <= await extend.local(data, 1080):
data = await submit.connect(url=f"{bot.domain}/app/getflower", data={"server": server, "flower": flower})
if data['code'] == 200:
data = data['data']
region_result = ""
for region in data:
region_list = data[region]
level_result = ""
for i in region_list:
if 'color' in i:
level_result += f"{i['name']}({i['color']})\n倍率:{i['price']}({','.join(i['line'])})\n"
else:
level_result += f"{i['name']}\n倍率:{i['price']}({','.join(i['line'])})\n"
region_result += f"{region}\n{level_result.strip()}\n"
result = f"{server}·{flower}\n{region_result.strip()}"
await extend.update(await common.value(session), 1004, 30)
else:
result = f"{flower} 的数据收集中..."
else:
result = await extend.count(await extend.local(data, 1004))
return result
@staticmethod
async def sand(session):
data = await extend.select(await common.value(session))
content = await common.subtext(session)
if not content:
server = await static.data(0, data)
else:
server = await static.data(1, content[0])
if not server:
return "请输入正确的服务器!"
if await extend.local(data, 1005) <= await extend.local(data, 1080):
data = await submit.connect(url=f"{bot.domain}/app/getSand", data={"server": server})
if data['code'] == 200:
data = data['data']
result = f"[CQ:image,file={data['url']},cache=false]"
await extend.update(await common.value(session), 1005, 30)
else:
result = "找不到相关信息!"
else:
result = await extend.count(await extend.local(data, 1005))
return result
@staticmethod
async def pve(session):
data = await extend.select(await common.value(session))
content = await common.subtext(session)
if not content:
return "请输入关键字!"
name = await static.data(3, content[0])
if not name:
return "请输入正确的关键字!"
if '×' in name:
text = name.split('×')
return f"{content[0]}·[PVE {text[0]}丨PVE {text[1]}]"
if await extend.local(data, 1006) <= await extend.local(data, 1080):
data = await submit.connect(url=f"{bot.domain}/app/getequipment",
data={'name': name, 'user': session.self_id})
if data['code'] == 200:
result = f"[CQ:image,file={data['data']['pve']},cache=false]"
await extend.update(await common.value(session), 1006, 30)
else:
result = "找不到相关信息!"
else:
result = await extend.count(await extend.local(data, 1006))
return result
@staticmethod
async def pvp(session):
data = await extend.select(await common.value(session))
content = await common.subtext(session)
if not content:
return "请输入关键字!"
name = await static.data(3, content[0])
if not name:
return "请输入正确的关键字!"
if '×' in name:
text = name.split('×')
return f"{content[0]}·[PVP {text[0]}丨PVP {text[1]}]"
if await extend.local(data, 1007) <= await extend.local(data, 1080):
data = await submit.connect(url=f"{bot.domain}/app/getequipment",
data={'name': name, 'user': session.self_id})
if data['code'] == 200:
result = f"[CQ:image,file={data['data']['pvp']},cache=false]"
await extend.update(await common.value(session), 1007, 30)
else:
result = "找不到相关信息!"
else:
result = await extend.count(await extend.local(data, 1007))
return result
@staticmethod
async def plan(session):
data = await extend.select(await common.value(session))
content = await common.subtext(session)
if not content:
return "请输入关键字!"
name = await static.data(3, content[0])
if not name:
return "请输入正确的关键字!"
if '×' in name:
text = name.split('×')
return f"{content[0]}·[绝境 {text[0]}丨绝境 {text[1]}]"
if await extend.local(data, 1008) <= await extend.local(data, 1080):
data = await submit.connect(url=f"{bot.domain}/app/getholes", data={'name': name})
if data['code'] == 200:
result = f"龙门绝境·推荐奇穴\n{data['data']['Despair']}"
await extend.update(await common.value(session), 1008, 30)
else:
result = "找不到相关信息!"
else:
result = await extend.count(await extend.local(data, 1008))
return result
@staticmethod
async def battle(session):
data = await extend.select(await common.value(session))
content = await common.subtext(session)
if not content:
return "请输入关键字!"
name = await static.data(3, content[0])
if not name:
return "请输入正确的关键字!"
if '×' in name:
text = name.split('×')
return f"{content[0]}·[绝境 {text[0]}丨绝境 {text[1]}]"
if await extend.local(data, 1009) <= await extend.local(data, 1080):
data = await submit.connect(url=f"{bot.domain}/app/getHoles", data={'name': name})
if data['code'] == 200:
result = f"战场任务·推荐奇穴\n{data['data']['Battle']}"
await extend.update(await common.value(session), 1009, 30)
else:
result = "找不到相关信息!"
else:
result = await extend.count(await extend.local(data, 1009))
return result
@staticmethod
async def heighten(session):
data = await extend.select(await common.value(session))
content = await common.subtext(session)
if not content:
return "[CQ:image,file=https://oss.nicemoe.cn/content/reinforcement/reinforcement.jpg,cache=false]"
name = await static.data(3, content[0])
if not name:
return "请输入正确的关键字!"
if '×' in name:
text = name.split('×')
return f"{content[0]}·[小药 {text[0]}丨小药 {text[1]}]"
if await extend.local(data, 1010) <= await extend.local(data, 1080):
data = await submit.connect(url=f"{bot.domain}/app/getheighten", data={'name': name})
if data['code'] == 200:
result = f"{name}·推荐药品\n增强食品:{data['data']['HeightenFood']}\n辅助食品:{data['data']['AuxiliaryFood']}\n增强药品:{data['data']['HeightenDrug']}\n辅助药品:{data['data']['AuxiliaryDrug']}"
await extend.update(await common.value(session), 1010, 30)
else:
result = "找不到相关信息!"
else:
result = await extend.count(await extend.local(data, 1010))
return result
@staticmethod
async def macro(session):
data = await extend.select(await common.value(session))
content = await common.subtext(session)
if not content:
return "请输入关键字!"
name = await static.data(3, content[0])
if not name:
return "请输入正确的关键字!"
if '×' in name:
text = name.split('×')
return f"{content[0]}·[宏 {text[0]}丨宏 {text[1]}]"
if await extend.local(data, 1011) <= await extend.local(data, 1080):
result = await submit.connect(url=f"{bot.domain}/app/getmacro", data={'name': name})
await extend.update(await common.value(session), 1011, 30)
else:
result = await extend.count(await extend.local(data, 1011))
return result
@staticmethod
async def macros(event):
data = await extend.select(event['group_id'])
content = str(event['message'])[:-1].strip()
if not content:
return "请输入关键字!"
name = await static.data(3, content)
if not name:
return "请输入正确的关键字!"
if '×' in name:
text = name.split('×')
return f"{content}·[{text[0]}宏丨{text[1]}宏]"
if await extend.local(data, 1011) <= await extend.local(data, 1080):
result = await submit.connect(url=f"{bot.domain}/app/getmacro", data={'name': name})
await extend.update(event['group_id'], 1011, 30)
else:
result = await extend.count(await extend.local(data, 1011))
return result
@staticmethod
async def prices(session):
data = await extend.select(await common.value(session))
content = await common.subtext(session)
if not content:
return "请输入关键字!"
if await extend.local(data, 1012) <= await extend.local(data, 1080):
data = await submit.connect(url=f"{bot.domain}/app/getprice", data={'name': content[0]})
if data['code'] == 200:
result, data = "", data['data'][0]
for each in data[:5]:
itemtime = f"20{each['tradeTime'].replace('/', '-')}"
price, itemname, saleCode, = each['price'], each['itemname'], each['saleCode']
saleCode = ''
if '' in saleCode:
saleCode = ''
exterior = f"{each['exterior']}·{itemname}"
result += f"{itemtime} 有人 {price:.0f} {saleCode}{exterior}\n"
result = result.strip()
await extend.update(await common.value(session), 1012, 30)
else:
result = "请输入正确的关键字!"
else:
result = await extend.count(await extend.local(data, 1012))
return result
@staticmethod
async def price(session):
data = await extend.select(await common.value(session))
content = await common.subtext(session)
if not content:
return "请输入关键字!"
if await extend.local(data, 1013) <= await extend.local(data, 1080):
data = await submit.content(
url=f"https://m.dololo.top/getAllItem/bjsj/0/2019-11-29/1/{content[0]}/x/x/x/x/x/0")
data = data['content']
result = ""
if len(data) > 0:
for each in data[:5]:
date, price, buyer, itemname = each['bjsj'], each['jg'], each['lx'], each['wpqc']
result += f"{date} 有人 {price:.0f} {buyer} {itemname}\n"
result = result.strip()
await extend.update(await common.value(session), 1013, 30)
else:
result = "请输入正确的关键字!"
else:
result = await extend.count(await extend.local(data, 1013))
return result
@staticmethod
async def method(session):
data = await extend.select(await common.value(session))
content = await common.subtext(session)
if not content:
return "请输入关键字!"
if await extend.local(data, 1014) <= await extend.local(data, 1080):
data = await submit.connect(url=f"{bot.domain}/app/getmethod", data={'name': content[0]})
if data['code'] == 200:
data = data['data']
result = f"{content[0]}·前置条件\n触发方式:{data['method']}\n满足条件:{data['need']}\n其他可能:{data['other']}\n物品奖励:{data['reward']}"
await extend.update(await common.value(session), 1014, 30)
else:
result = "请输入正确的关键字!"
else:
result = await extend.count(await extend.local(data, 1014))
return result
@staticmethod
async def achievement(session):
data = await extend.select(await common.value(session))
content = await common.subtext(session)
if not content:
return "请输入关键字!"
name = content[0].replace('[', '').replace(']', '')
if await extend.local(data, 1015) <= await extend.local(data, 1080):
data = await submit.content(url="https://helper.jx3box.com/api/achievement/search",
params={'keyword': name})
data = data['data']['achievements']
if len(data) > 0:
item = data[0]['ID']
result = f"[{data[0]['Name']}]·对应地址:https://jx3api.com/api/jump.php?id={item}"
await extend.update(await common.value(session), 1015, 30)
else:
result = "请输入正确的关键字!"
else:
result = await extend.count(await extend.local(data, 1015))
return result
@staticmethod
async def exam(session):
data = await extend.select(await common.value(session))
content = await common.subtext(session)
if not content:
return "请输入关键字!"
question = content[0]
if await extend.local(data, 1016) <= await extend.local(data, 1080):
data = await submit.connect(url=f"{bot.domain}/app/getexam", data={'question': question})
if data['code'] == 200:
result = ""
data = data['data']
for i in range(min(2, len(data))):
result += "Q:{}\nA:{}\n\n".format(data[i]['question'], data[i]['answer'])
result = f"{result.strip()}\n还有({len(data) - 2})项,输入更多关键词以便精准查找..."
await extend.update(await common.value(session), 1016, 10)
else:
result = "请输入正确的关键字!"
else:
result = await extend.count(await extend.local(data, 1016))
return result
@staticmethod
async def travel(session):
data = await extend.select(await common.value(session))
content = await common.subtext(session)
if not content:
return "请输入关键字!"
name = content[0]
if await extend.local(data, 1017) <= await extend.local(data, 1080):
data = await submit.connect(url=f'{bot.domain}/app/gettravel', data={'map': name})
if data['code'] == 200:
data = data['data']
result = f"[CQ:image,file={data[0]['imagePath']}]\n家具 : {data[0]['name']}\n品质 : {data[0]['qualityLevel']}\n需要家园等级 : {data[0]['levelLimit']}\n风水评分 : {data[0]['geomanticScore']}\n观赏评分 : {data[0]['viewScore']}\n实用评分 : {data[0]['practicalScore']}\n坚固评分 : {data[0]['hardScore']}\n趣味评分 : {data[0]['interestingScore']}"
await extend.update(await common.value(session), 1017, 30)
else:
result = "请输入正确的关键字!"
else:
result = await extend.count(await extend.local(data, 1017))
return result
@staticmethod
async def furniture(session):
data = await extend.select(await common.value(session))
content = await common.subtext(session)
if not content:
return "请输入关键字!"
if await extend.local(data, 1018) <= await extend.local(data, 1080):
data = await submit.connect(url=f"{bot.domain}/app/getfurniture", data={'name': content[0]})
if data['code'] == 200:
data = data['data']
result = f"装饰属性·{content[0]}\n[CQ:image,file={data['imagePath']}]\n来源 : {data['source']}\n品质 : {data['qualityLevel']}\n价格 : {data['architecture']}\n需要家园等级 : {data['levelLimit']}\n风水评分 : {data['geomanticScore']}\n观赏评分 : {data['viewScore']}\n实用评分 : {data['practicalScore']}\n坚固评分 : {data['hardScore']}\n趣味评分 : {data['interestingScore']}"
await extend.update(await common.value(session), 1018, 30)
else:
result = '请输入正确的关键字!'
else:
result = await extend.count(await extend.local(data, 1018))
return result
@staticmethod
async def announcement(session):
data = await extend.select(await common.value(session))
if await extend.local(data, 1019) <= await extend.local(data, 1080):
data = await submit.connect(url=f"{bot.domain}/app/getannounce")
if data['code'] == 200:
data = data['data']
result = ""
for each in data[:3]:
result += f"标题:{each['title']}\n链接:{each['url']}\n\n"
result = result.strip()
await extend.update(await common.value(session), 1019, 30)
else:
result = "找不到相关信息!"
else:
result = await extend.count(await extend.local(data, 1019))
return result
@staticmethod
async def adventure(session):
data = await extend.select(await common.value(session))
content = await common.subtext(session)
if not content:
return "请输入关键字!"
if len(content) == 1:
server = await static.data(0, data)
advent = await static.data(4, content[0])
else:
server = await static.data(1, content[0])
advent = await static.data(4, content[1])
if not server:
return "请输入正确的服务器!"
if not advent:
return "请输入正确的关键字!"
if await extend.local(data, 1020) <= await extend.local(data, 1080):
data = await submit.connect(url=f"{bot.domain}/app/getserendipity",
data={'server': server, 'serendipity': advent})
if data['code'] == 200:
result = ""
for each in data['data'][:5]:
timeArray = time.localtime(each['time'])
otherStyleTime = time.strftime("%m月%d%H:%M", timeArray)
result += f"\n————————————————\n玩家:{each['name']} \n时间:{otherStyleTime}"
result = f"[{server}·{advent}]{result}"
await extend.update(await common.value(session), 1020, 30)
else:
result = "找不到相关信息!"
else:
result = await extend.count(await extend.local(data, 1020))
return result
@staticmethod
async def personal(session):
data = await extend.select(await common.value(session))
content = await common.subtext(session)
if not content:
return "请输入关键字!"
if len(content) == 1:
server = await static.data(0, data)
name = content[0]
else:
server = await static.data(1, content[0])
name = content[1]
if not server:
return "请输入正确的服务器!"
if not name:
return "请输入正确的关键字!"
if await extend.local(data, 1021) <= await extend.local(data, 1080):
data = await submit.connect(url=f"{bot.domain}/app/getserendipity", data={'server': server, 'name': name})
if data['code'] == 200:
result = ""
data = data['data']
for i in range(len(data)):
timeArray = time.localtime(data[i]['time'])
otherStyleTime = time.strftime("%m月%d%H:%M", timeArray)
if await static.data(4, data[i]['serendipity']):
result += f"\n————————————————\n奇遇:{data[i]['serendipity']} \n时间:{otherStyleTime}"
result = f"[{server}·{name}]{result}"
await extend.update(await common.value(session), 1021, 30)
else:
result = "找不到相关信息!"
else:
result = await extend.count(await extend.local(data, 1021))
return result
@staticmethod
async def music(session):
data = await extend.select(await common.value(session))
content = await common.subtext(session)
if not content:
return "请输入关键字!"
if await extend.local(data, 1022) <= await extend.local(data, 1080):
params = {'format': 'json', 'w': content[0]}
data = await submit.content(url='https://c.y.qq.com/soso/fcgi-bin/client_search_cp', params=params)
result = f"[CQ:music,type=qq,id={data['data']['song']['list'][0]['songid']},content={data['data']['song']['list'][0]['singer'][0]['name']} <{list(bot.config.NICKNAME)[0]}>]"
await extend.update(await common.value(session), 1022, 30)
else:
result = await extend.count(await extend.local(data, 1022))
return result
@staticmethod
async def netease(session):
data = await extend.select(await common.value(session))
content = await common.subtext(session)
if not content:
return "请输入关键字!"
if await extend.local(data, 1023) <= await extend.local(data, 1080):
data = await submit.connect(url="http://music.163.com/api/search/pc", data={'s': content[0], 'type': 1})
result = f"[CQ:music,type=163,id={data['result']['songs'][0]['id']}]"
await extend.update(await common.value(session), 1023, 30)
else:
result = await extend.count(await extend.local(data, 1023))
return result
@staticmethod
async def world(session):
data = await extend.select(await common.value(session))
if await extend.local(data, 1024) <= await extend.local(data, 1080):
data = await submit.connect(url=f"{bot.domain}/app/getrandom")
if data['code'] == 200:
result = data['data']['text']
await extend.update(await common.value(session), 1024, 15)
else:
result = "找不到相关信息!"
else:
result = await extend.count(await extend.local(data, 1024))
return result
@staticmethod
async def gest(session):
data = await extend.select(await common.value(session))
content = await common.subtext(session)
if not content:
return "请输入关键字!"
name = await static.data(3, content[0])
if not name:
return "请输入正确的关键字!"
if '×' in name:
text = name.split('×')
return f"{content[0]}·[阵眼 {text[0]}丨阵眼 {text[1]}]"
if await extend.local(data, 1025) <= await extend.local(data, 1080):
data = await submit.connect(url=f"{bot.domain}/app/getgest", data={'name': name})
if data['code'] == 200:
result = f"{data['data']['name']}·{data['data']['skillName']}"
temp = ""
for data in data['data']['descs']:
temp += f"{data['name']}:{data['desc']}\n"
result = f"{result}\n{temp.strip()}"
await extend.update(await common.value(session), 1025, 30)
else:
result = "找不到相关信息!"
else:
result = await extend.count(await extend.local(data, 1025))
return result
@staticmethod
async def pendant(session):
data = await extend.select(await common.value(session))
content = await common.subtext(session)
if not content:
return "请输入关键字!"
if await extend.local(data, 1026) <= await extend.local(data, 1080):
data = await submit.connect(url=f"{bot.domain}/app/getPendant", data={'name': content[0]})
if data['code'] == 200:
data = data['data']
result = f"挂件详情·{data['Name']}\n挂件类型:{data['Type']}\n使用特效:{data['Use']}\n挂件说明:{data['Explain']}\n挂件出自:{data['Obtain']}"
await extend.update(await common.value(session), 1026, 30)
else:
result = "找不到相关信息!"
else:
result = await extend.count(await extend.local(data, 1026))
return result
@staticmethod
async def dog(session):
data = await extend.select(await common.value(session))
if await extend.local(data, 1029) <= await extend.local(data, 1080):
data = await submit.connect(url=f"{bot.domain}/extend/getdog")
if data['code'] == 200:
result = data['data']['text']
await extend.update(await common.value(session), 1029, 10)
else:
result = "找不到相关信息!"
else:
result = await extend.count(await extend.local(data, 1029))
return result
@staticmethod
async def explain(session):
data = await extend.select(await common.value(session))
if await extend.local(data, 1048) <= await extend.local(data, 1080):
result = bot.config.EXPLAIN_URL
await extend.update(await common.value(session), 1049, 30)
else:
result = await extend.count(await extend.local(data, 1049))
return result
@staticmethod
async def lock(session):
data = await extend.select(await common.value(session))
content = await common.subtext(session)
if not content:
return "请输入服务器!"
else:
server = await static.data(1, content[0])
if not server:
return "请输入正确的服务器!"
if await extend.local(data, 1050) <= await extend.local(data, 1080):
await extend.lock(server, await common.value(session))
await extend.update(await common.value(session), 1050, 86400)
result = f"{server} 绑定完成!"
else:
result = await extend.count(await extend.local(data, 1050))
return result

@ -0,0 +1,94 @@
# -*- coding: utf-8 -*
"""
@Software : PyCharm
@File : database.py
@Author : 梦影
@Time : 2021/04/25 19:29:28
"""
import traceback
import aiomysql
from nonebot.log import logger
class MySql:
def __init__(self):
self.coon = None
self.pool = None
async def initpool(self, bot):
try:
logger.debug("mysql will connect mysql~")
__pool = await aiomysql.create_pool(**bot.MYSQL_CONFIG)
return __pool
except:
logger.error('mysql connect error.', exc_info=True)
async def getCurosr(self):
conn = await self.pool.acquire()
# 返回字典格式
cur = await conn.cursor(aiomysql.DictCursor)
return conn, cur
async def query(self, query, param=None):
"""
查询操作
:param query: sql语句
:param param: 参数
:return:
"""
conn, cur = await self.getCurosr()
try:
await cur.execute(query, param)
return await cur.fetchall()
except:
logger.error(traceback.format_exc())
finally:
if cur:
await cur.close()
# 释放掉conn,将连接放回到连接池中
await self.pool.release(conn)
async def execute(self, query, param=None):
"""
增删改 操作
:param query: sql语句
:param param: 参数
:return:
"""
conn, cur = await self.getCurosr()
try:
await cur.execute(query, param)
if cur.rowcount == 0:
return False
else:
return True
except:
logger.error(traceback.format_exc())
finally:
if cur:
await cur.close()
# 释放掉conn,将连接放回到连接池中
await self.pool.release(conn)
async def MySqlInit(bot, socketList): # 数据库初始化
table = {
"main": "CREATE TABLE `main`(`ID` INT(12) NOT NULL AUTO_INCREMENT PRIMARY KEY, `Value` BIGINT(20) NOT NULL UNIQUE, `Main` VARCHAR(20), `Relet` BIGINT(20), `Users` BIGINT(20), `Robot` BIGINT(20), `CD.1001` BIGINT(20) DEFAULT 0, `CD.1002` BIGINT(20) DEFAULT 0, `CD.1003` BIGINT(20) DEFAULT 0, `CD.1004` BIGINT(20) DEFAULT 0, `CD.1005` BIGINT(20) DEFAULT 0, `CD.1006` BIGINT(20) DEFAULT 0, `CD.1007` BIGINT(20) DEFAULT 0, `CD.1008` BIGINT(20) DEFAULT 0, `CD.1009` BIGINT(20) DEFAULT 0, `CD.1010` BIGINT(20) DEFAULT 0, `CD.1011` BIGINT(20) DEFAULT 0, `CD.1012` BIGINT(20) DEFAULT 0, `CD.1013` BIGINT(20) DEFAULT 0, `CD.1014` BIGINT(20) DEFAULT 0,`CD.1015` BIGINT(20) DEFAULT 0, `CD.1016` BIGINT(20) DEFAULT 0, `CD.1017` BIGINT(20) DEFAULT 0, `CD.1018` BIGINT(20) DEFAULT 0, `CD.1019` BIGINT(20) DEFAULT 0, `CD.1020` BIGINT(20) DEFAULT 0, `CD.1021` BIGINT(20) DEFAULT 0, `CD.1022` BIGINT(20) DEFAULT 0, `CD.1023` BIGINT(20) DEFAULT 0, `CD.1024` BIGINT(20) DEFAULT 0, `CD.1025` BIGINT(20) DEFAULT 0, `CD.1026` BIGINT(20) DEFAULT 0, `CD.1027` BIGINT(20) DEFAULT 0, `CD.1028` BIGINT(20) DEFAULT 0, `CD.1029` BIGINT(20) DEFAULT 0, `CD.1030` BIGINT(20) DEFAULT 0, `CD.1031` BIGINT(20) DEFAULT 0, `CD.1032` BIGINT(20) DEFAULT 0, `CD.1033` BIGINT(20) DEFAULT 0, `CD.1034` BIGINT(20) DEFAULT 0, `CD.1035` BIGINT(20) DEFAULT 0, `CD.1036` BIGINT(20) DEFAULT 0, `CD.1037` BIGINT(20) DEFAULT 0, `CD.1038` BIGINT(20) DEFAULT 0, `CD.1039` BIGINT(20) DEFAULT 0, `CD.1040` BIGINT(20) DEFAULT 0, `CD.1041` BIGINT(20) DEFAULT 0, `CD.1042` BIGINT(20) DEFAULT 0, `CD.1043` BIGINT(20) DEFAULT 0, `CD.1044` BIGINT(20) DEFAULT 0, `CD.1045` BIGINT(20) DEFAULT 0, `CD.1046` BIGINT(20) DEFAULT 0, `CD.1047` BIGINT(20) DEFAULT 0, `CD.1048` BIGINT(20) DEFAULT 0, `CD.1049` BIGINT(20) DEFAULT 0, `CD.1050` BIGINT(20) DEFAULT 0)",
"status": "CREATE TABLE `status`(`id` INT(12) NOT NULL AUTO_INCREMENT PRIMARY KEY, `server` VARCHAR(20) NOT NULL, `status` INT(12) NOT NULL DEFAULT 1)",
"switch": "CREATE TABLE `switch`(`id` INT(12) NOT NULL AUTO_INCREMENT PRIMARY KEY, `value` BIGINT(20) NOT NULL UNIQUE, `random` BIGINT(20) DEFAULT 0, `news` BIGINT(20) DEFAULT 0, `nlpchat` BIGINT(20) DEFAULT 0, `scheduler` BIGINT(20) DEFAULT 0, `member` VARCHAR(255))",
}
for n in table:
sql = f"SHOW TABLES LIKE '%{n}%'"
if await bot.client.query(sql):
continue
await bot.client.execute(table[n])
logger.critical(f"MySQL > 创建数据表[{n}]成功!")
for i in socketList:
sql = "SELECT * FROM `status` WHERE `server` = %s"
if await bot.client.query(sql, i):
continue
sql = "INSERT INTO `status`(`server`) VALUES (%s)"
await bot.client.execute(sql, i)
logger.critical(f"MySQL > 插入数据值[{i}]成功!")

@ -0,0 +1,120 @@
# -*- coding: utf-8 -*
"""
@Software : PyCharm
@File : dict.py
@Author : 梦影
@Time : 2021/04/26 18:14:16
"""
serverList = {
'长安城': ['长安城', '长安'],
'龙争虎斗': ['龙争虎斗', '龙虎'],
'蝶恋花': ['蝶恋花', '蝶服'],
'侠者成歌': ['侠者成歌'],
'剑胆琴心': ['剑胆琴心', '剑胆', '煎蛋'],
'幽月轮': ['幽月轮', '六合一'],
'乾坤一掷': ['乾坤一掷', '华乾'],
'斗转星移': ['斗转星移', '姨妈', '风雨大姨妈', '姨妈服'],
'唯我独尊': ['唯我独尊', '唯满侠', '鹅服'],
'梦江南': ['梦江南', '双梦镇', '双梦'],
'绝代天骄': ['绝代天骄', '绝代', '电八'],
'天鹅坪': ['天鹅坪', '纵月', '纵月六只鹅'],
'破阵子': ['破阵子', '念破'],
'飞龙在天': ['飞龙在天', '飞龙', '双二'],
'青梅煮酒': ['青梅煮酒', '青梅'],
}
flowerList = {
"绣球花": ["绣球花", "绣球", "一级绣球", "一级绣球花", "二级绣球", "二级绣球花", "红色绣球", "红色绣球花", "白色绣球", "白色绣球花", "紫色绣球", "紫色绣球花",
"黄色绣球", "黄色绣球花", "蓝色绣球", "蓝色绣球花", "粉色绣球", "粉色绣球花"],
"郁金香": ["郁金香", "一级郁金香", "二级郁金香", "红色郁金香", "粉色郁金香", "金色郁金香", "白色郁金香", "混色郁金香"],
"牵牛花": ["牵牛花", "牵牛", "一级牵牛", "一级牵牛花", "二级牵牛", "二级牵牛花", "红色牵牛", "红色牵牛花", "绯色牵牛", "绯色牵牛花", "紫色牵牛", "紫色牵牛花",
"黄色牵牛", "黄色牵牛花", "蓝色牵牛", "蓝色牵牛花"],
"玫瑰": ["玫瑰", "玫瑰花", "一级玫瑰", "一级玫瑰花", "二级玫瑰", "二级玫瑰花", "三级玫瑰", "三级玫瑰花", "红色玫瑰", "红色玫瑰花", "黄色玫瑰", "黄色玫瑰花",
"蓝色玫瑰", "蓝色玫瑰花", "橙色玫瑰", "橙色玫瑰花", "粉色玫瑰", "粉色玫瑰花", "绿色玫瑰", "绿色玫瑰花", "混色玫瑰", "混色玫瑰花", "白色玫瑰", "白色玫瑰花",
"黑色玫瑰", "黑色玫瑰花", "紫色玫瑰", "紫色玫瑰花"],
"百合": ["百合", "百合花", "一级百合", "一级百合花", "二级百合", "二级百合花", "黄色百合", "黄色百合花", "粉色百合", "粉色百合花", "白色百合", "白色百合花",
"橙色百合", "橙色百合花", "绿色百合", "绿色百合花"],
"荧光菌": ["荧光菌", "蘑菇", "一级荧光菌", "一级蘑菇", "二级荧光菌", "二级蘑菇", "红色荧光菌", "红色蘑菇", "黄色荧光菌", "黄色蘑菇", "白色荧光菌", "白色蘑菇",
"蓝色荧光菌", "蓝色蘑菇", "紫色荧光菌", "紫色蘑菇"],
"羽扇豆花": ["羽扇豆花", "羽扇", "豆花", "一级羽扇豆花", "一级羽扇", "一级豆花", "二级羽扇豆花", "二级羽扇", "二级豆花", "三级羽扇豆花", "三级羽扇", "三级豆花",
"白色羽扇豆花", "白色羽扇", "白色豆花", "红色羽扇豆花", "红色羽扇", "红色豆花", "紫色羽扇豆花", "紫色羽扇", "紫色豆花", "黄色羽扇豆花", "黄色羽扇",
"黄色豆花", "粉色羽扇豆花", "粉色羽扇", "粉色豆花", "蓝色羽扇豆花", "蓝色羽扇", "蓝色豆花", "黄白色羽扇豆花", "黄白色羽扇", "黄白色豆花", "黄粉色羽扇豆花",
"黄粉色羽扇", "黄粉色豆花"],
"葫芦": ["橙葫芦", "白葫芦", "紫葫芦", "红葫芦", "绿葫芦", "蓝葫芦", "青葫芦", "黄葫芦", "葫芦", "黄色蘑菇", "白色荧光菌", "白色蘑菇", "蓝色荧光菌",
"蓝色蘑菇", "紫色荧光菌", "紫色蘑菇"],
"": ["普通麦子", "紫麦", "绿麦", "黑麦", "麦子", ""],
"芜菁": ["芜菁·白", "芜菁·紫红", "芜菁·青白", "芜菁·白", "芜菁"],
"青菜": ["普通青菜", "紫冠青菜", "青菜"],
}
sectList = {
"离经易道": ["离经易道", "离经", "奶花", "花奶"],
"花间游": ["花间游", "花间"],
"云裳心经": ["云裳心经", "云裳", "奶秀", "秀奶"],
"冰心诀": ["冰心诀", "冰心"],
"洗髓经": ["洗髓经", "洗髓"],
"易筋经": ["易筋经", "易筋"],
"紫霞功": ["紫霞功", "紫霞", "气纯"],
"太虚剑意": ["太虚剑意", "太虚", "剑纯"],
"铁牢律": ["铁牢律", "铁牢"],
"傲血战意": ["傲血战意", "傲血", "傲雪"],
"山居剑意": ["山居剑意", "问水", "山居", "藏剑"],
"补天诀": ["补天诀", "补天", "奶毒", "毒奶"],
"毒经": ["毒经"],
"天罗诡道": ["天罗诡道", "天罗", "田螺"],
"惊羽诀": ["惊羽诀", "惊羽", "鲸鱼"],
"明尊琉璃体": ["明尊琉璃体", "明尊"],
"焚影圣诀": ["焚影圣诀", "焚影"],
"笑尘诀": ["笑尘诀", "笑尘", "丐帮"],
"铁骨衣": ["铁骨衣", "铁骨"],
"分山劲": ["分山劲", "分山"],
"相知": ["相知", "奶歌", "歌奶"],
"莫问": ["莫问"],
"北傲诀": ["北傲诀", "北傲", "霸刀"],
"凌海诀": ["凌海诀", "凌海", "蓬莱"],
"隐龙诀": ["隐龙诀", "隐龙", "凌雪"],
"太玄经": ["太玄经", "衍天", "太玄", "衍天宗"],
"离经×花间": ["万花"],
"云裳×冰心": ["七秀"],
"洗髓×易筋": ["少林"],
"紫霞×太虚": ["纯阳"],
"铁牢×傲血": ["天策"],
"补天×毒经": ["五毒"],
"天罗×惊羽": ["唐门"],
"明尊×焚影": ["明教"],
"铁骨×分山": ["苍云"],
"相知×莫问": ["长歌"],
}
serendipityList = {
'三尺青锋': ['三尺青锋'],
'三山四海': ['三山四海'],
'乱世舞姬': ['乱世舞姬'],
'塞外宝驹': ['塞外宝驹'],
'天涯无归': ['天涯无归'],
'少年行': ['少年行'],
'惜往日': ['惜往日'],
'扶摇九天': ['扶摇九天'],
'护佑苍生': ['护佑苍生'],
'故园风雨': ['故园风雨'],
'济苍生': ['济苍生'],
'清风捕王': ['清风捕王'],
'炼狱厨神': ['炼狱厨神'],
'生死判': ['生死判'],
'茶馆奇缘': ['茶馆奇缘'],
'虎啸山林': ['虎啸山林'],
'阴阳两界': ['阴阳两界'],
'雪山恩仇': ['雪山恩仇'],
'韶华故': ['韶华故'],
'黑白路': ['黑白路'],
'兔江湖': ['兔江湖'],
'平生心愿': ['平生心愿'],
'白日梦': ['白日梦'],
'舞众生': ['舞众生'],
'茶馆悬赏': ['茶馆悬赏'],
'劝学记': ['劝学记'],
'侠行囧途':['侠行囧途'],
'流年如虹':['流年如虹']
}

@ -0,0 +1,43 @@
# -*- coding: utf-8 -*
"""
@Software : PyCharm
@File : member.py
@Author : 梦影
@Time : 2021/04/28 19:51:29
"""
from nonebot import on_request, RequestSession, on_notice, NoticeSession
from plugin.common import bot, common
from nonebot.log import logger
@on_request('group')
async def _(session: RequestSession):
user_id = session.ctx['user_id']
group_id = session.ctx['group_id']
if not await common.token(group_id):
# 机器人被邀请
if session.ctx['sub_type'] == 'invite':
if user_id in bot.config.SUPERUSERS: # 被超级用户邀请入群,邀请入群之前请先进行授权,否则会被拒绝!
await session.approve()
logger.info(f"管理员:[{user_id}]邀请你加入[{group_id}],已同意!")
else:
await session.reject()
logger.info(f"陌生人:[{user_id}]邀请你加入[{group_id}],已拒绝!")
# 某人申请入群
if session.ctx['sub_type'] == 'add':
await session.approve()
logger.info(f"[{user_id}]申请加入[{group_id}],已同意!")
@on_notice('group_increase')
async def welcome(session: NoticeSession):
if not await common.token(await common.value(session)):
sql = 'SELECT * FROM `switch` WHERE `value` = %s'
data = await bot.client.query(sql, await common.value(session))
data = await common.next(data)
if data['member']:
result = data['member'].replace("[@QQ]", f"[CQ:at,qq={session.event['user_id']}]")
logger.info(result)
await session.send(result)

@ -0,0 +1,73 @@
# -*- coding: utf-8 -*
"""
@Software : PyCharm
@File : __init__.py
@Author : 梦影
@Time : 2021/04/27 22:22:13
"""
from plugin.common import bot, robot, common
from plugin.random.content import seasun
from plugin.random.config import extend
from nonebot.log import logger
from nonebot import aiocqhttp
command = f"{list(bot.config.NICKNAME)[0]}"
func = {command: seasun.content}
@bot.on_message('group') # 聊天功能
async def nlpchat(event: aiocqhttp.Event):
message = str(event['message'])
value = await common.tencent(message)
if value:
if value[0] == str(event.self_id):
message = message.replace(f"[CQ:at,qq={value[0]}]", list(bot.config.NICKNAME)[0])
if list(bot.config.NICKNAME)[0] in message and message[0:3] != command:
print(message)
if not await common.token(event['group_id']):
result = await seasun.nlpchat(message)
else:
result = await common.token(event['group_id'])
logger.info(result)
await robot.event(event, result)
return
@bot.on_message('group') # 语音合成
async def voice(event: aiocqhttp.Event):
message = str(event['message'])
if func.get(message[0:3], None):
if not await common.token(event['group_id']):
result = await func[message[0:3]](message[0:3])
else:
result = await common.token(event['group_id'])
logger.info(result)
await robot.event(event, result)
return
@bot.on_message('group') # 随机骚话
async def random(event: aiocqhttp.Event):
message = str(event['message'])
if len(message) >= 5 and 'CQ' not in message and await extend.rand():
switch = await common.table('switch', 'Value', event['group_id'], 'random')
if switch and not await common.token(event['group_id']):
result = await seasun.random(event)
logger.info(result)
await robot.event(event, result)
return
@bot.on_message('group') # 自由聊天
async def randchat(event: aiocqhttp.Event):
message = str(event['message'])
if len(message) >= 2 and 'CQ' not in message and await extend.chat():
switch = await common.table('switch', 'Value', event['group_id'], 'nlpchat')
if switch and not await common.token(event['group_id']):
result = await seasun.nlpchat(message)
logger.info(result)
await robot.event(event, result)
return

@ -0,0 +1,29 @@
# -*- coding: utf-8 -*
"""
@Software : PyCharm
@File : config.py
@Author : 梦影
@Time : 2021/04/28 19:56:08
"""
from plugin.common import bot
import random
class extend:
@staticmethod
async def rand(): # 文字触发几率 # 随机模块
if random.randint(1, 100) <= bot.config.RANDOM_MAX_VALUE:
result = True
else:
result = False
return result
@staticmethod
async def chat(): # 聊天触发几率 # 随机模块
if random.randint(1, 100) <= bot.config.NLPCHAT_MAX_VALUE:
result = True
else:
result = False
return result

@ -0,0 +1,61 @@
# -*- coding: utf-8 -*
"""
@Software : PyCharm
@File : content.py
@Author : 梦影
@Time : 2021/04/28 19:56:13
"""
from plugin.common import bot, robot, submit
import random
class seasun:
@staticmethod
async def nlpchat(message):
data = {'question': message, 'appid': bot.config.NLPCHAT_APPID, 'appkey': bot.config.NLPCHAT_APPKEY,
'name': list(bot.config.NICKNAME)[0]}
data = await submit.connect(url=f"{bot.domain}/extend/getnlpchat", data=data)
if data['code'] == 200:
result = data['data']['answer']
else:
result = None
return result
@staticmethod
async def content(message): # 语音合成中转
result = await seasun.voice(message)
if result:
result = f"[CQ:record,file={result}]"
else:
result = "找不到相关信息!"
return result
@staticmethod
async def random(event):
text = await seasun.text()
if random.randint(1, 2) == 1:
return f"{await robot.sender(event)} {text}"
else:
result = await seasun.voice(text)
result = f"[CQ:record,file={result}]"
return result
@staticmethod
async def text():
data = await submit.connect(url=f"{bot.domain}/app/getrandom")
if data['code'] == 200:
return data['data']['text']
else:
return None
@staticmethod
async def voice(text: str):
data = {'appkey': bot.config.ALIYUN_APPKEY, 'access': bot.config.ALIYUN_ACCESS,
'secret': bot.config.ALIYUN_SECRET, 'text': text}
data = await submit.connect(url=f"{bot.domain}/extend/getaliyun", data=data)
if data['code'] == 200:
return data['data']['url']
else:
return None

@ -0,0 +1,30 @@
# -*- coding: utf-8 -*
"""
@Software : PyCharm
@File : scheduler.py
@Author : 梦影
@Time : 2021/04/28 21:15:58
"""
from plugin.common import bot, robot, common
import nonebot
import datetime
job = nonebot.scheduler.scheduled_job
@job('cron', minute='0', hour='0', day_of_week='*', misfire_grace_time=5)
async def exit():
for value in bot.config.ROBOT.LIST:
group_list = await robot.group_list(self_id=value)
for group_data in group_list:
sql = 'SELECT * FROM main WHERE Value = %s'
data = await bot.client.query(sql, group_data['group_id'])
if data:
data = await common.next(data)
result = (datetime.datetime.now() - datetime.datetime.fromtimestamp(data['Relet'])).days
if result >= bot.config.ROBOT_EXIT_TIME:
await bot.set_group_leave(self_id=value, group_id=group_data['group_id'])
else:
await bot.set_group_leave(self_id=value, group_id=group_data['group_id'])

@ -0,0 +1,108 @@
# -*- coding: utf-8 -*
"""
@Software : PyCharm
@File : superuser.py
@Author : 梦影
@Time : 2021/04/25 19:39:50
"""
from plugin.common import robot, bot, static, common
from nonebot.permission import SUPERUSER
from nonebot import CommandSession, on_command
from nonebot.log import logger
import asyncio
import time
class super:
@staticmethod
async def new_group_token(session, content): # 新增一个群的授权
number = int(content[2]) * 86400
server = None
if len(content) == 4:
server = await static.data(1, content[3]) # 寻找主服务器全称
sql = "SELECT * FROM main WHERE Value = %s"
data = await bot.client.query(sql, content[1])
if not data:
number = time.time() + number # 计算授权天数
sql = "INSERT INTO main(Value, Main, Relet, Users, Robot) VALUES (%s, %s, %s, %s, %s)"
await bot.client.execute(sql, (content[1], server, number, session.ctx.user_id, session.self_id))
if not await bot.client.query("SELECT * FROM switch WHERE value = %s", content[1]):
sql = "INSERT INTO switch(value) VALUES (%s)" # 插入群开关数据值
await bot.client.execute(sql, content[1])
dwTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(number))
result = f"{list(bot.config.NICKNAME)[0]}·新增时间\n群号:{content[1]}\n新增:{content[2]}\n区服:{server}\n过期:{dwTime}"
logger.info(result)
return result
data = await common.next(data)
if time.time() > data['Relet']: # 本地时间大于数据库时间
number = time.time() + number # 重新计算授权天数
else:
number = data['Relet'] + number # 计算授权天数,数据库时间小于本地时间
server = server if server else data['Main']
sql = "UPDATE main SET Main = %s, Relet = %s, Users = %s, Robot = %s WHERE Value = %s"
await bot.client.execute(sql, (server, number, session.ctx.user_id, session.self_id, content[1])) # 更新授权数据
dwTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(number))
result = f"{list(bot.config.NICKNAME)[0]}·追加时间\n群号:{content[1]}\n追加:{content[2]}\n区服:{server}\n过期:{dwTime}"
logger.info(result)
return result
@staticmethod
async def modify_group_token(session, content): # 修改某个群的授权
sql = "SELECT * FROM `main` WHERE `Value` = %s"
data = await bot.client.query(sql, content[1])
if data:
data = await common.next(data)
sql = "UPDATE main SET Value = %s, Users = %s, Robot = %s WHERE ID = %s"
await bot.client.execute(sql, (content[2], session.ctx.sender['user_id'], session.self_id, data['ID']))
dwTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(data['Relet']))
result = f"{list(bot.config.NICKNAME)[0]}·授权信息\n群号:{content[2]}\n区服:{data['Main']}\n过期:{dwTime}"
else:
result = "找不到相关信息!"
logger.info(result)
return result
@staticmethod
async def del_group_token(session, subtext): # 取消某个群的授权
sql = "SELECT * FROM main WHERE Value = %s"
data = await bot.client.query(sql, subtext[1])
if data:
sql = "UPDATE main SET Relet = %s, Users = %s, Robot = %s WHERE Value = %s"
await bot.client.execute(sql, (1582128000, session.ctx.sender['user_id'], session.self_id, subtext[1]))
result = f"{list(bot.config.NICKNAME)[0]}·授权信息\n已取消对:{subtext[1]} 的授权!"
else:
result = "找不到相关信息!"
logger.info(result)
return result
hold = super()
Func = {
"授权群": hold.new_group_token,
"修改授权": hold.modify_group_token,
"取消授权": hold.del_group_token
}
@on_command('G', permission=SUPERUSER, only_to_me=True)
async def admin(session: CommandSession):
content = await common.subtext(session)
if len(content) >= 2 and content[0] == '发送群消息': # 发送消息给所有已授权的群
text = str(session.ctx['message'])[8:]
for value in bot.config.ROBOT_LIST:
asyncio.ensure_future(group.send(value, text))
await asyncio.sleep(0.1)
if Func.get(content[0], None):
result = await Func[content[0]](session, content)
await session.send(result)
class group:
@staticmethod
async def send(value: int, message: str):
logger.info(message)
group_list = await robot.group_list(self_id=value)
for group_data in group_list:
if not await common.token(group_data['group_id']):
await robot.group_send(self_id=value, group_id=group_data['group_id'], message=message)

@ -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 > 连接被关闭!') # 服务端主动关闭

@ -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)

@ -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)
Loading…
Cancel
Save