Skip to content

Commit

Permalink
bluh
Browse files Browse the repository at this point in the history
  • Loading branch information
DoroWolf committed Oct 3, 2024
1 parent 26b7b1b commit 6b68d50
Show file tree
Hide file tree
Showing 17 changed files with 4,262 additions and 1,649 deletions.
2 changes: 1 addition & 1 deletion modules/arcaea/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ async def _(msg: Bot.MessageSession):
for x in resp['value']:
rank += 1
r.append(f'{rank}. {x["title"]["en"]} ({x["status"]})')
await msg.finish('\n'.join(r))
await msg.finish(r)
else:
await msg.finish(msg.locale.t("arcaea.message.get_failed"))

Expand Down
10 changes: 5 additions & 5 deletions modules/core/modules.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,9 +281,9 @@ def module_reload(module, extra_modules, base_module=False):

if msglist:
if not recommend_modules_help_doc_list:
await msg.finish('\n'.join(msglist))
await msg.finish(msglist)
else:
await msg.send_message('\n'.join(msglist))
await msg.send_message(msglist)
if recommend_modules_help_doc_list and ('-g' not in msg.parsed_msg or not msg.parsed_msg['-g']):
confirm = await msg.wait_confirm(msg.locale.t("core.message.module.recommends",
modules='\n'.join(recommend_modules_list) + '\n\n' +
Expand All @@ -293,7 +293,7 @@ def module_reload(module, extra_modules, base_module=False):
msglist = []
for x in recommend_modules_list:
msglist.append(msg.locale.t("core.message.module.enable.success", module=x))
await msg.finish('\n'.join(msglist))
await msg.finish(msglist)
else:
await msg.finish()
else:
Expand Down Expand Up @@ -505,7 +505,7 @@ async def _(msg: Bot.MessageSession):
msg.locale.t(
"core.message.help.more_information.donate",
url=Config('donate_url', cfg_type=str)))
await msg.finish('\n'.join(help_msg))
await msg.finish(help_msg)


async def modules_help(msg: Bot.MessageSession, legacy):
Expand Down Expand Up @@ -600,4 +600,4 @@ async def modules_help(msg: Bot.MessageSession, legacy):
msg.locale.t(
"core.message.help.more_information.document",
url=Config('help_url', cfg_type=str)))
await msg.finish('\n'.join(help_msg))
await msg.finish(help_msg)
5 changes: 3 additions & 2 deletions modules/github/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from core.utils.http import get_url
from modules.github.utils import dirty_check, dark_check

SEARCH_LIMIT = 5

async def search(msg: Bot.MessageSession, keyword: str):
result = await get_url('https://api.github.com/search/repositories?q=' + keyword, 200,
Expand All @@ -17,9 +18,9 @@ async def search(msg: Bot.MessageSession, keyword: str):
items_out.append(str(item['full_name'] + ': ' + str(Url(item['html_url']))))
except TypeError:
continue
message = msg.locale.t("github.message.search") + '\n' + '\n'.join(items_out[0:5])
message = msg.locale.t("github.message.search") + '\n' + '\n'.join(items_out[0:SEARCH_LIMIT])
if result['total_count'] > 5:
message += '\n' + msg.locale.t("message.collapse", amount="5")
message += '\n' + msg.locale.t("message.collapse", amount=SEARCH_LIMIT)

is_dirty = await dirty_check(message) or dark_check(message)
if is_dirty:
Expand Down
15 changes: 8 additions & 7 deletions modules/idlist/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,26 @@
from core.component import module
from core.utils.http import get_url

api = 'https://ca.projectxero.top/idlist/search'
API = 'https://ca.projectxero.top/idlist/search'
SEARCH_LIMIT = 5

i = module('idlist', doc=True, support_languages=['zh_cn'])


@i.command('<query> {{idlist.help}}')
async def _(msg: Bot.MessageSession, query: str):
query_options = {'q': query, 'limit': '6'}
query_url = api + '?' + urllib.parse.urlencode(query_options)
query_options = {'q': query, 'limit': f'{SEARCH_LIMIT + 1}'}
query_url = API + '?' + urllib.parse.urlencode(query_options)
resp = await get_url(query_url, 200, fmt='json')
result = resp['data']['result']
plain_texts = []
if result:
for x in result[0:5]:
for x in result[0:SEARCH_LIMIT]:
v = x["value"].split('\n')[0]
plain_texts.append(f'{x["enumName"]}{x["key"]} -> {v}')
if resp['data']['count'] > 5:
plain_texts.append(msg.locale.t('message.collapse', amount='5') + msg.locale.t('idlist.message.collapse'))
if resp['data']['count'] > SEARCH_LIMIT:
plain_texts.append(msg.locale.t('message.collapse', amount=SEARCH_LIMIT) + msg.locale.t('idlist.message.collapse'))
plain_texts.append('https://ca.projectxero.top/idlist/' + resp['data']['hash'])
await msg.finish('\n'.join(plain_texts))
await msg.finish(plain_texts)
else:
await msg.finish(msg.locale.t('idlist.message.none'))
2 changes: 1 addition & 1 deletion modules/maimai/libraries/maimaidx_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -566,7 +566,7 @@ async def get_plate_process(msg: Bot.MessageSession, payload: dict, plate: str,
prompt.append(msg.locale.t('maimai.message.plate.remaster', song_remain=len(song_remain_remaster)))

if song_remain:
await msg.send_message('\n'.join(prompt))
await msg.send_message(prompt)

song_record = [[s['id'], s['level_index']] for s in verlist]

Expand Down
16 changes: 9 additions & 7 deletions modules/ncmusic/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
from core.utils.http import get_url
from core.utils.text import isint

SEARCH_LIMIT = 10

ncmusic = module('ncmusic',
developers=['bugungu', 'DoroWolf'],
desc='{ncmusic.help.desc}', doc=True,
Expand All @@ -21,7 +23,7 @@ async def search(msg: Bot.MessageSession, keyword: str):
if song_count == 0:
await msg.finish(msg.locale.t('ncmusic.message.search.not_found'))

songs = result['result']['songs'][:10]
songs = result['result']['songs'][:SEARCH_LIMIT]

if not msg.parsed_msg.get('--legacy', False) and msg.Feature.image:

Expand All @@ -48,9 +50,9 @@ async def search(msg: Bot.MessageSession, keyword: str):
legacy = False
for img in imgs:
send_msg.append(Image(img))
if song_count > 10:
song_count = 10
send_msg.append(I18NContext("message.collapse", amount="10"))
if song_count > SEARCH_LIMIT:
song_count = SEARCH_LIMIT
send_msg.append(I18NContext("message.collapse", amount=SEARCH_LIMIT))

if song_count == 1:
send_msg.append(I18NContext('ncmusic.message.search.confirm'))
Expand Down Expand Up @@ -90,9 +92,9 @@ async def search(msg: Bot.MessageSession, keyword: str):
send_msg += f"({' / '.join(song['album']['transNames'])})"
send_msg += f"({song['id']}\n"

if song_count > 10:
song_count = 10
send_msg += msg.locale.t("message.collapse", amount="10")
if song_count > SEARCH_LIMIT:
song_count = SEARCH_LIMIT
send_msg += msg.locale.t("message.collapse", amount=SEARCH_LIMIT)

if song_count == 1:
send_msg += '\n' + msg.locale.t('ncmusic.message.search.confirm')
Expand Down
185 changes: 185 additions & 0 deletions modules/oba/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
import re
from datetime import datetime

from config import Config
from core.builtins import Bot, Image, Plain
from core.component import module
from core.utils.http import get_url

API = 'https://bd.bangbang93.com/openbmclapi'
TOP_LIMIT = 10

oba = module('oba', desc='{oba.help.desc}', developers='WorldHim')


def size_convert(value):
units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
size = 1024.0
for i in range(len(units)):
if (value / size) < 1:
return '%.2f%s' % (value, ' ' + units[i])
value /= size


async def latest_version():
try:
version = await get_url(f'{API}/metric/version', fmt='json')
return f'''{version.get('version')}@{version.get('_resolved').split('#')[1][:7]}'''
except Exception:
return None

def search_cluster(clusterList: dict, key: str, value: str):
result = []
regex = re.compile(value, re.IGNORECASE)

for (rank, node) in enumerate(clusterList, 1):
if regex.search(node.get(key)):
result.append((rank, node))
elif 'sponsor' in node and regex.search(node.get('sponsor').get(key)):
result.append((rank, node))

return result


@oba.command()
@oba.command('status {{oba.help.status}}')
async def status(msg: Bot.MessageSession):
dashboard = await get_url(f'{API}/metric/dashboard', fmt='json')

current_nodes = dashboard.get('currentNodes')
load = f"{round(dashboard.get('load') * 100, 2)}%"
bandwidth = dashboard.get('bandwidth')
current_bandwidth = round(dashboard.get('currentBandwidth'), 2)
hits = dashboard.get('hits')
size = size_convert(dashboard.get('bytes'))
version = await latest_version()

msg_list = [msg.locale.t('oba.message.status.detail',
current_nodes=current_nodes,
load=load,
bandwidth=bandwidth,
current_bandwidth=current_bandwidth,
hits=hits,
size=size
)]
if version:
msg_list.append(msg.locale.t('oba.message.status.version', version=version))
msg_list.append(msg.locale.t('oba.message.query_time', query_time=msg.ts2strftime(datetime.now().timestamp(), timezone=False)))
await msg.finish(msg_list)


@oba.command('node [<rank>] {{oba.help.rank}}')
async def rank(msg: Bot.MessageSession, rank: int = 1):
rank_list = await get_url(f'{API}/metric/rank', fmt='json')
node = rank_list[rank - 1]
status = '🟩' if node.get('isEnabled') else '🟥'
name = node.get('name')
_id = node.get('_id')
hits = node.get('metric').get('hits')
size = size_convert(node.get('metric').get('bytes'))

msg_list = [status, msg.locale.t('oba.message.node', name=name, id=_id, hits=hits, size=size)]
msg_list.append(msg.locale.t('oba.message.query_time', query_time=msg.ts2strftime(datetime.now().timestamp(), timezone=False)))

if 'sponsor' not in node:
await msg.finish(msg_list)
else:
await msg.send_message(msg_list)

sponsor = node.get('sponsor')
name = sponsor.get('name')
url = sponsor.get('url')
banner = sponsor.get('banner')

send_msg = msg.locale.t('oba.message.sponsor', name=name, url=url)
try:
await msg.finish([Plain(send_msg), Image(banner)])
except Exception:
await msg.finish(send_msg)


@oba.command('top [<rank>] {{oba.help.top}}')
async def top(msg: Bot.MessageSession, rank: int = 1):
rankList = await get_url(f'{API}/metric/rank', fmt='json')
rank = 1 if rank <= 0 else rank

node_list = []
for i in range(rank - 1, rank - 1 + TOP_LIMIT):
node = rankList[i]
sponsor = node.get('sponsor', msg.locale.t("unknown"))
try:
sponsor_name = sponsor.get('name')
except AttributeError:
sponsor_name = msg.locale.t("unknown")

try:
status = '🟩' if node.get('isEnabled') else '🟥'
name = node.get('name')
_id = node.get('_id')
hits = node.get('metric').get('hits')
size = size_convert(node.get('metric').get('bytes'))
node_list.append(f"{status} | {msg.locale.t('oba.message.top',
rank=i + 1,
name=name,
id=_id,
hits=hits,
size=size,
sponsor_name=sponsor_name)}")
except KeyError:
break

node_list.append(msg.locale.t('message.collapse', amount=TOP_LIMIT))
await msg.finish(node_list)


@oba.command('search <keyword> {{oba.help.search}}')
async def search(msg: Bot.MessageSession, keyword: str):
rank_list = await get_url(f'{API}/metric/rank', fmt='json')

match_list = await search_cluster(rank_list, 'name', keyword)

node_list = []
for rank, node in match_list:
sponsor = node.get('sponsor', msg.locale.t("unknown"))
try:
sponsor_name = sponsor.get('name')
except AttributeError:
sponsor_name = msg.locale.t("unknown")

try:
status = '🟩' if node.get('isEnabled') else '🟥'
name = node.get('name')
_id = node.get('_id')
hits = node.get('metric').get('hits')
size = size_convert(node.get('metric').get('bytes'))
node_list.append(f"{status} | {msg.locale.t('oba.message.top',
rank=rank,
name=name,
id=_id,
hits=hits,
size=size,
sponsor_name=sponsor_name)}")
except KeyError:
break

if node_list:
if len(node_list) > TOP_LIMIT:
node_list = node_list[:TOP_LIMIT]
node_list.append(msg.locale.t('message.collapse', amount=TOP_LIMIT))
await msg.finish(node_list)
else:
await msg.finish(msg.locale.t('oba.message.search.not_found'))


@oba.command('sponsor {{oba.help.sponsor}}')
async def sponsor(msg: Bot.MessageSession):
sponsor = await get_url(f'{API}/sponsor', fmt='json')
cluster = await get_url(f'{API}/sponsor/{str(sponsor['_id'])}', fmt='json')
name = cluster.get('name')
url = cluster.get('url')
banner = cluster.get('banner')
send_msg = msg.locale.t('oba.message.sponsor', name=name, url=url)
try:
await msg.finish([Plain(send_msg), Image(banner)])
except Exception:
await msg.finish(send_msg)
15 changes: 15 additions & 0 deletions modules/oba/locales/zh_cn.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"oba.help.desc": "获取 OpenBMCLAPI 相关数据。",
"oba.help.rank": "获取指定排名的 OpenBMCLAPI 节点状态。",
"oba.help.search": "查找指定名称的 OpenBMCLAPI 节点状态。",
"oba.help.sponsor": "获取随机赞助商。",
"oba.help.status": "获取 OpenBMCLAPI Dashboard 数据。",
"oba.help.top": "获取指定排名之前的 OpenBMCLAPI 节点状态。",
"oba.message.node": "节点名:${name}\n节点 ID:${id}\n节点请求:${hits} | 数据量:${size}",
"oba.message.query_time": "请求时间:${query_time}",
"oba.message.search.not_found": "未找到结果。",
"oba.message.sponsor.detail": "赞助商:${name}\n赞助商网站:${url}\n注意:此处展示 OpenBMCLAPI 的节点赞助商,与 Teahouse Studio 无任何从属关系。",
"oba.message.status.detail": "在线节点数:${current_nodes} | 负载:${load}\n总带宽:${bandwidth} Mbps | 出网带宽:${current_bandwidth} Mbps\n当日请求:${hits} | 数据量:${size}\nOpenBMCLAPI 最新版本: ${version}",
"oba.message.status.version": "OpenBMCLAPI 最新版本: ${version}",
"oba.message.top": "${rank} | ${name} | ${id}\n${hits} | ${size}\n赞助商 ${sponsor_name}"
}
Loading

0 comments on commit 6b68d50

Please sign in to comment.