LegendWechatBot 项目进程 Week6(2025-04-08 ~ 2025-04-14)

系统功能更新

数据库更新

  • 更新了获取所有白名单群聊的方法
  • 更新了通过微信号获取用户信息的方法
  • 更新了设置群聊简介的方法

敏感词更新

  • 更新了敏感词增删及保存的方法

插件更新

加群插件

在微信机器人项目中, 交流群是必不可少的, 但要是通过群主一个个手动拉人进群, 那也太麻烦了.因此, 我们需要实现一个自动加群的功能, 这样一来, 机器人就可以自动将新用户拉入群聊中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# plugins/GroupInvite/main.py
@on_text_message
async def send_group_invite(self, bot: LegendWechatBot, msg: WxMsg):
if not self.enable:
return

if msg.from_group():
to, at = msg.roomid, msg.sender
else:
to, at = msg.roomid, None

try:
# 检查是否为私聊消息
if msg.content == '进群':
bot.sendMsg('自动拉群功能: 发送`进群 Legend`进入随机交流群\n发送`进群 群聊列表`查看所有群聊\n发送`进群 群聊序号`获取指定群聊的邀请链接\n仅能在私聊中使用', to, at)

if msg.from_group():
return

# 检查消息内容是否为邀请指令
if msg.content.startswith("进群 "):
sub = msg.content.split(" ")[1] # 提取群聊 ID

chatroom_list = LegendBotDB().get_chatrooms()

logger.debug(chatroom_list)

if sub == "Legend":
# 随机选择一个群聊 ID
chatroom_id = random.choice(chatroom_list['id'])
bot.sendMsg(f"已发送邀请链接,请点击链接加入群聊:", msg.sender)
bot.invite_chatroom_members(chatroom_id, [msg.sender])
return

if sub == "群聊列表":
res = '所有群聊列表\n'
# 编号(从1开始)+简介
for i, chatroom in enumerate(chatroom_list):
res += f"{i+1}. {chatroom['description']}\n"
bot.sendMsg(res, msg.sender)
return

# 检查群聊是否在白名单中
try:
chatroom_id = chatroom_list[int(sub)]
except:
bot.sendMsg('命令格式出错', msg.sender)
return
# 获取群聊邀请链接
bot.sendMsg(f"加群邀请已发送", msg.sender)
bot.invite_chatroom_members(chatroom_id['id'], [msg.sender])
return

except Exception as e:
logger.error(f"发送群聊邀请链接失败: {e}")
logger.error(traceback.format_exc())
bot.sendMsg("发送群聊邀请链接失败,请检查日志", msg.sender)

成语插件

一个小插件, 可以作为插件模板, 实现了成语的查询和成语接龙的功能

  • 成语对象

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    # plugins/Idiom/main.py
    class Chengyu(object):
    def __init__(self) -> None:
    self.df = pd.read_csv(f"idiom.csv", delimiter="\t")
    self.cys, self.zis, self.yins = self._build_data()

    def _build_data(self):
    df = self.df.copy()
    df["shouzi"] = df["chengyu"].apply(lambda x: x[0])
    df["mozi"] = df["chengyu"].apply(lambda x: x[-1])

    df["shouyin"] = df["pingyin"].apply(lambda x: x.split(" ")[0])
    df["moyin"] = df["pingyin"].apply(lambda x: x.split(" ")[-1])

    cys = dict(zip(df["chengyu"], df["moyin"]))
    zis = df.groupby("shouzi").agg({"chengyu": set})["chengyu"].to_dict()
    yins = df.groupby("shouyin").agg({"chengyu": set})["chengyu"].to_dict()

    return cys, zis, yins

    def isChengyu(self, cy: str) -> bool:
    return self.cys.get(cy, None) is not None

    def getNext(self, cy: str, tongyin: bool = True) -> str:
    """获取下一个成语
    cy: 当前成语
    tongyin: 是否允许同音字
    """
    zi = cy[-1]
    ansers = list(self.zis.get(zi, {}))
    try:
    ansers.remove(cy) # 移除当前成语
    except Exception as e:
    pass # Just ignore...

    if ansers:
    return random.choice(ansers)

    # 如果找不到同字,允许同音
    if tongyin:
    yin = self.cys.get(cy)
    ansers = list(self.yins.get(yin, {}))

    try:
    ansers.remove(cy) # 移除当前成语
    except Exception as e:
    pass # Just ignore...

    if ansers:
    return random.choice(ansers)

    return None

    def getMeaning(self, cy: str) -> str:
    ress = self.df[self.df["chengyu"] == cy].to_dict(orient="records")
    if ress:
    res = ress[0]
    rsp = res["chengyu"] + "\n" + res["pingyin"] + "\n" + res["jieshi"]
    if res["chuchu"] and res["chuchu"] != "无":
    rsp += "\n出处:" + res["chuchu"]
    if res["lizi"] and res["lizi"] != "无":
    rsp += "\n例子:" + res["lizi"]
    return rsp
    return None

  • 插件实现

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    # plugins/Idiom/main.py
    @on_text_message
    async def handle_idiom(self, bot: LegendWechatBot, msg: WxMsg):
    if not self.enable:
    return

    if msg.from_group():
    to, at = msg.roomid, msg.sender
    else:
    to, at = msg.sender, None

    try:
    if msg.content == "成语":
    bot.sendMsg(
    "成语插件相关命令:\n"
    "`成语查询 成语` - 查询成语的详细信息\n"
    "`成语接龙 成语` - 根据输入的成语进行接龙\n"
    "`成语帮助` - 查看帮助信息",
    to,
    at,
    )
    return
    # 成语查询功能
    if msg.content.startswith("成语查询 "):
    idiom = msg.content[5:]
    if not self.chengyu.isChengyu(idiom):
    bot.sendMsg(f"未找到成语: {idiom}", to, at)
    return

    meaning = self.chengyu.getMeaning(idiom)
    if meaning:
    bot.sendMsg(meaning, to, at)
    else:
    bot.sendMsg(f"未找到成语 {idiom} 的详细信息", to, at)
    return

    # 成语接龙功能
    elif msg.content.startswith("成语接龙 "):
    idiom = msg.content[5:]
    if not self.chengyu.isChengyu(idiom):
    bot.sendMsg(f"未找到成语: {idiom}", to, at)
    return

    next_idiom = self.chengyu.getNext(idiom)
    if next_idiom:
    bot.sendMsg(f"接龙成语: {next_idiom}", to, at)
    else:
    bot.sendMsg(f"未找到可以接龙的成语", to, at)
    return

    # 成语帮助功能
    elif msg.content == "成语帮助":
    bot.sendMsg(
    "成语插件相关命令:\n"
    "`成语查询 成语` - 查询成语的详细信息\n"
    "`成语接龙 成语` - 根据输入的成语进行接龙\n"
    "`成语帮助` - 查看帮助信息",
    to,
    at,
    )
    return

    except Exception as e:
    logger.error(f"处理成语命令时发生错误: {e}")
    logger.error(traceback.format_exc())
    bot.sendMsg("处理成语命令时发生错误,请检查日志", to, at)

管理员功能

实现了管理员功能, 包括 - 积分查改 - 黑名单查改 - 用户信息查询 - 群聊简介修改 - 群聊白名单设置 - 敏感词查改

todo list

这周没有

为什么呢

1
2

基础功能已经全不完善, 机器人可以投入使用了, 剩下来要做的就是不断扩充插件功能, 以满足更复杂的生产环境

该休息一下了

等我长大了, 一定不再搞这种灰色产业项目了, 寄人篱下太痛苦了

如果真要有那么几条待办的话...

  • OI学习笔记
  • 线性代数学习笔记
  • AI学习笔记

项目已开源至 Github ,欢迎star和fork 若你觉得对你的开发有帮助, 或是对你的生活提供了方便, 欢迎来 爱发电 赞助 爱发电 如果想一起开发或贡献插件等, 欢迎在相关标准制定后按照标准提交PR, 或 联系作者