D
D
darknos232021-03-09 01:23:56
In contact with
darknos23, 2021-03-09 01:23:56

How to send a photo to a VK conversation with a bot using Python?

I am newbie and just started to understand pythone. I want to send a photo to a VK conversation using a bot, for example, if the user wrote "photo" and the bot sent a photo, but I just can't figure out how to do it. Please help, and please be very detailed.
Thanks in advance!!!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
HemulGM, 2021-03-09
@HemulGM

You need the following VK API methods in order:

  • photos.getMessagesUploadServer
  • post request with file sending ( link )
  • photos.saveMessagesPhoto

Well, sending as an attachment.
Pascal example
procedure TFormMain.SendPic(Stream: TStream; FileName: string; PeerId: Integer; ReplyTo: Integer);
var
  Url: string;
  Response: TVkPhotoUploadResponse;
  Photos: TVkPhotos;
begin
  if VK.Photos.GetMessagesUploadServer(Url, PeerId) then
  begin
    if VK.Photos.Upload(Response, Url, Stream, FileName) then
    try
      if VK.Photos.SaveMessagesPhoto(Photos, Response) then
      try
        if ReplyTo <> 0 then
          VK.Messages.New.PeerId(PeerId).ReplyTo(ReplyTo).Attachment(Photos.ToAttachments).Send.Free
        else
          VK.Messages.New.PeerId(PeerId).Attachment([FileName]).Send.Free;
      finally
        Photos.Free;
      end;
    finally
      Response.Free;
    end;
  end;
end;

Although, in Pascal there is a shorter version
procedure TFormMain.SendPic(const FileNames: TArray<string>; PeerId: Integer);
var
  Photos: TAttachmentArray;
begin
  if VK.Photos.UploadForMessage(Photos, PeerId, FileNames) then
    VK.Messages.New.PeerId(PeerId).Attachment(Photos).Send.Free;
end;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question