简体   繁体   中英

How to fix "cannot convert from 'bool' to 'string'" error?

i'm trying to mod an existing discord bot, and i'm getting this error when i try to run it. I'm trying to make one exception when it verifies if the message was sent from a bot or not.

private async Task MessageReceivedHandler(SocketMessage msg)
        {
            try
            {

                if (msg.Author.IsBot || !_bot.Ready.Task.IsCompleted) //no bots, wait until bot connected and initialized
                throw new ArgumentNullException(msg.Author.Id == 1234)
                    return;

                if (!(msg is SocketUserMessage usrMsg))
                    return;

#if !GLOBAL_NADEKO
                // track how many messagges each user is sending
                UserMessagesSent.AddOrUpdate(usrMsg.Author.Id, 1, (key, old) => ++old);
#endif

                var channel = msg.Channel as ISocketMessageChannel;
                var guild = (msg.Channel as SocketTextChannel)?.Guild;

                await TryRunCommand(guild, channel, usrMsg).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                _log.Warn("Error in CommandHandler");
                _log.Warn(ex);
                if (ex.InnerException != null)
                {
                    _log.Warn("Inner Exception of the error in CommandHandler");
                    _log.Warn(ex.InnerException);
                }
            }
        }```

You have a couple issues.

First:

throw new ArgumentNullException(msg.Author.Id == 1234)

The constructor for ArgumentNullException takes a string that is supposed to be "The name of the parameter that caused the exception". You are giving it a bool .

But you only have one argument, and by this line you already know it's not null. So maybe just ArgumentException is more appropriate, and write a sentence that describes why the argument is not acceptable.

Second, I don't think this does what you think it does:

if (msg.Author.IsBot || !_bot.Ready.Task.IsCompleted) //no bots, wait until bot connected and initialized
throw new ArgumentNullException(msg.Author.Id == 1234)
    return;

If an if statement is not followed by { } , then only the one next line is considered part of the conditional code. (this is true of for , foreach , etc. - read more about "embedded statements" here )

In other words, this is the equivalent to what you have:

if (msg.Author.IsBot || !_bot.Ready.Task.IsCompleted) {
    throw new ArgumentNullException(msg.Author.Id == 1234)
}
return;

It will either throw an exception, or return. All the code after the return will never be reached. I don't think that's what you want.

This is one reason I always use braces around single-line code blocks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM