[docs]classMultipartData:def__init__(self):self.boundary="---------------discord.http"self.bufs:list[bytes]=[]@propertydefcontent_type(self)->str:""" `str`: The content type of the multipart data """returnf"multipart/form-data; boundary={self.boundary}"
[docs]defattach(self,name:str,data:Union[File,BufferedIOBase,dict,str],*,filename:Optional[str]=None,content_type:Optional[str]=None)->None:""" Attach data to the multipart data Parameters ---------- name: `str` Name of the file data data: `Union[File, io.BufferedIOBase, dict, str]` The data to attach filename: `Optional[str]` Filename to be sent on Discord content_type: `Optional[str]` The content type of the file data (Defaults to 'application/octet-stream' if not provided) """ifnotdata:returnNonestring=f"\r\n--{self.boundary}\r\nContent-Disposition: form-data; name=\"{name}\""iffilename:string+=f"; filename=\"{filename}\""matchdata:casexifisinstance(x,File):string+=f"\r\nContent-Type: {content_typeor'application/octet-stream'}\r\n\r\n"data=data.data# type: ignorecasexifisinstance(x,BufferedIOBase):string+=f"\r\nContent-Type: {content_typeor'application/octet-stream'}\r\n\r\n"casexifisinstance(x,dict):string+="\r\nContent-Type: application/json\r\n\r\n"data=json.dumps(data)case_:string+="\r\n\r\n"data=str(data)self.bufs.append(string.encode("utf8"))ifgetattr(data,"read",None):# Check if the data has a read method# If it does, it's a file-like objectdata=data.read()# type: ignoreifisinstance(data,str):# If the data is a string, encode it to bytes# Sometimes data.read() returns a string due to things like StringIOdata=data.encode("utf-8")# type: ignoreself.bufs.append(data)# type: ignorereturnNone
[docs]deffinish(self)->bytes:""" `bytes`: Return the multipart data to be sent to Discord """self.bufs.append(f"\r\n--{self.boundary}--\r\n".encode("utf8"))returnb"".join(self.bufs)