Download photos from Instagram using the Vkontakte bot

  • Tutorial


In this publication, we will write a VKontakte bot that accepts a link to a photo from Instagram, and sends this photo back.


We create a group in Vkontakte and in the community settings include messages:
"Community Management" - "Messages".


First, let's try to create an "echo bot".


The following libraries will be needed to work


falcon==1.2.0
gunicorn==19.7.1
py-vkontakte==5.53.4
requests==2.18.3

We need to get TOKEN, with which we can send messages on behalf of the community:


"Community Management" - "Settings" - "Work with API" - "Access Keys" .



There are two ways to receive new messages: “Callback API” or “Long Poll”.
Will use the "Callback API".


"Callback API" sends data in json format.


{ 
   "type":"message_new", 
   "object":{ 
      "id":1, 
      "date":1499441696, 
      "out":0, 
      "user_id":1, 
      "read_state":0, 
      "title":" ... ", 
      "body":"Hello" 
   }, 
   "group_id":1, 
   "secret":"111111" 
}

In the "Callback API" you must specify the server address. As the server we will use falcon


"Community Management" - "Settings" - "Work with API" - "Callback API".




Confirm the server for the "Callback API":


import falcon
GROUP_ID = "YOUR GROUP ID"
CONFIRMATION = "YOUR CONFIRMATION CODE"
class Bot(object):
    def on_post(self, req, resp):
        if req.content_length:
            data = json.loads(req.stream.read())
        if "confirmation" == data.get("type") and GROUP_ID == data.get("group_id"):
            resp.data = CONFIRMATION
application = falcon.API()
application.add_route('/', Bot())

Now we will write a handler for receiving new messages and sending them. To send a message will use the py-vkontakte library .


# ....
import vk
api = vk.Api(TOKEN)  # которые вы получили выше
group = api.get_group(GROUP_ID)
class Bot(object):
    def on_post(self, req, resp):
       # ....
        user_id = data.get('object').get('user_id')
        text = data.get('object').get('body')
        if "message_new" == data.get("type"):
            group.send_message(user_id, text)
            resp.data = b"ok"
# ....

In order to tell Vkontakte that we have successfully read the message, you need to send the string "ok".


"Echo-bot" is ready, you can run it


gunicorn bot:application

We write a bot that sends photos from Instagram


Instagram documentation says that if you add / media to https://instagram.com/p/fA9uwTtkSN/ , the JPG file will return.


To begin with, we will write a function that will check that the message sent by the user is a link to the Instagram site.


from urllib.parse import urlsplit
def is_instagram_link(self, link):
    url = urlsplit(link)
    if url.netloc in ["www.instagram.com", "instagram.com"]:
        return True
    return False

Let's write a function that adds / media to the link and downloads this JPG


import io
from urllib.parse import urljoin
import requests
def get_instagram_photo(self, instagram_photo_link):
    url = urljoin(instagram_photo_link, 'media/?size=l')
    response = requests.get(url)
    if not response.ok:
        raise ValueError()
    file_like = ('photo.jpg', io.BytesIO(response.content))
    return file_like

? size = l is a parameter that indicates the size of the returned JPG
if not response.ok: - the link may be
incorrect , we need to check this file_like = ('photo.jpg', io.BytesIO (response.content)) - we ’re ready received jpg to send


Add is_instagram_linkand get_instagram_photoin class Botand change the logic of work, when a new message arrives, we send JPG.


class Bot(object):
    def on_post(self, req, resp):
        # ....
        if "message_new" == data.get("type"):
            if not self.is_instagram_link(message_text):
                group.send_messages(user_id, message='Отправьте пожалуйста ссылку на фото из instagram.com')
            else:
                try:
                    instagram_photo = self.get_instagram_photo(instagram_photo_link=message_text)
                    group.send_messages(user_id, image_files=[instagram_photo])
                except ValueError:
                    group.send_messages(user_id, message='Не могу найти фото, проверьте пожалуйста ссылку')
        resp.data = b'ok'
# ....

An example of the bot
Source code


Additional links:



Also popular now: