我正在discord.net中编写一个discordbot,并且在获取命令时遇到问题,我的错误处理程序发现这是一个未知命令。有什么想法吗
这些是我的脚本:
命令处理程序:
using System;
using System.Collections.Generic;
using System.Text;
using Discord.Commands;
using Discord.WebSocket;
using Microsoft.Extensions.Configuration;
using System.Threading.Tasks;
using Discord;
using System.Reflection;
namespace fucking_kill_me.Services
{
public class CommandHandler
{
public static IServiceProvider _provider;
public static DiscordSocketClient _discord;
public static CommandService _commands;
public static IConfigurationRoot _config;
public CommandHandler(DiscordSocketClient discord, CommandService commands, IConfigurationRoot config, IServiceProvider provider)
{
_provider = provider;
_config = config;
_discord = discord;
_commands = commands;
_discord.Ready += OnReady;
_discord.MessageReceived += OnMessageReceived;
}
private async Task OnMessageReceived(SocketMessage arg)
{
var msg = arg as SocketUserMessage;
if (msg.Author.IsBot) return;
var context = new SocketCommandContext(_discord, msg);
int pos = 0;
if(msg.HasStringPrefix(_config["prefix"], ref pos) || msg.HasMentionPrefix(_discord.CurrentUser, ref pos))
{
var result = await _commands.ExecuteAsync(context, pos, _provider);
if (!result.IsSuccess)
{
var reason = result.Error;
await context.Channel.SendMessageAsync($"The following error occured: n{reason}");
Console.WriteLine(reason);
}
}
}
private Task OnReady()
{
Console.WriteLine($"Logged into {_discord.CurrentUser.Username}#{_discord.CurrentUser.Discriminator}");
return Task.CompletedTask;
}
}
}
命令:
using Discord.Commands;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace fucking_kill_me.Modules
{
class GeneralCommands : ModuleBase
{
[Command("ping")]
public async Task Ping()
{
await Context.Channel.SendMessageAsync("PongBama");
}
}
}
非常感谢您的帮助,谢谢
附言:如果你需要更多的文件,请告诉我。我用这个视频作为参考,https://www.youtube.com/watch?v=uOV1rg_ecMo&t=6s
模块类需要是公共的,Discord.NET才能获取它们。
尝试将class GeneralCommands : ModuleBase
更改为public class GeneralCommands : ModuleBase
我试图将您的代码与我的代码进行比较,我注意到您的代码中缺少_commands.AddModulesAsync
。
因此,在我的代码中,我将GeneralCommands
添加到服务集合中,并将其添加到_commands.AddModulesAsync
中。
这是的样子
private readonly ServiceProvider _serviceProvider = ServiceProviderUtilities.ConfigureServices();
public async Task MainAsync{
...
await _commandService.AddModulesAsync(Assembly.GetEntryAssembly(), _serviceProvider);
...
_client.MessageReceived += MessageReceivedAsync;
...
}
public class ServiceProviderUtilities
{
public static ServiceProvider ConfigureServices()
{
return new ServiceCollection()
.AddSingleton<GeneralCommands>()
.BuildServiceProvider();
}
}