Readme

Send Chunked Discord Message

This function is used to send a message to a Discord webhook. If the message exceeds the maximum character limit (2000 characters), it will be divided into chunks and sent as multiple messages.

Parameters

message (string): The message to be sent to the Discord webhook.

Return Value

This function does not return any value.

Example Usage:

const message = "This is a long message that needs to be sent to Discord. It may exceed the character limit, so it will be divided into smaller chunks.";
await @ktodaz.sendDiscordMessage(message);

In the above example, the sendDiscordMessage function is used to send the message to the Discord webhook. If the message exceeds 2000 characters, it will be split into smaller chunks and sent as separate messages.

Required Secrets:

Ensure you have added the secret for discord_webhook in your val.town secrets settings (Profile -> Secrets)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { discordWebhook } from "https://esm.town/v/stevekrouse/discordWebhook?v=7";
import process from "node:process";
export const sendDiscordMessage = async (
message: string,
webhook_url: string = process.env.discord_webhook,
) => {
function chunkString(str) {
const chunks = [];
let startIndex = 0;
while (startIndex < str.length) {
let endIndex = startIndex + 2000;
if (endIndex >= str.length) {
chunks.push(str.slice(startIndex));
break;
}
const chunk = str.slice(startIndex, endIndex + 1);
const lastNewlineIndex = chunk.lastIndexOf("\n");
if (lastNewlineIndex !== -1) {
endIndex = startIndex + lastNewlineIndex;
chunks.push(str.slice(startIndex, endIndex + 1));
startIndex = endIndex + 1;
}
else {
chunks.push(chunk);
startIndex = endIndex + 1;
}
}
return chunks;
}
const discordMsgs = chunkString(message);
for (const msg of discordMsgs) {
try {
await discordWebhook({
url: webhook_url,
content: msg,
});
} catch (e) {
console.error(e);
}
}
};
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
v19 was merged from the PR "Fix IP block rate limit" by stevekrouse
Comments
Nobody has commented on this val yet: be the first!
September 3, 2024