Esempio n. 1
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()
Esempio n. 2
0
    Dispatcher,
    BotLongpollExtension,
    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,
    )
Esempio n. 3
0
    Dispatcher,
    UserLongpollExtension,
    DefaultRouter,
    EventTypeFilter,
    FromMeFilter,
    TextFilter,
    UserId,
)
from vkwave.client import AIOHTTPClient
from vkwave.api import API, BotSyncSingleToken, Token
from vkwave.longpoll import UserLongpollData, UserLongpoll
from vkwave.types.user_events import EventId

logging.basicConfig(level=logging.DEBUG)

bot_token = Token("token")
router = DefaultRouter()


# EventTypeFilter((3, 4, 5, 18)) == EventTypeFilter(EventId.MESSAGE_EVENT.value)
@router.registrar.with_decorator(EventTypeFilter(EventId.MESSAGE_EVENT.value),
                                 FromMeFilter(from_me=True))
async def from_me(event: UserEvent):
    print("from me:", event.object.object.text)


# FromMeFilter(from_me=False) -> message from other user
# FromMeFilter(from_me=True) -> message from me
@router.registrar.with_decorator(EventTypeFilter((3, 4, 5, 18)),
                                 FromMeFilter(from_me=False),
                                 TextFilter("hello"))
Esempio n. 4
0
import asyncio

from vkwave.api import Token, BotSyncSingleToken, API
from vkwave.bots.utils import PhotoUploader
from vkwave.client import AIOHTTPClient

client = AIOHTTPClient()
api = API(clients=client, tokens=BotSyncSingleToken(Token("token")),)

uploader = PhotoUploader(api.get_context())
# same with VoiceUploader etc.


async def main():
    big_attachment = await uploader.get_attachments_from_links(
        peer_id=1234,
        links=[
            "https://user-images.githubusercontent.com/28061158/75329873-7f738200-5891-11ea-9565-fd117ea4fc9e.jpg",
            "https://camo.githubusercontent.com/9c8d6519e5997860b7a4b28f74719c0c2f83142b/68747470733a2f2f692e696d6775722e636f6d2f386955334578366c2e6a7067",
            "https://user-images.githubusercontent.com/28061158/74590410-239e3300-501f-11ea-9774-27ee507a1e1e.jpg",
        ],
    )
    await api.get_context().messages.send(user_id=1234, attachment=big_attachment, random_id=0)


asyncio.get_event_loop().run_until_complete(main())
Esempio n. 5
0
import asyncio

from vkwave.api import Token, BotSyncSingleToken, API
from vkwave.bots import PhotoUploader, WallPhotoUploader, DocUploader
from vkwave.client import AIOHTTPClient

client = AIOHTTPClient()
api = API(
    clients=client,
    tokens=BotSyncSingleToken(Token("token")),
)

uploader = PhotoUploader(api.get_context())


# same with VoiceUploader etc.
async def main():
    big_attachment = await uploader.get_attachments_from_links(
        peer_id=1234,
        links=[
            "https://user-images.githubusercontent.com/28061158/75329873-7f738200-5891-11ea-9565-fd117ea4fc9e.jpg",
            "https://camo.githubusercontent.com/9c8d6519e5997860b7a4b28f74719c0c2f83142b/68747470733a2f2f692e696d6775722e636f6d2f386955334578366c2e6a7067",
            "https://user-images.githubusercontent.com/28061158/74590410-239e3300-501f-11ea-9774-27ee507a1e1e.jpg",
        ],
    )
    await api.get_context().messages.send(user_id=1234,
                                          attachment=big_attachment,
                                          random_id=0)


async def wall_upload():
Esempio n. 6
0
from vkwave.bots import (
    BaseEvent,
    TokenStorage,
    Dispatcher,
    DefaultRouter,
    EventTypeFilter,
    CommandsFilter,
    GroupId,
)
from vkwave.bots.core.dispatching.extensions.callback.conf import ConfirmationStorage
from vkwave.client import AIOHTTPClient
from vkwave.api import BotSyncSingleToken, Token, API
from vkwave.types.bot_events import BotEventType

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


@router.registrar.with_decorator(CommandsFilter(["hello"]),
                                 EventTypeFilter(BotEventType.MESSAGE_NEW))
async def hello_handler(event: BaseEvent):
    await event.api_ctx.messages.send(
        peer_id=event.object.object.message.peer_id,
        message="hellooooooooooooo!",
        random_id=0,
    )


async def main():
Esempio n. 7
0
import logging
from vkwave.types.objects import MessagesMessageAttachmentType, BaseBoolInt
from vkwave.bots.utils.keyboards import Keyboard
from vkwave.bots.utils.keyboards.keyboard import ButtonColor

from constants import commands, sberkot_stickers
from db import connection
import db
import generate
from properties import TOKEN, GROUP_ID

TALKING = False

bot = SimpleLongPollBot(tokens=TOKEN, group_id=GROUP_ID)
client = AIOHTTPClient()
api = API(clients=client, tokens=BotSyncSingleToken(Token(TOKEN)), )
router = DefaultRouter()
logging.basicConfig(level=logging.INFO)
db.execute_query(connection,
                 """
CREATE TABLE IF NOT EXISTS messages( 
id INTEGER PRIMARY KEY AUTOINCREMENT,
peer_id INTEGER,
text TEXT NOT NULL,
from_id INTEGER,
name TEXT NOT NULL default unknown,
date TEXT NOT NULL default unknown);
""")


# help page
Esempio n. 8
0
from data import config, template_messages as temp_msgs
from data.database import db
from recognition_audio import text_generator, voice_generator, file_manager, combinator
from utils.fsm import GetterText, GetterVoice, GetterMemText, GetterMemAudio
from utils.markups import DEFAULT_MARKUP, CANCEL_MARKUP, MEMS_MARKUP

logging.basicConfig(
    level=logging.ERROR,
    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
)

client = AIOHTTPClient()
api = API(
    clients=client,
    tokens=BotSyncSingleToken(Token(config.BOT_TOKEN)),
)

uploader = VoiceUploader(api.get_context())

bot = SimpleLongPollBot(tokens=config.BOT_TOKEN, group_id=config.GROUP_ID)

fsm = FiniteStateMachine()
bot.router.registrar.add_default_filter(
    StateFilter(fsm, ..., ..., always_false=True))
bot.router.registrar.add_default_filter(
    EventTypeFilter(BotEventType.MESSAGE_NEW.value))


async def get_user_data(message: bot.SimpleBotEvent) -> dict:
    user_data = (await bot.api_context.users.get(
Esempio n. 9
0
    # not the greatest implementation, but you can make any

    method = error["error"]["request_params"]["method"]
    request_params = {}
    for param in error["error"]["request_params"]:
        if param["key"] in ("oauth", "v", "method"):
            continue
        request_params[param["key"]] = param["value"]

    key = await solve_captcha(error["error"]["captcha_img"])

    request_params.update({"captcha_sid": error["error"]["captcha_sid"], "captcha_key": key})
    return await api_ctx.api_request(method, params=request_params)


# Easy way

bot = SimpleLongPollBot(tokens="MyToken", group_id=123456789)
bot.api_session.api.default_api_options.error_dispatcher.add_handler(14, captcha_handler)


# Not easy way


api_session = API(BotSyncSingleToken(Token("MyToken")), AIOHTTPClient())
api = api_session.get_context()
dp = Dispatcher(api_session, TokenStorage[GroupId]())
lp_extension = BotLongpollExtension(dp, BotLongpoll(api, BotLongpollData(123456789)))

api_session.default_api_options.error_dispatcher.add_handler(14, captcha_handler)