🎉 Pipedream raises $20M Series A 🎉
Read the blog post and TC Techcrunch article.
← Pipedream + Discord Webhook integrations

Send Message (Advanced) with Discord Webhook APIon New Scheduled Tasks from Pipedream API

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

Trigger workflow on
New Scheduled Tasks from the Pipedream API
Next, do this
Send Message (Advanced) with the Discord Webhook API
No credit card required
Into to Pipedream
Watch us build a workflow
Watch us build a workflow
7 min
Watch now ➜
Trusted by 250,000+ developers from startups to Fortune 500 companies:
Trusted by 250,000+ developers from startups to Fortune 500 companies

Developers Pipedream

Getting Started

This integration creates a workflow with a Pipedream trigger and Discord Webhook 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 trigger
    1. Connect your Pipedream account
    2. Optional- Configure Secret
  3. Configure the Send Message (Advanced) action
    1. Connect your Discord Webhook account
    2. Optional- Configure Message
    3. Optional- Configure Thread ID
    4. Optional- Configure Username
    5. Optional- Configure Avatar URL
    6. Optional- Configure Include link to workflow
    7. Optional- Configure Embeds
  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.1.0
Key:pipedream-new-scheduled-tasks

Trigger Code

import pipedream from "../../pipedream.app.mjs";
import { uuid } from "uuidv4";

export default {
  key: "pipedream-new-scheduled-tasks",
  name: "New Scheduled Tasks",
  type: "source",
  description:
    "Exposes an HTTP API for scheduling messages to be emitted at a future time",
  version: "0.1.0",
  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 `x-pd-secret` HTTP header when making requests",
    },
    http: {
      label: "Endpoint",
      description: "The endpoint where you'll send task scheduler requests",
      type: "$.interface.http",
      customResponse: true,
    },
    db: "$.service.db",
  },
  methods: {
    // To schedule future emits, we emit to the selfChannel of the component
    selfChannel() { return "self"; },
    // Queue for future emits that haven't yet been delivered
    queuedEventsChannel() { return "$in"; },
  },
  async run(event) {
    const {
      body,
      headers,
      path,
      $channel,
      $id,
    } = event;

    const componentId = process.env.PD_COMPONENT;
    const selfChannel = this.selfChannel();
    const inChannel = this.queuedEventsChannel();

    // Subscribe the component to itself. We do this here because even in
    // the activate hook, the component isn't available to take subscriptions.
    // 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;
      }

      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
    if (path === "/cancel") {
      const { id } = body;

      if (this.secret && headers["x-pd-secret"] !== this.secret) {
        this.http.respond({
          status: 400,
          body: {
            msg: "Secret on incoming request doesn't match the configured secret",
          },
          headers: {
            "content-type": "application/json",
          },
        });
        return;
      }

      let msg, status;
      try {
        // List events in the $in channel - the queue of
        // scheduled events, to be emitted in the future
        const events = await this.pipedream.listEvents(
          componentId,
          inChannel,
        );
        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
        console.log(
          await this.pipedream.deleteEvent(
            componentId,
            eventToCancel.id,
            inChannel,
          ),
        );
        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 x-pd-secret HTTP header when making 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:Send a simple or structured message (using embeds) to a Discord channel
Version:0.3.0
Key:discord_webhook-send-message-advanced

Action Code

import common from "../send-message-common.mjs";

export default {
  ...common,
  key: "discord_webhook-send-message-advanced",
  name: "Send Message (Advanced)",
  description: "Send a simple or structured message (using embeds) to a Discord channel",
  version: "0.3.0",
  type: "action",
  props: {
    ...common.props,
    message: {
      propDefinition: [
        common.props.discordWebhook,
        "message",
      ],
      optional: true,
    },
    embeds: {
      propDefinition: [
        common.props.discordWebhook,
        "embeds",
      ],
    },
  },
  async run({ $ }) {
    const {
      message,
      avatarURL,
      threadID,
      username,
      includeSentViaPipedream,
      embeds,
    } = this;

    if (!message && !embeds) {
      throw new Error("This action requires at least 1 message OR embeds object. Please enter one or the other above.");
    }

    try {
      // No interesting data is returned from Discord
      await this.discordWebhook.sendMessage({
        avatarURL,
        threadID,
        username,
        embeds,
        content: includeSentViaPipedream
          ? this.appendPipedreamText(message ?? "")
          : message,
      });
      $.export("$summary", "Message sent successfully");
    } catch (err) {
      const unsentMessage = this.getUserInputProps();
      $.export("unsent", unsentMessage);
      throw err;
    }
  },
};

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
Discord WebhookdiscordWebhookappThis component uses the Discord Webhook app.
Messagemessagestring

Enter a simple message up to 2000 characters. This is the most commonly used field. However, it's optional if you pass embed content.

Thread IDthreadIDstring

If provided, the message will be posted to this thread

Usernameusernamestring

Overrides the current username of the webhook

Avatar URLavatarURLstring

If used, it overrides the default avatar of the webhook

Include link to workflowincludeSentViaPipedreamboolean

Defaults to true, includes a link to this workflow at the end of your Discord message.

Embedsembedsany

Optionally pass an array of embed objects. E.g., {{ [{"description":"Use markdown including *Italic* **bold** __underline__ ~~strikeout~~ [hyperlink](https://google.com) `code`"}] }}. To pass data from another step, enter a reference using double curly brackets (e.g., {{steps.mydata.$return_value}}).
Tip: Construct the embeds array in a Node.js code step, return it, and then pass the return value to this step.

Action Authentication

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

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

webhook.incomingemailidentify

About Discord Webhook

Use this app to send messages to a channel using Discord's incoming webhooks