This guide demonstrates how to use PyFed to interact with Mastodon using the ActivityPub protocol. The example shows how to send a message (Note) to a Mastodon user using federation.
- Python 3.9 or higher
- Virtual environment (recommended)
- ngrok installed (for local testing)
- A Mastodon account to send messages to
- Clone the repository and set up the environment:
# Create and activate virtual environment
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt- Set up ngrok for local testing:
# Start ngrok on port 8880
ngrok http 8880Save the ngrok URL (e.g., "12f8-197-211-61-33.ngrok-free.app") for configuration.
- Create a
config.pyfile in the examples directory with your settings:
CONFIG = {
"domain": "12f8-197-211-61-33.ngrok-free.app", # Your ngrok URL (without https://)
"user": "testuser",
"keys_path": "example_keys",
"port": 8880
}- Create the keys directory:
mkdir example_keys- Start the key server:
python examples/minimal_server.pyThe key server will handle key management and HTTP signatures automatically.
-
Ensure both ngrok and the key server are running
-
Run the examples:
python examples/send_message.pyor
python examples/follow.pyor
python examples/like.pyor
python examples/announce.pyor
python examples/block.py- Check the logs for the federation process:
- WebFinger lookup
- Actor discovery
- Message delivery
- HTTP signatures
Common issues and solutions:
-
Connection Issues
- Verify ngrok is running and URL is correct
- Check if key server is running on port 8880
- Ensure ngrok URL is properly set in config
-
WebFinger Lookup Fails
- Verify the Mastodon username is correct
- Check if the instance is online
- Ensure proper network connectivity
-
Delivery Errors
- Verify your ngrok URL is current (they expire)
- Check key server logs for signature issues
- Ensure Mastodon instance is reachable
The example demonstrates several key PyFed features:
-
Key Management
- Automatic key generation and management via key server
- Handles HTTP signatures for federation
-
Federation
- WebFinger protocol for user discovery
- ActivityPub protocol for message delivery
-
Activity Creation
- Creates ActivityPub Note objects
- Wraps them in Create activities
- Try sending different types of activities
- Implement inbox handling for responses
- Add error handling and retries
- Explore other ActivityPub interactions