如何让我的命令在Discord.Net中工作



所以我想我知道可能是什么问题,但我不确定如何解决它。我对C#编码很陌生。我已经在node中编码Discord机器人一年多了,所以切换有点困难。我按照Discord.NET文档和指南中的说明进行操作。这是程序文件中的代码

using System;
using System.Threading.Tasks;
using Discord;
using Discord.WebSocket;
namespace GalacticBot
{
class MainClass
{
public static void Main(string[] args) => new MainClass().MainAsync().GetAwaiter().GetResult();
private DiscordSocketClient client;
// Calls the class holding information
private Config config = new Config();
public async Task MainAsync()
{
client = new DiscordSocketClient();
// Logs to console
client.Log += Log;
// Uses the token to start the bot
await client.LoginAsync(TokenType.Bot, config.TestToken);
await client.StartAsync();
await Task.Delay(-1);
}
private Task Log(LogMessage msg)
{
Console.WriteLine(msg.ToString());
return Task.CompletedTask;
}
}
}

这是CommandHandler文件中的代码

using System;
using System.Reflection;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
namespace GalacticBot
{
public class CommandHandler
{
private readonly DiscordSocketClient client;
private readonly CommandService commands;
private readonly Config config = new Config();
public CommandHandler(DiscordSocketClient _client, CommandService _commands)
{
client = _client;
commands = _commands;
}
public async Task InstallCommandsAsync()
{
client.MessageReceived += HandleCommandAsync;
await commands.AddModulesAsync(assembly: Assembly.GetEntryAssembly(), services: null);
}
private async Task HandleCommandAsync(SocketMessage MessageParam)
{
var message = MessageParam as SocketUserMessage;
if (message == null) return;
int ArgPos = 0;
// If there's no prefix or the message is from a bot then nothing happens
if (!(message.HasCharPrefix('!', ref ArgPos) || message.HasMentionPrefix(client.CurrentUser, ref ArgPos)) || message.Author.IsBot) return;
var context = new SocketCommandContext(client, message);
await commands.ExecuteAsync(
context: context,
argPos: ArgPos,
services: null
);
}
}
}

这是命令本身的代码

using System;
using System.Threading.Tasks;
using Discord.Commands;
public class Hi : ModuleBase<SocketCommandContext>
{
[Command("hey")]
[Summary("Just says hi.")]
public async Task SayAsync()
{
Console.WriteLine("Command used");
await Context.Channel.SendMessageAsync("Just saying hi!");
}
}

命令中的Console.WriteLine用于测试目的,看看它是否正在尝试工作。我的想法是,我不会在任何地方调用和使用CommandHandler类。我不知道这是不是问题所在,如果是,我不知道我需要做什么。

经过更多的谷歌搜索和尝试了许多不同的想法,我终于找到了解决方案。Anu6is的正确之处在于,您必须创建一个新实例并调用install方法。这导致在启动bot时返回null

private static DiscordSocketClient _client;
private static CommandService _commands;
private CommandHandler commandHandler;

在MainAsync中,我必须创建CommandService的一个新实例,一个传递_client和_commands的命令处理程序的新实例,然后调用InstallCommandsAsync方法

_commands = new CommandService();
commandHandler = new CommandHandler(_client, _commands);
await commandHandler.InstallCommandsAsync();

更改后,构建成功,没有任何警告,测试命令也起作用。希望这能在某个时候帮助到其他人。

相关内容

  • 没有找到相关文章

最新更新