Skip to content

Commit

Permalink
Merge pull request #113 from Redmomn/main
Browse files Browse the repository at this point in the history
fix: 对多bot实例情况进行简单的适配
  • Loading branch information
yzyyz1387 authored Jan 10, 2024
2 parents fc06351 + 0828cf9 commit f7cea86
Show file tree
Hide file tree
Showing 8 changed files with 70 additions and 46 deletions.
4 changes: 2 additions & 2 deletions nonebot_plugin_admin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,11 @@


@driver.on_bot_connect
async def _():
async def _(bot: nonebot.adapters.Bot):
await init()
bot = nonebot.get_bot()
await switcher_integrity_check(bot)


__plugin_meta__ = PluginMetadata(
name="不简易群管",
description="Nonebot2 群管插件 插件",
Expand Down
9 changes: 5 additions & 4 deletions nonebot_plugin_admin/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ async def _(bot: Bot, matcher: Matcher, event: GroupMessageEvent):
sb = At(event.json())
gid = event.group_id
if sb:
baning = banSb(gid, ban_list=sb, time=time)
baning = banSb(bot, gid, ban_list=sb, time=time)
try:
async for baned in baning:
if baned:
Expand All @@ -60,7 +60,7 @@ async def _(bot: Bot, matcher: Matcher, event: GroupMessageEvent):
sb = At(event.json())
gid = event.group_id
if sb:
baning = banSb(gid, ban_list=sb, time=0)
baning = banSb(bot, gid, ban_list=sb, time=0)
try:
async for baned in baning:
if baned:
Expand All @@ -70,7 +70,8 @@ async def _(bot: Bot, matcher: Matcher, event: GroupMessageEvent):
await fi(matcher, '权限不足')


ban_all = on_command('/all', aliases={'/全员'}, permission=SUPERUSER | GROUP_ADMIN | GROUP_OWNER | DEPUTY_ADMIN, priority=1,
ban_all = on_command('/all', aliases={'/全员'}, permission=SUPERUSER | GROUP_ADMIN | GROUP_OWNER | DEPUTY_ADMIN,
priority=1,
block=True)


Expand Down Expand Up @@ -388,4 +389,4 @@ async def _(bot: Bot, matcher: Matcher, event: GroupMessageEvent): # by: @tom-s
except ActionFailed as e:
await log_fi(matcher, '撤回失败', f"撤回失败 {e}")
else:
pass
pass
2 changes: 1 addition & 1 deletion nonebot_plugin_admin/auto_ban.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ async def _(bot: Bot, event: GroupMessageEvent, matcher: Matcher):
except ActionFailed:
logger.info('消息撤回失败')
if ban:
baning = banSb(gid, ban_list=[event.get_user_id()], scope=ts)
baning = banSb(bot, gid, ban_list=[event.get_user_id()], scope=ts)
async for baned in baning:
if baned:
try:
Expand Down
4 changes: 2 additions & 2 deletions nonebot_plugin_admin/broadcast.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,11 +122,11 @@ async def _(
await add_avoid_group(event, gid, matcher, state)


async def add_avoid_group(event: MessageEvent, args, matcher: Matcher, state: T_State):
async def add_avoid_group(event: MessageEvent, bot: Bot, args, matcher: Matcher, state: T_State):
uid = str(event.user_id)
args = str(args).replace("+", "").strip()
groups = str(args).split(" ")
groups_bot = await get_bot().get_group_list()
groups_bot = await bot.get_group_list()
g_list = []
for g in groups_bot:
g_list.append(str(g["group_id"]))
Expand Down
60 changes: 41 additions & 19 deletions nonebot_plugin_admin/group_msg.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@
import random

import requests
from nonebot import require, get_bot, get_driver
from nonebot import require, get_bots, get_driver
from nonebot.log import logger

from .func_hook import check_func_status

try:
scheduler = require('nonebot_plugin_apscheduler').scheduler
except BaseException:
Expand Down Expand Up @@ -101,15 +103,25 @@ async def send_morning():
await asyncio.sleep(random.randint(1, 10))
# await get_bot().send_private_msg(user_id = fire_user_id, message = "🌞早,又是元气满满的一天") #
# 当未连接到onebot.v11协议端时会抛出异常
for gid in send_group_id:
if await check_func_status('group_msg', gid):
if send_mode == 1:
await get_bot().send_group_msg(group_id=gid,
message=f"{random.choice(send_sentence_morning)}")
if send_mode == 2:
await get_bot().send_group_msg(group_id=gid, message=hitokoto())
logger.info('群聊推送消息')
sendSuccess = True
bots = get_bots()
for bot in bots.values():
for gid in send_group_id:
if await check_func_status('group_msg', gid):
if send_mode == 1:
try:
await bot.send_group_msg(group_id=gid,
message=f"{random.choice(send_sentence_morning)}")
except Exception:
# 这个机器人没有加这个群
pass
if send_mode == 2:
try:
await bot.send_group_msg(group_id=gid, message=hitokoto())
except Exception:
# 这个机器人没有加这个群
pass
logger.info('群聊推送消息')
sendSuccess = True
except ValueError as E:
logger.error("ValueError:{}", E)
logger.error('群聊推送消息插件获取bot失败,1s后重试')
Expand All @@ -127,15 +139,25 @@ async def send_night():
await asyncio.sleep(random.randint(1, 10))
# await get_bot().send_private_msg(user_id = fire_user_id, message = "🌛今天续火花了么,晚安啦") #
# 当未连接到onebot.v11协议端时会抛出异常
for gid in send_group_id:
if await check_func_status('group_msg', gid):
if send_mode == 1:
await get_bot().send_group_msg(group_id=gid,
message=f"{random.choice(send_sentence_night)}")
if send_mode == 2:
await get_bot().send_group_msg(group_id=gid, message=hitokoto())
logger.info('群聊推送消息')
sendSuccess = True
bots = get_bots()
for bot in bots.values():
for gid in send_group_id:
if await check_func_status('group_msg', gid):
if send_mode == 1:
try:
await bot.send_group_msg(group_id=gid,
message=f"{random.choice(send_sentence_night)}")
except Exception:
# 这个机器人没有加这个群
pass
if send_mode == 2:
try:
await bot.send_group_msg(group_id=gid, message=hitokoto())
except Exception:
# 这个机器人没有加这个群
pass
logger.info('群聊推送消息')
sendSuccess = True
except ValueError as E:
logger.error("ValueError:{}", E)
logger.error('群聊推送消息插件获取bot失败,1s后重试')
Expand Down
2 changes: 1 addition & 1 deletion nonebot_plugin_admin/img_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ async def send_pics_ban(bot: Bot, event: GroupMessageEvent, scope: list = None):
logger.info('检测到违规图片,撤回成功')
except ActionFailed:
logger.info('检测到违规图片,但权限不足,撤回失败')
baning = banSb(gid, ban_list=uid, scope=scope)
baning = banSb(bot, gid, ban_list=uid, scope=scope)
async for baned in baning:
if baned:
try:
Expand Down
33 changes: 17 additions & 16 deletions nonebot_plugin_admin/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,19 +120,20 @@ async def init():
if not word_path.exists():
await mk('file', word_path, 'w', content='123456789\n')
if not switcher_path.exists():
bot = nonebot.get_bot()
logger.info('创建开关配置文件,分群设置, 图片检测和违禁词检测,防撤回,广播,早晚安默认关,其他默认开')
g_list = (await bot.get_group_list())
switcher_dict = {}
for group in g_list:
switchers = {}
for fn_name in admin_funcs:
switchers.update({fn_name: True})
if fn_name in ['img_check', 'auto_ban', 'group_msg', 'particular_e_notice', 'group_recall']:
switchers.update({fn_name: False})
switcher_dict.update({str(group['group_id']): switchers})
with open(switcher_path, 'w', encoding='utf-8') as swp:
swp.write(f"{json.dumps(switcher_dict)}")
bots = nonebot.get_bots()
for bot in bots.values():
logger.info('创建开关配置文件,分群设置, 图片检测和违禁词检测,防撤回,广播,早晚安默认关,其他默认开')
g_list = (await bot.get_group_list())
switcher_dict = {}
for group in g_list:
switchers = {}
for fn_name in admin_funcs:
switchers.update({fn_name: True})
if fn_name in ['img_check', 'auto_ban', 'group_msg', 'particular_e_notice', 'group_recall']:
switchers.update({fn_name: False})
switcher_dict.update({str(group['group_id']): switchers})
with open(switcher_path, 'w', encoding='utf-8') as swp:
swp.write(f"{json.dumps(switcher_dict)}")
if not limit_word_path.exists(): # 要联网的都丢最后面去
if (config_path / '违禁词_简单.txt').exists():
with open(config_path / '违禁词_简单.txt', 'r', encoding='utf-8') as f:
Expand Down Expand Up @@ -194,7 +195,7 @@ async def mk(type_, path_, *mode, **kwargs):
raise Exception('type_参数错误')


async def banSb(gid: int, ban_list: list, time: int = None, scope: list = None):
async def banSb(bot: Bot, gid: int, ban_list: list, time: int = None, scope: list = None):
"""
构造禁言
:param gid: 群号
Expand All @@ -204,7 +205,7 @@ async def banSb(gid: int, ban_list: list, time: int = None, scope: list = None):
:return:禁言操作
"""
if 'all' in ban_list:
yield nonebot.get_bot().set_group_whole_ban(
yield bot.set_group_whole_ban(
group_id=gid,
enable=True
)
Expand All @@ -220,7 +221,7 @@ async def banSb(gid: int, ban_list: list, time: int = None, scope: list = None):
# if cb_notice:
# await nonebot.get_bot().send_group_msg(group_id = gid, message = 'SUPERUSER无法被禁言')
else:
yield nonebot.get_bot().set_group_ban(
yield bot.set_group_ban(
group_id=gid,
user_id=qq,
duration=time,
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

setuptools.setup(
name="nonebot-plugin-admin",
version="0.4.5.2",
version="0.4.5.3",
author="yzyyz1387",
author_email="[email protected]",
keywords=("pip", "nonebot2", "nonebot", "admin", "nonebot_plugin"),
Expand Down

0 comments on commit f7cea86

Please sign in to comment.