Discord.NET:Bot没有处理输入

时间:2018-03-28 18:23:35

标签: c# discord discord.net

我试图做出警告"对于采用SocketGuildUser参数的bot的命令,将警告int加1。但是,当我尝试为SocketGuildUser输入用户@mention时,它应该有效,会抛出异常。

[Command("warn")]
    public async Task WarnUser(SocketGuildUser user)
    {
        string warningDirectory = @"D:\HumbleBot\HumbleBot\Warnings";
        string warningText = @"D:\HumbleBot\HumbleBot\Warnings\warnings.json";

        if (!Directory.Exists(warningDirectory))
            Directory.CreateDirectory(warningDirectory);

        Dictionary<ulong, uint> UserWarnings = new Dictionary<ulong, uint>();
        UserWarnings = JsonConvert.DeserializeObject
                       <Dictionary<ulong, uint>>
                       (File.ReadAllText(warningText));

        if (!UserWarnings.ContainsKey(id)) //Exception thrown here
            UserWarnings.Add(id, 0);

        UserWarnings.TryGetValue(id, out uint warningNum);
        UserWarnings[id] = warningNum++;

        string json = JsonConvert.SerializeObject(UserWarnings);
        File.WriteAllText(warningText, json);
        //builder
    }

输入:〜警告@ Stratus#6727 输出(在控制台中):对象引用未设置为对象的实例。

编辑:添加了剩下的代码;事实证明它与此有关而不是我所添加的内容。它可能与文件读/写有关,或者我以错误的方式使用JsonConvert。

2 个答案:

答案 0 :(得分:0)

如果我没记错的话,参数SocketGuildUser有点挑剔。你可能想试试这个:

public async Task WarnPlayer(SocketUser u)
{
    SocketGuildUser user = (SocketGuildUser)u;

答案 1 :(得分:0)

在我的SLN中,SocketUser工作正常,如果没有用户被标记,也许你也应该抓住它(为你添加默认值)

    [Command("warn")]
    public async Task WarnPlayer(SocketUser user = null)
    {
        if (user != null)
        {

        Dictionary<string, uint> PlayerWarnings = JsonConvert
            .DeserializeObject<Dictionary<string, uint>>(File.ReadAllText(warningText));

        PlayerWarnings.Add(user.Username, 1);

        PlayerWarnings.TryGetValue(user.Username, out uint warningNum);

        EmbedBuilder builder = new EmbedBuilder();

        builder.WithDescription
                ($"{user.Username} has been given a warning. They now have {warningNum}")
            .WithColor(Color.Gold)
            .WithThumbnailUrl(user.GetAvatarUrl());

        await ReplyAsync("", false, builder.Build());
        }
        else
        {
            EmbedBuilder builder = new EmbedBuilder();

            builder.WithDescription
                    ($"Please select a user to warn.")
                .WithColor(Color.Red)
                .WithThumbnailUrl(user.GetAvatarUrl());

            await ReplyAsync("", false, builder.Build());
        }
    }

编辑:也许您还想将user.Username更改为user.DiscordId,因为我认为可以更改用户名。