Exemplo n.º 1
0
    def __init__(
        self,
        tokens: typing.Union[str, typing.List[str]],
        bot_type: BotType,
        router: typing.Optional[BaseRouter] = None,
        group_id: typing.Optional[int] = None,
        uvloop: bool = False,
    ):
        if uvloop:
            import uvloop

            asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

        self.group_id = group_id
        self.bot_type = bot_type
        self.api_session = create_api_session_aiohttp(tokens, bot_type)
        self.api_context: APIOptionsRequestContext = self.api_session.api.get_context(
        )
        if self.bot_type is BotType.USER:
            if not isinstance(tokens, str):
                raise RuntimeError("Only one str token")

            self.SimpleBotEvent = SimpleUserEvent
            self._lp = UserLongpoll(self.api_context, UserLongpollData())
            self._token_storage = UserTokenStorage[UserId](tokens)
            self.dispatcher = Dispatcher(self.api_session.api,
                                         self._token_storage)
            self._lp = UserLongpollExtension(self.dispatcher, self._lp)
        else:
            self.SimpleBotEvent = SimpleBotEvent
            self._lp = BotLongpoll(self.api_context, BotLongpollData(group_id))
            self._token_storage = TokenStorage[GroupId]()
            self.dispatcher = Dispatcher(self.api_session.api,
                                         self._token_storage)
            self._lp = BotLongpollExtension(self.dispatcher, self._lp)

        self.middleware_manager = self.dispatcher.middleware_manager  # auf
        self.add_middleware = self.middleware_manager.add_middleware

        self.router = router or DefaultRouter()
        self.dispatcher.add_router(self.router)

        self.text_filter = TextFilter
        self.event_type_filter = EventTypeFilter
        self.payload_filter = PayloadFilter
        self.chat_action_filter = ChatActionFilter
        self.command_filter = CommandsFilter
        self.regex_filter = RegexFilter
        self.state_filter = StateFilter
        self.vbml_filter = VBMLFilter
        self.reply_filter = ReplyMessageFilter
        self.args_filter = MessageArgsFilter
        self.fwd_filter = FwdMessagesFilter
        self.conversation_type_filter = MessageFromConversationTypeFilter
        self.text_contains_filter = TextContainsFilter
        self.payload_contains_filter = PayloadContainsFilter
        self.text_startswith_filter = TextStartswithFilter
        if self.bot_type is BotType.USER:
            self.from_me_filter = FromMeFilter
Exemplo n.º 2
0
async def main():
    # await bb.start()
    # stor.asyncio_loop.stop()
    # return

    path = os.path.dirname(os.path.abspath(__file__))
    full_path = f"{path}/base/config{mode}.json"
    with open(full_path, 'r') as file:
        stor.config = json.load(file)
    bot_tokens = Token(stor.config['TOKEN'])
    user_tokens = Token(stor.config['USER_TOKEN'])
    stor.config['BASEFILE'] = f"{path}/base/{stor.config['BASEFILE']}"
    stor.config['LOGFILE'] = f"{path}/base/{stor.config['LOGFILE']}"
    stor.config['CONFIG'] = full_path

    logging.basicConfig(level=stor.config['LOGLEVEL'],
                        filename=stor.config['LOGFILE'])
    logging.addLevelName(11, 'OK')
    logging.addLevelName(12, 'DONE')
    logging.addLevelName(13, 'NO')
    logging.addLevelName(14, 'BAD')

    base_logger = logging.getLogger('base')
    command_logger = logging.getLogger('co')
    utils.st.logger = command_logger

    stor.start_time = int(time.time())

    user_client = AIOHTTPClient()
    user_tokens = [UserSyncSingleToken(tok) for tok in user_tokens]
    stor.user_api = API(user_tokens, user_client)

    client = AIOHTTPClient()
    tokens = [BotSyncSingleToken(tok) for tok in bot_tokens]
    api_session = API(tokens, client)
    api = api_session.get_context()
    lp_data = BotLongpollData(stor.config['GROUP_ID'])
    longpoll = BotLongpoll(api, lp_data)
    token_storage = TokenStorage[GroupId]()
    dp = Dispatcher(api_session, token_storage)
    dp.add_router(await hand.initiate_router(DefaultRouter()))
    await dp.cache_potential_tokens()
    await base.initiate(stor.config['BASEFILE'], base_logger)

    # storage = ConfirmationStorage()
    # storage.add_confirmation(GroupId(stor.config['GROUP_ID']),stor.config['CONFIRMATION'])
    # cb_extension = AIOHTTPCallbackExtension(
    #     dp, path="/", host="0.0.0.0", port=80, secret=stor.config['SECRET'], confirmation_storage=storage
    # )

    lp_extension = BotLongpollExtension(dp, longpoll)

    # await cb_extension.start()
    await lp_extension.start()
Exemplo n.º 3
0
from vkwave.api import API
from vkwave.bots import DefaultRouter
from vkwave.bots import MessageFromConversationTypeFilter
from vkwave.bots import SimpleBotEvent
from vkwave.bots import simple_bot_message_handler
from vkwave.client import AIOHTTPClient

from database import utils as db
from database.models import Chat
from database.models import FinancialCategory
from services import filters
from services import keyboard as kbs
from services.finances import generate_debtors_call
from services.logger.config import config

finances_router = DefaultRouter()
api_session = API(tokens=os.getenv("VK_TOKEN"), clients=AIOHTTPClient())
api = api_session.get_context()
logger.configure(**config)


@simple_bot_message_handler(
    finances_router,
    filters.PLFilter({"button": "finances"}),
    MessageFromConversationTypeFilter("from_pm"),
)
@logger.catch()
async def finances(ans: SimpleBotEvent):
    with logger.contextualize(user_id=ans.object.object.message.from_id):
        await ans.answer(
            "Список финансовых категорий",
Exemplo n.º 4
0
import os

from loguru import logger
from vkwave.api import API
from vkwave.bots import ChatActionFilter
from vkwave.bots import CommandsFilter
from vkwave.bots import DefaultRouter
from vkwave.bots import MessageFromConversationTypeFilter
from vkwave.bots import SimpleBotEvent
from vkwave.bots import simple_bot_message_handler
from vkwave.client import AIOHTTPClient

from services.logger.config import config
from services.media import translate_string

chats_router = DefaultRouter()
api_session = API(tokens=os.getenv("VK_TOKEN"), clients=AIOHTTPClient())
api = api_session.get_context()
logger.configure(**config)


@simple_bot_message_handler(
    chats_router,
    ChatActionFilter("chat_invite_user"),
)
@logger.catch()
async def greeting(ans: SimpleBotEvent):
    with logger.contextualize(user_id=ans.object.object.message.from_id):
        await ans.answer("Привет!")

Exemplo n.º 5
0
    DefaultRouter,
    SimpleBotEvent,
    simple_bot_message_handler,
    PayloadFilter,
    FiniteStateMachine,
    State,
    ForWhat,
    StateFilter,
    CommandsFilter,
    Keyboard,
)

from db.models.user import User
from utils.constants import MENU_KB

coin_flip_router = DefaultRouter()

fsm = FiniteStateMachine()


class CoinState:
    bet = State("bet")
    coin = State("coin")


@simple_bot_message_handler(coin_flip_router, CommandsFilter("exit"))
async def games(event: SimpleBotEvent):
    if await fsm.get_data(event, for_what=ForWhat.FOR_USER) is not None:
        await fsm.finish(event=event, for_what=ForWhat.FOR_USER)
    return await event.answer(
        message=
Exemplo n.º 6
0
    DefaultRouter,
    GroupId,
    EventTypeFilter,
    PayloadFilter,
    CommandsFilter,
    Keyboard,
)
from vkwave.client import AIOHTTPClient
from vkwave.api import BotSyncSingleToken, Token, API
from vkwave.longpoll.bot import BotLongpoll, BotLongpollData
from vkwave.types.bot_events import BotEventType

logging.basicConfig(level=logging.DEBUG)
bot_token = Token("123")
gid = 123
router = DefaultRouter()


@router.registrar.with_decorator(CommandsFilter(["hello"]),
                                 EventTypeFilter(BotEventType.MESSAGE_NEW))
async def kb_handler(event: BaseEvent):
    kb = Keyboard(one_time=True)
    kb.add_text_button(text="123456", payload={"hello": "world"})
    await event.api_ctx.messages.send(
        peer_id=event.object.object.message.peer_id,
        message="123",
        keyboard=kb.get_keyboard(),
        random_id=0,
    )

Exemplo n.º 7
0
from vkwave.bots import DefaultRouter
from vkwave.bots import MessageFromConversationTypeFilter
from vkwave.bots import SimpleBotEvent
from vkwave.bots import simple_bot_message_handler
from vkwave.client import AIOHTTPClient

from database import utils as db
from database.models import Chat
from services import call
from services import filters
from services import keyboard as kbs
from services import media
from services.exceptions import EmptyCallMessage
from services.logger.config import config

call_router = DefaultRouter()
api_session = API(tokens=os.getenv("VK_TOKEN"), clients=AIOHTTPClient())
api = api_session.get_context()
logger.configure(**config)


@simple_bot_message_handler(
    call_router,
    filters.PLFilter({"button": "call"}),
    MessageFromConversationTypeFilter("from_pm"),
)
@logger.catch()
async def start_call(ans: SimpleBotEvent):
    with logger.contextualize(user_id=ans.object.object.message.from_id):
        if db.chats.get_list_of_chats_by_group(
                db.admin.get_active_group(
Exemplo n.º 8
0
from vkwave.bots import DefaultRouter, SimpleBotEvent, simple_bot_message_handler

from utils.constants import MENU_KB

menu_router = DefaultRouter()


@simple_bot_message_handler(
    menu_router, )
async def menu(event: SimpleBotEvent):
    return await event.answer(
        message=
        f"Выберите дальнейшее действие, {event['current_user'].first_name}",
        keyboard=MENU_KB.get_keyboard(),
    )
Exemplo n.º 9
0
from vkwave.bots import (
    DefaultRouter,
    simple_bot_message_handler,
    SimpleBotEvent,
    BaseEvent,
)
from vkwave.bots.core import BaseFilter
from vkwave.bots.core.dispatching.filters.base import FilterResult
from vkwave.bots.storage.types import Key

from helpers import get_schedule_and_days
from storage import storage
from utils import create_text_schedule

current_day_schedule_router = DefaultRouter()


class IsDayRequestMessage(BaseFilter):
    async def check(self, event: BaseEvent) -> FilterResult:
        return FilterResult(event.object.object.message.payload and json.loads(
            event.object.object.message.payload).get("day") is not None)


@simple_bot_message_handler(current_day_schedule_router, IsDayRequestMessage())
async def day_schedule(event: SimpleBotEvent):
    # TODO: слать инлайн клаву снова
    schedule, days = await get_schedule_and_days()

    day_data: str = json.loads(event.object.object.message.payload)["day"]
Exemplo n.º 10
0
from vkwave.bots import (
    DefaultRouter,
    SimpleBotEvent,
    simple_bot_message_handler,
    PayloadFilter,
)

from utils.constants import GAMES_KB

games_router = DefaultRouter()


@simple_bot_message_handler(games_router, PayloadFilter({"command": "games"}))
async def games(event: SimpleBotEvent):
    return await event.answer(message=f"Выберите игру",
                              keyboard=GAMES_KB.get_keyboard())
Exemplo n.º 11
0
import datetime

from vkwave.bots import (
    DefaultRouter,
    simple_bot_message_handler,
    SimpleBotEvent,
    PayloadFilter,
)

from helpers import create_one_day_schedule
from utils import get_now, is_weekend

tomorrow_schedule_router = DefaultRouter()


@simple_bot_message_handler(tomorrow_schedule_router,
                            PayloadFilter({"command": "tomorrow"}))
async def tomorrow(event: SimpleBotEvent):
    now = get_now()
    tomorrow_date = now + datetime.timedelta(days=1)
    if is_weekend(tomorrow_date):
        return "завтра выходной, хд"

    await event.answer(
        await create_one_day_schedule(tomorrow_date, tomorrow=True),
        dont_parse_links=True,
    )
Exemplo n.º 12
0
from vkwave.bots import (
    DefaultRouter,
    simple_bot_message_handler,
    PayloadFilter,
    SimpleBotEvent,
)

from helpers import get_current_schedule_for_which_and_next, get_current_lesson
from utils import create_text_schedule_for_one_lesson

current_lesson_router = DefaultRouter()


@simple_bot_message_handler(current_lesson_router,
                            PayloadFilter({"command": "which"}))
async def send_schedule(event: SimpleBotEvent):
    current_schedule = await get_current_schedule_for_which_and_next()
    if current_schedule is None:
        return "Какие пары иди спи"

    current_lesson = get_current_lesson(current_schedule)
    if current_lesson is not None:
        return await event.answer(
            message=create_text_schedule_for_one_lesson(current_lesson),
            dont_parse_links=True,
        )

    return "Сейчас пары нет"
Exemplo n.º 13
0
    DefaultRouter,
    simple_bot_message_handler,
    PayloadFilter,
    SimpleBotEvent,
)

from helpers import (
    get_current_schedule_for_which_and_next,
    get_current_lesson,
    get_schedule_and_days,
    create_next_lesson_message,
    correct_schedule,
)
from utils import get_now, get_current_timedelta

next_lesson_router = DefaultRouter()


@simple_bot_message_handler(next_lesson_router, PayloadFilter({"command": "next"}))
async def next_lesson(event: SimpleBotEvent):
    schedule, days = await get_schedule_and_days()
    now = get_now()
    current_schedule = await get_current_schedule_for_which_and_next()

    if current_schedule is None:
        return "некст пара не обнаружена))"
    current_timedelta = get_current_timedelta()
    current_lesson = get_current_lesson(current_schedule)

    message = create_next_lesson_message(
        current_schedule=current_schedule,
Exemplo n.º 14
0
from vkwave.bots import MessageFromConversationTypeFilter
from vkwave.bots import SimpleBotEvent
from vkwave.bots import simple_bot_message_handler
from vkwave.client import AIOHTTPClient

from database import utils as db
from database.models import Chat
from database.models import Student
from services import filters
from services import keyboard as kbs
from services.chats import get_confirm_message
from services.chats import prepare_set_from_db
from services.chats import prepare_set_from_vk
from services.logger.config import config

preferences_router = DefaultRouter()
api_session = API(tokens=os.getenv("VK_TOKEN"), clients=AIOHTTPClient())
api = api_session.get_context()
logger.configure(**config)


@simple_bot_message_handler(
    preferences_router,
    filters.PLFilter({"button": "settings"}),
    MessageFromConversationTypeFilter("from_pm"),
)
@logger.catch()
async def open_preferences(ans: SimpleBotEvent):
    with logger.contextualize(user_id=ans.object.object.message.from_id):
        active_group = db.admin.get_active_group(
            db.students.get_system_id_of_student(ans.object.object.message.from_id),
Exemplo n.º 15
0
from vkwave.bots import (
    DefaultRouter,
    simple_bot_message_handler,
    SimpleBotEvent,
    PayloadFilter,
)

from utils import get_now, create_percent, is_weekend

attend_apparently_router = DefaultRouter()


@simple_bot_message_handler(attend_apparently_router,
                            PayloadFilter({"command": "go"}))
async def send_go(event: SimpleBotEvent):
    now = get_now()
    if is_weekend(now):
        return "В выходные поучиться захотелось?"

    percent = create_percent(user_id=event.object.object.message.from_id,
                             now=now)

    await event.answer(f"Идти на пары стоит с вероятностью {percent}%")
Exemplo n.º 16
0
from vkwave.bots import DefaultRouter, SimpleBotEvent, simple_bot_message_handler
from vkwave.types.objects import MessagesMessageAttachmentType
from vkwave.bots.core.dispatching import filters
from loguru import logger
import random
import requests

vk_msg_from_chat = DefaultRouter()

tg_bot = None
CONFIG_OBJ = None


def config_vk_hand(c=None):
    global CONFIG_OBJ
    if not c:
        return CONFIG_OBJ
    CONFIG_OBJ = c


def setup_tg_bot_to_vk_handler(new_global):
    global tg_bot
    tg_bot = new_global


def check_if_chat_in_config(peer_id: int) -> None:
    global CONFIG_OBJ
    if peer_id not in CONFIG_OBJ['vk']['chats']:
        CONFIG_OBJ['vk']['chats'].append(peer_id)

Exemplo n.º 17
0
from vkwave.bots import (
    DefaultRouter,
    simple_bot_message_handler,
    SimpleBotEvent,
    PayloadFilter,
)

from helpers import create_one_day_schedule
from utils import get_now, is_weekend

today_schedule_router = DefaultRouter()


@simple_bot_message_handler(today_schedule_router, PayloadFilter({"command": "today"}))
async def today(event: SimpleBotEvent):
    now = get_now()
    if is_weekend(now):
        return "ниче нет"

    await event.answer(await create_one_day_schedule(now), dont_parse_links=True)
Exemplo n.º 18
0
import time
import datetime

from vkwave.bots import (
    DefaultRouter,
    simple_bot_message_handler,
    PayloadFilter,
    SimpleBotEvent,
)

from db.models.user import User

bonus_router = DefaultRouter()


@simple_bot_message_handler(bonus_router, PayloadFilter({"command": "bonus"}))
async def bonus(event: SimpleBotEvent):
    user: User = event["current_user"]
    if time.time() - user.last_bonus_time <= 86400:
        return await event.answer(
            f"Бонус доступен раз в день, следующий будет доступен -"
            f" {datetime.datetime.fromtimestamp(86400 + user.last_bonus_time)}"
        )
    user.last_bonus_time = time.time()
    user.balance += 1000
    await user.commit()
    return await event.answer("Получен бонус 1000!")
Exemplo n.º 19
0
import hyperjson
from loguru import logger
from vkwave.api import API
from vkwave.bots import DefaultRouter
from vkwave.bots import MessageFromConversationTypeFilter
from vkwave.bots import SimpleBotEvent
from vkwave.bots import simple_bot_message_handler
from vkwave.client import AIOHTTPClient

from database import utils as db
from database.models import Student
from services import filters
from services import keyboard as kbs
from services.logger.config import config

contacts_router = DefaultRouter()
api_session = API(tokens=os.getenv("VK_TOKEN"), clients=AIOHTTPClient())
api = api_session.get_context()
logger.configure(**config)


@simple_bot_message_handler(
    contacts_router,
    filters.PLFilter({"button": "contacts"}),
    MessageFromConversationTypeFilter("from_pm"),
)
@logger.catch()
async def start_contacts(ans: SimpleBotEvent):
    with logger.contextualize(user_id=ans.object.object.message.from_id):
        db.shortcuts.update_admin_storage(
            db.students.get_system_id_of_student(
Exemplo n.º 20
0
from github import Github
from loguru import logger
from vkwave.api import API
from vkwave.bots import DefaultRouter
from vkwave.bots import MessageFromConversationTypeFilter
from vkwave.bots import SimpleBotEvent
from vkwave.bots import simple_bot_message_handler
from vkwave.client import AIOHTTPClient

from database import utils as db
from services import filters
from services import keyboard as kbs
from services.logger.config import config

report_router = DefaultRouter()
api_session = API(tokens=os.getenv("VK_TOKEN"), clients=AIOHTTPClient())
api = api_session.get_context()
logger.configure(**config)


@simple_bot_message_handler(
    report_router,
    filters.PLFilter({"button": "report_error"}),
    MessageFromConversationTypeFilter("from_pm"),
)
@logger.catch()
async def start_reporting(ans: SimpleBotEvent):
    db.shortcuts.update_admin_storage(
        db.students.get_system_id_of_student(ans.object.object.message.from_id),
        state_id=db.bot.get_id_of_state("wait_issue_title"),