K
K
kreyNie2021-07-29 01:07:33
Python
kreyNie, 2021-07-29 01:07:33

How to attach a photo to a VK bot message?

Good day! The other day I was puzzled by the idea of ​​attaching a photo to a message. The photo itself is not stored on the computer, but is taken from the request URL.

def getSteamItemImageFromUrl(classID: str):
     STEAM_URL = 'https://steamcommunity-a.akamaihd.net/economy/image/class/730/'
     response = get(STEAM_URL + classID + '/330fx250f', stream=True).content
     image = BytesIO(response).getvalue()
     return b64encode(image)

Here I get an image in byte representation, then I need to upload it to the VK server, but I run into a problem that the function stupidly does not want to accept bytes into itself and says that there is no such image in the directory. The code itself with the publication on the VK server
def uploadImageToServer(image) -> str:
    """Загружает изображение на сервер, возвращает строку для attachment"""
    upload = vk_api.VkUpload(vk)
    photo = upload.photo_messages(image)
    return f"photo_{photo['owner_id']}_{photo['id']}"

The photo_messages method just does not accept the image parameter, which is in byte representation.
Actually, the error itself: f = open(filename, 'rb')
FileNotFoundError: [Errno 2] No such file or directory
, followed by a string of bytes

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
SKEPTIC, 2021-07-29
@pro100chel

Save the image as a file and already in upload.photo_messages(image)the image variable specify the path to the file.

import secrets


def getSteamItemImageFromUrl(classID: str):
    STEAM_URL = 'https://steamcommunity-a.akamaihd.net/economy/image/class/730/'
    response = get(STEAM_URL + classID + '/330fx250f', stream=True).content
    filename = secrets.token_hex(16) + '.jpg'

    with open(filename, 'wb') as file:
        file.write(response)

    return filename


def uploadImageToServer(image) -> str:
    """Загружает изображение на сервер, возвращает строку для attachment"""
    upload = vk_api.VkUpload(vk)
    photo = upload.photo_messages(image)
    return f"photo_{photo['owner_id']}_{photo['id']}"

Here is something that should happen. After sending the photo to the server, you can delete it from the disk.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question