Skip to content

Commit

Permalink
feat: 优化指令装饰器并新增指令装饰器demo
Browse files Browse the repository at this point in the history
  • Loading branch information
SaucePlum committed Jun 13, 2022
1 parent b74a705 commit 2c339c2
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 5 deletions.
12 changes: 7 additions & 5 deletions botpy/ext/command_util.py
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
from functools import wraps

from botpy import BotAPI
from botpy.message import Message


Expand All @@ -15,17 +16,18 @@ def __init__(self, commands: tuple or str):
def __call__(self, func):
@wraps(func)
async def decorated(*args, **kwargs):
api: BotAPI = kwargs["api"]
message: Message = kwargs["message"]
if isinstance(self.commands, tuple):
for command in self.commands:
if self.commands in message.content:
if command in message.content:
# 分割指令后面的指令参数
params = message.content.split(self.commands)[1].strip()
return await func(message=message, params=params)
elif isinstance(self.commands, str):
return await func(api=api, message=message, params=params)
elif self.commands in message.content:
# 分割指令后面的指令参数
params = message.content.split(self.command)[1].strip()
return await func(message=message, params=params)
params = message.content.split(self.commands)[1].strip()
return await func(api=api, message=message, params=params)
else:
return False

Expand Down
56 changes: 56 additions & 0 deletions examples/demo_at_reply_command.py
@@ -0,0 +1,56 @@
# -*- coding: utf-8 -*-
import os

import botpy
from botpy import logging, BotAPI
from botpy.ext.command_util import Commands
from botpy.message import Message
from botpy.ext.yaml_util import YamlUtil

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

_log = logging.get_logger()


@Commands("你好")
async def hello(api: BotAPI, message: Message, params=None):
_log.info(params)
# 第一种用reply发送消息
await message.reply(content=params)
# 第二种用api.post_message发送消息
await api.post_message(channel_id=message.channel_id, content=params, msg_id=message.id)
return True


@Commands("晚安")
async def good_night(api: BotAPI, message: Message, params=None):
_log.info(params)
# 第一种用reply发送消息
await message.reply(content=params)
# 第二种用api.post_message发送消息
await api.post_message(channel_id=message.channel_id, content=params, msg_id=message.id)
return True


class MyClient(botpy.Client):
async def on_at_message_create(self, message: Message):
# 注册指令handler
handlers = [
hello,
good_night,
]
for handler in handlers:
if await handler(api=self.api, message=message):
return



if __name__ == "__main__":
# 通过预设置的类型,设置需要监听的事件通道
# intents = botpy.Intents.none()
# intents.public_guild_messages=True

# 通过kwargs,设置需要监听的事件通道
intents = botpy.Intents(public_guild_messages=True)
client = MyClient(intents=intents)
client.run(appid=test_config["appid"], token=test_config["token"])

0 comments on commit 2c339c2

Please sign in to comment.