Attachment Models

Classes for representing message attachments and media content.

Overview

Attachments represent various types of media and content that can be sent or received in messages. fbchat-muqit supports a wide variety of attachment types including images, videos, files, stickers, and Facebook-specific content like posts, reels, and profiles.

from fbchat_muqit import ImageAttachment, VideoAttachment, PostAttachment

# Attachments are automatically parsed from messages

# inside on_message()
message = await client.fetch_message_info(message_id, thread_id)

for attachment in message.attachments:
    if isinstance(attachment, ImageAttachment):
        print(f"Image: {attachment.preview.url}")
    elif isinstance(attachment, VideoAttachment):
        print(f"Video: {attachment.playable_url}")

Attachment Types

class fbchat_muqit.AttachmentType

Bases: str, Enum

static maketrans()

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

__init__(*args, **kwds)
__new__(value)
capitalize()

Return a capitalized version of the string.

More specifically, make the first character have upper case and the rest lower case.

casefold()

Return a version of the string suitable for caseless comparisons.

center(width, fillchar=' ', /)

Return a centered string of length width.

Padding is done using the specified fill character (default is a space).

count(sub[, start[, end]]) int

Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.

encode(encoding='utf-8', errors='strict')

Encode the string using the codec registered for encoding.

encoding

The encoding in which to encode the string.

errors

The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.

endswith(suffix[, start[, end]]) bool

Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.

expandtabs(tabsize=8)

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

find(sub[, start[, end]]) int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

format(*args, **kwargs) str

Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).

format_map(mapping) str

Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).

index(sub[, start[, end]]) int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

isalnum()

Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

isalpha()

Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

isascii()

Return True if all characters in the string are ASCII, False otherwise.

ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.

isdecimal()

Return True if the string is a decimal string, False otherwise.

A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.

isdigit()

Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.

isidentifier()

Return True if the string is a valid Python identifier, False otherwise.

Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.

islower()

Return True if the string is a lowercase string, False otherwise.

A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

isnumeric()

Return True if the string is a numeric string, False otherwise.

A string is numeric if all characters in the string are numeric and there is at least one character in the string.

isprintable()

Return True if the string is printable, False otherwise.

A string is printable if all of its characters are considered printable in repr() or if it is empty.

isspace()

Return True if the string is a whitespace string, False otherwise.

A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

istitle()

Return True if the string is a title-cased string, False otherwise.

In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

isupper()

Return True if the string is an uppercase string, False otherwise.

A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

join(iterable, /)

Concatenate any number of strings.

The string whose method is called is inserted in between each given string. The result is returned as a new string.

Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’

ljust(width, fillchar=' ', /)

Return a left-justified string of length width.

Padding is done using the specified fill character (default is a space).

lower()

Return a copy of the string converted to lowercase.

lstrip(chars=None, /)

Return a copy of the string with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.

partition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original string and two empty strings.

removeprefix(prefix, /)

Return a str with the given prefix string removed if present.

If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.

removesuffix(suffix, /)

Return a str with the given suffix string removed if present.

If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.

replace(old, new, count=-1, /)

Return a copy with all occurrences of substring old replaced by new.

count

Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

rfind(sub[, start[, end]]) int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

rindex(sub[, start[, end]]) int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

rjust(width, fillchar=' ', /)

Return a right-justified string of length width.

Padding is done using the specified fill character (default is a space).

rpartition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing two empty strings and the original string.

rsplit(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the end of the string and works to the front.

rstrip(chars=None, /)

Return a copy of the string with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

split(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the front of the string and works to the end.

Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.

splitlines(keepends=False)

Return a list of the lines in the string, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends is given and true.

startswith(prefix[, start[, end]]) bool

Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.

strip(chars=None, /)

Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

swapcase()

Convert uppercase characters to lowercase and lowercase characters to uppercase.

title()

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all remaining cased characters have lower case.

translate(table, /)

Replace each character in the string using the given translation table.

table

Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.

The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

upper()

Return a copy of the string converted to uppercase.

zfill(width, /)

Pad a numeric string with zeros on the left, to fill a field of the given width.

The string is never truncated.

AUDIO = 'MessageAudio'
EXTERNALURL = 'ExternalUrl'
FACEBOOKGAME = 'MessengerBusinessMessage'
FACEBOOKPOST = 'Story'
FACEBOOKPRODUCT = 'CommerceProductItemShare'
FACEBOOKPROFILE = 'User'
FACEBOOKREEL = 'Video'
FACEBOOKSTORY = 'source:fb_story'
FILE = 'MessageFile'
GIF = 'MessageAnimatedImage'
IMAGE = 'MessageImage'
LOCATION = 'MessageLocation'
SHARE = 'ExtensibleMessageAttachment'
STICKER = 'Sticker'
VIDEO = 'MessageVideo'

Media Attachments

Image Attachment

class fbchat_muqit.ImageAttachment

Bases: Struct

Image attachment with preview and dimensions.

filename: str

The filename of the Image.

id: str

The Image Id of the Attachment. The Id can be used to send picture without uploading to Facebook server.

large_preview: Image

The preview of the image for desktop.

original_dimensions: Dimension

The height and weight of the image.

original_extension: str

The extension of the Image, such as jpg, png

preview: Image

The preview of the image.

render_as_sticker: bool

wether sent as Sticker or not

thumbnail: Image

The original Image probably.

type: AttachmentType

Type of the attachment.

Video Attachment

class fbchat_muqit.VideoAttachment

Bases: Struct

Video attachment with duration and preview.

filename: str

filename of the video

id: str

The Id of the video.

large_preview: Image

Preview image of the video for desktop.

original_dimensions: Dimension

Height and Width of the Video.

playable_duration: int

Duration of the video.

playable_url: str

The url for playing the video also can be used to download it.

preview: Image

Preview image of the video.

type: AttachmentType

Type of the Video.

GIF Attachment

class fbchat_muqit.GifAttachment

Bases: Struct

animated_image: Image

The gif information including its url.

filename: str

Filename of the Gif.

id: str

Gif Id of the Attachment.

original_dimensions: Dimension

The Dimension of the gif.

preview_image: Image

Preview of the gif.

type: AttachmentType

Sticker Attachment

class fbchat_muqit.StickerAttachment

Bases: Struct

Sticker attachment with Its information.

frame_count: int

The frame count of the Sticker If It’s an animated Sticker

frame_rate: int

The frame rate of the Sticker

frames_per_column: int

Animated Sticker’s frame per column

frames_per_row: int

Animated Sticker’s frame per row

height: int

Height of the Sticker

id: str

The Id of the Sticker

label: str

The label/words used for this Sticker

pack: Value

The Pack id of the Sticker if the Sticker is part of a Pack.

padded_sprite_image_2x: Image | None

Padded Sprite Sheet

sprite_image: Image | None

Sprite sheet of the Sticker

sprite_image_2x: Image | None

Sprite sheet of the Sticker for desktop screen

type: AttachmentType

Type of the Attachment.

url: str

The url of the Sticker

width: int

Width of the Sticker

Audio Attachment

class fbchat_muqit.AudioAttachment

Bases: Struct

Audio attachment

filename: str

filename of the Audio

is_voicemail: bool

wether It is voicemail

playable_duration: int

Duration of the Audio message.

playable_url: str

Playable url of the Audio

type: AttachmentType

Type of the Attachment.

File Attachment

class fbchat_muqit.FileAttachment

Bases: Struct

General file attachment. It can be any kind of file such as pdf, txt, html, docs etc.

download_url: str | None

The url of the file can be used to download

is_malicious: bool | None

)

Type:

Wether the file is detected as malicious or not. Not really trustable

mimetype: str | None

Type of the file such as pdf, txt etc.

type: AttachmentType

Type of the Attachment.

Facebook Content Attachments

Post Attachment

class fbchat_muqit.PostAttachment

Bases: Struct

Represents a Facebook Post Attachment shared to Messenger

description: str

The description of the Facebook Post

id: str

The id of the Attachment

post: Post

The extra information about the Post

post_preview: Media

The Post preview details

post_url: str

The url of the Facebook Post

source: str | None

source of the post such as Page name or User’s name etc.

title: str

The title of the Facebook Post.

type = 'Story'

Type of the Attachment

Reel Attachment

class fbchat_muqit.ReelAttachment

Bases: Struct

Represents A Facebook Reel Shared to Messenger. Any Facebook video shared in both Facebook and Instagram is also counted as Reel.

description: str | None

Reels description.

id: str

Id of the Reel Attachment.

media: Media

Extra information about the Reel

source: str

source can be the Reel’s author profile name or Page name

title: str

The title of the Reel.

type = 'Video'

Type of Attachment.

url: str

Url of the Reel

video_id: str

The Video Id of the Reel.

Profile Attachment

class fbchat_muqit.ProfileAttachment

Bases: Struct

Facebook profile share attachment

cover_photo: Image | None

Cover photo of the Shared User

id: str

Attachment Id

profile_id: str

Shared User’s Facebook uid.

profile_name: str

Shared User’s profile name

profile_picture: Image

profile picture of the Shared User’s

profile_url: str

Url of the Shared profile

type = 'User'

Attachment Type

Product Attachment

class fbchat_muqit.ProductAttachment

Bases: Struct

id: str

Attachment Id.

product_name: str

The name of the Shared Facebook Product

product_price: str

The product price (can be in any currency)

type = 'CommerceProductItemShare'

Attachment Type

url: str

Url to the product

Other Attachments

Location Attachment

class fbchat_muqit.LocationAttachment

Bases: Struct

Location attachment with coordinates.

address: str | None

Address of the Location

id: str

Id of the Attachment

is_live: bool

True if the Location is live Location.

latitude: float | None

Latitude of the Location

longitude: float | None

Longitude of the Location

media: Media

The preview of the Location Attachment.

type: AttachmentType

Type of the attachment

url: str

Location’s url

External Attachment

class fbchat_muqit.ExternalAttachment

Bases: Struct

Any Link not related to Facebook Meta is ExternalUrl Attachment.such as YT link, website link etc.

description: str | None

description of the url source’s content

id: str

Attachment Id

media: Media | None

The shared url’s content information Such as if any Youtube video url will inlcude video thumbnail, name, duration details.

title: str | None

Title of the The url content

type = 'ExternalUrl'

Attachment Type.

url: str

Url of the Attachment

Shared Attachment

class fbchat_muqit.SharedAttachment

Bases: Struct

Represents Unknown Attachment shared to Messenger

description: str | None

The description of the Shared Attachment

id: str

The Attachment Id.

media: Media | None

Extra information about the shared Attachment.

title: str | None

The title of the Shared Attachment

type = 'source:fb_story'

Attachment Type

Supporting Classes

Dimension

class fbchat_muqit.Dimension

Bases: Struct

width and height of image

height: int

height of the image

width: int

weight of the image

Image

class fbchat_muqit.Image

Bases: Struct

An Image url with extra info.

height: int

height of the image

url: str

url of the image

width: int

width of the image

Media

class fbchat_muqit.Media

Bases: Struct

id: str

The id of the picture/video

is_playable: bool

True if It’s an video otherwise False

playable_duration: int

The duration of the video sometimes it may be show 0 if it fails to get the duration of the video.

playable_url: str | None

The url to play the video.

preview: Image

Thumbnail’s information.

type: str | None

Can be an Image/Video/Audio

Author

class fbchat_muqit.Author

Bases: Struct

Profile details of the author of the shared attachment

cover_photo: dict

The Author’s profile cover photo sometimes may not be provided.

id: str

The Facebook uid of the Post Author (user, page)

name: str

Name of the Facebook

picture: Image

Profile picture information of the Author.

url: str

The Author’s profile url

GroupInfo

class fbchat_muqit.GroupInfo

Bases: Struct

Minimum Group information

name: str

Group name

url: str

Group’s url

Post

class fbchat_muqit.Post

Bases: Struct

Shared Facebook Post’s information

author: List[Author]

The Author of the post (Page, User e.g.)

creation_time: int

The time post was published

description: Value | None

Description of the post

feedback_id: PostId

Encoded post id can be used for reacting, sharing, commenting etc.

group: GroupInfo | None

If it is a Group post, some info maybe included

post_id: str

Facebook post id of the Post

title: Value | None

Title of the post.

Usage Examples

Checking Attachment Types

import asyncio
from fbchat_muqit import (
   Client, ImageAttachment, VideoAttachment,
   StickerAttachment, FileAttachment
)

async def main():
    msg_id = "mid.behw.........."
    thread_id = "1000973........."
    async with Client(cookies_file_path="cookies.json") as client:
        message = await client.fetch_message_info(msg_id, thread_id)

        if message and message.attachments:
            for attachment in message.attachments:
                if isinstance(attachment, ImageAttachment):
                   print(f"📷 Image: {attachment.filename}")
                   print(f"   URL: {attachment.preview.url}")
                   print(f"   Size: {attachment.original_dimensions.width}x"
                         f"{attachment.original_dimensions.height}x")

                elif isinstance(attachment, VideoAttachment):
                   print(f"🎥 Video: {attachment.filename}")
                   print(f"   Duration: {attachment.playable_duration}ms")
                   print(f"   URL: {attachment.playable_url}")

                elif isinstance(attachment, StickerAttachment):
                   print(f"😊 Sticker: {attachment.label}")
                   print(f"   Animated: {attachment.frame_count > 0}")

                elif isinstance(attachment, FileAttachment):
                   print(f"📎 File")
                   print(f"   Type: {attachment.mimetype}")
                   print(f"   Download: {attachment.download_url}")

asyncio.run(main())

Downloading Attachments

from fbchat_muqit import Client
from fbchat_muqit.models import Message, ImageAttachment


client = Client("cookies.json")


# Usage
@client.event
async def on_message(message: Message):
    # if the message has a image attachment download the image
    if message.attachments:
        for attachment in message.attachments:
            if isinstance(attachment, ImageAttachment):
                await client.download(attachment.large_preview.url, attachment.filename)

client.run()

Working with Facebook Content’s Attachment

from fbchat_muqit import PostAttachment, ReelAttachment, ProfileAttachment

for attachment in message.attachments:
    if isinstance(attachment, PostAttachment):
        print(f"📝 Facebook Post")
        print(f"   Title: {attachment.title}")
        print(f"   Author: {attachment.post.author[0].name}")
        print(f"   URL: {attachment.post_url}")

    elif isinstance(attachment, ReelAttachment):
        print(f"🎬 Facebook Reel")
        print(f"   Title: {attachment.title}")
        print(f"   Creator: {attachment.source}")
        print(f"   URL: {attachment.url}")

    elif isinstance(attachment, ProfileAttachment):
        print(f"👤 Profile Shared")
        print(f"   Name: {attachment.profile_name}")
        print(f"   URL: {attachment.profile_url}")

See Also

  • Message Models - Message models that contain attachments

  • Client - Client methods for sending attachments

  • /guides/attachments - Guide on working with attachments