A
A
Andrey2019-02-05 02:26:46
Python
Andrey, 2019-02-05 02:26:46

How to send a photo using VK API using Python?

The goal is to send a photo with a VKontakte message, after uploading it.
Using the photos.getMessagesUploadServer VK API method, I get a link to upload a photo:

link = 'https://api.vk.com/method/photos.getMessagesUploadServer?access_token=' + my_token + '&v=5.92' 
answer = requests.get(link)
text = html2text.HTML2Text().handle(answer.text)
url = eval(text)['response']['upload_url']

Further, downloading from this link, I get "InvalidURL: Failed to parse: https:\"
file_ = {'photo_file': ('photo.jpg', open('photo.jpg', 'rb'))}
answer2 = requests.post(url, files=file_)

Tried the same:
url_fixed = url.replace('\\','/')
file_ = {'photo_file': ('photo.jpg', open('photo.jpg', 'rb'))}
answer2 = requests.post(url_fixed, files=file_)

In response to me: "InvalidURL: No host supplied"
Either I did not understand how post requests work, or I did not understand what VK wants

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail, 2019-02-05
@lightarhont

More or less like this

import vk, requests, os 
       
        session = vk.Session(access_token=access_token)
        api = vk.API(session, v='5.8')
        profile = api.users.get(user_id=user_id, fields=["photo_100",'sex','nickname', 'bdate'])[0]
        
        #Записываем на диск фото с vk
        data = requests.get(profile['photo_100'])
        filename = os.path.join(os.getcwd()+'/static/usersdata/photos', user_id+'.jpg')
        try:
            f=open(filename,'wb')
            f.write(data.content)
            f.close()
        except FileNotFoundError:
            return {'errorfilewrite': True}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question