async def upload_photo(self, encoded_image) -> Attachment: data = aiohttp.FormData() data.add_field('photo', encoded_image, filename='picture.png', content_type='multipart/form-data') upload_url = ( await self.method('photos.getMessagesUploadServer'))['upload_url'] async with aiohttp.ClientSession() as sess: async with sess.post(upload_url, data=data) as resp: result = json.loads(await resp.text()) hues.warn(result) if not result: return None data = dict(photo=result['photo'], hash=result['hash'], server=result['server']) result = (await self.method('photos.saveMessagesPhoto', data))[0] link = "" for k in result: if "photo_" in k: link = result[k] return Attachment("photo", result["owner_id"], result["id"], "", link)
async def get_full_data(self, message_data: Dict = None) -> None: self._full_attaches = [] self._full_forwarded = [] if not message_data: values = {'message_ids': self.msg_id} # Получаем полную информацию о сообщении в ВК full_message_data = await self.vk.method('messages.getById', values) if not full_message_data or not full_message_data[ 'items']: # Если пришёл пустой ответ от VK API return message = full_message_data['items'][0] else: message = message_data if "attachments" in message: for raw_attach in message["attachments"]: attach = Attachment.from_raw(raw_attach) # Создаём аттач self._full_attaches.append( attach) # Добавляем к нашему внутреннему списку аттачей if 'fwd_messages' in message: self._full_forwarded, self.brief_forwarded = await self.parse_forwarded_messages( message)
async def upload_photo(self, multipart_data: BinaryIO) -> Optional[Attachment]: # Лимит загрузки фотографий на сервера вк - 7000 в день if isinstance(db, peewee_async.Manager): status, created = await db.get_or_create(BotStatus, id=0) if status: if time.time() - status.timestamp > 60 * 60 * 24: status.timestamp = time.time() status.photos = 0 elif status.photos >= 6969: return None else: status.photos += 1 await db.update(status) sender = self.get_default_sender("photos.getMessagesUploadServer") data = aiohttp.FormData() data.add_field('photo', multipart_data, filename='picture.png', content_type='multipart/form-data') upload_url = (await self.method('photos.getMessagesUploadServer', send_from=sender))['upload_url'] async with aiohttp.ClientSession() as sess: async with sess.post(upload_url, data=data) as resp: result = json.loads(await resp.text()) if not result: return None data = dict(photo=result['photo'], hash=result['hash'], server=result['server']) result = (await self.method('photos.saveMessagesPhoto', data, send_from=sender))[0] url = "" for k in result: if "photo_" in k: url = result[k] return Attachment("photo", result["owner_id"], result["id"], "", url)
async def upload_photo(self, encoded_image) -> Attachment: if isinstance(db, peewee_async.Manager): status, created = await db.get_or_create(BotStatus, id=0) if status: if time.time() - status.timestamp > 60 * 60 * 24: status.timestamp = time.time() status.photos = 0 elif status.photos >= 6969: return None else: status.photos += 1 await db.update(status) data = aiohttp.FormData() data.add_field('photo', encoded_image, filename='picture.png', content_type='multipart/form-data') upload_url = ( await self.method('photos.getMessagesUploadServer'))['upload_url'] async with aiohttp.ClientSession() as sess: async with sess.post(upload_url, data=data) as resp: result = json.loads(await resp.text()) if not result: return None data = dict(photo=result['photo'], hash=result['hash'], server=result['server']) result = (await self.method('photos.saveMessagesPhoto', data))[0] link = "" for k in result: if "photo_" in k: link = result[k] return Attachment("photo", result["owner_id"], result["id"], "", link)
async def upload_photo(self, encoded_image) -> Attachment: files = {'file': ('picture.png', encoded_image)} upload_url = ( await self.method('photos.getMessagesUploadServer'))['upload_url'] response = requests.post(upload_url, files=files) result = json.loads(response.text) data = dict(photo=result['photo'], hash=result['hash'], server=result['server']) result = (await self.method('photos.saveMessagesPhoto', data))[0] link = "" for k in result: if "photo_" in k: link = result[k] return Attachment("photo", result["owner_id"], result["id"], "", link)
async def upload_doc(self, multipart_data: BinaryIO, filename="image.png") -> Optional[Attachment]: sender = self.get_default_sender("docs.getWallUploadServer") data = aiohttp.FormData() data.add_field('file', multipart_data, filename=filename, content_type='multipart/form-data') v = {} if GROUP_ID: v = {'group_id': GROUP_ID} upload_url = (await self.method('docs.getWallUploadServer', v, send_from=sender))['upload_url'] async with aiohttp.ClientSession() as sess: async with sess.post(upload_url, data=data) as resp: result = json.loads(await resp.text()) if not result: return None data = dict(file=result['file']) result = (await self.method('docs.save', data, send_from=sender))[0] url = "" if "url" in result: url = result["url"] for k in result: if "photo_" in k: url = result[k] return Attachment("doc", result["owner_id"], result["id"], "", url)
async def full_attaches(self): # Если мы уже получали аттачи для этого сообщения, возвратим их if self._full_attaches: return self._full_attaches self._full_attaches = [] values = {'message_ids': self.msg_id, 'preview_length': 1} # Получаем полную информацию о сообщении в ВК (включая аттачи) full_message_data = await self.vk.method('messages.getById', values) if not full_message_data: # Если пришёл пустой ответ от VK API return [] message = full_message_data['items'][0] if "attachments" not in message: # Если нет аттачей return # Проходимся по всем аттачам for raw_attach in message["attachments"]: # Тип аттача a_type = raw_attach['type'] # Получаем сам аттач attach = raw_attach[a_type] link = "" # Ищём ссылку на фото for k, v in attach.items(): if "photo_" in k: link = v # Получаем access_key для аттача key = attach.get('access_key') attach = Attachment(a_type, attach['owner_id'], attach['id'], key, link) # Добавляем к нашему внутреннему списку аттачей self._full_attaches.append(attach) return self._full_attaches