Scripting Guide

Python Scripting

Write clean, readable scripts using Python's intuitive syntax, powerful standard library, and extensive ecosystem of packages.

Overview

Python is a beginner-friendly language known for its clear, readable syntax. It's perfect for quick scripts and complex automation alike, with access to thousands of libraries for any task you can imagine.

Clean Syntax

Readable code with minimal boilerplate and clear structure.

Rich Libraries

Access to Python's extensive standard library and packages.

Quick Iteration

No compilation needed - just write and run your scripts.

Data Handling

Excellent built-in support for JSON, regex, and data structures.

When to Use Python

  • Quick scripts and prototypes
  • Text processing and regex operations
  • Data manipulation and transformation
  • When readability is a priority
  • Integration with Python libraries

Setup

Python scripting uses the embedded Python interpreter included with FaustBot. No additional installation is required.

1

Create a Python Script

In your action, add a Run Script effect and select Python as the language.

2

Write Your Code

Define an Execute() function that returns True for success or False for failure.

3

Access the API

Use the CPH object and args dictionary to interact with FaustBot and access trigger data.

Script Structure

Python scripts require an Execute() function as the entry point.

Basic Python script structure
def Execute():
    # Your code here
    CPH.SendMessage("Hello from Python!")
    return True

Available Objects

These objects are automatically available in your scripts:

ObjectDescription
CPHMain API object for all FaustBot functionality
argsDictionary containing trigger event data

Variables & Data

Access trigger event data and persistent variables using Python's dictionary syntax.

Working with variables
def Execute():
    # Access trigger event data
    username = args["user"]
    message = args["message"]

    # Get user variables with defaults
    points = CPH.GetUserVar(username, "points", 0)
    watch_time = CPH.GetUserVar(username, "watchTime", 0)

    # Get global variables
    total_followers = CPH.GetGlobalVar("totalFollowers", 0)
    recent_users = CPH.GetGlobalVar("recentUsers", [])

    # Set variables
    CPH.SetUserVar(username, "points", points + 100)
    CPH.SetGlobalVar("lastUser", username, True)

    return True

Common Args Keys

KeyDescription
userUsername of the user who triggered the action
messageThe chat message content
platformPlatform name (twitch, youtube, kick, etc.)
isSubscriberWhether the user is a subscriber
isModeratorWhether the user is a moderator

Python Features

List Comprehensions

Use Python's powerful list comprehensions for concise data transformations.

Data filtering and transformation
def Execute():
    # List comprehension for filtering
    all_users = get_all_users()
    top_users = [u for u in all_users if u["points"] > 1000]

    # Sort by points descending
    top_users.sort(key=lambda u: u["points"], reverse=True)
    top_10 = top_users[:10]

    # Format with f-strings
    leaderboard = " | ".join(
        f"{i+1}. {u['name']}: {u['points']} pts"
        for i, u in enumerate(top_10)
    )

    CPH.SendMessage(f"Top 10: {leaderboard}")
    return True

def get_all_users():
    # Implementation here
    return []

HTTP Requests

Make API calls using the built-in HTTP methods.

Making HTTP requests
import json

def Execute():
    # Simple GET request
    response = CPH.HttpGet("https://api.example.com/data")
    data = json.loads(response)

    # POST with JSON body
    payload = {
        "user": args["user"],
        "action": "reward",
        "amount": 100
    }
    result = CPH.HttpPost(
        "https://api.example.com/update",
        json.dumps(payload),
        "application/json"
    )

    # Handle response
    if json.loads(result).get("success"):
        CPH.SendMessage("Update successful!")

    return True

Advanced Patterns

Classes & Data Classes

Use Python classes and dataclasses for structured data.

Using classes
from dataclasses import dataclass
from typing import Optional
from datetime import datetime

@dataclass
class UserStats:
    username: str
    points: int
    watch_time: int
    first_seen: Optional[datetime] = None

    def get_rank(self) -> str:
        if self.points >= 10000:
            return "Legend"
        if self.points >= 5000:
            return "Elite"
        if self.points >= 1000:
            return "Veteran"
        return "Newcomer"

    def formatted_time(self) -> str:
        hours = self.watch_time // 3600
        minutes = (self.watch_time % 3600) // 60
        return f"{hours}h {minutes}m"

def Execute():
    user = args["user"]

    stats = UserStats(
        username=user,
        points=CPH.GetUserVar(user, "points", 0),
        watch_time=CPH.GetUserVar(user, "watchTime", 0),
        first_seen=CPH.GetUserVar(user, "firstSeen")
    )

    msg = f"{stats.username} is a {stats.get_rank()} with {stats.points} points!"
    msg += f" Watch time: {stats.formatted_time()}"
    CPH.SendMessage(msg)

    return True

Error Handling

Use try/except blocks for robust error handling.

Error handling
def Execute():
    try:
        # Validate input
        user = args.get("user")
        if not user:
            raise ValueError("user is required")

        message = args.get("message", "").strip()
        amount = parse_amount(message)

        # Process the reward
        give_points(user, amount)
        CPH.SendMessage(f"Gave {amount} points to {user}!")

        return True

    except ValueError as e:
        CPH.LogWarn(f"Invalid input: {e}")
        CPH.SendMessage("Usage: !reward <amount>")
        return False

    except Exception as e:
        CPH.LogError(f"Unexpected error: {e}")
        return False

def parse_amount(text):
    if not text:
        raise ValueError("Amount is required")
    try:
        amount = int(text)
        if amount <= 0:
            raise ValueError("Amount must be positive")
        return amount
    except (ValueError, TypeError):
        raise ValueError(f"Invalid number: {text}")

def give_points(user, amount):
    current = CPH.GetUserVar(user, "points", 0)
    CPH.SetUserVar(user, "points", current + amount)

External Libraries

Import Python's standard library modules and custom scripts.

Using libraries
# Add custom library path
import sys
sys.path.append("/path/to/my/scripts")

# Import standard library modules
import json
import re
from datetime import datetime, timedelta
from collections import defaultdict

# Import custom module
from my_helpers import process_message, format_duration

def Execute():
    user = args["user"]
    message = args["message"]

    # Use regex for pattern matching
    match = re.match(r"!give (\w+) (\d+)", message)
    if match:
        target = match.group(1)
        amount = int(match.group(2))
        give_points(target, amount)

    # Use datetime for time operations
    last_claim = CPH.GetUserVar(user, "lastClaim")
    if last_claim:
        last_time = datetime.fromisoformat(last_claim)
        if datetime.now() - last_time < timedelta(hours=1):
            remaining = timedelta(hours=1) - (datetime.now() - last_time)
            CPH.SendMessage(f"Wait {format_duration(remaining)} to claim again")
            return True

    return True

Library Tips

  • Standard library modules (json, re, datetime) are always available
  • Add custom script paths with sys.path.append()
  • Place shared modules in a dedicated scripts folder
  • Use virtual environments for complex dependencies