How do I send text and stamps with LINE Bot?

Issue Description

I would like to send LINE stickers after sending generated text from the OpenAI API using a LINE Bot. The flow is as follows:

The user enters a keyword in the LINE Bot (e.g., “doll”).

  1. send a request to the OpenAI API to generate a horror story related to the keyword.
  2. send the horror story back to LINE as a text message.
  3. want to send stickers after the text message.

I’m using the Messaging API.
https://developers.line.biz/ja/docs/messaging-api/sticker-list/

When I execute the code, steps 1, 2, and 3 are successful. However, the stickers are not being sent.

The execution environment is as follows:

  • GitHub Codespaces
  • JavaScript
"@line/bot-sdk": "^7.5.2",
"axios": "^1.4.0",
"express": "^4.18.2",
"line-bot-sdk": "^0.1.4",
"openai": "^3.2.1"

Problem/Error Occurring

When I run the code, the following error is displayed. The error occurs when trying to send the sticker message:

@xxxx ➜ /workspaces/xxxx/boot/02-line-bot (main) $ node horror2.js
Running Express server on port 3000...
Received: [
{
type: 'message',
message: { type: 'text', id: 'xxxx', text: 'tea' },
webhookEventId: 'xxxx',
deliveryContext: { isRedelivery: false },
timestamp: 1685232670580,
source: { type: 'user', userId: 'xxxx' },
replyToken: 'xxxx',
mode: 'active'
}
]
[
{
role: 'system',
content: 'You are a seasoned ghost storyteller. Please write a horror story using the keyword provided by the user.'
},
{ role: 'user', content: 'tea' }
]
Sticker message sending error: HTTPError: Request failed with status code 400
at HTTPClient.wrapError (/workspaces/xxxx/boot/02-line-bot/node_modules/@line/bot-sdk/dist/http.js:89:20)
at /workspaces/xxxx/boot/02-line-bot/node_modules/@line/bot-sdk/dist/http.js:19:88
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async HTTPClient.post (/workspaces/xxxx/boot/02-line-bot/node_modules/@line/bot-sdk/dist/http.js:33:21)
at async sendStickerMessage (/workspaces/xxxx/boot/02-line-bot/horror2.js:82:5)
at async handleEvent (/workspaces/xxxx/boot/02-line-bot/horror2.js:71:5)
at async Promise.all (index 0) {
statusCode: 400,
statusMessage: 'Bad Request',
originalError: [AxiosError: Request failed with status code 400] {
code: 'ERR_BAD_REQUEST',
config: {
transitional: [Object],
adapter: [Function: httpAdapter],
transformRequest: [Array],
transformResponse: [Array],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: [Object],
validateStatus: [Function: validateStatus],
headers: [Object],
method: 'post',
url: 'https://api.line.me/v2/bot/message/reply',
data: '{"messages":[{"type":"sticker","packageId":"446","stickerId":"2027"}],"replyToken":"xxxx","notificationDisabled":false}'
},
request: ClientRequest {
_events: [Object: null prototype],
_eventsCount: 7,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
destroyed: false,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: false,
maxRequestsOnConnectionReached: false,
_defaultKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
strictContentLength: false,
_contentLength: 147,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
_closed: false,
socket: [TLSSocket],
_header: 'POST /v2/bot/message/reply HTTP/1.1rn' +
'Accept: application/json, text/plain, /rn' +
'Content-Type: application/jsonrn' +
'Authorization: Bearer xxxxrn' +
'User-Agent: @line/bot-sdk/7.5.2rn' +
'Content-Length: 147rn' +
'Host: api.line.mern' +
'Connection: keep-alivern' +
'rn',
_keepAliveTimeout: 0,
_onPendingData: [Function: nop],
agent: [Agent],
socketPath: undefined,
method: 'POST',
maxHeaderSize: undefined,
insecureHTTPParser: undefined,
joinDuplicateHeaders: undefined,
path: '/v2/bot/message/reply',
_ended: true,
res: [IncomingMessage],
aborted: false,
timeoutCb: [Function: emitRequestTimeout],
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: true,
host: 'api.line.me',
protocol: 'https:',
_redirectable: [Writable],
[Symbol(kCapture)]: false,
[Symbol(kBytesWritten)]: 0,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype],
[Symbol(errored)]: null,
[Symbol(kHighWaterMark)]: 16384,
[Symbol(kUniqueHeaders)]: null
},
response: {
status: 400,
statusText: 'Bad Request',
headers: [Object],
config: [Object],
request: [ClientRequest],
data: [Object]
}
}
}
^C
@xxxx ➜ /workspaces/xxxx/boot/02-line-bot (main) $

Code

'use strict';

// ########################################
//               Initialization and Configuration
// ########################################

// Load modules
const line = require('@line/bot-sdk');
const openai = require('openai');
const express = require('express');

const PORT = process.env.PORT || 3000;

// Configuration
const config = {
    channelSecret: 'CHANNEL_SECRET',
    channelAccessToken: 'CHANNEL_ACCESS_TOKEN'
};

// Create client
const client = new line.Client(config);
const gptConfig = new openai.Configuration({
    organization: process.env.OPENAI_ORGANIZATION || "ORGANIZATION_ID",
    apiKey: process.env.OPENAI_API_KEY || 'API_KEY',
});

const gpt = new openai.OpenAIApi(gptConfig);

const makeCompletion = async (userMessage) => {
  const prompt = {
    role: 'system',
    content: 'You are a skilled ghost storyteller. Please write a ghost story using the keywords specified by the user.' // Enter the prompt
  };

  userMessage.unshift(prompt);
  console.log(userMessage);
  return await gpt.createChatCompletion({
    model: 'gpt-3.5-turbo',
    messages: userMessage,
    temperature: 0.5,
    n: 1
  });
};

// Handle message events
async function handleEvent(event) {
  // Ignore non-text message types
  if (event.type !== 'message' || event.message.type !== 'text') {
    return Promise.resolve(null);
  }

  const userMessage = [
    {
      role: 'user',
      content: event.message.text
    }
  ];

  // Send a request to the ChatGPT API
  try {
    const completion = await makeCompletion(userMessage);
    // Get the response
    const reply = completion.data.choices[0].message.content;
    // Send the reply to LINE
    await client.replyMessage(event.replyToken, {
      type: 'text',
      text: reply
    });

    // Send a sticker message
    await sendStickerMessage(event.replyToken);
  } catch (error) {
    // Output the error to the log if an error occurs
    console.error('Error sending message:', error);
    return Promise.resolve(null);
  }
}

// Send a sticker message
async function sendStickerMessage(replyToken) {
  try {
    await client.replyMessage(replyToken, {
      type: 'sticker',
      packageId: '446', // Replace with the package ID of the sticker
      stickerId: '2027' // Replace with the sticker ID
    });
    console.log('Sticker message sent');
  } catch (error) {
    console.error('Error sending sticker message:', error);
  }
}

const app = express();
app.get('/', (req, res) => res.send('Hello LINE BOT! (HTTP GET)'));
app.post('/webhook', line.middleware(config), (req, res) => {
  if (req.body.events.length === 0) {
    res.send('Hello LINE BOT! (HTTP POST)');
    console.log('Verification event received!');
    return;
  } else {
    console.log('Received:', req.body.events);
  }

  Promise.all(
    req.body.events.map((event) => {
      if (event.type === 'message' && event.message.type === 'text') {
        return handleEvent(event);
      } else if (event.type === 'message' && event.message.type === 'sticker') {
        return handleMessageEvent(event);
      } else {
        return null;
      }
    })
  ).then((result) => res.json(result));
});

app.listen(PORT);
console.log(`Running Express server on port ${PORT}...`);

Troubleshooting Steps Taken

I attempted troubleshooting with the help of ChatGPT, but I couldn’t identify the specific issue. Since I don’t have experience writing code, I couldn’t narrow down the areas that need to be fixed. I would appreciate any advice or key points to check.

Error when using react-scratchcard-v2 on mobile: Unable to preventDefault inside passive event listener invocation

I am using react-scratchcard-v2 to create a scratchcard game. It works fine on desktop, but when using it with touch (either on mobile or in the mobile view of Dev Tools), it still works, but I get his error, which prevents any further functionality (sound in my case) from working:

react-dom.development.js:6878 Unable to preventDefault inside passive
event listener invocation.
preventDefault @ react-dom.development.js:6878
Scratch2._this.handleMouseMove @ index.tsx:197
callCallback2 @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291
executeDispatch @ react-dom.development.js:9041
processDispatchQueueItemsInOrder @ react-dom.development.js:9073
processDispatchQueue @ react-dom.development.js:9086
dispatchEventsForPlugins @ react-dom.development.js:9097
(anonymous) @ react-dom.development.js:9288
batchedUpdates$1 @ react-dom.development.js:26140
batchedUpdates @ react-dom.development.js:3991
dispatchEventForPluginEventSystem @ react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465
dispatchEvent @ react-dom.development.js:6457
dispatchContinuousEvent @ react-dom.development.js:6444

That’s my code:

import "./style.css";
import { useEffect, useState } from "react";
import ScratchCard from "react-scratchcard-v2";

const scratchingSound = new Audio("./sounds/scratching.mp3");
scratchingSound.loop = true;

interface IScratchAreaProps {
  value: 0 | 10 | 100 | 1000;
}

const ScratchArea = ({ value }: IScratchAreaProps) => {
  const [
    amount,
    // setAmount
  ] = useState(value);
  const [
    amountSrc,
    // setAmountSrc
  ] = useState(`./assets/${amount}.svg`);
  const [
    iconSrc,
    // setIconSrc
  ] = useState(amount === 0 ? "./assets/banana.svg" : "./assets/coin.svg");

  const [isClicked, setIsClicked] = useState(false);
  const [isScratching, setIsScratching] = useState(false);

  const handleMouseDown = (event: React.MouseEvent<HTMLDivElement>) => {
    if (event.button === 0) {
      setIsClicked(true);
      setIsScratching(true);
    }
  };

  const handleMouseUp = () => {
    setIsClicked(false);
    setIsScratching(false);
  };

  const handleMouseEnter = () => {
    if (isClicked) {
      setIsScratching(true);
    }
  };

  const handleMouseLeave = () => {
    if (isClicked) {
      setIsScratching(false);
    }
  };

  useEffect(() => {
    const handleWindowMouseUp = () => {
      if (isClicked) {
        setIsClicked(false);
        setIsScratching(false);
      }
    };
    window.addEventListener("mouseup", handleWindowMouseUp);

    return () => {
      window.removeEventListener("mouseup", handleWindowMouseUp);
    };
  }, [isClicked]);

  useEffect(() => {
    const handleWindowMouseUp = () => {
      if (isClicked) {
        setIsClicked(false);
        setIsScratching(false);
      }
    };

    window.addEventListener("mouseup", handleWindowMouseUp);

    return () => {
      window.removeEventListener("mouseup", handleWindowMouseUp);
    };
  }, [isClicked]);

  useEffect(() => {
    if (isScratching) {
      scratchingSound.currentTime = 0;
      scratchingSound.volume = 0.3;
      scratchingSound.play();
    } else {
      scratchingSound.pause();
    }
  }, [isScratching]);

  return (
    <div
      className="scratcharea-container"
      onMouseDown={handleMouseDown}
      onMouseUp={handleMouseUp}
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
    >
      <ScratchCard
        width={170}
        height={170}
        image="./assets/scratch_card.svg"
        finishPercent={60}
        onComplete={() => console.log("complete")}
        brushSize={15}
        fadeOutOnComplete={false}
      >
        <div className="scratcharea">
          <img className="revealed-icon" alt="revealed icon" src={iconSrc} />
          <img
            className="revealed-amount"
            alt="revealed amount"
            src={amountSrc}
          />
        </div>
      </ScratchCard>
      <div
        onClick={() => console.log("Help modal opened!")}
        className="help-button"
      />
    </div>
  );
};

export default ScratchArea;

I tried removing all event handlers, but the error persists. There is also a live deployment if you want to check it: Deployment

Thanks for any help.

React JS receipt print

I am using React JS with TS. I want to print receipts using epson thermal printer. Tried epson SDK but didn’t work, also tried react-thermal-printer package and still not working. I always got the receipts size in a wrong way.I am using print portal to handle this.

How to get media controls for Web Audio API on iOS and Android mobile lock screens?

I’m developing a web app that plays many short samples via the Web Audio API. I’m trying to implement media controls on the mobile lock screens (both iOS and Android) using the Media Session API. Here’s the code I’m using:

const initLockScreenCtrls = () => {
  if ('mediaSession' in navigator && !lockScreenControlsAreInit) {
    lockScreenControlsAreInit = true;

    navigator.mediaSession.setActionHandler('play', function () {
      document.getElementById('playPause').click();
    });

    navigator.mediaSession.setActionHandler('pause', function () {
      document.getElementById('playPause').click();
    });
    console.log(navigator.mediaSession.playbackState); // yields "playing"
  }
}

document.addEventListener('click', initLockScreenCtrls, {once: true});

This code sort of works on desktop (with an additional silent <audio> element hack, which I’d rather avoid), but doesn’t help with the mobile lock screen controls issue.

How can I get lock screen media controls to work for the Web Audio API on mobile platforms?

Running an old project, dependency errors from ESLint. How do I solve this?

So i’m trying to running an old project from 2019, there are problems from Eslint,
I tried adding new versions to see if it would work, but it’s still causing conflicts, and npm run dev doesn’t run.
I’ve already tried deleting node_modules and .nuxt multiple times and running npm install multiple times. I’ve also tried npm install –legacy-peer-deps. The node_modules folder gets installed, but ESLint erros prevents the project from running.

My package.json file looks like this:
enter image description here

The errors I’m seeing are:
enter image description here

I have already tried removing Eslint from the project, but it seems that the project doesn’t run properly without Eslint. I’m not sure why, but I’m getting errors related to page requests when Eslint is not present.

Chrome extension to close idle open tabs

So I have two questions here. The first is:

I am trying to write a code for an extension that closes idle open tabs in Google Chrome after a set amount of time. For testing, I have made this set time to be 10 seconds. This is my manifest.json

{
  "manifest_version": 3,
  "name": "Idle Tab Closer",
  "version": "1.0",
  "permissions": ["tabs", "idle"],
  "background": {
    "service_worker": "background.js"
  }
}

And this is my background.js

chrome.idle.onStateChanged.addListener((state) => {
  if (state === "idle") {
    chrome.tabs.query({}, (tabs) => {
      const currentTime = Date.now();
      const tenSeconds = 10 * 1000; // 10 seconds in milliseconds

      tabs.forEach((tab) => {
        chrome.tabs.get(tab.id, (currentTab) => {
          if (currentTab.lastFocusedWindow && currentTab.lastFocusedWindow.focused) {
            const tabLastActive = currentTab.lastFocusedWindow.focusedTime || currentTab.lastFocusedWindow.timestamp;
            if (currentTime - tabLastActive > tenSeconds) {
              chrome.tabs.remove(tab.id);
            }
          }
        });
      });
    });
  }
});

But this code does not work. It does not result in errors, but the tabs still do not close after this set amount of time. What I do is I switch to a tab and then wait for the other tabs to close but they never do.

The second question is simple: Is there a place to keep asking questions safely and get help with my project without spamming stackoverflow or get into risk of having my account closed?

Thank you!

Correct naming of joined collection in lookup mongoose

There is a problem with the naming of joined collection, which does not find it.

This is our collection schema. in which collection transaction is related to ExpenseRecurring

    const transaction = Schema(
  {
     ..
     ...,
    expenseRecurring: {
      type: SchemaTypes.ObjectId,
      ref: 'ExpenseRecurring',
      required: false,
    },
   ...
   ....
  {
    timestamps: true,
  }
);

But when we want to use the connection between them, we have no output. which is probably a naming problem

const aggregate = [
{
{
  $lookup: {
    from: 'expenserecurrings',
    localField: 'expenseRecurring',
    foreignField: '_id',
    as: 'expenseRecurring',
  },
},
{
  $unwind: '$expenseRecurring',
},
{
  $match: { ...filter },
},

];
When I delete this lookup, all the data is returned.

I tested expenserecurrings,expenseRecurrings,ExpenseRecurrings,ExpenseRecurring

Why is JavaScript and HTML pointing a constant error? [closed]

I dont find the error
i tried change the letters but the error is always the same
the browser is pointing a error

const menorValor = 1;
const maiorValor = 100;
const numeroSecreto = gerarNumeroAleatorio();

function gerarNumeroAleatorio() {
    return parseInt(Math.random() * maiorValor + 1);
}

console.log('Número Secreto:', numeroSecreto);

const elementoMenorValor = document.getElementById('menor-valor');
elementoMenorValor.innerHTML = menorValor;



How to trigger useEffect even if the dependency hasn’t change

I have these reactJS components

const Parent = props => {

  useEffect(() => {
        if (reduxState.item) {
            setActiveItem(reduxState.item);
        }
    }, [dispatch, reduxState.item, setKey]);

  return (
    <ChildComponent
        activeItem={activeItem}
    />
  );
}

and

const Child = props => {
    const activeItem = props.activeItem;
    useEffect(() => {
        if(activeItem) {
            updateSelect(activeItem);
        }
    }, [activeItem, updateSelect]);
}

when I load the page, useEffect is not executed, because is null.

Then, an event (REDUX) in Parent generates a value for activeItem, and the useEffect in Child gets triggered.

If another event with the same value occurs, Child is rendered again, but useEffect is not triggered, because activeItem is still the same.

Is there a way to reset activeItem right after I called updateSelect?

I already tried this with no luck:

const Child = props => {
    const [activeItem, setActiveItem] = useState(props.activeItem);
    useEffect(() => {
        if(activeItem) {
            updateSelect(activeItem);
            setActiveItem(null);
        }
    }, [activeItem, updateSelect]);
}

I know I could also remove the dependencies, but I only need the useEffect in Child to be triggered when the redux event occurs.

Why am I receiving a syntax error in my React app despite my syntax appearing correct?

Here is my app.js

import React from 'react';
import ReactDOM from 'react-dom';
import Characters from './components/Characters';

const App = () => {
return (
 <div>
 <h1>Star Wars Characters</h1>
 <Characters />
 </div>
 );
 };

 ReactDOM.render(<App />, document.getElementById('root'));


export default App;

here is my character.js

import React, { useState, useEffect } from 'react';
import styled from 'styled-components';

const CharacterContainer = styled.div`
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
`;

const Characters = () => {
const [characters, setCharacters] = useState([]);

useEffect(() => {
fetch('https://swapi.dev/api/people/')
.then((response) => response.json())
.then((data) => setCharacters(data.results))
.catch((error) => console.error(error));
}, []);

return (
<div>
{characters.map((character, index) => (
<CharacterContainer key={index}>{character.name}</CharacterContainer>))}
</div>
);
};

im trying to render a list pulling data from a mock api. my function is suppose to loop over each character pulling the data whenever the character is selected.

I’ve tried a lot of different stuff. 4 hours of attempts. i just dont know. i feel like the answer is right in my face.

Infinite Image Carousel Fixing Animation On Loop

I have been reworking an infinite image carousel and trying to add some fun animations. So far I have been having success, except when I get to the end and it loops back around. I understand why the animation breaks but I am not figuring out how to fix it without breaking the entire carousel. I think the problem is obvious when you see the code:

const elem = (selector,parent) => (parent || document).querySelector(selector);
const elems = (selector,parent) => (parent || document).querySelectorAll(selector);
const newElem = (tag,properties) => Object.assign(document.createElement(tag),properties);

function createCarousel(carousel) {
    const slideSpeed = 3000;
    const pause = 1500;

    const carouselWrap = elem('.carousel-wrap',carousel);
    carouselWrap.style.overflow = 'visible';
    carousel.parentElement.classList.add('box-shadow');
    const carouselSlides = elems('.carousel-slide',carouselWrap);
    carouselSlides.forEach((e) => e.style.zIndex = `-1`);
    const totalSlides = carouselSlides.length;
    const indicators = [];
    if (totalSlides < 2) return;

    console.log(carouselSlides.length);

    let currentSlide = 0;
    let interval;

    function animate(ms = slideSpeed,cs = currentSlide) {
        currentSlideMod = ((cs % totalSlides + totalSlides) % totalSlides);
        carouselWrap.style.transition = `${ms}ms ease-in-out`;
        carouselWrap.style.transform = `translateX(${(-cs - 1) * 100}%)`;
        carouselSlides.forEach((slide, i) => slide.classList.toggle('active',currentSlideMod === i));
        indicators.forEach((indicator, i) => {
            indicator.classList.toggle('active',currentSlideMod === i);
            indicator.classList.toggle('next',currentSlideMod+1 === i);
            if (currentSlideMod === totalSlides-1) indicator.classList.toggle('next',0 === i);
        });
    }

    function previous() {
        if (currentSlide <= -1) return;
        currentSlide -= 1;
        animate();
    }

    function next() {
        if (currentSlide >= totalSlides) return;
        currentSlide += 1;
        animate();
    }

    function goto(index) {
        currentSlide = index;
        animate();
    }

    function play() {
        interval = setInterval(next, pause + slideSpeed);
    }

    function stop() {
        clearInterval(interval);
    }
    
    carouselWrap.firstElementChild.addEventListener('transitionend', () => {
        if (currentSlide <= -1) currentSlide = totalSlides - 1;
        if (currentSlide >= totalSlides) currentSlide = 0;
        animate(0)
    });

    const nav = newElem('nav', {});

    carouselSlides.forEach((slide,i) => {
        slide.addEventListener('wheel', () => {})
        const indicator = newElem('button', {
            type: 'button',
            onclick: () => goto(i),
        });
        indicators.push(indicator);
    });

    nav.append(...indicators);
    carousel.append(nav);

    carouselWrap.prepend(carouselSlides[totalSlides - 1].cloneNode(true));
    carouselWrap.append(carouselSlides[0].cloneNode(true));
    
    carousel.addEventListener('pointerenter', () => stop());
    carousel.addEventListener('pointerleave', () => play());

    animate(0)
    play();
}

elems('.carousel').forEach(createCarousel);
* {
    box-sizing: border-box;
}
.carousel,.carousel-wrap,.carousel-slide {
    margin: 0;
    position: relative;
    overflow: hidden;
}
.carousel {
    aspect-ratio: 16 / 9;
    isolation: isolate;
    position: relative;
}
.box-shadow .carousel::after {
    content: ' ';
    width: 100%;
    height: 100%;
    position: absolute;
    inset: 0;
    box-shadow: inset 0 0 0.75rem black;
    pointer-events: none;
}
.carousel nav {
    margin: 0 auto;
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 999;
    display: flex;
    justify-content: center;
    gap: 1em;
    pointer-events: none;
}
.carousel nav button {
    padding: 0.5em;
    border: 0.5em solid white;
    background: teal;
    cursor: pointer;
    border-radius: 50%;
    transition: background 0.75s ease;
    pointer-events: auto;
}
.carousel nav button:where(.active,.next,:hover,:focus) {
    background-color: teal;
    transition: background 0.25s 0s ease-in-out;
}
.carousel nav button.next {
    transition: background 0.75s 2.5s;
}
.carousel nav button.active {
    background: teal;
    transition: background 0.75s;
}
.carousel-wrap {
    height: 100%;
    display: flex;
    overflow-x: scroll;
    scroll-snap-type: x mandatory;
    box-shadow: inset 0 0 0.75rem black;
}
.carousel-slide {
    flex: 1 0 100%;
    scroll-snap-align: start;
}
.carousel-slide figure {
    margin: 0;
    width: 100%;
    height: 100%;
}
.carousel-slide img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    scale: 0.95;
    transition: scale 0.75s 0s ease-in-out;
    background: blue;
}
.carousel-slide.active img {
    scale: 1;
    transition: scale 0.75s 2.25s ease-in-out;
}
.carousel-slide figcaption {
    padding: 1rem 1rem;
    width: 100%;
    position: absolute;
    bottom: 0;
    color: white;
}
        <section class="carousel">
            <div class="carousel-wrap">
                <a href="#" class="carousel-slide"><figure>
                    <img src="" alt="">
                    <figcaption><h3>Slide 1</h3></figcaption>
                </figure></a>
                <a href="#" class="carousel-slide"><figure>
                    <img src="" alt="">
                    <figcaption><h3>Slide 2</h3></figcaption>
                </figure></a>
                <a href="#" class="carousel-slide"><figure>
                    <img src="" alt="">
                    <figcaption><h3>Slide 3</h3></figcaption>
                </figure></a>
                <a href="#" class="carousel-slide"><figure>
                    <img src="" alt="">
                    <figcaption><h3>Slide 4</h3></figcaption>
                </figure></a>
                <a href="#" class="carousel-slide"><figure>
                    <img src="" alt="">
                    <figcaption><h3>Slide 5</h3></figcaption>
                </figure></a>
                <a href="#" class="carousel-slide"><figure>
                    <img src="" alt="">
                    <figcaption><h3>Slide 6</h3></figcaption>
                </figure></a>
                <a href="#" class="carousel-slide"><figure>
                    <img src="" alt="">
                    <figcaption><h3>Slide 7</h3></figcaption>
                </figure></a>
                <a href="#" class="carousel-slide"><figure>
                    <img src="" alt="=">
                    <figcaption><h3>Slide 8</h3></figcaption>
                </figure></a>
                <a href="#" class="carousel-slide"><figure>
                    <img src="" alt="">
                    <figcaption><h3>Slide 9</h3></figcaption>
                </figure></a>
            </div>
        </section>

Hopefully someone has some idea on how I can make this work. I have tried delaying when the “active” class gets added at the end but nothing I try such as “setInterval” seems to do anything… Still rather newbie with JS so appreciate all the help.

Put if condition within find method for 0th element

I have an object with keys

const People = {
    groupA : ['Amy','Beth'],
    groupB : ['Ben','Matt'],
    groupC : ['Jen','Eli'], 
};

Now I am declaring a varieable where I will pass the values dynamical. for example

const Person = Object.entries(People).find(([,values])=>values.includes('Amy'))[0]
console.log(Person) //output 'groupA'

But when In pass something thats not in the object, its throwing an undefined error. I was not able to understand where to put the if condition.

const Person1 = Object.entries(a).find(([,values])=>values.includes('Brad'))[0]
console.log(Person1) // output should be undefined

I tried putting if conditions but was not able to handle both scenerios.

How can I retrieve text from an external URL in After Effects using JavaScript?

I’m trying to create a plugin for After Effects 2023 using Microsoft Visual Studio Code. But I’m fairly new for creating something like that. I stuck at working on getting text from the url. I’ve actually uploaded both test.txt and test.json (tried one by one ) files to my hosting and trying to reach the text inside. I’ve managed to get the text if I use .txt file on locally but the important part is taking text from my web page.

To be more clear, I’ve a button called Get Text on my UI, and I’ve uploaded test.txt file which includes a number for testing to my hosting. How can i reach that .text/.json files and get the text from them? I failed everytime to getting texts.

I’ve tried to use XMLHttpRequest, sockets and Fetch. But as I’ve said before I’m fairly new at this so not sure if I made everything correctly

Example;

var url = "https://example.com/plugin/test.txt";
var xhr = new XMLHttpRequest();
  xhr.open("GET", url, false);
  xhr.send();

  if (xhr.status === 200) {
    var content = xhr.responseText;
    if (content === "50") {
      alert("Yup,it's 50!");
    } else {
      alert("Nope!");
    }
  } else {
    alert("Error: " + xhr.status);
  }
}

React navbar not displaying after refresh with reactstrap – what’s wrong?

needing serious help.

I’m trying to get my Navbar to show, but somehow is not working.
These are my current files;

import "./components/App.css"
import Navbar from "./components/Navbar";
import { Routes, Route } from "react-router-dom";
import Home from "./components/Pages/Home"
import About from "./components/Pages/About"


function App() {
  return(
    <>
    <Navbar />
    <div className="container">
      <Routes>
        <Route path="/" element={<Home/>} />
        <Route path="/" element={<About/>} />

      </Routes>
    </div>
    </>
  )
}
export default App;
import React from "react";

export const Home = () => {
  return (
    <div>
      <h1>Home</h1>
    </div>
  );
};

export default Home;
import React, { useState } from "react";
import  { Collapse, Nav, NavbarBrand, NavbarToggler, NavLink, NavItem } from 'reactstrap';

function Navbar() {
  const [click, setClick] = useState(false);

  const handleClick = () => setClick(!click);
  return (
    <div>
     <Navbar color= 'light' light expand ='md'>
     <NavbarBrand href= "/">react</NavbarBrand>

     <NavbarToggler onClick={this.toggle} />
     <Collapse isOpen={this.state.isOpen} navbar>
      <Nav className="m1-auto" navbar>
        <NavItem>
        <NavLink
                exact
                to="/about"
                activeClassName="active"
                className="nav-links"
                onClick={handleClick}
              >
                About
              </NavLink>
        </NavItem>

      </Nav>
     </Collapse>

     </Navbar>
    </div>
  )

}
export default Navbar;

Expecting the navbar to show but every time i refresh, it won’t load. So I’m not too sure the error.

Expecting the navbar to show but every time i refresh, it won’t load. So I’m not too sure the error.
Expecting the navbar to show but every time i refresh, it won’t load. So I’m not too sure the error.
Expecting the navbar to show but every time i refresh, it won’t load. So I’m not too sure the error.