Skip to content

Instantly share code, notes, and snippets.

@cryptiklemur
Created September 28, 2017 22:24
Show Gist options
  • Save cryptiklemur/4805501420ed5d4443df3dbd92b0f2af to your computer and use it in GitHub Desktop.
Save cryptiklemur/4805501420ed5d4443df3dbd92b0f2af to your computer and use it in GitHub Desktop.
import {Mutex} from "await-semaphore";
import {Channel} from "eris";
import {setInterval} from "timers";
const mutex: Mutex = new Mutex();
export default class ChannelBuffer<T> {
private _messages: T[] = [];
constructor(private _channel: Channel, tick: Function, interval: number = 1000) {
setInterval(async () => {
const release: any = await mutex.acquire();
let messages: T[] = this._messages.slice();
this._messages.length = 0;
release();
if (messages.length === 0) {
return;
}
tick(this._channel, messages);
}, interval);
}
public addItem(obj: T): void {
mutex.acquire().then((release) => {
this._messages.push(obj);
release();
});
}
};
import {Channel} from "eris";
import {injectable} from "inversify";
import ChannelBuffer from "./ChannelBuffer";
@injectable()
export default class MessageBuffer {
private readonly _buffers: Array<ChannelBuffer<string>> = [];
public AddItem(channel: Channel, message: string): void {
if (!this._buffers[channel.id]) {
this._buffers[channel.id] = new ChannelBuffer<string>(
channel,
async (channel, messages) => {
let builder: string = "";
for (let message of messages) {
if (builder.length + message.length > 2000) {
await channel.createMessage(builder);
builder = "";
}
builder += `${message}\n`;
}
await channel.createMessage(builder);
},
);
}
this._buffers[channel.id].addItem(message);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment