示例#1
0
async def test_token_session_auth_token_request_without_token(vk_server):
    url = f'http://{vk_server.host}:{vk_server.port}'
    s = TokenSession('token')
    s.REQUEST_URL = f'{url}/method/'
    with pytest.raises(VkAuthError):
        await s.send_api_request('users.get.error', {'user_ids': 1})
    await s.close()
示例#2
0
async def test_token_session_auth_token_free_request_without_token(
        vk_server, user_1_data):
    url = f'http://{vk_server.host}:{vk_server.port}'
    s = TokenSession()
    s.REQUEST_URL = f'{url}/method/'
    result = await s.send_api_request('users.get', {'user_ids': 1})
    await s.close()
    assert result == user_1_data
示例#3
0
 def test_auth_token_free_request_without_token(self):
     s = TokenSession()
     result = yield from s.send_api_request('users.get', {'user_ids': 1})
     s.close()
     self.assertListEqual(result, [{
         'id': 1,
         'last_name': 'Дуров',
         'first_name': 'Павел'
     }])
示例#4
0
	def __init__(self, token, group_id, message_raid, symbols, send_keyboard=False, keyboard_text="Raidy perfect.."):
		"""
	:param token: Токен паблика ВКонтакте
	:param group_id: ID паблика ВКонтакте
	:param message_raid: Сообщение для рейда
	:param symbols: Количество символов для обрезки сообщения
			(см. utils.py -> trimming_message)
	:param send_keyboard: Отправление клавиатуры
	:param keyboard_text: Текст для клавиатуры (если не указан, то
			по умолчанию будет использоватся <<Raidy perfect...>>)
		"""
		self.token = token
		self.group_id = group_id
		self.message_raid = message_raid
		self.symbols = symbols if symbols > 2 else 5
		self.send_keyboard = send_keyboard
		self.keyboard_text = keyboard_text
		self.keyboard = self._create_keyboard(text=self.keyboard_text) # keyboard object (json) after generation

		self.session = TokenSession(access_token=self.token) # vk session object
		self.api = API(self.session) # API object
		self.lp = BotsLongPoll(self.api, mode=2, group_id=self.group_id) # longpoll object

		self.logger = Log("raid_log") # logger object. create log file (raid_log.log)

		self.message_util = MessagesUtil(self.text, self.symbols) # MessagesUtil initialization
示例#5
0
 def __init__(self, config_filename):
     config = json.from_path(config_filename)
     session = TokenSession(access_token=config['token'])
     self.api = API(session)
     self.longpoll = BotsLongPoll(session,
                                  mode=0,
                                  group_id=config['group_id'])
示例#6
0
async def run(config):
    interval = int(config.interval)
    client = motor.motor_asyncio.AsyncIOMotorClient(config.mongo_url)
    db = client.memes_db
    collection = db.test_collection
    session = TokenSession(config.vk.token)
    api = API(session)

    bot = Bot(api_token=config.token, proxy=config.proxy['proxy_url'])
    channel = bot.channel("@MemesAggregation")

    while True:
        logging.info('Start checking groups')
        for group in config.vk.groups:
            asyncio.sleep(1)
            r = await api('wall.get', domain=group)
            for item in r['items']:
                if len(item['attachments']
                       ) == 1 and item['marked_as_ads'] == 0 and item[
                           'attachments'][0]['type'] == 'photo':
                    url = item['attachments'][0]['photo']['photo_604']
                    name = re.findall('(?=\w+\.\w{3,4}$).+', url)[0]
                    if await collection.find_one({'name': name}) is None:
                        logging.info('Found new meme')
                        collection.insert_one({'name': name})
                        # TODO: Make it async
                        urllib.request.urlretrieve(url, f"data/images/{name}")
                        await channel.send_photo(
                            photo=open(f"data/images/{name}", "rb"))
                        os.remove(f"data/images/{name}")

        logging.info('Groups checked, waiting for next time...')
        await asyncio.sleep(interval)
示例#7
0
 async def get_wall_id_from_public_url(url: str) -> Optional[int]:
     try:
         screen_name, check_id = url.split("/")[-1], None
         async with TokenSession(VK_TOKEN) as session:
             api = API(session)
             wall_object = await api.utils.resolveScreenName(
                 screen_name=screen_name)
             if wall_object:
                 return (-wall_object["object_id"] if wall_object["type"]
                         in ["group", "page"] else wall_object["object_id"])
             else:
                 if screen_name.startswith("id", 0):
                     check_id = int(screen_name[2:])
                 elif screen_name.startswith("public", 0):
                     check_id = -int(screen_name[6:])
                 elif screen_name.startswith("club", 0):
                     check_id = -int(screen_name[4:])
                 if check_id:
                     check_data = await api.wall.get(owner_id=check_id,
                                                     count=1)["items"]
                     if check_data:
                         return check_id
                 return check_id
     except Exception as err:
         logger.error(f"User failed input vk_wall url - {err}")
         return None
示例#8
0
 async def _session(self):
     session = TokenSession(access_token=self.token)
     try:
         yield API(session)
     except Exception as err:
         logger.error(f"Error: {err}")
         raise
     finally:
         await session.close()
示例#9
0
    def test_wait_valid_with_token_session(self):
        s = TestAuthSession(login=USER_LOGIN, password=USER_PASSWORD, app_id=APP_ID, scope='messages')
        yield from s.authorize()
        s.close()

        api = API(TokenSession(s.access_token))
        lp = LongPoll(api, mode=2, wait=2)

        response = yield from lp.wait()
        self.assertTrue('ts' in response)
        self.assertTrue('updates' in response)
示例#10
0
    def vk(self):
        if not hasattr(self, 'vk_api'):
            loop = asyncio.get_event_loop()
            connector = aiohttp.TCPConnector(verify_ssl=False)
            session = aiohttp.ClientSession(connector=connector)
            driver = HttpDriver(loop=loop, session=session)
            self.session = TokenSession(access_token=self.credentials.token,
                                        driver=driver)
            self.vk_api = API(self.session)

        return self.vk_api
示例#11
0
 def __init__(self, token: str, pg_user: str, pg_password: str, pg_database: str, pg_host: str):
     self._session = TokenSession(access_token=token)
     self._session.API_VERSION = '5.101'
     self._api = API(self._session)
     asyncio.get_event_loop().run_until_complete(init_orm(pg_user, pg_password, pg_database, pg_host))
示例#12
0
 async def test_auth_token_request_without_token(self):
     s = TokenSession('token')
     s.REQUEST_URL = 'https://{}/method/'.format(self.base_url)
     with self.assertRaises(VkAuthError):
         await s.send_api_request('users.get.error', {'user_ids': 1})
     await s.close()
示例#13
0
 async def test_auth_token_free_request_without_token(self):
     s = TokenSession()
     s.REQUEST_URL = 'https://{}/method/'.format(self.base_url)
     result = await s.send_api_request('users.get', {'user_ids': 1})
     await s.close()
     self.assertListEqual(result, [{'id': 1, 'last_name': 'Дуров', 'first_name': 'Павел'}])
示例#14
0
 async def test_auth_with_token(self):
     s = TokenSession('token')
     with self.assertRaises(VkAuthError):
         await s.authorize()
     await s.close()
示例#15
0
def get_service_api():
    session = TokenSession(access_token=SERVICE_TOKEN, )
    api = API(session)
    return api
示例#16
0
async def test_token_session_auth_with_empty_token(vk_server):
    s = TokenSession()
    with pytest.raises(VkAuthError):
        await s.authorize()
    await s.close()
示例#17
0
 def test_auth_token_nonfree_request_without_token(self):
     s = TokenSession()
     with self.assertRaises(VkAuthError):
         yield from s.send_api_request('messages.get')
     s.close()
示例#18
0
 def test_auth_token_free_request_without_token(self):
     s = TokenSession()
     result = yield from s.send_api_request('users.get', {'user_ids': 1})
     s.close()
     self.assertListEqual(result, [{'id': 1, 'last_name': 'Дуров', 'first_name': 'Павел'}])
示例#19
0
import asyncio

from aiovk.longpoll import BotsLongPoll
import os
from aiovk import TokenSession, API
from dotenv import load_dotenv
from utils.message import Message

from vk_bot.bot import VkBot

load_dotenv()

ses = TokenSession(access_token=str(os.getenv('BOT_VK_KEY')))
api = API(ses)
lp = BotsLongPoll(api, int(os.getenv('GROUP_ID')), version=100)
loop = asyncio.get_event_loop()


async def write_msg(vk_bot: VkBot = None,
                    message: Message = None,
                    peer_id=None):
    if vk_bot and vk_bot.text is not None:
        await api.messages.send(peer_id=int(vk_bot.peer_id),
                                message=vk_bot.text,
                                keyboard=vk_bot.keyboard)
    elif message:
        await api.messages.send(peer_id=peer_id, message=message)


async def get_user_title(vk_bot: VkBot):
    res = (await api.users.get(user_ids=int(vk_bot.from_id)))[0]
示例#20
0
 def test_auth_with_token(self):
     s = TokenSession(self._token)
     with self.assertRaises(VkAuthError):
         yield from s.authorize()
     s.close()
示例#21
0
async def run_vk_bot(app):

    bot_swarm = []
    active_bots = await User.find(filter={"details.vkbot.enable": True})
    for bot in active_bots.objects:
        bot_unit = {"bot": bot, "groups": []}
        for group in bot["details"]["vkbot"]["groups"]:
            session = TokenSession(access_token=group["access_token"])
            lp = BotsLongPoll(session, mode=2, group_id=group["group_id"])
            # TODO handle last updates on restart
            # if "ts" in params:
            #     lp.ts = params["ts"]
            bot_unit['groups'].append(lp)
        bot_swarm.append(bot_unit)

    while True:
        for bot_unit in bot_swarm:
            bot = bot_unit["bot"]

            for group in bot_unit['groups']:
                result = await group.wait()
                updates = result['updates']
                for update in updates:
                    if update["type"] == 'wall_post_new':
                        post = update["object"]

                        attachments = []
                        if post.get('attachments'):
                            for row_attachment in post['attachments']:
                                if row_attachment['type'] == 'photo':
                                    attachments.append({
                                        "type":
                                        "Document",
                                        "mediaType":
                                        "image/jpeg",
                                        "url":
                                        row_attachment['photo']["photo_807"],
                                        "name":
                                        "null"
                                    })

                        # process tags
                        extra_tag_list = []
                        if bot["details"]["vkbot"]["tags"]:
                            extra_tag_list.extend(
                                bot["details"]["vkbot"]["tags"])
                        content, footer_tags, object_tags = process_tags(
                            extra_tag_list, post['text'])
                        body = f"{content}{footer_tags}"

                        activity = Create(
                            bot, {
                                "type": "Create",
                                "cc": [],
                                "object": {
                                    "type": "Note",
                                    "summary": None,
                                    "sensitive": False,
                                    "content": body,
                                    "attachment": attachments,
                                    "tag": object_tags
                                }
                            })
                        await activity.save(tg_sent=True)
                        await activity.deliver()
                        logger.info(
                            f"vkontakte entry '{post['id']}' of {bot.name} federating"
                        )

        await asyncio.sleep(app.config.VK_POLLING_TIMEOUT)
示例#22
0
 def test_auth_token_nonfree_request_without_token(self):
     s = TokenSession()
     with self.assertRaises(VkAuthError):
         yield from s.send_api_request('messages.get')
     s.close()
示例#23
0
 def test_auth_with_token(self):
     s = TokenSession(self._token)
     with self.assertRaises(VkAuthError):
         yield from s.authorize()
     s.close()