我正在开发一个C#discord bot,我已经成功让机器人响应以" c开头的短语! "并使用正确的命令进行响应,但是如果提到机器人,我希望机器人使用GIF进行回复。如果有人可以帮助解释为什么这不起作用以及如何解决它会很好。这是我现在的代码:
private async Task HandleCommandAsync(SocketMessage arg)
{
var message = arg as SocketUserMessage;
if (message is null || message.Author.IsBot) return;
int argPos = 0;
if (message.HasStringPrefix("", ref argPos))
{
var context = new SocketCommandContext(_client, message);
var result = await _commands.ExecuteAsync(context, argPos, _services);
if (!result.IsSuccess)
Console.WriteLine(result.ErrorReason);
}
if (message.HasMentionPrefix(_client.CurrentUser, ref argPos))
{
var embed = new EmbedBuilder();
embed.WithImageUrl("https://cdn.discordapp.com/attachments/138522037181349888/438774275546152960/Ping_Discordapp_GIF-downsized_large.gif");
await ReplyAsync("", false, embed.Build());
}
答案 0 :(得分:0)
最好创建一个Modules文件夹,并在单独的.cs文件中添加命令。为此,您需要在启动_client之后但在调用LoginAsync之前添加此行代码。
_client.MessageReceived += HandleCommandAsync;
await _commands.AddModulesAsync(Assembly.GetEntryAssembly());
然后,创建一个单独的新类。您的命令可以接受SocketGuildUser作为参数。在聊天类型!help @name中调用命令:
public class Help : ModuleBase<SocketCommandContext>
{
[Command("help")]
public async Task HelpAsync(SocketGuildUser user)
{
await ReplyAsync($"{user.Mention} needs a lot of help!");
}
}
你的HandleCommandAsync应如下所示:
private async Task HandleCommandAsync(SocketMessage arg)
{
var message = arg as SocketUserMessage;
if (message == null || message.Author.IsBot) return;
int argPos = 0;
if (message.HasStringPrefix("!", ref argPos) ||
message.HasMentionPrefix(_client.CurrentUser, ref argPos))
{
var context = new SocketCommandContext(_client, message);
var result = await _commands.ExecuteAsync(context, argPos, _services);
if (!result.IsSuccess)
{
Console.WriteLine(result.ErrorReason);
}
}
}
答案 1 :(得分:0)
我同意Solarcloud所说的关于分离模块的内容,但这是您必须修改代码的全部内容:
private async Task HandleCommandAsync(SocketMessage arg)
{
var message = arg as SocketUserMessage;
if (message is null || message.Author.IsBot) return;
int argPos = 0;
if (message.HasStringPrefix("", ref argPos))
{
var context = new SocketCommandContext(_client, message);
var result = await _commands.ExecuteAsync(context, argPos, _services);
if (!result.IsSuccess)
Console.WriteLine(result.ErrorReason);
}
if (message.content.contains(_client.CurrentUser.Mention.Replace("!", "")))
{
var embed = new EmbedBuilder();
embed.WithImageUrl("https://cdn.discordapp.com/attachments/138522037181349888/438774275546152960/Ping_Discordapp_GIF-downsized_large.gif");
await ReplyAsync("", false, embed.Build());
}
替换以防万一您的机器人ID返回@<!123456789>
,摆脱它可以正常工作。