Discord: how to catch direct message from user to bot?

Andrew picture Andrew · Mar 9, 2017 · Viewed 8.3k times · Source

I am creating own bot for Discrod server. So far I have managed to give it commands like "!roll" into the chat and bot catches it replies "you rolled 6" to the chat as well.

client.UsingCommands(input => { input.PrefixChar = '!' });
command.CreateCommand("roll").Do(async (e) => { 
  await channel.SendMessage(username + " rolls " + rng.Next(1, 7)) });

But I dislike the way people are typing commands into the chat because it might be disruptive at some point. I would like to create a possibility to call command by direct message from the user to the bot. You'd DM bot "roll" and it will write to the chat "andrew rolled 1".

But I have no idea how to do that or if it is even possible. Any ideas?

Answer

Kaynn picture Kaynn · Mar 11, 2017

One solution could be using Delegates/EventHandlers

    var client = new DiscordClient();
        client.MessageCreated += (s, e) =>
            {
                if (!e.Message.IsAuthor && e.Message.ToLower().Contains("roll")){
/*Code here*/
}       
            }
            EventHandler<MessageEventArgs> handler = new EventHandler<MessageEventArgs>(HandleMessageCreated);
            client.MessageCreated += handler;

Just make sure you place this delegate/EventHandler code below the Command Services setup, and the bot won't double-post when someone does !roll.
Also, you can use IsPrivate variable on channel Object to check if the message sent on the channel is a DM/PM channel or not.

In case you need the documentations for Discord.NET v0.9.6, here it is.

Also, you may want to consider using Discord.NET v1.0.0+ instead.