Rishav
Rishav

Reputation: 4078

Make Discord-Bot to reply same message for any command

I want my bot to reply the same message for no matter whatever command it receives. I know how to reply to commands when they are knows but here I want to reply a particular string irrespective of the command.

I tried:

[Command("")]
public async Task gg()
{
    await ReplyAsync("gg");
    await Context.Channel.SendMessageAsync("hi there");
}

but apparently I get a runtime error as it can not add a blank or null command. (error log is useless) Not placing the [Command(string)] at all would never trigger the task for what I could make out.

Upvotes: 0

Views: 4151

Answers (2)

WQYeo
WQYeo

Reputation: 4056

Assuming that you where following the Discord.NET documentation tutorials in setting up a command service...

You probably have a HandleCommand function, or something equivalent to that. It should contain a line of code that looks like this:
if(!(message.HasStringPrefix("PREFIX", ref argPos))) return;
Which basically means "if this message does not have the prefix at the start, exit the function". (Where message is a SocketUserMessage and argPos is a int, usually 0)

Put your line of code after that, so it would look like this...

//Blah
if(!(message.HasStringPrefix("PREFIX", ref argPos))) { return; }
await message.Channel.SendMessageAsync("blah");
//stuff

But, if you want the bot to only reply if the bot doesn't find a suitable command for the current command the user send, you can do this instead:

if(!(message.HasStringPrefix("PREFIX", ref argPos))) { return; }
            var context = new CommandContext(client, message);
            var result = await commands.ExecuteAsync(context, argPos, service);

            if(!result.IsSuccess) {
                //If Failed to execute command due to unknown command
                if(result.Error.Value.Equals(CommandError.UnknownCommand)) {
                    await message.Channel.SendMessageAsync("blah");
                } else {
                    //blah
                }
            }

Upvotes: 3

lorisleitner
lorisleitner

Reputation: 698

It's not possible to implement this as a command. You have to subscribe to the MessageReceived Event of your DiscordSocketClient and simply send a message back to the channel when it fires.

private async Task OnMessageReceived(SocketMessage socketMessage)
{
    // We only want messages sent by real users 
    if (!(socketMessage is SocketUserMessage message))
        return;

    // This message handler would be called infinitely
    if (message.Author.Id == _discordClient.CurrentUser.Id)
        return;

    await socketMessage.Channel.SendMessageAsync(socketMessage.Content);
}

Upvotes: 0

Related Questions