Exemple #1
0
from module import Blueprint, Method
from module import types
from dutymanager.units.utils import send_msg
from dutymanager.db.methods import AsyncDatabase

bot = Blueprint()
db = AsyncDatabase.get_current()


async def unbind_chat(uid: str):
    if uid in db.chats:
        chat_id = await db.remove_chat(uid)
        await send_msg(chat_id, "✅ Чат успешно отвязан.")


@bot.on.message_event(
    Method.SEND_SIGNAL,
    text=["отвязать", "отвязать <uid>"]
)
async def send_signal(event: types.SendSignal, uid: str = None):
    uid = uid if uid else event.object.chat
    await unbind_chat(uid)


@bot.on.message_event(
    Method.SEND_MY_SIGNAL,
    text=["отвязать", "отвязать <uid>"]
)
async def send_my_signal(event: types.SendMySignal, uid: str = None):
    uid = uid if uid else event.object.chat
    await unbind_chat(uid)
Exemple #2
0
"""

Tools for vk-bot

"""

from module import Blueprint
from typing import Optional

bp = Blueprint()

__all__ = ("get_chat", "send_msg", "get_msg_id", "get_msg_ids", "get_history",
           "edit_msg", "get_attachments", "bp")


async def get_attachments(message_id: int) -> Optional[str]:
    attachments = []
    data = (await bp.api.request("messages.getById",
                                 {"message_ids": message_id}))["items"][0]
    if not data["attachments"]:
        return
    for x in data["attachments"]:
        kind = x["type"]
        if kind != "link":
            attachments.append(f"{kind}{x[kind]['owner_id']}_{x[kind]['id']}")
    return ",".join(attachments)


async def get_history(peer_id: int, count: int = 200) -> dict:
    history = (await bp.api.request("messages.getHistory", {
        "peer_id": peer_id,
Exemple #3
0
from dutymanager.db.methods import AsyncDatabase
from module import Blueprint, Method
from module import types

bot = Blueprint(name="Information")
db = AsyncDatabase.get_current()
patterns = ["инфо", "инфа", "-i", "info"]


async def abstract_info(uid: str, local_id: str, method: str):
    pass


@bot.event.message_signal(Method.SEND_SIGNAL, text=patterns, lower=True)
async def send_signal(event: types.SendSignal):
    pass


@bot.event.message_signal(Method.SEND_MY_SIGNAL, text=patterns, lower=True)
async def send_my_signal(event: types.SendMySignal):
    pass
Exemple #4
0
from dutymanager.db.methods import AsyncDatabase
from dutymanager.units.vk_script import msg_edit
from module import Blueprint, Method
from module import types

bot = Blueprint(name="Settings")
db = AsyncDatabase.get_current()


async def set_limit(limit: int, uid: str, local_id: int):
    peer_id = db.chats(uid)
    if limit <= 0:
        return await msg_edit(peer_id=peer_id,
                              local_id=local_id,
                              message="❗ Лимит должен быть не меньше 0.")
    db.settings.change(page_limit=limit)
    db.create_pages(limit)
    await msg_edit(peer_id=peer_id,
                   local_id=local_id,
                   message="✅ Лимит шаблонов на одной странице был изменён.")


@bot.event.message_signal(Method.SEND_MY_SIGNAL,
                          text="лимит <page:int>",
                          lower=True)
async def send_my_signal(event: types.SendMySignal, page: int):
    await set_limit(page, event.object.chat,
                    event.message.conversation_message_id)


@bot.event.message_signal(Method.SEND_SIGNAL,
Exemple #5
0
"""

File to work with VK Script compilation

"""
from module.utils import logger
from module import Blueprint

bot = Blueprint(name="VK Script")
__all__ = ('execute', 'get_chat', 'msg_edit', 'msg_send', 'delete_messages',
           'friends_method')


async def execute(code: str):
    logger.debug("Formatting result:\n{}", code)
    return await bot.api.request("execute", {"code": code})


async def friends_method(requests: list, add: bool = True):
    method = ('API.friends.delete({"user_id": requests[a]});' if not add else
              'API.friends.add({"user_id": requests[a], "follow": 0});')
    code = """var requests = %s;
    var a = 0;
    while (a < requests.length) {
        %s
        a = a + 1;
    }
    return 1;"""
    for i in range(0, len(requests), 25):
        await execute(code % (requests[i:i + 25], method))
Exemple #6
0
from dutymanager.files.errors import VK_ERROR, CANT_BIND_CHAT
from dutymanager.units.vk_script import get_chat, msg_edit
from dutymanager.db.methods import AsyncDatabase
from dutymanager.units.vk_script import msg_send
from tortoise.exceptions import BaseORMException
from dutymanager.units.utils import *
from module import VKError, types
from module.utils import logger
from module import Blueprint

bot = Blueprint(name="Base")
db = AsyncDatabase.get_current()


@bot.event.print_bookmark()
async def print_bookmark(event: types.PrintBookmark):
    peer_id = db.chats(event.object.chat)
    local_id = event.object.conversation_message_id
    description = event.object.description
    try:
        await msg_send(peer_id, f"🔼 Перейти к закладке «{description}»",
                       local_id)
    except (IndexError, VKError) as e:
        e = list(e.args)[0]
        await send_msg(peer_id,
                       VK_ERROR.get(e, "❗ Произошла неизвестная ошибка."))


@bot.event.ban_get_reason()
async def ban_get_reason(event: types.BanGetReason):
    peer_id = db.chats(event.object.chat)
Exemple #7
0
from dutymanager.units.vk_script import friends_method
from dutymanager.files.dicts import workers_state
from dutymanager.units.utils import get_requests
from asyncio import AbstractEventLoop, sleep
from module.utils import logger
from module import Blueprint

bot = Blueprint(name="Worker")


class Worker:
    """
    TODO: Recreate worker class.
    """
    def __init__(self, loop: AbstractEventLoop = None):
        self.metadata = {
            "online": self.online,
            "friends": self.friends,
            "deleter": self.deleter
        }
        self.loop = loop

    def dispatch(self):
        for k, v in self.metadata.items():
            if workers_state[k]:
                self.loop.create_task(v())
        logger.debug("Workers have been dispatched.")

    @staticmethod
    async def online():
        while workers_state["online"]:
Exemple #8
0
from dutymanager.db.methods import AsyncDatabase
from dutymanager.units.utils import get_by_local
from module import Blueprint, Method
from module import types

bot = Blueprint(name="Trusted")
db = AsyncDatabase.get_current()
Exemple #9
0
from module import Blueprint, Message
from ..additions.ping import responses
from dutymanager.files.msgs import ping_state
from time import time as current
from datetime import datetime

bot = Blueprint(name="LongPoll")


@bot.on.chat_message(text=list(responses.keys()), lower=True)
async def wrapper(ans: Message):
    if bot.user_id == ans.from_id:
        await bot.api.messages.edit(
            peer_id=ans.peer_id,
            message_id=ans.message_id,
            message=ping_state.format("[User LP]",
                                      responses[ans.text.lower()].upper(),
                                      round(current() - ans.date, 2),
                                      datetime.fromtimestamp(ans.date),
                                      datetime.fromtimestamp(int(current()))))