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.
public class EventTask : ITask, IDeathListener, ITickListener {
// Start gets called once the Task is registered by
// PluginCore.cs using RegisterTask(). This ensures that
// the Context variable has been set to the current bot's context.
public override async Task Start() {
// We can register events here for the events that do
// not have an inheritable listener class.
// (unlike inheritable listeners these events will ignore
// the Exec() function)
EventsContext.Events.onChat += OnChatMessageReceived;
}
// The stop method is called once the plugin is stopped for this bot.
public override async Task Stop() {
// It is important to unregister any events that we register manually
// (in Start).
Context.Events.onChat -= OnChatMessageReceived;
}
// Determines wether the listeners (IDeathListener, ITickListener) will execute.
// If this returns true then the listeners do execute normally,
// otherwise the events will not be called.
public override bool Exec() {
// Always execute.
return true;
}
// Event is called when bot dies and Exec() returns true,
// this is because we inherit from IDeathListener.
public async Task OnDeath() {
Console.WriteLine($"Oh no, the bot {Context.Player.GetUsername()} just died!");
}
public async Task OnTick() {
// This is called each tick (~50ms) while Exec() returns true.
}
public void OnChatMessageReceived(IBotContext context, IChat message, byte position) {
if (!Exec()) return; // manually check if Exec tells us to execute.
Console.WriteLine($"Message received: {message.GetText()}");
}
}
public class EventTask : ITask, IDeathListener, ITickListener {
public override async Task Start() {
Context.Events.onChat += OnChatMessageReceived;
}
public override async Task Stop() {
Context.Events.onChat -= OnChatMessageReceived;
}
public override bool Exec() {
return true;
}
public async Task OnDeath() {
Console.WriteLine($"Oh no, the bot {Context.Player.GetUsername()} just died!");
}
public async Task OnTick() { }
public void OnChatMessageReceived(IBotContext context, IChat message, byte position) {
if (!Exec()) return;
Console.WriteLine($"Message received: {message.GetText()}");
}
}
You can find out all of the available inheritable Listener classes here.
Last updated