Skip to content

Commit

Permalink
📝 v0.1.10
Browse files Browse the repository at this point in the history
🐛 fix:修复了下载卫星数据的bug
✨ feat: 支持自定义截图,命令`/s`
  • Loading branch information
yzyyz1387 committed Sep 29, 2023
1 parent 890a33d commit 08b4fc6
Show file tree
Hide file tree
Showing 7 changed files with 257 additions and 76 deletions.
27 changes: 24 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,15 +208,36 @@ nb plugin install nonebot-plugin-cqsat

</details>

### 查看Tevel系列卫星截图
- 发送`/t` 即可查看网站https://www.df2et.de/tevel/的截图

### 查看相关网页截图
- 发送`/s` 即可查看相关网站的截图 例如 `/s t a`
- t https://www.df2et.de/tevel/
- a https://amsat.org/status/index.php
- css https://sathunt.com/
- home https://github.com/yzyyz1387/cqsat
- [ ]...
- 机器人superuser可使用/截图指令

### /截图
- 机器人superuser可使用/截图指令
- `/截图 add url=xxx path=xxx cmd=xxx proxy=xxx **kwargs`
- url: 截图网址
- path: 截图保存路径
- cmd: 截图命令
- kwargs: 其他参数
- 若要使用代理,请在机器人`.env.*`配置`sat_proxy_url=http://xx:port`
- `/截图 del url=xxx path=xxx cmd=xxx`
- url /path /cmd 其中之一即可
- `/截图 get`
- 查看当收录的截图支持列表
- `/截图 default`
- 恢复默认

### 娱乐信令
- 发送`/v` ,根据提示回复一条语音,即可对该语音加上信令音
- 可选参数
- `-p` 加前置音 例如:`/v -p`
- `-n[数字]` 加噪音 例如:`/v -n5`
- 使用示例: `/v -n5 -p`

### 网格 【私聊、群内】

Expand Down
1 change: 1 addition & 0 deletions cqsat/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
class Config(BaseModel, extra=Extra.ignore):
nonebot_plugin_go_cqhttp: Optional[bool] = False
go_cqhttp_path: Optional[str] = './'
sat_proxy_url: Optional[str] = None


global_config = get_driver().config
Expand Down
2 changes: 1 addition & 1 deletion cqsat/sat/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@
# @Email : youzyyz1384@qq.com
# @File : __init__.py.py
# @Software: PyCharm
from . import calculate_sat, sat_handle
from . import calculate_sat, sat_handle, shoot_handle, sat_shoot_url_bank
43 changes: 20 additions & 23 deletions cqsat/sat/calculate_sat.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,22 +95,21 @@ async def download_css_data():
async def download_ham_sat():
Path.mkdir(LOCAL) if not Path.exists(LOCAL) else ...
await get_tian_gong()

url = "https://amsat.org/tle/current/nasabare.txt"
if timeCompare(CACHE_OTHER, DATA_DICT):
logger.info("读取在线数据...")
ham_sat_ = await http_get(url, type_='json')
ham_sat_ = (await http_get(url))
if not ham_sat_:
logger.error(f"从 {url} 下载数据出错")
return None
else:
logger.debug("写入本地数据...")
await write_(DATA_DICT, json.dumps(str(ham_sat_), ensure_ascii=False))
await write_(HAM_SAT, ham_sat_)
CACHE_OTHER.touch()
return ham_sat_
else:
logger.info("读取本地数据...")
ham_sat_ = json.loads(await read_all(DATA_DICT))
ham_sat_ = await read_all(HAM_SAT)
return ham_sat_


Expand All @@ -119,25 +118,23 @@ async def data2Tle() -> Dict[str, list]:
将在线数据转换成TLE轨道报
:return:
"""
content = await download_ham_sat()
content = {k.upper(): v for k, v in content.items()}
if type(content) == dict:
return content
else:
logger.info("载入卫星TLE数据...")
count = 0
data = {}
temp = []
# 将数据分割成行TLE轨道报
for line in content.split('\n'):
count += 1
temp.append(line)
if count % 3 == 0:
data[temp[0]] = temp[1:]
count = 0
temp = []
await write_(DATA_DICT, json.dumps(data, ensure_ascii=False))
return data
(await download_ham_sat())
content = await read_all(HAM_SAT)
logger.info("载入卫星TLE数据...")
count = 0
data = {}
temp = []
# 将数据分割成行TLE轨道报
for line in content.split('\n'):
count += 1
temp.append(line)
if count % 3 == 0:
data[temp[0]] = temp[1:]
count = 0
temp = []
await write_(DATA_DICT, json.dumps(str(data), ensure_ascii=False))
data = {k.upper(): v for k, v in data.items()}
return data


async def calculate(name: str, location: list, time=ephem.now()) -> Optional[list]:
Expand Down
45 changes: 3 additions & 42 deletions cqsat/sat/sat_handle.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,34 +224,7 @@ async def _(bot: Bot, event: MessageEvent, state: T_State, args: Message = Comma
for sat in sat_list:
reply = "\n".join(sat)
messages.append(reply)
if isinstance(event, GroupMessageEvent):
await bot.send_group_forward_msg(
group_id=event.group_id,
messages=[
{
"type": "node",
"data": {
"name": "卫星列表",
"uin": bot.self_id,
"content": r
},
}
for r in messages
])
else:
await bot.send_private_forward_msg(
user_id=bot.self_id,
messages=[
{
"type": "node",
"data": {
"name": "卫星列表",
"uin": bot.self_id,
"content": r
},
}
for r in messages
])
await send_forward_msg(bot, event, "收录卫星列表", messages)


specified = on_command("查询卫星", aliases={"计算卫星"}, block=True)
Expand Down Expand Up @@ -315,11 +288,10 @@ async def aps():
return
today = datetime.now().strftime("%Y-%m-%d")
try:
await download_ham_sat()

data = (await yaml_load(CONFIG))
except FileNotFoundError:
data = await download_ham_sat()
# FIXME ↑???
data = await data2Tle()

for group in data:
for qq in data[group]:
Expand Down Expand Up @@ -392,15 +364,4 @@ async def aps():

# 定时任务

query_tevel = on_command("/小火车", aliases={"/t", "/查询小火车"}, block=True)


@query_tevel.handle()
async def query_tevel_(bot: Bot, event: MessageEvent, state: T_State, args: Message = CommandArg()):
if not args:
url = "https://www.df2et.de/tevel/"
await shoot_scr(url, img_output=SHOOTS_OUT_PATH / "tevel.png")
try:
await query_tevel.send(MessageSegment.image(f"file:///{Path(SHOOTS_OUT_PATH / 'tevel.png').resolve()}"))
except:
await query_tevel.send("图片发送失败,哪里出错了?")
128 changes: 128 additions & 0 deletions cqsat/sat/shoot_handle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
# python3
# -*- coding: utf-8 -*-
# @Time : 2023-09-29 16:19
# @Author : yzyyz
# @Email : youzyyz1384@qq.com
# @File : shoot_handle.py
# @Software: PyCharm
import re
from datetime import datetime, timedelta

from nonebot import on_command, require
from nonebot.adapters import Message
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, MessageSegment, MessageEvent
from nonebot.adapters.onebot.v11.exception import ActionFailed
from nonebot.internal.params import ArgStr
from nonebot.params import CommandArg
from nonebot.permission import SUPERUSER
from nonebot.typing import T_State

from .calculate_sat import download_ham_sat, data2Tle, calculate, get_tian_gong
from .sat_shoot_url_bank import *
from ..log import log
from ..path import *
from ..config import *
from ..utils import *

if plugin_config.sat_proxy_url:
logger.info(plugin_config.sat_proxy_url)

shoot_web = on_command("/s", aliases={"/S"}, block=True)

url_bank = UrlBank()


@shoot_web.handle()
async def query_tevel_(bot: Bot, event: MessageEvent, state: T_State, args: Message = CommandArg()):
not_found = True
Iter_msgs = []
for item in (url_bank.get()):
tips = ""
for k, v in item.items():
if k in ['url', 'cmd']:
tips += f"{k}:{v}\n"
Iter_msgs.append(tips)
if args:
args = str(args).strip().split(" ")
for item in (url_bank.get()):
for arg in args:
if arg in item["cmd"]:
not_found = False
url = item["url"]
path = SHOOTS_OUT_PATH / item["path"]
locator = item.get("locator", "html")
time_out = item.get("time_out", 0)
proxy = item.get("proxy", None)
timeout = item.get("timeout", 30000)
if path.exists():
last_time = datetime.fromtimestamp(path.stat().st_mtime)
TIME_NOW = (datetime.now())
TIME_DIFF = TIME_NOW - last_time
if TIME_DIFF > timedelta(minutes=float(time_out)):
logger.info("超时,重新截图")
await shoot_scr(url, locator=locator, img_output=path, proxy=proxy, timeout=timeout)
else:
await shoot_scr(url, locator=locator, img_output=path, proxy=proxy, timeout=timeout)
try:
await shoot_web.send(MessageSegment.image(f"file:///{Path(path).resolve()}"))
except Exception as e:
await shoot_web.finish(f"图片发送失败,哪里出错了?\n{e}")

if not args or not_found:
await shoot_web.send(f"请输入参数:\n例如:/s t a css\n支持的参数:")
await send_forward_msg(bot, event, "收录截图列表", Iter_msgs)


bank_handle = on_command("/截图", aliases={"/shoot"}, block=True, permission=SUPERUSER)


@bank_handle.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State, args: Message = CommandArg()):
if args:

# args: add url=xxx cmd=xxx path=xxx locator=xxx
# 检查是否有中文、中文符号
if re.findall(r'[\u4e00-\u9fa5,。?!:;“”‘’()【】、]', str(args)):
await bank_handle.finish(
"参数错误:不得包含中文字符\n/截图add url=xxx cmd=xxx path=xxx locator=xxx time_out=123 ...")
args = str(args).strip().split(" ")
keyword_ = {}
if args[0] == "add":
for arg in args:
if "=" in arg:
arg = arg.split("=")
keyword_[arg[0]] = (arg[1]).replace("&#93;", "]").replace("&#91;", "[").replace("&#61;", "=")
if keyword_:
if not keyword_.get("url", None) or not keyword_.get("cmd", None) or not keyword_.get("path", None):
await bank_handle.finish("参数错误:\n/截图add url=xxx cmd=xxx path=xxx locator=xxx time_out=123 "
"...\n必须包含url、cmd、path")
url_bank.add(**keyword_)
await bank_handle.finish("添加成功")
else:
await bank_handle.finish("参数错误:\n/截图add url=xxx cmd=xxx path=xxx locator=xxx time_out=123 "
"...\n必须包含url、cmd、path")
elif args[0] == "del":
for arg in args:
if "=" in arg:
arg = arg.split("=")
keyword_[arg[0]] = arg[1].replace("&#93;", "]").replace("&#91;", "[").replace("&#61;", "=")
if keyword_:
url_bank.remove(**keyword_)
await bank_handle.finish("删除成功")
else:
await bank_handle.finish("参数错误:\n/截图del url=xxx cmd=xxx path=xxx"
"...\n必须包含url、cmd、path其中之一")
elif args[0] == "get":
data = url_bank.get()
messages = []
for i in data:
reply = ""
for k, v in i.items():
if k in ['cmd', 'url', 'path']:
reply += f"{k}:{v}\n"
messages.append(reply)

await send_forward_msg(bot, event, "收录截图列表", messages)
elif args[0] == "default":
url_bank.default()
await bank_handle.finish("恢复默认成功")
Loading

0 comments on commit 08b4fc6

Please sign in to comment.