Creating Services
Services are long-lived classes listening for events Discord sends via the gateway, i.e. classes that inherit DiscordBotService
.
See more: xref
I called the class I made HelloService
. The name can be anything and you can have as many services as you want.
Now, paste the following code in:
using System;
using System.Linq;
using System.Threading.Tasks;
using Disqord;
using Disqord.Bot.Hosting;
using Disqord.Rest;
namespace MyBot
{
// DiscordBotService is required to mark the class as a service.
public class HelloService : DiscordBotService
{
// The phrases the service will respond to.
private readonly string[] _phrases = { "hi", "hey", "hello" };
// OnNonCommandReceived fires for messages that do not contain any of our prefixes etc.
protected override async ValueTask OnNonCommandReceived(BotMessageReceivedEventArgs e)
{
// Ignores messages sent outside of guilds.
// By default the bot ignores DMs anyways, but this is just an example.
if (e.GuildId == null)
return;
// Ignores all system messages, e.g. pin or boost messages.
if (e.Message is not IUserMessage)
return;
// Ignores messages sent by bots.
// This also prevents the bot responding to itself infinitely.
if (e.Message.Author.IsBot)
return;
// Ignores messages without any of the above defined phrases.
if (!_phrases.Any(phrase => e.Message.Content.Contains(phrase, StringComparison.OrdinalIgnoreCase)))
return;
// Responds to the phrase by mentioning the author.
await Bot.SendMessageAsync(e.ChannelId, new LocalMessage()
.WithContent($"Hello, {e.Message.Author.Mention}!"));
}
}
}
This adds a basic service that responds to anyone saying hi
, hey
, or hello
. Let's try it out! Boot up your bot and type any of the phrases in a channel.