Events (basic)
A basic code example that shows you how to make a plugin listen for certain events.

EventTask.cs

Task class that will be registered in PluginBase.cs and will be responsible to handle/report events that we receive from the server.
Commented Code
Raw Code
1
public class EventTask : ITask, IDeathListener, ITickListener {
2
3
// Start gets called once the Task is registered by
4
// PluginCore.cs using RegisterTask(). This ensures that
5
// the Context variable has been set to the current bot's context.
6
public override async Task Start() {
7
// We can register events here for the events that do
8
// not have an inheritable listener class.
9
// (unlike inheritable listeners these events will ignore
10
// the Exec() function)
11
EventsContext.Events.onChat += OnChatMessageReceived;
12
}
13
14
// The stop method is called once the plugin is stopped for this bot.
15
public override async Task Stop() {
16
// It is important to unregister any events that we register manually
17
// (in Start).
18
Context.Events.onChat -= OnChatMessageReceived;
19
}
20
21
// Determines wether the listeners (IDeathListener, ITickListener) will execute.
22
// If this returns true then the listeners do execute normally,
23
// otherwise the events will not be called.
24
public override bool Exec() {
25
// Always execute.
26
return true;
27
}
28
29
// Event is called when bot dies and Exec() returns true,
30
// this is because we inherit from IDeathListener.
31
public async Task OnDeath() {
32
Console.WriteLine(quot;Oh no, the bot {Context.Player.GetUsername()} just died!");
33
}
34
35
public async Task OnTick() {
36
// This is called each tick (~50ms) while Exec() returns true.
37
}
38
39
public void OnChatMessageReceived(IBotContext context, IChat message, byte position) {
40
if (!Exec()) return; // manually check if Exec tells us to execute.
41
Console.WriteLine(quot;Message received: {message.GetText()}");
42
}
43
}
Copied!
1
public class EventTask : ITask, IDeathListener, ITickListener {
2
3
public override async Task Start() {
4
Context.Events.onChat += OnChatMessageReceived;
5
}
6
7
public override async Task Stop() {
8
Context.Events.onChat -= OnChatMessageReceived;
9
}
10
11
public override bool Exec() {
12
return true;
13
}
14
15
public async Task OnDeath() {
16
Console.WriteLine(quot;Oh no, the bot {Context.Player.GetUsername()} just died!");
17
}
18
19
public async Task OnTick() { }
20
21
public void OnChatMessageReceived(IBotContext context, IChat message, byte position) {
22
if (!Exec()) return;
23
Console.WriteLine(quot;Message received: {message.GetText()}");
24
}
25
}
Copied!
You can find out all of the available inheritable Listener classes here.
Last modified 1yr ago
Copy link