Skip to content

Commit

Permalink
核心部分多平台适配(ing)
Browse files Browse the repository at this point in the history
  • Loading branch information
LambdaYH committed Jan 12, 2024
1 parent 1b0b28d commit 5638345
Show file tree
Hide file tree
Showing 68 changed files with 1,969 additions and 1,244 deletions.
2 changes: 1 addition & 1 deletion .env
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
ENVIRONMENT=prod
DRIVER=~fastapi
DRIVER=~fastapi+~httpx

# nonebot_plugin_wordcloud
wordcloud_background_color = white
Expand Down
22 changes: 16 additions & 6 deletions migang/core/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
from migang.core.cross_platform import ( # noqa
GROUP,
SUPERUSER,
GROUP_ADMIN,
Session,
MigangSession,
)

from .message import broadcast # noqa
from .rules import GroupTaskChecker # noqa
from .utils.task_operation import check_task # noqa
from .utils.config_operation import get_config, sync_get_config # noqa
from .permission import BAD, GOOD, BLACK, NORMAL, EXCELLENT, Permission # noqa
from .path import ( # noqa
DATA_PATH,
Expand All @@ -10,12 +19,6 @@
RESOURCE_PATH,
TEMPLATE_PATH,
)
from .utils.config_operation import ( # noqa
get_config,
sync_get_config,
pre_init_manager,
post_init_manager,
)
from .manager import ( # noqa
CDItem,
TaskItem,
Expand All @@ -25,3 +28,10 @@
ConfigItem,
CountPeriod,
)
from .event_register import ( # noqa
shutdown,
pre_init_manager,
post_init_manager,
pre_init_manager_l2,
post_init_manager_l2,
)
1 change: 1 addition & 0 deletions migang/core/constant.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ID_MAX_LENGTH = 16
47 changes: 22 additions & 25 deletions migang/core/core_plugins/bank/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,16 @@
from datetime import datetime

from pil_utils import BuildImage
from nonebot.params import Startswith
from arclet.alconna import Args, Alconna
from nonebot.plugin import PluginMetadata
from nonebot import on_fullmatch, on_startswith
from tortoise.transactions import in_transaction
from nonebot.adapters.onebot.v11 import MessageEvent, MessageSegment
from nonebot_plugin_alconna import UniMessage, on_alconna

from migang.core import ConfigItem, get_config
from migang.core.cross_platform import Session
from migang.core.models.bank import DepositType
from migang.core.models import Bank, UserProperty
from migang.core.cross_platform.adapters import supported_adapters

__plugin_meta__ = PluginMetadata(
name="银行",
Expand All @@ -22,7 +23,7 @@
我的存款
""".strip(),
type="application",
supported_adapters={"~onebot.v11"},
supported_adapters=supported_adapters,
)

__plugin_category__ = "基础功能"
Expand All @@ -35,47 +36,43 @@
),
)

deposit_coins = on_startswith("存金币", priority=True, block=True)
take_coins = on_startswith("取金币", priority=5, block=True)
my_deposit = on_fullmatch("我的存款", priority=5, block=True)
deposit_coins = on_alconna(Alconna("存金币", Args["amount", int]), priority=5, block=True)
take_coins = on_alconna(Alconna("取金币", Args["amount", int]), priority=5, block=True)
my_deposit = on_alconna("我的存款", priority=5, block=True)

bg_path = Path(__file__).parent / "images" / "bg.jpg"


@deposit_coins.handle()
async def _(event: MessageEvent, cmd: str = Startswith()):
amount = event.get_plaintext().removeprefix(cmd).strip()
if not amount.isdigit():
async def _(amount: int, session: Session):
if amount <= 0:
await deposit_coins.finish("存入金额必须为正整数")
amount = int(amount)
async with in_transaction() as connection:
now_gold = await UserProperty.get_gold(
user_id=event.user_id, connection=connection
user_id=session.user_id, connection=connection
)
if now_gold < amount:
await deposit_coins.finish("背包里的金币不够存哦~")
await UserProperty.modify_gold(
user_id=event.user_id,
user_id=session.user_id,
gold_diff=-amount,
description="存入银行",
connection=connection,
)
await Bank(user_id=event.user_id, amount=amount).save(
await Bank(user_id=session.user_id, amount=amount).save(
update_fields=["amount"], using_db=connection
)
await deposit_coins.send(f"{amount}金币已经存放妥当了")


@take_coins.handle()
async def _(event: MessageEvent, cmd: str = Startswith()):
amount = event.get_plaintext().removeprefix(cmd).strip()
if not amount.isdigit():
await deposit_coins.finish("存入金额必须为正整数")
amount = int(amount)
async def _(amount: int, session: Session):
if amount <= 0:
await deposit_coins.finish("取出金额必须为正整数")
ori_amount = amount
async with in_transaction() as connection:
total_demand_deposit = await Bank.get_total_demand_deposit(
user_id=event.user_id, connection=connection
user_id=session.user_id, connection=connection
)
if total_demand_deposit < amount:
await take_coins.finish("您未在这存放足够的金币哦~")
Expand All @@ -85,7 +82,7 @@ async def _(event: MessageEvent, cmd: str = Startswith()):
now = datetime.utcnow()
all_demand_deposit = (
await Bank.filter(
user_id=event.user_id, deposit_type=DepositType.demand_deposit
user_id=session.user_id, deposit_type=DepositType.demand_deposit
)
.order_by("-time")
.all()
Expand All @@ -109,7 +106,7 @@ async def _(event: MessageEvent, cmd: str = Startswith()):
await demand_deposit.delete(using_db=connection)
amount -= demand_deposit.amount
await UserProperty.modify_gold(
user_id=event.user_id,
user_id=session.user_id,
gold_diff=ori_amount + total_earned,
description="从银行中取出",
connection=connection,
Expand All @@ -118,8 +115,8 @@ async def _(event: MessageEvent, cmd: str = Startswith()):


@my_deposit.handle()
async def _(event: MessageEvent):
total_demand_deposit = await Bank.get_total_demand_deposit(user_id=event.user_id)
async def _(session: Session):
total_demand_deposit = await Bank.get_total_demand_deposit(user_id=session.user_id)
# 定期存款,懒得写
# time_deposit = await Bank.filter(
# user_id=event.user_id, deposit_type=DepositType.time_deposit
Expand Down Expand Up @@ -148,4 +145,4 @@ async def _(event: MessageEvent):
)
bg_img = bg_img.resize_canvas(size=(demand_img.width + 30, demand_img.height + 30))
bg_img.paste(img=demand_img, pos=(15, 15), alpha=True)
await my_deposit.send(MessageSegment.image(bg_img.save_png()))
await my_deposit.send(UniMessage.image(bg_img.save_png()))
65 changes: 41 additions & 24 deletions migang/core/core_plugins/chat/__init__.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
import random
from typing import List
from pathlib import Path

from nonebot.log import logger
from nonebot.rule import to_me
from nonebot.matcher import Matcher
from nonebot.adapters import Bot, Event
from nonebot.plugin import PluginMetadata
from nonebot import on_keyword, on_message
from nonebot.adapters.onebot.v11 import (
GROUP,
Bot,
Message,
MessageSegment,
GroupMessageEvent,
)
from nonebot_plugin_alconna import Text, UniMsg, UniMessage
from nonebot_plugin_userinfo import UserInfo, EventUserInfo

from migang.core import ConfigItem, get_config
from migang.core.cross_platform import GROUP
from migang.core import Session, ConfigItem, get_config
from migang.core.utils.image import image_file_to_bytes
from migang.core.cross_platform.adapters import supported_adapters

from .message_manager import MessageManager
from .chatgpt import do_chat, not_at_rule, get_gpt_chat
Expand All @@ -29,7 +29,7 @@
与Bot普普通通的对话吧!
""".strip(),
type="application",
supported_adapters={"~onebot.v11"},
supported_adapters=supported_adapters,
)

__plugin_config__ = (
Expand All @@ -51,33 +51,44 @@
chat = on_message(rule=to_me(), priority=998, permission=GROUP)
message_manager = MessageManager(hello, anti_zuichou, get_gpt_chat, no_result)
# 没at时候把消息送给naturel_gpt处理
on_message(priority=998, block=False, rule=not_at_rule).append_handler(do_chat)
on_message(
priority=998, block=False, rule=not_at_rule, permission=GROUP
).append_handler(do_chat)


@chat.handle()
async def _(matcher: Matcher, bot: Bot, event: GroupMessageEvent):
if "CQ:xml" in str(event.message) or event.get_plaintext().startswith("/"):
async def _(
matcher: Matcher,
bot: Bot,
event: Event,
message: UniMsg,
session: Session,
user_info: UserInfo = EventUserInfo(),
):
plain_text = event.get_plaintext()
if "CQ:xml" in str(message) or plain_text.startswith("/"):
return
user_name = event.sender.card or event.sender.nickname
reply = await message_manager.reply(
user_id=event.user_id,
user_name=user_name,
session=session,
user_name=user_info.user_name,
nickname=list(bot.config.nickname)[0],
bot=bot,
matcher=matcher,
plain_text=event.get_plaintext(),
event=event,
message=message,
)
if not reply:
return
logger.info(
f"用户 {event.user_id}{event.group_id if isinstance(event, GroupMessageEvent) else ''} "
f"问题:{event.message} ---- 回答:{reply}"
f"用户 {session.user_id}{session.group_id if session.is_group else ''} "
f"问题:{message} ---- 回答:{reply}"
)
reply = str(reply)
for t in await get_config("text_filter"):
reply = reply.replace(t, "*")
await chat.send(Message(reply))
texts: List[Text] = reply.get(Text)
for text in texts:
for t in await get_config("text_filter"):
text.text = text.text.replace(t, "*")
await reply.send()


# 加一点祖传回复
Expand All @@ -93,16 +104,22 @@ async def _(matcher: Matcher, bot: Bot, event: GroupMessageEvent):
@wenhao.handle()
async def _():
if random.random() < 0.30:
await wenhao.send(MessageSegment.image(custom_chat_path / "wenhao.jpg"))
await UniMessage.image(
await image_file_to_bytes(custom_chat_path / "wenhao.jpg")
).send()


@tanhao.handle()
async def _():
if random.random() < 0.30:
await tanhao.send(MessageSegment.image(custom_chat_path / "tanhao.jpg"))
await UniMessage.image(
await image_file_to_bytes(custom_chat_path / "tanhao.jpg")
).send()


@huoguo.handle()
async def _():
if random.random() < 0.30:
await huoguo.send(MessageSegment.image(custom_chat_path / "huoguo.jpg"))
await UniMessage.image(
await image_file_to_bytes(custom_chat_path / "huoguo.jpg")
).send()
29 changes: 22 additions & 7 deletions migang/core/core_plugins/chat/chatgpt/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from nonebot.typing import T_State
from nonebot.matcher import Matcher
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent
from nonebot.adapters import Bot, Event
from nonebot_plugin_alconna import UniMsg, UniMessage

from migang.core.manager import config_manager
from migang.core import ConfigItem, pre_init_manager
from migang.core import Session, ConfigItem, MigangSession, pre_init_manager

from ..exception import BreakSession
from .chat import do_chat, pre_check
Expand Down Expand Up @@ -119,16 +120,30 @@ async def _():
# ========================= #


async def get_gpt_chat(matcher: Matcher, event: GroupMessageEvent, bot: Bot):
async def get_gpt_chat(
matcher: Matcher,
event: Event,
bot: Bot,
message: UniMessage,
session: MigangSession,
):
state = {}
if await pre_check(event=event, bot=bot, state=state):
await do_chat(matcher=matcher, event=event, bot=bot, state=state)
if await pre_check(
message=message, event=event, bot=bot, state=state, session=session
):
await do_chat(
matcher=matcher, event=event, bot=bot, state=state, session=session
)
raise BreakSession("由naturel_gpt处理发送逻辑")


async def not_at_rule(bot: Bot, event: GroupMessageEvent, state: T_State) -> bool:
async def not_at_rule(
bot: Bot, event: Event, state: T_State, message: UniMsg, session: Session
) -> bool:
# 只响应非at事件,at事件让别的去管
if event.is_tome():
return False

return await pre_check(event=event, bot=bot, state=state)
return await pre_check(
message=message, event=event, bot=bot, state=state, session=session
)
Loading

0 comments on commit 5638345

Please sign in to comment.