Exemple #1
0
from utils import Data as data
from vkbottle.bot import BotLabeler

help = [
	"/MyLVL - мой уровень",
	"/LVL & <rep_mes> - посмотреть уровень участника",
	"/Tele <count> & <rep_mes> - передать свою exp другому",
	"/TopLVL[ <от> <до>] - топ 10 участников",
	"/TopTemp[ <от> <до>] - временный топ 10 участников",
	"/Info & <rep_mes> - узнать вес сообщения"
]

bl = BotLabeler()

@bl.chat_message(command = 'mylvl')
async def mylvl(message):
	await data.lvl.send_work(id := message.from_id)
	await message.answer(data.lvl[id])

@bl.chat_message(command = 'lvl', with_reply_message = True)
async def lvl(message):
	await data.lvl.send_work(id := message.reply_message.from_id)
	await message.answer(data.lvl[id])

@bl.chat_message(command = ['tele <exp:pos>', 'tele <exp:inc[up]>'], with_reply_message = True, from_id_pos = True)
async def tele(message, exp):
	if exp == 'up': exp = await data.lvl.atta(message.reply_message.text, message.reply_message.attachments)
	await data.lvl.remove_exp(id1 := message.from_id, exp = exp)
	await data.lvl.update_lvl(id2 := message.reply_message.from_id, exp = exp)
	await data.lvl.send(id1, id2)
	await message.answer(f"{exp:+}Ⓔ:\n{data.lvl[id2]}\n{-exp:+}Ⓔ:\n{data.lvl[id1]}")
Exemple #2
0
async def test_rules(api: API):
    assert await base.FromPeerRule(123).check(fake_message(api, peer_id=123))
    assert not await base.FromUserRule().check(fake_message(api, from_id=-1))
    assert await base.VBMLRule("i am in love with <whom>", vbml.Patcher()).check(
        fake_message(api, text="i am in love with you")
    ) == {"whom": "you"}
    assert await base.FuncRule(lambda m: m.text.endswith("!")).check(
        fake_message(api, text="yes!")
    )
    assert not await base.PeerRule().check(fake_message(api, peer_id=1, from_id=1))
    assert await base.PayloadMapRule([("a", int), ("b", str)]).check(
        fake_message(api, payload=json.dumps({"a": 1, "b": ""}))
    )
    assert await base.PayloadMapRule([("a", int), ("b", [("c", str), ("d", dict)])]).check(
        fake_message(api, payload=json.dumps({"a": 1, "b": {"c": "", "d": {}}}))
    )
    assert await base.PayloadMapRule({"a": int, "b": {"c": str, "d": dict}}).check(
        fake_message(api, payload=json.dumps({"a": 1, "b": {"c": "", "d": {}}}))
    )
    assert await base.StickerRule(sticker_ids=[1, 2]).check(
        fake_message(api, attachments=[{"type": "sticker", "sticker": {"sticker_id": 2}}])
    )

    assert (
        await AndRule(base.FromPeerRule(123), base.FromPeerRule([1, 123])).check(
            fake_message(api, peer_id=123)
        )
        is not False
    )
    assert (
        await OrRule(base.FromPeerRule(123), base.FromPeerRule([1, 123])).check(
            fake_message(api, peer_id=1)
        )
        is not False
    )
    assert await NotRule(base.FromPeerRule(123)).check(fake_message(api, peer_id=1)) is not False
    assert await base.RegexRule(r"Hi .*?").check(fake_message(api, text="Hi bro")) == {"match": ()}
    assert await base.RegexRule("Hi (.*?)$").check(fake_message(api, text="Hi bro")) == {
        "match": ("bro",)
    }
    assert await base.RegexRule(r"Hi .*?").check(fake_message(api, text="Hi")) != {"match": ()}

    assert base.PayloadMapRule.transform_to_map({"a": int, "b": {"c": str, "d": dict}}) == [
        ("a", int),
        ("b", [("c", str), ("d", dict)]),
    ]
    assert await base.CommandRule("cmd", ["!", "."], 2).check(
        fake_message(api, text="!cmd test bar")
    ) == {"args": ("test", "bar")}
    assert (
        await base.CommandRule("cmd", ["!", "."], 2).check(fake_message(api, text="cmd test bar"))
        is False
    )

    # todo: if args are more than args_count do join excess args with last
    assert (
        await base.CommandRule("cmd", ["!", "."], 1).check(fake_message(api, text="cmd test bar"))
        is False
    )

    assert (
        await base.CommandRule("cmd", ["!", "."], 3).check(fake_message(api, text="cmd test bar"))
        is False
    )

    labeler = BotLabeler()
    labeler.vbml_ignore_case = True
    assert (
        await labeler.get_custom_rules({"text": "privet"})[0].check(
            fake_message(api, text="Privet")
        )
        == {}
    )
    labeler.vbml_ignore_case = False
    assert not await labeler.get_custom_rules({"text": "privet"})[0].check(
        fake_message(api, text="Private")
    )
    assert await base.PayloadRule({"cmd": "text"}).check(
        fake_message(api, payload='{"cmd":"text"}')
    )
    assert await base.PayloadRule([{"cmd": "text"}, {"cmd": "ne text"}]).check(
        fake_message(api, payload='{"cmd":"text"}')
    )
    s_mock_message = fake_message(api)
    s_mock_message.state_peer = StatePeer(peer_id=1, state=FirstMockState.MOCK)
    assert await base.StateRule(state=FirstMockState.MOCK).check(s_mock_message)
    assert not await base.StateRule(state=SecondMockState.MOCK).check(s_mock_message)
    assert await base.StateRule(state=None).check(fake_message(api))
    assert await base.StateGroupRule(state_group=None).check(fake_message(api))
    sg_mock_message = fake_message(api)
    sg_mock_message.state_peer = StatePeer(peer_id=1, state=FirstMockState.MOCK, payload={})
    assert await base.StateGroupRule(state_group=FirstMockState).check(sg_mock_message)
    assert not await base.StateGroupRule(state_group=SecondMockState).check(sg_mock_message)
Exemple #3
0
bot.labeler.vbml_ignore_case = True  # type: ignore
# You can add default flags if ignore case is False
# <bot.labeler.default_flags = ...>

# We can add rule to custom_rules and it will be accessible
# in handlers in any place but is it of importance that
# labeler is always local (shortcuts work only for a local
# instance, for eg Bot, Blueprint, or pure Labeler)
bot.labeler.custom_rules["spam"] = SpamRule

# BotLabeler has fixed views. If you want to add yours you need
# to implement custom labeler, take it in account that labeler
# views are GLOBAL(!)
bot.labeler.views()  # {"message": MessageView, "raw": RawEventView}

bot.labeler.load(BotLabeler())  # Labeler can be loaded in another labeler

# Patcher for vbml rule shortcut can be set:
# <bot.labeler.patcher = ...>


# We will add some states
# The comments for states are skipped because
# we have another topic of the example
class SpamState(BaseStateGroup):
    GOOD = 1
    BAD = 2


# Lets add some handlers
@bot.on.chat_message(spam=["!", ".", "?", "$", "#", "@", "%"])
Exemple #4
0
async def test_rules(api: API):
    assert await rules.FromPeerRule(123).check(fake_message(api, peer_id=123))
    assert not await rules.FromUserRule().check(fake_message(api, from_id=-1))
    assert await rules.VBMLRule(
        "i am in love with <whom>",
        vbml.Patcher()).check(fake_message(api,
                                           text="i am in love with you")) == {
                                               "whom": "you"
                                           }
    assert await rules.FuncRule(lambda m: m.text.endswith("!")).check(
        fake_message(api, text="yes!"))
    assert not await rules.PeerRule(from_chat=True).check(
        fake_message(api, peer_id=1, from_id=1))
    assert await rules.PayloadMapRule([
        ("a", int), ("b", str)
    ]).check(fake_message(api, payload=json.dumps({
        "a": 1,
        "b": ""
    })))
    assert await rules.PayloadMapRule([("a", int),
                                       ("b", [("c", str), ("d", dict)])]
                                      ).check(
                                          fake_message(api,
                                                       payload=json.dumps({
                                                           "a": 1,
                                                           "b": {
                                                               "c": "",
                                                               "d": {}
                                                           }
                                                       })))
    assert await rules.PayloadMapRule({
        "a": int,
        "b": {
            "c": str,
            "d": dict
        }
    }).check(
        fake_message(api,
                     payload=json.dumps({
                         "a": 1,
                         "b": {
                             "c": "",
                             "d": {}
                         }
                     })))
    assert await rules.StickerRule(sticker_ids=[1, 2]).check(
        fake_message(api,
                     attachments=[{
                         "type": "sticker",
                         "sticker": {
                             "sticker_id": 2
                         }
                     }]))

    assert (await AndFilter(rules.FromPeerRule(123),
                            rules.FromPeerRule([1, 123])).check(
                                fake_message(api, peer_id=123)) is not False)
    assert (await
            OrFilter(rules.FromPeerRule(123),
                     rules.FromPeerRule([1, 123
                                         ])).check(fake_message(api,
                                                                peer_id=1))
            is not False)
    assert await rules.RegexRule(r"Hi .*?").check(
        fake_message(api, text="Hi bro")) == {
            "match": ()
        }
    assert await rules.RegexRule("Hi (.*?)$").check(
        fake_message(api, text="Hi bro")) == {
            "match": ("bro", )
        }
    assert not await rules.RegexRule(r"Hi .*?").check(
        fake_message(api, text="Hi")) == {
            "match": ()
        }
    assert rules.PayloadMapRule.transform_to_map({
        "a": int,
        "b": {
            "c": str,
            "d": dict
        }
    }) == [
        ("a", int),
        ("b", [("c", str), ("d", dict)]),
    ]

    labeler = BotLabeler()
    labeler.vbml_ignore_case = True
    assert (await labeler.get_custom_rules({"text": "privet"})
            [0].check(fake_message(api, text="Privet")) == {})
    labeler.vbml_ignore_case = False
    assert not await labeler.get_custom_rules({"text": "privet"})[0].check(
        fake_message(api, text="Private"))
    assert await rules.PayloadRule({
        "cmd": "text"
    }).check(fake_message(api, payload='{"cmd":"text"}'))
    assert await rules.PayloadRule([{
        "cmd": "text"
    }, {
        "cmd": "ne text"
    }]).check(fake_message(api, payload='{"cmd":"text"}'))
    assert await rules.StateRule(state=None).check(fake_message(api))
    assert not await rules.StateRule(state=MockIntEnum.MOCK).check(
        fake_message(api))
    assert await rules.StateGroupRule(state_group=None).check(fake_message(api)
                                                              )
    sg_mock_message = fake_message(api)
    sg_mock_message.state_peer = StatePeer(peer_id=1,
                                           state=MockIntEnum.MOCK,
                                           payload={})
    assert await rules.StateGroupRule(state_group=MockIntEnum
                                      ).check(sg_mock_message)