-2

I'm retrieving a JSON-conform data-structure from a live chat API, but when a chat message shows an image the message value shows the url in its own format, embedded in between %%%[ and ]%%%.

The below object gives a preview on what was just described ...

{
  events: [{
    method: "chat",
    object: {
      message: {
        bgColor: null,
        color: "#494949",
        font: "default",
        message: "%%%[emoticon name|https://example.org/name.jpg|67|45|/emoticon_report/name/]%%%"
      },
      user: {
        gender: "m",
        username: ""
      }
    },
    id: "text"
  }],
  nextUrl: "text"
}

While processing the above data structure I would like to replace each message value that features the emoticon-format of ... %%%[ ... ]%%% ... by "Emoticon".

The code I'm working with right now is ...

const baseUrl = "example.com"
function getEvents(url) {
    fetch(url).then(response => response.json())
    .then(jsonResponse => {
        // Process messages
        for (const message of jsonResponse["events"]) {
            const method = message["method"]
            const object = message["object"]
            console.log(`Message ID: ${message["id"]}`)
            if (method === "chat") {
                console.log(`${object["user"]["username"]} sent chat message: ${object["message"]["message"]}`)
            } else {
                console.error("Unknown method:", method)
            }
        }

        // Once messages are processed, call getEvents again with 'nextUrl' to get new messages
        getEvents(jsonResponse["nextUrl"])
    })
    .catch(err => {
        console.error("Error:", err)
    })
}

getEvents(baseUrl)

At the moment the script's result is ...

Username: Hi

Username: %%%[emoticon name|https://example.org/name.jpg|67|45|/emoticon_report/name/]%%%

... but it should be changed to ...

Username: Hi

Username: Emoticon

Thank you for all the replies, it has helped a lot in figuring out some of the code. I've nearly got it done now. The only issue I'm still seeing is if the chat has posted multiple images with a message it cleans the whole message.

For example: Hello this is (image) so try (image) < this only shows Hello this is Emoticon

But I can live with that ;)

The final code that I've got includes the following line to clean it up:

var cleanmessage = chat.replace(/%%%\[emoticon.*]%%%/g, `Emoticon`);
vic73
  • 3
  • 2
  • This question is unclear. Can you type out the JSON in the question. Please provide current input JSON, desired output js variable. Type the example with multiple images if that is part of your question. – Daniel Lord Mar 11 '22 at 16:49
  • Dont use images. It is much better to copy paste text. You should show the json you have and json you want. Also show us what you have tried so far and what is the problem. – Serge Mar 11 '22 at 16:52
  • Thanks, but can you show what you want too, pls? – Serge Mar 11 '22 at 17:56
  • Firstly the OP does not work with a *json object* there is nothing like that. But the OP iterates over the `event` items of the response object's data-structure. For each item the OP wants to check the property value of `item.message.message`. Thus the OP's real question is ... _"How does one recognize an emoticon format?"_ – Peter Seliger Mar 11 '22 at 20:02
  • @vic73 ... Regarding the so far provided answers are there any questions left? – Peter Seliger Mar 12 '22 at 18:22

2 Answers2

0

From the above comments ...

"Firstly the OP does not work with a json object there is nothing like that. But the OP iterates over the event items of the response object's data-structure. For each item the OP wants to check the property value of item.message.message. Thus the OP's real question is ... 'How does one recognize an emoticon format?'"

The OP might have a look into ... String.prototype.startsWith

// faking the live chat API call for the further example code.

function fetch(/* fake api call url */) {
  return new Promise(resolve => {

    const responseData = '{"events":[{"method":"chat","object":{"message":{"bgColor":null,"color":"#494949","font":"default","message":"%%%[emoticon name|https://example.org/name.jpg|67|45|/emoticon_report/name/]%%%"},"user":{"gender":"m","username":""}},"id":"text"}],"nextUrl":"text"}';

    setTimeout(() => {
      resolve({ 
        json: () => JSON.parse(responseData),
      });
    }, 4000);
  });
}


const baseUrl = "example.com";

function getEvents(url) {
  console.log(`... fetch('${ url }') ...`);

  fetch(url)
    .then(response => response.json())
    .then(({ events, nextUrl }) => {
      // Process messages of chat events
      events
        .forEach(event => {
          const { method, object: { user, message }, id } = event;

          console.log(`Message event ID: ${ id }`);
          if (
            (method === 'chat') &&
            message.message.startsWith('%%%[emoticon')
          ) {
            // console.log(`${ user.username } sent chat message: ${ message.message }`);

            console.log(`${ user.username } sent chat message: ${ 'Emoticon' }`);

            // // and/or directly overwrite the data
            // message.message = 'Emoticon';            
          } else {
            console.error("Unknown method:", method);
          }
        });
      // Once messages are processed, call `getEvents`
      // again with 'nextUrl' to get new messages.
      getEvents(nextUrl);
    })
    .catch(err => {
      console.error("Error:", err);
    });
}

getEvents(baseUrl);
.as-console-wrapper { min-height: 100%!important; top: 0; }
Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
-1

Before using you object["message"]["message"] (or even better just object.message.message) just do a regex replace like this:

object.message.message.replace(/%%%\[emoticon.*]%%%/, 'Emoticon')

playground here : https://regex101.com/r/7Kf0VW/1

Michel Lamsoul
  • 232
  • 2
  • 4