Examples

Example Scripts and Actions

Ready-to-use examples for common streaming automation tasks. Copy, customize, and use in your own streams.

Overview

This collection includes practical examples that you can use as starting points for your own automations. Each example includes Python and Lua versions.

Chat Commands

Points Check Command

Let viewers check their point balance with ranks.

!points command
# !points - Check your point balance
def Execute():
    user = args["user"]
    display = args["displayName"]

    points = CPH.GetUserVar(user, "points", 0)
    rank = get_rank(points)

    CPH.SendMessage(f"{display} has {points:,} points ({rank})")
    return True

def get_rank(points):
    if points >= 100000: return "Legend"
    if points >= 50000: return "Master"
    if points >= 10000: return "Expert"
    if points >= 1000: return "Regular"
    return "Newcomer"

Custom Alerts

Tiered Follow Alerts

Different alert styles based on follower milestones.

Tiered follow alerts
# Tiered follow alerts with OBS
def Execute():
    user = args["displayName"]
    follower_count = CPH.GetGlobalVar("followerCount", 0) + 1
    CPH.SetGlobalVar("followerCount", follower_count, True)

    # Different alerts for milestones
    if follower_count % 100 == 0:
        # Milestone alert
        CPH.ObsShowSource("Alerts", "Milestone Animation")
        CPH.PlaySound("milestone.mp3")
        CPH.TwitchAnnounce(f"{user} is follower #{follower_count}!", "purple")
    elif follower_count % 10 == 0:
        # Every 10th follower
        CPH.ObsShowSource("Alerts", "Special Follow")
        CPH.PlaySound("special_follow.mp3")
        CPH.SendMessage(f"Welcome {user}! You're follower #{follower_count}!")
    else:
        # Standard follow
        CPH.ObsShowSource("Alerts", "Follow Animation")
        CPH.SendMessage(f"Welcome to the community, {user}!")

    # Hide alert after delay
    CPH.Wait(5000)
    CPH.ObsHideSource("Alerts", "Follow Animation")
    CPH.ObsHideSource("Alerts", "Special Follow")
    CPH.ObsHideSource("Alerts", "Milestone Animation")

    return True

Points System

Gambling Command

Let viewers risk their points with a chance to double them.

!gamble command
# !gamble <amount> - Risk points for a chance to win
import random

def Execute():
    user = args["user"]
    message = args.get("rawInput", "").strip()

    # Parse amount
    if not message:
        CPH.SendMessage("Usage: !gamble <amount> or !gamble all")
        return False

    current_points = CPH.GetUserVar(user, "points", 0)

    if message.lower() == "all":
        amount = current_points
    else:
        try:
            amount = int(message)
        except ValueError:
            CPH.SendMessage("Please enter a valid number!")
            return False

    # Validate
    if amount <= 0:
        CPH.SendMessage("Amount must be positive!")
        return False
    if amount > current_points:
        CPH.SendMessage(f"You only have {current_points} points!")
        return False

    # Gamble! 45% win chance
    if random.random() < 0.45:
        winnings = amount * 2
        new_total = current_points + amount
        CPH.SetUserVar(user, "points", new_total)
        CPH.SendMessage(f"You won! +{amount} points. New total: {new_total}")
    else:
        new_total = current_points - amount
        CPH.SetUserVar(user, "points", new_total)
        CPH.SendMessage(f"You lost {amount} points. Remaining: {new_total}")

    return True

OBS Automation

Automatic Scene Switcher

Automatically switch OBS scenes when you change games.

Game-based scene switching
# Automatic scene switching based on game
GAME_SCENES = {
    "Just Chatting": "Chat Scene",
    "Fortnite": "Gaming 16:9",
    "Valorant": "Gaming 16:9",
    "Minecraft": "Gaming Vertical",
    "League of Legends": "Gaming 16:9",
}

DEFAULT_SCENE = "Main Scene"

def Execute():
    game = args.get("gameName", "")

    # Get the appropriate scene
    scene = GAME_SCENES.get(game, DEFAULT_SCENE)

    # Switch scene
    CPH.ObsSetScene(scene)
    CPH.LogInfo(f"Switched to {scene} for {game}")

    # Update overlay text
    CPH.ObsSetSourceText("Now Playing", game or "Stream Starting...")

    return True

API Integration

Weather Command

Fetch and display weather data from an external API.

!weather command
# !weather <city> - Get current weather
import json

def Execute():
    city = args.get("rawInput", "").strip()
    if not city:
        CPH.SendMessage("Usage: !weather <city>")
        return False

    # API request (replace with your API key)
    api_key = CPH.GetGlobalVar("weatherApiKey")
    url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"

    try:
        response = CPH.HttpGet(url)
        data = json.loads(response)

        if data.get("cod") != 200:
            CPH.SendMessage(f"City '{city}' not found!")
            return False

        temp = data["main"]["temp"]
        feels_like = data["main"]["feels_like"]
        description = data["weather"][0]["description"]
        humidity = data["main"]["humidity"]

        CPH.SendMessage(
            f"Weather in {city}: {temp}C (feels like {feels_like}C), "
            f"{description}, {humidity}% humidity"
        )
        return True

    except Exception as e:
        CPH.LogError(f"Weather API error: {e}")
        CPH.SendMessage("Could not fetch weather data.")
        return False

API Key Required

This example uses OpenWeatherMap. Sign up at openweathermap.org for a free API key and store it using CPH.SetGlobalVar("weatherApiKey", "your-key").

Chat Games

Point Duels

Let viewers challenge each other to duels for points.

!duel command
# !duel <user> <amount> - Challenge someone to a duel
import random

def Execute():
    challenger = args["user"]
    challenger_display = args["displayName"]
    raw_input = args.get("rawInput", "").split()

    if len(raw_input) < 2:
        CPH.SendMessage("Usage: !duel @username <amount>")
        return False

    target = raw_input[0].lstrip("@").lower()
    try:
        amount = int(raw_input[1])
    except ValueError:
        CPH.SendMessage("Please enter a valid amount!")
        return False

    # Validate
    if target == challenger:
        CPH.SendMessage("You can't duel yourself!")
        return False

    challenger_points = CPH.GetUserVar(challenger, "points", 0)
    target_points = CPH.GetUserVar(target, "points", 0)

    if amount <= 0 or amount > challenger_points:
        CPH.SendMessage(f"You don't have enough points!")
        return False
    if amount > target_points:
        CPH.SendMessage(f"{target} doesn't have enough points!")
        return False

    # Store pending duel
    duel_data = {
        "challenger": challenger,
        "target": target,
        "amount": amount,
        "expires": 60  # seconds
    }
    CPH.SetGlobalVar(f"duel_{target}", duel_data)

    CPH.SendMessage(
        f"{challenger_display} challenges {target} to a {amount} point duel! "
        f"Type !accept to fight or !decline to refuse (60s)"
    )
    return True

# !accept - Accept a pending duel
def Execute_Accept():
    user = args["user"]
    duel_data = CPH.GetGlobalVar(f"duel_{user}")

    if not duel_data:
        CPH.SendMessage("You have no pending duels!")
        return False

    challenger = duel_data["challenger"]
    amount = duel_data["amount"]

    # Clear the duel
    CPH.SetGlobalVar(f"duel_{user}", None)

    # Fight!
    winner = random.choice([challenger, user])
    loser = user if winner == challenger else challenger

    # Transfer points
    winner_points = CPH.GetUserVar(winner, "points", 0)
    loser_points = CPH.GetUserVar(loser, "points", 0)

    CPH.SetUserVar(winner, "points", winner_points + amount)
    CPH.SetUserVar(loser, "points", loser_points - amount)

    CPH.SendMessage(f"{winner} wins the duel! +{amount} points from {loser}!")
    return True

Implementation Notes

  • Create separate actions for !duel, !accept, and !decline
  • Add a timer to expire pending duels
  • Consider adding cooldowns to prevent spam

More Resources

Looking for more examples and community-created scripts?