Get started by installing the SDK:

pip install posto-sdk

The SDK offers two main classes:

  1. PostoSDK: The core class providing direct API access with basic functionality.

  2. SocialMediaManager: An all-in-one solution that inherits all PostoSDK functionality while adding convenience methods.

Important: You only need to initialize SocialMediaManager to access all SDK features. There's no need to initialize both classes separately.

# All-in-one approach (recommended)
from posto_sdk import SocialMediaManager

# Initialize once and get access to all functionality
manager = SocialMediaManager()

# Use both basic PostoSDK methods and enhanced SocialMediaManager methods
channels = manager.get_active_channels()  # PostoSDK method
manager.post_to("instagram", "Hello world!")  # SocialMediaManager method

If you only need the core functionality, you can use PostoSDK directly:

from posto_sdk import PostoSDK

# Basic initialization
posto = PostoSDK.from_token(token="your_base64_encoded_token

Posting a Message

The core method for posting is post(). It accepts a message along with several optional keyword parameters that control target channels, scheduling, media attachments, and network settings.

Parameters

  • message (str) The text content you want to post.

  • to (int, str, or list) Specifies the channel(s) by which to post. Pass the channel ID (int) or name of the channel (str) or a list of them.

    • Example: to=2, to="News Feed", or to=[2, "Blog"].

  • when (datetime, str, or int, optional) Define when to post your message:

    • Immediate posting: Set to "now" or omit this parameter.

    • Relative time string: Use a string like "30m" for 30 minutes, "1h" for 1 hour, or "2d" for 2 days from now.

    • Human-readable string: Use strings like "tomorrow at 3pm" or "next Monday at noon".

    • Specific datetime: Pass a datetime object or a Unix timestamp (int).

  • media (str or list, optional) Path(s) or URL(s) to media files (images, videos) to attach. Accepts a single file (string) or a list of files.

    • The SDK will automatically download media from URLs if provided.

  • settings (dict, optional) Custom network settings to override the defaults for each channel's post. See the Custom Network Settings section for more details.

  • use_local_time (bool, default=True) Whether to interpret datetime strings in your local timezone. Set to False to use UTC.

Immediate Post

Post a message immediately to a single channel.

# Post an immediate message to channel with ID 2
result = posto.post("Hello World!", to=2)
print(result)

Scheduled Post (Relative Time)

Schedule a post to be published in, for example, 1 hour.

# Post a message scheduled 1 hour from now to channels 2 and 3
result = posto.post("Scheduled post in 1 hour", to=[2, 3], when="1h")
print(result)

Scheduled Post (Human-Readable Time)

Schedule a post using natural language time expressions.

# Schedule for tomorrow at 3pm in your local timezone
result = posto.post("Tomorrow's update!", to=[2, 3], when="tomorrow at 3pm")
print(result)

# Schedule for next Monday
result = posto.post("Next week's announcement", to=[2, 3], when="next Monday at 10am")
print(result)

Scheduled Post (Specific DateTime)

Schedule the post for a specific future datetime.

from datetime import datetime, timedelta

# Schedule a post 2 days from now
future_time = datetime.now() + timedelta(days=2)

result = posto.post("Post scheduled for a specific datetime", to=[2, 3], when=future_time)
print(result)

Post with Media Attachment

You can easily attach media (local file path or URL) along with your message.

# Post with an image attached that will be published in 1 hour
result = posto.post("Check out this cool photo!", to=[2, 3], media="path/to/image.jpg", when="1h")
print(result)

# Post with an image from a URL
result = posto.post("Check out this online photo!", to=[2, 3], media="https://example.com/image.jpg")
print(result)

For multiple media attachments, pass a list:

result = posto.post("Multiple images attached!", to="BlogChannel", media=["image1.jpg", "image2.jpg"])
print(result)

# Mix of local files and URLs
result = posto.post("Mixed media sources!", to="BlogChannel", 
                   media=["image1.jpg", "https://example.com/image2.jpg"])
print(result)

Custom Network Settings

Override default network settings (if necessary) by passing a settings dictionary. The keys in this dictionary depend on the specific network, but common options include toggles for attaching links, cutting post text, etc.

# Custom settings for the target network
custom_settings = {
    "attach_link": False,      # Do not attach a link by default
    "cut_post_text": True,     # Shorten the post text if necessary
    "custom_option": "value"   # Any additional settings your network may require
}

result = posto.post("Post with custom settings", to=2, settings=custom_settings)
print(result)

Channel Management

The SDK provides several methods to query and manage your social media channels.

List All Channels

# Get all available channels
channels = posto.channels
print(channels)

Get a Channel by ID

channel = posto.get_channel(2)
print(channel)

Find Channels by Name

# Case-insensitive partial matching
matching_channels = posto.get_channel_by_name("news")
print(matching_channels)

Get Channels by Network Type

# Get all Facebook channels
facebook_channels = posto.get_channels_by_type("facebook")
print(facebook_channels)

# Get all Twitter channels
twitter_channels = posto.get_channels_by_type("twitter")
print(twitter_channels)

Get Active Channels Only

# Get only channels that are active
active_channels = posto.get_active_channels()
print(active_channels)

Get Available Network Types

# Get a list of all available social network types
network_types = posto.get_channel_types()
print(network_types)

Refresh Channel List

# Force a refresh of the channel list from the server
posto.refresh_channels()

Schedule Management

The SDK provides a schedules property that gives you access to the ScheduleManager for managing scheduled posts.

List Schedules

# List all schedules (paginated)
schedules = posto.schedules.list()
print(schedules)

# List with filtering
error_schedules = posto.schedules.list(
    status="error",           # Filter by status
    network="facebook",       # Filter by network
    page=1,                   # Page number
    per_page=20               # Items per page
)
print(error_schedules)

# Filter by multiple statuses
pending_schedules = posto.schedules.list(
    status=["not_sent", "sending"],
    network=["facebook", "twitter"]
)
print(pending_schedules)

# Get a specific schedule by ID
specific_schedule = posto.schedules.list(schedule_id=123)
print(specific_schedule)

# Get schedules by group ID
group_schedules = posto.schedules.list(group_id="abc123")
print(group_schedules)

Retry Failed Schedules

# Retry a single failed schedule
retry_result = posto.schedules.retry(123)
print(retry_result)

# Retry multiple failed schedules
retry_results = posto.schedules.retry([123, 456, 789])
print(retry_results)

Delete Schedules

# Delete specific schedules by ID
delete_result = posto.schedules.delete(schedule_ids=[123, 456])
print(delete_result)

# Delete schedules with a specific status
delete_result = posto.schedules.delete(status="error")
print(delete_result)

# Delete schedules older than a certain time
delete_result = posto.schedules.delete(older_than="7d")  # 7 days
print(delete_result)

# Delete all schedules matching criteria
delete_result = posto.schedules.delete(
    status=["error", "draft"],
    all=True
)
print(delete_result)

# Delete all except specific IDs
delete_result = posto.schedules.delete(
    all=True,
    exclude_ids=[123, 456]  # These will be preserved
)
print(delete_result)

Network Settings Management

The SDK allows you to retrieve and manage network-specific settings.

Get Available Networks

# Get a list of all available social networks
networks = posto.get_available_networks()
print(networks)

Get Network Settings

# Get settings for a specific network
facebook_settings = posto.get_network_settings("facebook")
print(facebook_settings.get_available_settings())
print(facebook_settings.get_default_settings())

Save Network Settings

# Save custom settings for a network
posto.save_network_settings("twitter", {
    "post_text": "🚨 {post_title} 🚨",
    "cut_post_text": True
})

Settings Profiles

You can save and load settings profiles to reuse configurations across multiple posts.

# Save a settings profile
profile_settings = {
    "facebook": {"post_text": "Profile post for Facebook", "upload_media": True},
    "twitter": {"post_text": "Profile post for Twitter!"}
}

posto._settings_manager.save_settings_profile("daily_posts", profile_settings)

# Retrieve a settings profile
profile = posto._settings_manager.get_settings_profile("daily_posts")
print(profile)

# List all profiles
profiles = posto._settings_manager.list_settings_profiles()
print(profiles)

Error Handling

The SDK raises custom exceptions to help you manage errors:

  • MediaUploadError: Raised when media uploading fails.

  • ChannelError: Raised for channel-related issues.

  • PostingError: Raised if the post creation fails.

Always handle or log errors when calling post():

from posto_sdk import PostoSDK, MediaUploadError, ChannelError, PostingError

try:
    result = posto.post("Test post", to=2, media="image.jpg")
    
    if result.success:
        print(f"Post successful! Schedule Group ID: {result.schedule_group_id}")
    else:
        print(f"Post failed: {result.error_message}")
        
except MediaUploadError as e:
    print(f"Media upload failed: {str(e)}")
except ChannelError as e:
    print(f"Channel error: {str(e)}")
except PostingError as e:
    print(f"Posting error: {str(e)}")
except Exception as e:
    print(f"An unexpected error occurred: {str(e)}")

Understanding PostResult

The post() method returns a PostResult object with these properties:

  • success: Boolean indicating if the post was successful

  • schedule_group_id: ID of the schedule group (if successful)

  • error_message: Error message (if failed)

  • media_ids: List of uploaded media IDs

result = posto.post("Hello World!", to=2)

if result.success:
    print(f"Success! Schedule Group ID: {result.schedule_group_id}")
    if result.media_ids:
        print(f"Uploaded media IDs: {result.media_ids}")
else:
    print(f"Failed: {result.error_message}")

Complete Example

Below is a complete example that combines several of the features described above.

from datetime import datetime, timedelta
from posto_sdk.posto_sdk import PostoSDK

# Initialize the SDK with your credentials
posto = PostoSDK.from_credentials(username="your_username", password="your_password", debug=True)

# 1. Immediate post
result_immediate = posto.post("Hello World!", to=2)
print("Immediate post result:", result_immediate)

# 2. Scheduled post using a relative time string ("1h" means 1 hour from now)
result_scheduled_rel = posto.post("Scheduled post in 1 hour", to=[2, 3], when="1h")
print("Scheduled (relative) post result:", result_scheduled_rel)

# 3. Scheduled post using a specific datetime (2 days from now)
future_time = datetime.now() + timedelta(days=2)
result_scheduled_dt = posto.post("Post scheduled for specific datetime", to=[2, 3], when=future_time)
print("Scheduled (datetime) post result:", result_scheduled_dt)

# 4. Post with media attachment
result_media = posto.post("Check out this cool photo!", to=[2, 3], media="path/to/image.jpg", when="1h")
print("Post with media result:", result_media)

# 5. Post with custom network settings
custom_settings = {
    "attach_link": False,
    "cut_post_text": True,
    "custom_option": "value"
}
result_custom = posto.post("Post with custom settings", to=2, settings=custom_settings)
print("Post with custom settings result:", result_custom)

SocialMediaManager - All-in-One Solution

This guide covers the basics of using the SocialMediaManager class, which extends the base PostoSDK to simplify managing social media channels. You will learn how to initialize the SDK, set default posting options, post messages, schedule campaigns, and manage custom post styles.

Important Note on SocialMediaManager

SocialMediaManager is an all-in-one solution that inherits all functionality from PostoSDK. When you initialize SocialMediaManager, you don't need to separately initialize PostoSDK - you get access to all PostoSDK methods plus the additional convenience methods provided by SocialMediaManager.

1. Installation

Make sure you have installed the SDK and its dependencies. Then, you can import the SocialMediaManager in your project:

from posto_sdk.social_media_manager import SocialMediaManager

# Or more simply:
from posto_sdk import SocialMediaManager  # Recommended import style

2. Initialization

Initialize the SocialMediaManager with your credentials. The credentials are used to create an authentication token.

# Initialize the SocialMediaManager with your credentials
manager = SocialMediaManager(username="your_username", password="your_password")

# With debug mode enabled
manager = SocialMediaManager(username="your_username", password="your_password", debug=True)

# Now you can use both PostoSDK methods and SocialMediaManager methods
channels = manager.get_active_channels()  # PostoSDK method
manager.post_to("instagram", "Hello world!")  # SocialMediaManager method

3. Setting Default Post Settings

You can globally define post settings that apply to all channels of a network or to a specific channel.

3.1. Set Network Defaults

Use set_network_defaults to define defaults for a particular network (such as Twitter, Facebook, TikTok, etc.). These settings will apply to all channels within that network.

manager.set_network_defaults("twitter", {
    "post_text": "🚨 {post_title} 🚨",
    "cut_post_text": True
})

3.2. Set Channel Defaults

For channel-specific settings, use set_channel_defaults. If you pass a channel name, the method will find the corresponding channel ID.

manager.set_channel_defaults("my_business_instagram", {
    "post_text": "{post_title}\n.\n.\n.\n#business #updates",
    "upload_media": True
})

3.3. Clear Default Settings

You can clear default settings when needed:

# Clear all defaults
manager.clear_defaults()

# Clear defaults for a specific network
manager.clear_defaults(network="twitter")

# Clear defaults for a specific channel
manager.clear_defaults(network="instagram", channel_id="my_instagram")

4. Posting Messages

There are several ways to post messages using the SDK. Choose the one that best fits your needs.

4.1. Quick Post

Post a message immediately to all active channels.

Method Signature:

quick_post(message: str, image: Optional[str] = None, style: Optional[str] = None, settings: Optional[Dict[str, Any]] = None) -> bool
  • message: The post content.

  • image: A path (or URL) to an image file (if any).

  • style: Predefined style name (e.g., "announcement", "blog", or "product").

  • settings: A dictionary with network-specific overrides.

Example:

success = manager.quick_post(
    "Hello world! Check out our latest update!",
    image="path/to/image.jpg",
    style="announcement"
)

if success:
    print("Post was successful!")
else:
    print("Post failed; please check your configuration.")

4.2. Post to Specific Platforms

Use post_to to send a post to selected platforms. This method supports scheduling with the when parameter as well.

Method Signature:

post_to(
    platforms: Union[str, List[str]], 
    message: str, 
    image: Optional[str] = None, 
    when: Optional[str] = None,
    style: Optional[str] = None, 
    settings: Optional[Dict[str, Any]] = None
) -> bool
  • platforms: A single platform (e.g., "twitter") or a list of platforms (e.g., ["facebook", "instagram"]).

  • message: The text to post.

  • image: Optional image path or URL.

  • when: Schedule the post (e.g., "tomorrow", "tonight", "30m", "1h", "2d").

  • style: Predefined style (as in quick_post).

  • settings: A dictionary of custom settings for refining the post.

Example:

result = manager.post_to(
    platforms="twitter",
    message="Check out our new offer!",
    image="offer.jpg",
    when="1h",
    style="product",
    settings={
        "twitter": {"post_text": "🔥 {post_title} 🔥"}
    }
)

if result:
    print("Post scheduled successfully!")

4.3. Scheduling a Post

Schedule a post for a later time using the schedule_post method.

Method Signature:

schedule_post(
    message: str, 
    when: str, 
    image: Optional[str] = None, 
    platforms: Optional[List[str]] = None,
    style: Optional[str] = None,
    settings: Optional[Dict[str, Any]] = None
) -> bool
  • when: Can be friendly strings like "tomorrow" or "tonight", or a relative time like "30m", "1h", or "2d".

Example:

scheduled = manager.schedule_post(
    "Don't miss tomorrow's exclusive sale!",
    when="tomorrow",
    style="announcement"
)

if scheduled:
    print("Post scheduled for tomorrow!")
else:
    print("Scheduling failed.")

4.4. Creating a Campaign

A campaign is a series of posts scheduled over time.

Method Signature:

create_campaign(
    messages: List[str], 
    platforms: Optional[List[str]] = None,
    images: Optional[List[str]] = None,
    start_time: Optional[str] = None,
    hours_between_posts: int = 24,
    style: Optional[str] = None,
    settings: Optional[Dict[str, Any]] = None
) -> List[bool]
  • messages: List of messages.

  • platforms: List of target platforms. If omitted, the campaign is posted to all available networks.

  • images: Optional list of image paths/URLs for each post.

  • start_time: When the campaign should start (e.g., "tomorrow" or "tonight").

  • hours_between_posts: Interval between each post (default is 24 hours).

  • style: Predefined style.

  • settings: Network-specific custom settings.

Example:

messages = [
    "Campaign Day 1: Launch announcement! 🚀",
    "Campaign Day 2: Product feature update!",
    "Campaign Day 3: Customer success story!"
]

campaign_results = manager.create_campaign(
    messages=messages,
    start_time="tomorrow",
    hours_between_posts=24,
    style="blog"
)

if all(campaign_results):
    print("Campaign scheduled successfully!")
else:
    print("Some posts in the campaign failed to schedule.")

4.5. Creating a Quick Campaign

For a faster setup with sensible defaults, you can use create_quick_campaign.

Method Signature:

create_quick_campaign(
    messages: List[str], 
    interval: str = "1d", 
    start_time: Optional[str] = None
) -> bool
  • interval: Time between posts given as "1d", "1h", etc.

  • start_time: When the campaign should begin (e.g., "tomorrow").

Example:

quick_messages = [
    "Quick Campaign Day 1: Special announcement 🚀",
    "Quick Campaign Day 2: More details coming soon!",
    "Quick Campaign Day 3: Stay tuned for updates!"
]

if manager.create_quick_campaign(quick_messages, interval="1d", start_time="tomorrow"):
    print("Quick campaign scheduled successfully!")
else:
    print("Quick campaign scheduling failed.")

5. Customizing Post Styles

You can save and reuse custom post styles, which is very helpful if you frequently use specific formatting across different platforms.

5.1. Saving a Style

Method Signature:

save_style(name: str, settings: Dict[str, Dict[str, Any]]) -> None
  • name: A unique name for your style.

  • settings: A dictionary mapping social network identifiers (e.g., "twitter", "facebook") to their settings.

Example:

manager.save_style("my_announcement", {
    "twitter": {"post_text": "🎯 {post_title}", "cut_post_text": True},
    "facebook": {"post_text": "📢 Important Update:\n\n{post_title}", "attach_link": True}
})

5.2. Retrieving and Listing Styles

Get a saved style:
style_settings = manager.get_style("my_announcement")

List all available styles:

    available_styles = manager.list_styles()
    print("Available Styles:", available_styles)

6. Managing Channels & Defaults

Access your channels and review or clear default settings as needed.

6.1. Getting Channels

# Get all channels
all_channels = manager.get_channels()

# Filter channels by platform (e.g., Twitter)
twitter_channels = manager.get_channels("twitter")

6.2. Viewing & Clearing Defaults

# Get network defaults for TikTok
tiktok_defaults = manager.get_network_defaults("tiktok")

# Get channel defaults (passing either an ID or channel name)
instagram_defaults = manager.get_channel_defaults("my_instagram")

# Clear defaults for a specific network
manager.clear_defaults(network="twitter")

# Clear defaults for a specific channel
manager.clear_defaults(network="facebook", channel_id="my_facebook_channel")

7. Deleting Scheduled Posts

Manage your scheduled posts by deleting unwanted schedules.

7.1. Delete All Schedules with Filters

# Delete all pending (not sent) schedules for Twitter, excluding specific IDs if needed:
manager.delete_all_schedules(
    platforms=["twitter"],
    statuses=["not_sent"],
    exclude_ids=[123, 456]  # Optional: list IDs you want to keep
)

7.2. Delete Specific Scheduled Posts

# Delete specific schedule IDs
manager.delete_schedules([789, 1011])

8. Complete Example

Below is a simple script that brings many of these features together:

from posto_sdk import SocialMediaManager

# Initialize SocialMediaManager
manager = SocialMediaManager(username="your_username", password="your_password")

# Set defaults for Twitter
manager.set_network_defaults("twitter", {
    "post_text": "🚨 Breaking News: {post_title} 🚨",
    "cut_post_text": True
})

# Save a custom style for announcements
manager.save_style("my_announcement", {
    "twitter": {"post_text": "🎯 {post_title}", "cut_post_text": True},
    "facebook": {"post_text": "📢 Important Update:\n\n{post_title}", "attach_link": True}
})

# Make a quick post to all active channels
if manager.quick_post("Hello world! This is a quick update.", image="hello.jpg", style="my_announcement"):
    print("Quick post sent successfully!")
else:
    print("Quick post failed; check logs for details.")

# Schedule a post for tomorrow with custom settings
if manager.schedule_post(
    "Don't miss our exclusive sale tomorrow!",
    when="tomorrow",
    style="announcement"
):
    print("Post scheduled for tomorrow!")
else:
    print("Failed to schedule the post.")

# Launch a campaign with multiple scheduled posts
messages = [
    "Day 1: Launch announcement! 🚀",
    "Day 2: Feature spotlight ✨",
    "Day 3: Customer testimonials 💬"
]
campaign_results = manager.create_campaign(
    messages=messages,
    start_time="tomorrow",
    hours_between_posts=24,
    style="blog"
)
if all(campaign_results):
    print("Campaign scheduled successfully!")
else:
    print("Some campaign posts failed to schedule.")

SocialMediaManager Quick Reference

Here's a quick reference of all available methods in SocialMediaManager:

Posting Methods

  • quick_post(message, image=None, style=None, settings=None) - Post to all active channels

  • post_to(platforms, message, image=None, when=None, style=None, settings=None) - Post to specific platforms

  • schedule_post(message, when, image=None, platforms=None, style=None, settings=None) - Schedule a post

  • create_campaign(messages, platforms=None, images=None, start_time=None, hours_between_posts=24, style=None, settings=None) - Create a campaign

  • create_quick_campaign(messages, interval="1d", start_time=None) - Create a simple campaign

Style Management

  • save_style(name, settings) - Save a custom style

  • get_style(name) - Get a saved style

  • list_styles() - List all saved styles

Channel Management

  • get_channels(platform=None) - Get channels, optionally filtered by platform

  • find_channel(name) - Find a channel by name (case-insensitive partial match)

Default Settings

  • set_network_defaults(network, settings) - Set defaults for a network

  • set_channel_defaults(channel_id, settings) - Set defaults for a channel

  • get_network_defaults(network) - Get defaults for a network

  • get_channel_defaults(channel_id) - Get defaults for a channel

  • clear_defaults(network=None, channel_id=None) - Clear defaults

Schedule Management

  • delete_all_schedules(exclude_ids=None, platforms=None, statuses=None) - Delete schedules with filters

  • delete_schedules(schedule_ids) - Delete specific schedules

Last updated 21 hours ago

Last updated