Scheduled function not working

Hello!

My website is https://sunny-mousse-bc9ae9.netlify.app

I’m trying to do some scheduled functions following this tutorial Scheduled Functions | Netlify Docs

It actually works but not doing POST requests to a Discord webhook (this here is mentioned on the tutorial that I follow). So as the tutorial says, I should use either a synchronous or background function instead, but I think they won’t do it with a schedule, or if it does, how?

This are my codes:

import { schedule } from "@netlify/functions";

import { Webhook } from 'discord-webhook-node';
const hook = new Webhook("https://discord.com/api/webhooks/mywebhookid");

console.log("init")
const handler = async function(event, context) {
    hook.send("Prueba de la conexión. <@286402429258301440>")
    console.log("hola")
    return {
        statusCode: 200,
        body: "Hello"
    }
}

exports.handler = schedule("* * * */1 *", handler)

It does the schedule, it manages to do the console.log(“hola”) but not the hook.send. This gives an error saying Client network socket disconnected before secure TLS connection was established

I also tried this:

import { Webhook } from 'discord-webhook-node';
const hook = new Webhook("https://discord.com/api/webhooks/mywebhookid");



import type { Handler, HandlerEvent, HandlerContext } from "@netlify/functions";
import { schedule } from "@netlify/functions";

const myHandler: Handler = async (event: HandlerEvent, context: HandlerContext) => {
  console.log("Received event:", event);
  hook.send("Prueba de la conexión v2. <@286402429258301440>")

    return {
        statusCode: 200,
    };
};

const handler = schedule("*/1 * * * *", myHandler)

export { handler };

This code gives me reason: socket hang up error.

Thanks for your time.

Webhook.send is an async method: discord-webhook-node/webhook.js at master · matthew1232/discord-webhook-node · GitHub, you would need async statement like:

await hook.send("Prueba de la conexión v2. <@286402429258301440>")

The module’s documentation seems incorrect.

1 Like

Seems it’s the solution.

Copied the code in the documentation and added the hook.send. Appears it’s working perfectly now.

Code in case someone wants to take a look:

import type { Handler, HandlerEvent, HandlerContext } from "@netlify/functions";
import { schedule } from "@netlify/functions";

import { Webhook } from 'discord-webhook-node';
const hook = new Webhook("https://discord.com/api/webhooks/mywebhookid");

const myHandler: Handler = async (event: HandlerEvent, context: HandlerContext) => {
  console.log("1 minuto");
  await hook.send("Prueba de la conexión. <@286402429258301440>")

  return {
    statusCode: 200,
  };
};

const handler = schedule("*/1 * * * *", myHandler)

export { handler };