【发布时间】:2021-08-20 02:25:39
【问题描述】:
所以我想我知道可能是什么问题,但我不确定如何解决它。我对 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 类。我不知道这是否是问题所在,如果是,我不知道我需要做什么。
【问题讨论】:
-
My thought is that I'm not calling and using the CommandHandler class anywhere...是的,这是你的问题。鉴于您假设不调用它是一个问题,唯一明显的解决方案就是调用它。只需创建 CommandHandler 的新实例并调用它的 Install 方法 -
@Anu6is 老实说,我不确定我应该把它放在哪里或任何东西。就像我说的我对 C# 很陌生。我知道如何创建类的实例,但我必须输入参数,但我不确定要输入什么。我尝试了客户端和命令,但出现错误。
-
为什么不看看 repo 中的例子呢? github.com/discord-net/Discord.Net/tree/dev/samples/…
标签: c# discord discord.net