Skip to content

Commit c16315a

Browse files
SaucePlumGLGDLY
andauthored
refactor: 重构ext下的扩展工具 (#105)
* feat: 完善ws事件中Message数据的构建 * feat: 完善ws事件中User-Member数据的构建 * feat: 完善ws事件中Reaction、Audio、DirectMessage 以及 Forum(Thread类)数据的构建 feat: 去除EmbedField的value项(实际仅有name) * feat: 完善ws事件中监听文档并优化格式 refactor: 优化forum thread的事件数据名称 * fix: forum thread的事件数据名称更变后同步数据更改到其他文件 * refactor: 优化ext下的扩展工具 * refactor: 优化ext的convert_color模块 * refactor: 优化ext下的扩展工具 * refactor: 优化ext下的扩展工具 * docs: 修改一处表述不正确的地方 Co-authored-by: GLGDLY <[email protected]>
1 parent abb6152 commit c16315a

26 files changed

+216
-213
lines changed

botpy/api.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -735,9 +735,9 @@ async def mute_member(
735735
self, guild_id: str, user_id: str, mute_end_timestamp: str = None, mute_seconds: str = None
736736
) -> str:
737737
"""
738-
使频道中的所有成员禁言
738+
使频道中的指定成员禁言
739739
740-
用于将频道的全体成员(非管理员)禁言。
740+
用于将频道的指定成员(非管理员)禁言。
741741
需要使用的 token 对应的用户具备管理员权限。如果是机器人,要求被添加为管理员。
742742
743743
Args:
@@ -1181,6 +1181,7 @@ async def get_pins(self, channel_id: str) -> pins_message.PinsMessage:
11811181
)
11821182
return await self._http.request(route)
11831183

1184+
# 帖子相关接口
11841185
async def get_threads(self, channel_id: str) -> forum.ForumRsp:
11851186
"""
11861187
该接口用于获取子频道下的帖子列表。

botpy/ext/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@
22
"""
33
这里放一些可用的工具
44
方便开发者调用
5-
"""
5+
"""
Lines changed: 71 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -1,70 +1,71 @@
1-
"""
2-
对子频道转跳进行操作(#name)
3-
注意:
4-
1、发送格式要求严格(#name ),自动添加的空格不能删除
5-
2、无法识别真假转跳
6-
3、当子频道重名时无法准确识别
7-
4、当提供子频道转跳字段时请弃用本模块
8-
"""
9-
10-
__all__ = [
11-
"get_channel_jump",
12-
"get_channel_jump_strict",
13-
"escape_channel_jump"
14-
]
15-
16-
import re
17-
from typing import List, Dict
18-
19-
from botpy import BotAPI
20-
from botpy.message import Message
21-
22-
23-
def get_channel_jump(text: str = None, message: Message = None) -> List[str]:
24-
"""
25-
识别文本中的子频道转跳(粗略)
26-
:param message: 消息对象
27-
:param text: 文本,为空则message.content
28-
:return: 子频道名称列表(不带#)
29-
"""
30-
channel_jump_re = re.compile(r"#(.{1,12}?)(?= )")
31-
return channel_jump_re.findall(message.content if text is None else text)
32-
33-
34-
async def get_channel_jump_strict(api: BotAPI, message: Message = None, text: str = None,
35-
guild_id: str = None) -> Dict[str, str]:
36-
"""
37-
识别文本中的子频道转跳(准确)
38-
:param api: BotAPI
39-
:param message: 消息对象
40-
:param text: 文本,为空则message.content
41-
:param guild_id: 频道id,为空则message.guild_id
42-
:return: {子频道名称(不带#):子频道id} (去重)
43-
"""
44-
channels = await api.get_channels(guild_id or message.guild_id)
45-
text = message.content if text is None else text
46-
jumps = {}
47-
48-
for channel in channels:
49-
if "#%s " % channel["name"] in text:
50-
jumps[channel["name"]] = channel["id"]
51-
52-
return jumps
53-
54-
55-
async def escape_channel_jump(api: BotAPI, message: Message = None, text: str = None, guild_id: str = None) -> str:
56-
"""
57-
转义子频道转跳 (#name -> <#id>)
58-
:param api: BotAPI
59-
:param message: 消息对象
60-
:param text: 文本,为空则message.content
61-
:param guild_id: 频道id,为空则message.guild_id
62-
:return: 转义后的文本
63-
"""
64-
channels = await api.get_channels(guild_id or message.guild_id)
65-
text = message.content if text is None else text
66-
67-
for channel in channels:
68-
text = text.replace("#%s " % channel["name"], "<#%s> " % channel["id"])
69-
70-
return text
1+
# -*- coding: utf-8 -*-
2+
"""
3+
对子频道转跳进行操作(#name)
4+
注意:
5+
1、发送格式要求严格(#name ),自动添加的空格不能删除
6+
2、无法识别真假转跳
7+
3、当子频道重名时无法准确识别
8+
4、当提供子频道转跳字段时请弃用本模块
9+
"""
10+
11+
__all__ = [
12+
"get_channel_jump",
13+
"get_channel_jump_strict",
14+
"escape_channel_jump"
15+
]
16+
17+
import re
18+
from typing import List, Dict
19+
20+
from botpy import BotAPI
21+
from botpy.message import Message
22+
23+
24+
def get_channel_jump(text: str = None, message: Message = None) -> List[str]:
25+
"""
26+
识别文本中的子频道转跳(粗略)
27+
:param message: 消息对象
28+
:param text: 文本,为空则message.content
29+
:return: 子频道名称列表(不带#)
30+
"""
31+
channel_jump_re = re.compile(r"#(.{1,12}?)(?= )")
32+
return channel_jump_re.findall(message.content if text is None else text)
33+
34+
35+
async def get_channel_jump_strict(api: BotAPI, message: Message = None, text: str = None,
36+
guild_id: str = None) -> Dict[str, str]:
37+
"""
38+
识别文本中的子频道转跳(准确)
39+
:param api: BotAPI
40+
:param message: 消息对象
41+
:param text: 文本,为空则message.content
42+
:param guild_id: 频道id,为空则message.guild_id
43+
:return: {子频道名称(不带#):子频道id} (去重)
44+
"""
45+
channels = await api.get_channels(guild_id or message.guild_id)
46+
text = message.content if text is None else text
47+
jumps = {}
48+
49+
for channel in channels:
50+
if "#%s " % channel["name"] in text:
51+
jumps[channel["name"]] = channel["id"]
52+
53+
return jumps
54+
55+
56+
async def escape_channel_jump(api: BotAPI, message: Message = None, text: str = None, guild_id: str = None) -> str:
57+
"""
58+
转义子频道转跳 (#name -> <#id>)
59+
:param api: BotAPI
60+
:param message: 消息对象
61+
:param text: 文本,为空则message.content
62+
:param guild_id: 频道id,为空则message.guild_id
63+
:return: 转义后的文本
64+
"""
65+
channels = await api.get_channels(guild_id or message.guild_id)
66+
text = message.content if text is None else text
67+
68+
for channel in channels:
69+
text = text.replace("#%s " % channel["name"], "<#%s> " % channel["id"])
70+
71+
return text

botpy/ext/cog_yaml/__init__.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# -*- coding: utf-8 -*-
2+
import yaml
3+
4+
from typing import Dict, Any
5+
6+
7+
def read(yaml_path) -> Dict[str, Any]:
8+
"""
9+
读取指定目录的yaml文件
10+
11+
:param yaml_path: 相对当前的yaml文件绝对路径
12+
:return:
13+
"""
14+
# 加上 ,encoding='utf-8',处理配置文件中含中文出现乱码的情况。
15+
with open(yaml_path, "r", encoding="utf-8") as f:
16+
return yaml.safe_load(f)

botpy/ext/color_util.py

Lines changed: 0 additions & 40 deletions
This file was deleted.

botpy/ext/command_util.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# -*- coding: utf-8 -*-
22
from functools import wraps
3+
from typing import Union
34

45
from botpy import BotAPI
56
from botpy.message import Message
@@ -8,10 +9,13 @@
89
class Commands:
910
"""
1011
指令装饰器
12+
13+
Args:
14+
name (Union[tuple, str]): 字符串元组或单个字符串。
1115
"""
1216

13-
def __init__(self, commands: tuple or str):
14-
self.commands = commands
17+
def __init__(self, name: Union[tuple, str]):
18+
self.commands = name
1519

1620
def __call__(self, func):
1721
@wraps(func)
@@ -22,7 +26,7 @@ async def decorated(*args, **kwargs):
2226
for command in self.commands:
2327
if command in message.content:
2428
# 分割指令后面的指令参数
25-
params = message.content.split(self.commands)[1].strip()
29+
params = message.content.split(command)[1].strip()
2630
return await func(api=api, message=message, params=params)
2731
elif self.commands in message.content:
2832
# 分割指令后面的指令参数
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# -*- coding: utf-8 -*-
2+
from typing import Union
3+
4+
5+
def start(color: Union[tuple, str]) -> int:
6+
"""
7+
将 RGB 值的元组或 HEX 值的字符串转换为单个整数
8+
9+
Args:
10+
color (tuple or str): 输入RGB的三位tuple或HEX的sting颜色
11+
12+
Returns:
13+
颜色的 RGB 值。
14+
"""
15+
colors = []
16+
if isinstance(color, tuple):
17+
if len(color) == 3:
18+
for items in color:
19+
if not isinstance(items, int) or items not in range(256):
20+
raise TypeError("RGB颜色应为一个三位数的tuple,且当中每个数值都应该介乎于0和255之间,如(255,255,255)")
21+
colors.append(items)
22+
else:
23+
raise TypeError("RGB颜色应为一个三位数的tuple,且当中每个数值都应该介乎于0和255之间,如(255,255,255)")
24+
elif isinstance(color, str):
25+
colour = color.replace("#", "")
26+
if len(colour) == 6:
27+
for items in (colour[:2], colour[2:4], colour[4:]):
28+
try:
29+
items = int(items, 16)
30+
except ValueError:
31+
raise TypeError("该HEX颜色不存在,请检查其颜色值是否准确")
32+
if items not in range(256):
33+
raise TypeError("该HEX颜色不存在,请检查其颜色值是否准确")
34+
colors.append(items)
35+
else:
36+
raise TypeError('HEX颜色应为一个 #加六位数字或字母 的string,如"#ffffff"')
37+
else:
38+
raise TypeError('颜色值应为RGB的三位tuple,如(255,255,255);或HEX的sting颜色,如"#ffffff"')
39+
return colors[0] + 256 * colors[1] + (256**2) * colors[2]

botpy/ext/yaml_util.py

Lines changed: 0 additions & 16 deletions
This file was deleted.

examples/demo_announce.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
1+
# -*- coding: utf-8 -*-
12
import os
23

34
import botpy
45
from botpy import logging
6+
57
from botpy.message import Message
68
from botpy.types.announce import AnnouncesType
7-
from botpy.ext.yaml_util import YamlUtil
9+
from botpy.ext.cog_yaml import read
810

9-
test_config = YamlUtil.read(os.path.join(os.path.dirname(__file__), "config.yaml"))
11+
test_config = read(os.path.join(os.path.dirname(__file__), "config.yaml"))
1012

1113
_log = logging.get_logger()
1214

examples/demo_api_permission.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
#!/usr/bin/env python3
21
# -*- coding: utf-8 -*-
3-
import os.path
2+
import os
43

54
import botpy
65
from botpy import logging
6+
77
from botpy.message import Message
8-
from botpy.ext.yaml_util import YamlUtil
98
from botpy.types.permission import APIPermissionDemandIdentify
9+
from botpy.ext.cog_yaml import read
1010

11-
test_config = YamlUtil.read(os.path.join(os.path.dirname(__file__), "config.yaml"))
11+
test_config = read(os.path.join(os.path.dirname(__file__), "config.yaml"))
1212

1313
_log = logging.get_logger()
1414

0 commit comments

Comments
 (0)