This topic was automatically generated from Slack. You can find the original thread here.
Hi everyone! I’m using the Mastodon step to post a message, but running into a character limit in some cases. Is there an easy way to split the text into multiple messages, or do I need to use a custom script step for this?
You can split a string into multiple substrings based on a specific number of characters using JavaScript. Here’s an example function that does this: function splitStringByLength(text, maxLength) { const result = []; for (let i = 0; i < text.length; i += maxLength) { result.push(text.slice(i, i + maxLength)); } return result; } const text = "This is a long text that needs to be split into smaller chunks."; const maxLength = 20; const substrings = splitStringByLength(text, maxLength); console.log(substrings); In this example, the splitStringByLength function takes two arguments: the input text and the maximum number of characters per substring maxLength. It iterates through the text, slicing it into substrings of the specified length, and pushes them into an array called result. Finally, it returns the array of substrings.
To use the provided code within a Node.js code step in a Pipedream workflow, follow these steps: 1. Add a new code step to your workflow by clicking the “+” button below any existing step. 2. Select the option to “Run custom code”. 3. Choose the nodejs14.x runtime. 4. In the code editor, paste the following code: import { axios } from "@pipedream/platform"; function splitStringByLength(text, maxLength) { const result = []; for (let i = 0; i < text.length; i += maxLength) { result.push(text.slice(i, i + maxLength)); } return result; } export default defineComponent({ async run({ steps, $ }) { const text = "This is a long text that needs to be split into smaller chunks."; const maxLength = 20; const substrings = splitStringByLength(text, maxLength); console.log(substrings); // You can return the substrings array or use it in further steps return substrings; }, }); This code imports the necessary Pipedream package and defines the splitStringByLength function. It then uses the function within the run method of the Pipedream component to split the input text into substrings based on the specified maximum length. You can customize the text and maxLength variables as needed. The substrings array will be returned from the step and can be used in subsequent steps of your workflow.
I know how to go about splitting long text into shorter paragraphs according to the character limit. My question was whether I need to do this in a custom Python script, or if there is a way to do it automatically using the Mastodon step.