Search code examples
c#discorddsharp+

Bot not responding to command, except a direct mention


I created a c# console application to run a discord bot using DSharpPlus (v4.3.0). Currently, on my discord server, I just want to send a command to the bot (the command is named "lore") & have it respond with "Hi", however my bot isn't responding unless I do a direct mention of the bot. So, this works:

@MyBotName lore

This doesn't. In fact, it doesn't even seem to hit my code (I've specified my prefix as "!"):

!lore

Any idea why this may be? Here's my code:

Program.cs

 namespace MyBot
 {
     class Program
     {
         static void Main(string[] args)
         {
             Bot bot = new Bot();
             bot.RunAsync().GetAwaiter().GetResult();
         }
     }
 }

Bot.cs This class does most of the heavy lifting. I register my "lore" command about two-thirds the way down "Commands.RegisterCommands();"

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using DSharpPlus;
using DSharpPlus.CommandsNext;
using DSharpPlus.EventArgs;
using Newtonsoft.Json;
using MyBot.Models.Generic;
using Microsoft.Extensions.Logging;
using MyBot.Commands;
using System.Configuration;

namespace MyBot
{
    public class Bot
    {
        public readonly EventId BotEventId = new EventId(42, ConfigurationManager.AppSettings["BotName"]);
        public DiscordClient Client { get; private set; } 
        public CommandsNextExtension Commands { get; private set; }
        public async Task RunAsync()
        {
            var json = string.Empty;

            using (var fs = File.OpenRead("config.json"))
            {
                using(var sr = new StreamReader(fs, new UTF8Encoding(false)))
                {
                    json = await sr.ReadToEndAsync().ConfigureAwait(false);
                }
            }

            var configJson = JsonConvert.DeserializeObject<ConfigJson>(json);

            var config = new DiscordConfiguration
            {
                Token = configJson.Token,
                TokenType = TokenType.Bot,
                AutoReconnect = true,
                MinimumLogLevel = LogLevel.Debug                
            };

            Client = new DiscordClient(config);
            Client.Ready += OnClientReady;
            Client.GuildAvailable += GuildAvailable;
            Client.ClientErrored += ClientError;

            var commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes = new string[] {configJson.Prefix},
                EnableDms = false,
                EnableMentionPrefix = true,
                DmHelp = true                
            };
            
            Commands = Client.UseCommandsNext(commandsConfig);            
            Commands.RegisterCommands<LoreCommands>();

            await Client.ConnectAsync();

            //prevents command from terminating prematurely. 
            await Task.Delay(-1);

              
        }

        private Task OnClientReady(DiscordClient client, ReadyEventArgs e)
        {
            client.Logger.LogInformation(BotEventId, "Client is ready to process events.");

            return Task.CompletedTask;
        }

        private Task GuildAvailable(DiscordClient client, GuildCreateEventArgs e)
        {
            client.Logger.LogInformation(BotEventId, $"Guild available: {e.Guild.Name}");
            return Task.CompletedTask;
        }

        private Task ClientError(DiscordClient client, ClientErrorEventArgs e)
        {
            client.Logger.LogError(BotEventId, e.Exception, "Exception occured");
            return Task.CompletedTask;
        }
    }
}

LoreCommands.cs This is the command I want to run when I type "!lore" into discord. But it's not hitting unless I type "@MyBotName lore"

using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace MyBot.Commands
{
    public class LoreCommands : BaseCommandModule
    {
        [Command("lore")]
        public async Task Lore(CommandContext ctx)
        {
            await ctx.Channel.SendMessageAsync("Hi").ConfigureAwait(false);
        }
    }
}

Config.json I'm using the "!" prefix

{
  "Token": "<my token id>",
  "Prefix": "!" 
}

Solution

  • in the var config = new DiscordConfiguration you have to add Intents = DiscordIntents.All,so your code should look like this

            var config = new DiscordConfiguration
            {
                Token = configJson.Token,
                TokenType = TokenType.Bot,
                Intents = DiscordIntents.All
                AutoReconnect = true,
                MinimumLogLevel = LogLevel.Debug                
            };