← Pipedream + Twitch integrations

Block User with Twitch APIon New Scheduled Tasks (Alpha) from Pipedream API

Pipedream makes it easy to connect APIs for Twitch, Pipedream and + other apps remarkably fast.

Trigger workflow on
New Scheduled Tasks (Alpha) from the Pipedream API
Next, do this
Block User with the Twitch API
No credit card required
Trusted by 200,000+ developers from startups to Fortune 500 companies:
Trusted by 200,000+ developers from startups to Fortune 500 companies

Developers Pipedream

Getting Started

This integration creates a workflow with a Pipedream trigger and Twitch action. When you configure and deploy the workflow, it will run on Pipedream's servers 24x7 for free.

  1. Select this integration
  2. Configure the New Scheduled Tasks (Alpha) trigger
    1. Connect your Pipedream account
    2. Optional- Configure Secret
  3. Configure the Block User action
    1. Connect your Twitch account
    2. Configure User ID
    3. Optional- Select a Source Context
    4. Optional- Select a Reason
  4. Deploy the workflow
  5. Send a test event to validate your setup
  6. Turn on the trigger

Details

This integration uses pre-built, open source components from Pipedream's GitHub repo. These components are developed by Pipedream and the community, and verified and maintained by Pipedream.

To contribute an update to an existing component or create a new component, create a PR on GitHub. If you're new to Pipedream component development, you can start with quickstarts for trigger span and action development, and then review the component API reference.

Trigger

Description:Exposes an HTTP API for scheduling messages to be emitted at a future time
Version:0.0.3
Key:pipedream-new-scheduled-tasks

Trigger Code

const pipedream = require("../../pipedream.app.js");
const { uuid } = require("uuidv4");

module.exports = {
  key: "pipedream-new-scheduled-tasks",
  name: "New Scheduled Tasks (Alpha)",
  description:
    "Exposes an HTTP API for scheduling messages to be emitted at a future time",
  version: "0.0.3",
  dedupe: "unique", // Dedupe on a UUID generated for every scheduled task
  props: {
    pipedream,
    secret: {
      type: "string",
      secret: true,
      label: "Secret",
      optional: true,
      description:
        "**Optional but recommended**: if you enter a secret here, you must pass this value in the `secret` parameter HTTP POST requests",
    },
    http: {
      type: "$.interface.http",
      customResponse: true,
    },
    db: "$.service.db",
  },
  async run(event) {
    const { body, headers, path, $channel, $id } = event;
    const componentId = process.env.PD_COMPONENT;
    const selfChannel = "self";

    // Subscribe the component to itself, if not already.
    // Scheduled tasks are sent to the self channel, which
    // emits the message at the specified delivery_ts to this component.
    const isSubscribedToSelf = this.db.get("isSubscribedToSelf");
    if (!isSubscribedToSelf) {
      console.log(`Subscribing to ${selfChannel} channel for event source`);
      console.log(
        await this.pipedream.subscribe(componentId, componentId, selfChannel)
      );
      this.db.set("isSubscribedToSelf", true);
    }

    // SCHEDULE NEW TASK
    if (path === "/schedule") {
      const { timestamp, message } = body;
      const errors = [];

      // timestamp should be an ISO 8601 string. Parse and check
      // for validity below.
      const epoch = Date.parse(timestamp);

      // Secrets are optional, so we first check if the user configured
      // a secret, then check its value against the prop (validation below)
      if (this.secret && headers["x-pd-secret"] !== this.secret) {
        errors.push(
          "Secret on incoming request doesn't match the configured secret"
        );
      }
      if (!timestamp) {
        errors.push(
          "No timestamp included in payload. Please provide an ISO8601 timestamp in the 'timestamp' field"
        );
      }
      if (timestamp && !epoch) {
        errors.push("Timestamp isn't a valid ISO 8601 string");
      }
      if (!message) {
        errors.push("No message passed in payload");
      }
      if (errors.length) {
        console.log(errors);
        this.http.respond({
          status: 400,
          body: {
            errors,
          },
          headers: {
            "content-type": "application/json",
          },
        });
        return;
      }

      // Scheduled tasks are emitted to the self channel, which is delivered
      // to this same deployed component at the specified delivery_ts
      const $id = uuid();
      this.$emit(
        { ...body, $channel: selfChannel, $id },
        {
          name: selfChannel,
          id: $id,
          delivery_ts: epoch,
        }
      );

      this.http.respond({
        status: 200,
        body: {
          msg: "Successfully scheduled task",
          id: $id,
        },
        headers: {
          "content-type": "application/json",
        },
      });

      return;
    }

    // CANCEL SCHEDULED TASK
    // The user must pass a scheduled event UUID they'd like to cancel
    // We lookup the event by ID and delete it from the 'self' queue
    if (path === "/cancel") {
      const { id } = body;
      const errors = [];

      if (this.secret && headers["x-pd-secret"] !== this.secret) {
        errors.push(
          "Secret on incoming request doesn't match the configured secret"
        );
      }

      let msg, status;
      try {
        // List events in the self channel - the queue of
        // scheduled events, to be emitted in the future
        const events = await this.pipedream.listEvents(
          componentId,
          selfChannel
        );
        console.log(`Events: `, events);

        // Find the event in the list by id
        const eventToCancel = events.data.find((e) => {
          const { metadata } = e;
          return metadata.id === id;
        });

        console.log(`Event to cancel: `, eventToCancel);

        if (!eventToCancel) {
          console.log(`No event with ${id} found`);
          this.http.respond({
            status: 404,
            body: {
              msg: `No event with ${id} found`,
            },
          });
          return;
        }

        // Delete the event in the self channel, where it's queued up for delivery
        console.log(
          await this.pipedream.deleteEvent(
            componentId,
            eventToCancel.id,
            selfChannel
          )
        );
        status = 200;
        msg = `Cancelled scheduled task for event ${id}`;
      } catch (err) {
        status = 500;
        msg = "Failed to schedule task. Please see the logs";
        console.log(err);
      }

      this.http.respond({
        status,
        body: {
          msg,
        },
        headers: {
          "content-type": "application/json",
        },
      });

      return;
    }

    // INCOMING SCHEDULED EMIT
    if ($channel === selfChannel) {
      // Delete the channel name and id from the incoming event,
      // which were used only as metadata
      delete event.$channel;
      delete event.$id;
      this.$emit(event, {
        summary: JSON.stringify(event),
        id: $id,
        ts: +new Date(),
      });
    }
  },
};

Trigger Configuration

This component may be configured based on the props defined in the component code. Pipedream automatically prompts for input values in the UI and CLI.
LabelPropTypeDescription
PipedreampipedreamappThis component uses the Pipedream app.
Secretsecretstring

Optional but recommended: if you enter a secret here, you must pass this value in the secret parameter HTTP POST requests

N/Ahttp$.interface.httpThis component uses $.interface.http to generate a unique URL when the component is first instantiated. Each request to the URL will trigger the run() method of the component.
N/Adb$.service.dbThis component uses $.service.db to maintain state between component invocations.

Trigger Authentication

Pipedream uses API keys for authentication. When you connect your Pipedream account, Pipedream securely stores the keys so you can easily authenticate to Pipedream APIs in both code and no-code steps.

Your API key is in your Account Settings (Settings -> Account).

About Pipedream

Integration platform for developers

Action

Description:Blocks a user; that is, adds a specified target user to your blocks list
Version:0.0.1
Key:twitch-block-user

Action Code

const common = require("../common.js");

module.exports = {
  ...common,
  name: "Block User",
  key: "twitch-block-user",
  description: "Blocks a user; that is, adds a specified target user to your blocks list",
  version: "0.0.1",
  type: "action",
  props: {
    ...common.props,
    user: {
      propDefinition: [
        common.props.twitch,
        "user",
      ],
      description: "User ID of the user to be blocked",
    },
    sourceContext: {
      type: "string",
      label: "Source Context",
      description: "Source context for blocking the user. Valid values: \"chat\", \"whisper\".",
      optional: true,
      options: [
        "chat",
        "whisper",
      ],
    },
    reason: {
      type: "string",
      label: "Reason",
      description: "Reason for blocking the user. Valid values: \"spam\", \"harassment\", or \"other\".",
      optional: true,
      options: [
        "spam",
        "harassment",
        "other",
      ],
    },
  },
  async run() {
    const params = {
      target_user_id: this.user,
      source_context: this.sourceContext,
      reason: this.reason,
    };
    const {
      status,
      statusText,
    } = await this.twitch.blockUser(params);
    return status == 204
      ? "User Blocked Successfully"
      : `${status} ${statusText}`;
  },
};

Action Configuration

This component may be configured based on the props defined in the component code. Pipedream automatically prompts for input values in the UI.

LabelPropTypeDescription
TwitchtwitchappThis component uses the Twitch app.
N/Adb$.service.dbThis component uses $.service.db to maintain state between component invocations.
User IDuserstring

User ID of the user to be blocked

Source ContextsourceContextstringSelect a value from the drop down menu:chatwhisper
ReasonreasonstringSelect a value from the drop down menu:spamharassmentother

Action Authentication

Twitch uses OAuth authentication. When you connect your Twitch account, Pipedream will open a popup window where you can sign into Twitch and grant Pipedream permission to connect to your account. Pipedream securely stores and automatically refreshes the OAuth tokens so you can easily authenticate any Twitch API.

Pipedream requests the following authorization scopes when you connect your account:

analytics:read:extensionsanalytics:read:gamesbits:readchannel:read:subscriptionsclips:edituser:edituser:edit:broadcastuser:read:broadcastuser:read:emailuser:read:blocked_usersuser:manage:blocked_userschannel:read:editorschannel:manage:videosuser:read:subscriptions

About Twitch

Live streaming platform for gamers

More Ways to Connect Twitch + Pipedream

About Pipedream

Stop writing boilerplate code, struggling with authentication and managing infrastructure. Start connecting APIs with code-level control when you need it — and no code when you don't.

Into to Pipedream
Watch us build a workflow
Watch us build a workflow
4 min
Watch now ➜
"The past few weeks, I truly feel like the clichéd 10x engineer."
@heyellieday
Powerful features that scale
Manage concurrency and execution rate
Manage concurrency and execution rate

Queue up to 10,000 events per workfow and manage the concurrency and rate at which workflows are triggered.

Process large payloads up to 5 terabytes
Process large payloads up to 5 terabytes

Large file support enables you to trigger workflows with any data (e.g., large JSON files, images and videos) up to 5 terabytes.

Return custom responses to HTTP requests
Return custom responses to HTTP requests

Return any JSON-serializable response from an HTTP triggered workflow using $respond().

Use most npm packages
Use most npm packages

To use any npm package, just require() it -- there's no npm install or package.json required.

Maintain state between executions
Maintain state between executions

Use $checkpoint to save state in one workflow invocation and read it the next time your workflow runs.

Pass data between steps
Pass data between steps

Return data from any step to inspect it in a human-friendly way and reference the data in future steps via the steps object.