S
S
Semyon Novikov2018-05-09 00:03:33
Python
Semyon Novikov, 2018-05-09 00:03:33

How to send SVG image to user via VK-API in Python?

I need to get (or download) a picture from a link. Then send to the user in a personal message via vk-api. How can I do that? Does vk-api support SVG format at all or does it need to be converted? How to do it right? And it looks like the cairosvg library doesn't support SVG . And is it possible to shove a picture into a message? Here's something I didn't understand:

import vk_api
import json
import requests
import cairosvg
import vk_api.longpoll
from vk_api.longpoll import VkLongPoll , VkEventType , Event
try:
  from urllib.request import urlopen
  from PIL import Image
except:
  print("Import Error !")

token_vk = "*************************"

# инициализация бота
vk_session = vk_api.VkApi(token=token_vk)
vk = vk_session.get_api()

# инициализация лонгполлинга
longpoll = VkLongPoll(vk_session)

#много кода ...

def send_photo(photos):
  
  url = self.vk.method('photos.getMessagesUploadServer')['upload_url']
  photo_files = open_files(photos)
  response = self.vk.http.post(url, files=photo_files)
  close_files(photo_files)
  response = self.vk.method('photos.saveMessagesPhoto', response.json())
  
  return response

def state0(message: Event):
    text = message.text
    #бла-бла-бла
    cairosvg.svg2png(url='https://restcountries.eu/data/rus.svg', write_to='C:/Main/Programming/test.png')
    url2 = "C:/Main/Programming/test.png"
    image = Image.open(urlopen(url2))
    s = send_photo(image)

# отправляем сообщение
    vk.messages.send(
      user_id = message.user_id,	 # кому
      message = s					 # само сообщение хранится в переменной 's'
      )


# ожидаем события
for event in longpoll.listen():
  # если новое сообщение
  if event.type == VkEventType.MESSAGE_NEW and event.to_me:
    # получаем или создаём id пользователя в базе данных
    user, _ = User.get_or_create(vk_id=event.user_id) 
    if user.state == 0:
      state0(event)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Semyon Novikov, 2018-05-12
@semennovikov123

Already did it myself. Suddenly, someone will need a link to github . There is also a conversion of SVG to JPG, as well as sending a photo in a personal to VK.

D
David Webb, 2018-05-09
@dw9694

I wrote for my own needs, but if you look closely, you can catch the essence of how to upload a picture.

spoiler
import requests
import vk_api

BASE_DIR = os.path.dirname(os.path.abspath('__file__'))


class VKPage(object):
    def __init__(self, photo_album_id, post_owner_id):
        self.vk_session = vk_api.VkApi(LOGIN, PASSWORD, app_id='*****',
                                       config_filename='config.json')
        try:
            self.vk_session.authorization()
        except vk_api.AuthorizationError as error_msg:
            print(error_msg)
            return

        self.vk = self.vk_session.get_api()

        self.album_id = photo_album_id
        self.content_owner_id = self.groupIds()
        self.post_owner_id = post_owner_id


    def upload_photo(self, path_to_photo):

        upload = vk_api.VkUpload(self.vk_session)

        photo = upload.photo(  # Подставьте свои данные
            path_to_photo,
            album_id=self.album_id
        )

        vk_photo = 'photo{}_{}'.format(
            photo[0]['owner_id'], photo[0]['id']
        )

        return vk_photo


    def save_photo(self, url):
        r = requests.get(url)
        path_to_picture = BASE_DIR + '/picture.jpg'
        with open(path_to_picture, 'wb') as f:
            f.write(r.content)
        return path_to_picture

    def main(self):
        path_to_picture = self.save_photo(photo_res)
        self.vk.wall.post(owner_id=self.post_owner_id, message=text,
                          attachments=self.upload_photo(path_to_picture))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question