Discord.net:为什么我的 discord 命令根本无法被识别?
2020-11-27
2654
我正在 discord.net 中编写 discord 机器人,但在命令运行方面遇到了麻烦,我的错误处理程序发现这是一个未知命令。有什么想法吗?
这些是我的脚本:
命令处理程序:
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");
}
}
}
如能得到帮助,我们将不胜感激,谢谢!
PS:如果您需要更多文件,请告诉我。我使用这个视频作为参考, https://www.youtube.com/watch?v=uOV1rg_ecMo&t=6s
2个回答
模块类需要公开,以便 Discord.NET 能够拾取它们。
尝试将
class GeneralCommands : ModuleBase
更改为
public class GeneralCommands : ModuleBase
marens101
2020-12-17
我尝试将您的代码与我的代码进行比较,我注意到您的代码中缺少
_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();
}
}
Cuppyzh
2020-11-28