J
J
Jalal Nasirov2021-06-06 12:21:26
Python
Jalal Nasirov, 2021-06-06 12:21:26

How to get a picture from a user and send the same picture to the same user. vk_api python?

I need that when the user sends a picture to the bot, the bot sends this picture to him, or rather, save its URL to a variable in order to work with the picture in the future. I dug all over the Internet, but did not find anything normal and working. I know how to send a picture, knowing only the url, so the most important thing for me is to get the url of the sent picture.
This is what I was trying to do:

import vk_api
from vk_api.longpoll import VkLongPoll, VkEventType
token= '...'

vk_session = vk_api.VkApi(token=token)
session_api = vk_session.get_api()
longpoll = VkLongPoll(vk_session)


def sender(text):
    vk_session.method('messages.send', {'user_id': id, 'message': text, 'random_id': 0})
    
def send_photo(url):
    vk_session.method("messages.send", {"peer_id": id, "message": "TEST", "attachment": url, "random_id": 0})


for event in longpoll.listen():
    if event.type == VkEventType.MESSAGE_NEW:
        if event.to_me:
            
            msg = event.text.lower()
            
            id = event.user_id
            
            sender(msg)
            
    elif event.type == 'photo':
        if event.to_me:
            
            send_photo('photo-{}_{}'.format(event['user_id'], event['id']))

This is how to send an image using its url:
import vk_api
from vk_api.longpoll import VkLongPoll, VkEventType

vk_session = vk_api.VkApi(token='...')
session_api = vk_session.get_api()
longpoll = VkLongPoll(vk_session)


def sender(text):
    vk_session.method('messages.send', {'user_id': id, 'message': text, 'random_id': 0})


def send_photo(url):
    vk_session.method("messages.send", {"peer_id": id, "message": "TEST", "attachment": url, "random_id": 0})


for event in longpoll.listen():
    if event.type == VkEventType.MESSAGE_NEW:
        if event.to_me:
            msg = event.text.lower()
            id = event.user_id
            sender(msg)
            send_photo('photo-126879742_457245742')

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
UberPool, 2021-06-06
@Best_Loops

You can get a link to an image like this:

event.obj.message['attachments'][0]['photo']['sizes'][-1]['url']

If a similar task appears, just see what the event is and pull out the necessary information.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question