Guides

Scripting

Extend FaustBot's capabilities with custom scripts. Write complex logic, integrate external APIs, and create unique automations using your preferred language.

Overview

FaustBot's scripting system lets you write custom code that executes within your actions. Scripts have full access to the CPH API, allowing you to interact with platforms, manage variables, control OBS, and much more.

Script editor interface

When to Use Scripts

  • Complex conditional logic beyond if/else
  • Custom API integrations
  • Data processing and transformation
  • Advanced math and string manipulation
  • Integration with external services

Supported Languages

FaustBot supports multiple scripting languages through its plugin system.

JS

JavaScript

Familiar syntax for web developers.

  • Familiar syntax
  • Async support
  • JSON handling
C#

C#

Full .NET support with strong typing and excellent tooling.

  • Strong typing
  • Full API access
  • IDE support
C++

C++ / WASM

Native performance for computationally intensive tasks.

  • WebAssembly support
  • Maximum performance
  • Low-level control

Your First Script

Let's create a simple script that sends a message to chat. The structure varies slightly between languages, but the API calls are the same.

1

Create a Script Effect

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

Adding script effect to an action
2

Write the Code

Every script needs an Execute() function that returns a boolean. Return true to continue the action, or false to stop.

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

Test the Script

Save your action and trigger it. Check the logs for any errors.

Script Tips

  • Always handle exceptions to prevent action failures
  • Use CPH.LogInfo() to debug your scripts
  • Keep scripts focused on a single task
  • Test with different input scenarios

The CPH API

The CPH object provides access to all of FaustBot's functionality. It's automatically available in all scripts.

Working with Variables

Get and set global and user-scoped variables:

Variable operations
# Global variables
title = CPH.GetGlobalVar("streamTitle")
followers = CPH.GetGlobalVar("totalFollowers", 0)

# User variables
points = CPH.GetUserVar(user_id, "points", 0)
last_seen = CPH.GetUserVar(user_id, "lastSeen")

# Set variables
CPH.SetGlobalVar("streamTitle", "New Title!")
CPH.SetUserVar(user_id, "points", new_points)

# Persistent (survives restart)
CPH.SetGlobalVar("lifetimeSubs", count, True)

API Quick Reference

Logging

CPH.LogVerbose(message) Detailed debug logging
CPH.LogDebug(message) Debug information
CPH.LogInfo(message) General information
CPH.LogWarn(message) Warnings
CPH.LogError(message) Errors

Chat & Messaging

CPH.SendMessage(message, bot?) Send chat message
CPH.SendWhisper(user, message) Send whisper/DM
CPH.TwitchAnnounce(message, color?) Send announcement

Actions

CPH.RunAction(name, runImmediately?) Run action by name
CPH.RunActionById(id, runImmediately?) Run action by ID
CPH.DisableAction(name) Disable an action
CPH.EnableAction(name) Enable an action

Twitch

CPH.TwitchBanUser(user, reason?) Ban a user
CPH.TwitchTimeoutUser(user, duration, reason?) Timeout a user
CPH.TwitchSetTitle(title) Set stream title
CPH.TwitchSetGame(game) Set stream category

OBS

CPH.ObsSetScene(scene) Switch scene
CPH.ObsShowSource(scene, source) Show source
CPH.ObsHideSource(scene, source) Hide source
CPH.ObsSetSourceFilterState(source, filter, state) Toggle filter

See the full API reference for complete documentation.

Accessing Event Data

When a trigger fires, event data is passed to your script through the args dictionary/object.

Accessing event data
def Execute():
    # Basic event info
    user = args["user"]
    display_name = args["displayName"]
    message = args["message"]
    platform = args["platform"]

    # User roles (bool)
    is_mod = args.get("isModerator", False)
    is_sub = args.get("isSubscriber", False)

    # Platform-specific data
    if "bits" in args:
        bits = int(args["bits"])
        CPH.SendMessage(f"Thanks for the {bits} bits!")

    return True

Setting Output Variables

Scripts can set variables that are available to subsequent effects in the same action.

Setting output variables
def Execute():
    # Calculate something
    result = calculate_something()

    # Make it available to other effects
    CPH.SetArgument("myResult", result)
    CPH.SetArgument("processed", True)

    return True

# Later effects can use %myResult% and %processed%

Script Permissions

Scripts can be restricted by permission flags for security. By default, scripts run with standard permissions.

PermissionAllows
FileReadRead files from disk
FileWriteWrite files to disk
NetworkMake HTTP requests
ProcessExecute system processes
DatabaseDirect database access
TwitchTwitch API calls
YouTubeYouTube API calls
OBSOBS WebSocket commands

Permission Presets

  • Safe - Variables, Actions, Commands (no external access)
  • Standard - Safe + FileRead, Audio, TTS, Platform APIs
  • Network - Standard + HTTP requests, Discord
  • Full - All permissions (use with caution)

Debugging

Use logging and the script console to debug issues.

Logging

Debug logging with error handling
def Execute():
    CPH.LogInfo("Script started")

    try:
        user = args["user"]
        CPH.LogDebug(f"Processing user: {user}")

        # Your logic here
        result = do_something()
        CPH.LogInfo(f"Result: {result}")

        return True
    except Exception as e:
        CPH.LogError(f"Script failed: {e}")
        return False

Script Console

The Script Console shows real-time output from your scripts, including logs and errors.

Script console output and debugging

Debugging Tips

  • Use try/catch blocks to handle errors gracefully
  • Log input values at the start of your script
  • Check if keys exist before accessing optional data
  • Test with the Test Action feature using mock data
  • Start simple and add complexity gradually