How can I count discord messages using a discord bot and a datastore?

This topic was automatically generated from Slack. You can find the original thread here.

Hi I’m trying to count discord messages. Currently I’m using the discord bot and saving a number in a datastore every hour. However as the discord bot emits an event for each message at once it is only counting 1 event each time the workflow is triggered.

I have tried editing the source code of the discord bot and adding in a delay for when each event is emitted, but it then started to only emit a single event each hour. I don’t suppose anyone has any ideas how I could approach this or where I may have gone wrong with the code?

} else {
messages.forEach((message, i) => {
setTimeout(() => {
this.$emit(message, {
summary: message.content,
id: message.id, // dedupes events based on this ID
});
}, i * 1000);
});
}

Hi, good question.

Instead of trying to modify the source, have you thought about incrementing the data store value on every event in the workflow?

You would have to retrieve the latest data store value in the same workflow, then add 1 and store it as the latest value.

Hey Pierce yes that is exactly what I have done. However, when multiple messages are emitted at the same time the increment doesn’t work.

Ah ok, so you have a race condition.

You could potentially set the number of workers to 1, so that way only one message can be processed at a time.

That would help with this race condition without code changes.

oh i see that would be this yes?

Screenshot 2023-02-24 at 15.48.36.png

I’ve ripped through my invocations today testing, but fingers crossed this will do it. Many thanks for your help. :raised_hands:

Yup! That’s the setting to control workers. So now they’ll be processed one at a time.

Sure thing :grinning: