Skip to content

Creating events

Within this package you can create event listeners to listen to eventsub events.

Listening to events

By default, when you join to a channel you will listen only ChannelChatMessage event. To listen to the other events you will need to specify them when joining to a channel.

1
chatbot.channels.join("channelId", ["ChannelUpdate", "ChannelFollow"]);

As you can see in the example above the chatbot is joining to a channel and then listening to the ChannelUpdate and ChannelFollow events.

You may notice that you can only subscribe to events at joining a channel, but, for your luck, you can subscribe to events whenever you want.

When you join to a channel a ChannelProfile class is created and stored in the profiles collection within the chatbot instance.

With this class you can either unlisten events or subscribe to one or more events.

Here is an example of how get that channel profile and manage its events:

1
const profile = chatbot.profiles.get("channelId");
2
3
//could be undefined if is not found
4
if (profile) {
5
//adding one event
6
await profile.addEvent("StreamOnline");
7
//adding more than one event
8
await profile.addEvent(["ChannelChatClear", "ChannelFollow"]);
9
//removing event
10
await profile.removeEvent("StreamOnline");
11
}

Create your first event

Before creating our first event listener we must set our events directory in the paths option of ChatBotOptions, where all the events are going to be located.

1
import { ChatBot } from '@twitchfy/chatbot';
2
3
const chatbot = new ChatBot({
4
//rest of options
5
...opts,
6
paths: {
7
output: 'dist',
8
commands: 'commands',
9
events: 'events'
10
}
11
})

Now that we have set up our events base directory we are going to create our first event with createEvent function to listen to streams which go online.

events/StreamOnline.ts
1
import { createEvent } from "@twitchfy/chatbot";
2
3
export default createEvent({
4
event: "StreamOnline",
5
//data received by each event. See in the docs
6
async run(chatbot, data) {
7
const stream = await data.broadcaster.stream();
8
//could be null because api internal caching.
9
if (stream) {
10
return await chatbot.messages.send(
11
data.chatroomId,
12
`${data.broadcaster.toString()} is currently streaming ${
13
stream.game.name
14
}`
15
);
16
} else
17
return await chatbot.messages.send(
18
data.chatroomId,
19
`${data.broadcaster.toString()} is currently streaming.`
20
);
21
},
22
});