Exemple #1
0
    def init_vk(self):
        """Инициализация сессии ВК API"""
        if self.token:
            self.api_session = TokenSession(access_token=self.token,
                                            driver=RatedDriver())
            self.group_api = aiovk.API(self.api_session)

        if self.login and self.password:
            self.login = self.login
            self.password = self.password
            self.api_session = ImplicitSession(
                self.login,
                self.password,
                self.appid,
                scope=self.scope,
                driver=RatedDriver())  # all scopes
            self.user_api = aiovk.API(self.api_session)

        if not self.user_api and not self.group_api:
            fatal(
                'Вы попытались инициализировать объект класса VkPlus без данных для авторизации!'
            )

        # Паблик API используется для методов, которые не нуждаются в регистрации (users.get и т.д)
        # Используется только при access_token сообщества вместо аккаунта
        if self.token:
            self.public_api_session = TokenSession(driver=RatedDriver())
            self.public_api = aiovk.API(self.public_api_session)
async def main(login, password):
    session = VkSession(login=login,
                        password=password,
                        app_id=APP_ID,
                        scope=APP_SCOPE)
    logger.debug("Authorizing attempt")
    await session.authorize()

    api = aiovk.API(session)

    logger.debug("Requesting profile info")
    user_info = await api("account.getProfileInfo")

    logger.info("First/Last name: %s %s" %
                (user_info["first_name"], user_info["last_name"]))

    if not os.path.exists(LOGS_PATH):
        os.mkdir(LOGS_PATH)

    user_id = user_info["id"]
    file_name = time.strftime(f"{user_id}-%Y.%m.%d-%H.%M.%S.json")

    with open(f"{LOGS_PATH}\\{file_name}", "w+", encoding="utf-8") as file:
        json.dump(user_info, file, indent=4, ensure_ascii=False)

    await session.close()
Exemple #3
0
 def __init__(self, loop: AbstractEventLoop, token: str, chatname: str):
     self._aiohttp_client = aiohttp.ClientSession(loop=loop)
     self._vk_session = aiovk.TokenSession(access_token=token)
     self._api = aiovk.API(self._vk_session)
     self._log = Logger('VKAPI')
     self._bound_chatname = chatname
     self._longpoll = aiovk.LongPoll(self._api, mode=2)
     random.seed()
Exemple #4
0
    def __init__(self, *args, **kwargs):
        self.loop = asyncio.get_event_loop()
        self.vk_token = kwargs.get('vk_token', 0)
        self.ai_token = kwargs.get('ai_token', 0)
        self.peer_id = kwargs.get('peer_id', 0)

        self.session = aiovk.TokenSession(access_token=self.vk_token)
        self.vk = aiovk.API(self.session)
        self.ai = apiai.ApiAI(self.ai_token)
Exemple #5
0
async def listen():
    asyncio.create_task(garbage_collector())
    async with aiovk.TokenSession(TOKEN) as vk_session:
        vk_session.API_VERSION = '5.100'
        api = aiovk.API(vk_session)
        asyncio.create_task(courier_notificator(api))
        long_poll = aiovk.longpoll.BotsLongPoll(vk_session, 2, GROUP_ID)
        while True:
            updates = (await long_poll.wait())['updates']
            for event in updates:
                if event['type'] == 'message_new':
                    asyncio.create_task(on_message(api, event['object']))
Exemple #6
0
 async def main(self):
     async with aiovk.TokenSession(access_token=self.token) as session:
         self.api = aiovk.API(session)
         self.async_redis_pool = await aioredis.create_redis_pool(
             ('localhost', 6379), timeout=1)
         while True:
             if self.stop:
                 break
             try:
                 await asyncio.wait_for(self.start_task(), timeout=10)
             except asyncio.TimeoutError:
                 log.info('Error timeout request_period')
             await asyncio.sleep(1)
         self.async_redis_pool.close()
         await self.async_redis_pool.wait_closed()
Exemple #7
0
async def main(service):
    async with aiovk.TokenSession(access_token=TOKEN) as session:
        api = aiovk.API(session)
        chat_id = await get_chat_id(api, CHAT_NAME)
        photo_server_uri = await get_photo_server(api, chat_id)

        if chat_id is None:
            return -1
        else:
            print(t.cyan('Listening to chat id'), t.yellow(str(chat_id)))
        lp = aiovk.longpoll.LongPoll(api, mode=2)
        while True:
            new_data = await lp.wait()
            updates = new_data['updates']
            if len(updates) > 0:
                for update in updates:
                    if update[0] == 4 and update[3] == chat_id:
                        # This is a legit message
                        message_chat = update[5]
                        message_text = update[6]
                        print(
                            t.green(
                                f"New message received in chat {message_chat}:"
                            ), message_text)

                        link = await find_link(message_text)
                        if link:
                            link_hash = await hash_link(link)
                            link_hash = str(link_hash)

                            if link_hash in KNOWN_UID:
                                print(t.green('Found link: '), t.blue(link),
                                      t.yellow(f"({link_hash})"),
                                      t.green(', already known'))
                            else:
                                print(t.green('Found new link: '),
                                      t.blue(link), t.yellow(f"({link_hash})"))
                                screen_id = await generate_screenshot(
                                    link, service)
                                print(t.green('Generated screenshot for '),
                                      t.yellow(screen_id))

                            asyncio.ensure_future(
                                reply(api, chat_id, link, link_hash,
                                      photo_server_uri))
                            await cleanup_hashes(IMAGE_PATH)
Exemple #8
0
 def __init__(self):
     self.capitals_quize = [('1', 'Чехии', 'Прага'), ('2', 'Италии', 'Рим'),
                            ('3', 'Греции', 'Афины'),
                            ('4', 'Испании', 'Мадрид'),
                            ('5', 'Канады', 'Оттава'),
                            ('6', 'Ливии', 'Триполи'),
                            ('7', 'Кении', 'Найроби'),
                            ('8', 'Боливии', 'Сукре'),
                            ('9', 'Йемена', 'Сана'),
                            ('10', 'Гайаны', 'Джорджтаун')]
     # {"peer_id" : "last_q"}
     self.history = {}
     # {"peer_id": {"user_id" : "result"}}
     self.results = {}
     self.TOKEN = 'eab10371bb86ac259709c026c81c7b774c1fc9ae13c484c55e377598551cc92e63840a6518a14eb955d28'
     self.session = aiovk.TokenSession(access_token=self.TOKEN)
     self.api = aiovk.API(self.session)
     self.lp = aiovk.longpoll.BotsLongPoll(self.session, group_id=202376739)
     self.delay = 10
     self.database = db.DB()
     asyncio.get_event_loop().run_until_complete(self.connect())
Exemple #9
0
import asyncio
import aiovk
import longpool
from config import *

aiovk.TokenSession.API_VERSION = "5.120"  # Edit vk api version in lib

api = aiovk.API(
    aiovk.TokenSession(access_token=VK_TOKEN))  # Authorize with token
longpool = longpool.init(
    api, GROUP_ID,
    "messages")  # or longpool = longpool.init(api, GROUP_ID, {mode})
bot_loop = asyncio.get_event_loop()


async def info(data):
    print(
        f'\nMessage from: {data["from_id"]}\nPeer_id: {data["peer_id"]}\nText: {data["text"]}'
    )


async def start():

    async for messages in longpool.listen():  # Listen longpool
        await info(messages)


if __name__ == '__main__':
    try:
        bot_loop.run_until_complete(start())
    except KeyboardInterrupt:
                owner_id *= -1

    co_posts = list()
    while offset != total:
        co_posts.append(get_posts(owner_id, count, offset))
        offset += count

    for co_post in asyncio.as_completed(co_posts):
        posts = await co_post
        dictionary = split_text_from_post(posts)
        await saving_data(conn, dictionary)

    await manager.close_connection()
    await session.close()
    print(time.time() - start)


if __name__ == "__main__":
    TABLE = 'words'
    token = "ae40397aae40397aae40397a9dae3682b9aae40ae40397ace0bf838aa1fa57fa14979f7"
    session = aiovk.TokenSession(access_token=token)
    vk_api = aiovk.API(session)

    manager = ConnectionManager()
    href_pattern = re.compile(r'https://vk.com/(?P<name>\w+)')
    # total = int(input('Введите кол-во постов (кол-во / 100)'))
    total = 200

    event_loop = asyncio.get_event_loop()
    event_loop.run_until_complete(spider())