【问题标题】:Discord.NET 1.0 How to Put Commands Into a New .cs FileDiscord.NET 1.0 如何将命令放入新的 .cs 文件中
【发布时间】:2018-06-04 18:58:32
【问题描述】:

我正在尝试将我的所有命令放入他们自己的 .cs 文件中的类中。它使文件混乱,因为启动和命令在同一个文件上。似乎大多数其他人从一开始就有这个,但我不是其中之一。这是我现在拥有的:

启动:

using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Diagnostics;

using Discord;
using Discord.WebSocket;
using Discord.Commands;

using Microsoft.Extensions.DependencyInjection;

namespace LockBot__1._0_
{

    public class Program
    {
        private CommandService _commands;
        private DiscordSocketClient _client;
        private IServiceProvider _services;

        public static void Main(string[] args)
            => new Program().StartAsync().GetAwaiter().GetResult();

        public async Task StartAsync()
        {
            _client = new DiscordSocketClient();
            _commands = new CommandService();

            _services = new ServiceCollection()
                .AddSingleton(_client)
                .AddSingleton(_commands)
                .BuildServiceProvider();

            await InstallCommandsAsync();

            string token = "SomeToken";
            await _client.LoginAsync(TokenType.Bot, token);
            await _client.StartAsync();

            await Task.Delay(-1);
        }

        public async Task InstallCommandsAsync()
        {
            _client.Ready += SetGamePlayAsync;
            _client.MessageReceived += HandleCommandAsync;
            await _commands.AddModulesAsync(Assembly.GetEntryAssembly());
        }

        private async Task HandleCommandAsync(SocketMessage messageParam)
        {
            var message = messageParam as SocketUserMessage;
            if (message == null) return;

            int argPos = 0;
            if (!(message.HasCharPrefix('~', ref argPos) || message.HasMentionPrefix(_client.CurrentUser, ref argPos))) return;

            var context = new SocketCommandContext(_client, message);

            var result = await _commands.ExecuteAsync(context, argPos, _services);
            if (!result.IsSuccess)
                await context.Channel.SendMessageAsync(result.ErrorReason);
        }

        public async Task SetGamePlayAsync()
        {
            await _client.SetGameAsync("locksteel.me | ~help");
        }
    }

命令(缩短):

    [Name("Miscellaneous")]
    public class Misc : ModuleBase<SocketCommandContext>
    {
        Random rand = new Random();

        [Command("flip")]
        [Name("flip")]
        [Summary("Flips a coin.")]
        [Alias("coin", "coinflip")]
        public async Task FlipAsync()
        {
            string flipToSend;
            int flip = rand.Next(1, 3);
            if ((flip == 1) && !(flip == 2))
            {
                flipToSend = "Heads.";
            }
            else if ((flip == 2) && !(flip == 1))
            {
                flipToSend = "Tails.";
            }
            else
            {
                Debug.WriteLine("~flip error: error establishing random number");
                return;
            }
            await Context.Channel.SendMessageAsync(flipToSend);
            Debug.WriteLine("~flip executed successfully in " + Context.Guild.Name);
        }
    }

注意:我对编码还是很陌生,对 Discord 机器人制作更是陌生,所以请记住这一点。

【问题讨论】:

    标签: c# command discord discord.net


    【解决方案1】:

    在我的 program.cs 中,我与您相似:

    using Discord;
    using Discord.Commands;
    using Discord.WebSocket;
    using Microsoft.Extensions.DependencyInjection;
    using System;
    using System.Reflection;
    using System.Threading.Tasks;
    
    namespace Discordbot_Techxas
    {
        class Program
        {
            static void Main(string[] args) => new Program().RunBotAsync().GetAwaiter().GetResult();
    
            private DiscordSocketClient _client;
            private CommandService _commands;
            private IServiceProvider _services;
    
            public async Task RunBotAsync()
            {
                _client = new DiscordSocketClient();
                _commands = new CommandService();
    
                _services = new ServiceCollection()
                    .AddSingleton(_client)
                    .AddSingleton(_commands)
                    .BuildServiceProvider();
                //You need to add the Token for your Discord Bot to the code below.
                string botToken = "YOUR CODE HERE";
    
                //event subscriptions
                _client.Log += Log;
                _client.UserJoined += AnnounceUserJoined;
    
                await RegisterCommandsAsync();
    
                await _client.LoginAsync(TokenType.Bot, botToken);
    
                await _client.StartAsync();
    
                await Task.Delay(-1);
            }
    
            private async Task AnnounceUserJoined(SocketGuildUser user)
            {
                var guild = user.Guild;
                var channel = guild.DefaultChannel;
                await channel.SendMessageAsync($"Welcome, {user.Mention}");
            }
    
            private Task Log(LogMessage arg)
            {
                Console.WriteLine(arg);
    
                return Task.CompletedTask;
            }
    
            public async Task RegisterCommandsAsync()
            {
                _client.MessageReceived += HandleCommandAsync;
    
                await _commands.AddModulesAsync(Assembly.GetEntryAssembly());
            }
    
            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) || 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);
                }
            }
        }
    }
    

    然后我的每一个命令文件都被激活,如果基于以下。所以 !ping 去:

    using Discord;
    using Discord.Commands;
    using System.Threading.Tasks;
    
    namespace Discordbot_Techxas.Modules
    {
        public class Ping : ModuleBase<SocketCommandContext>
        {
            [Command("ping")]
            public async Task PingAsync()
            {
                EmbedBuilder builder = new EmbedBuilder();
    
                builder.WithTitle("Ping!")
                    .WithDescription($"PONG back to you {Context.User.Mention} (This will be a never ending game of Ping/Pong)")
                    .WithColor(Color.DarkRed);
    
                await ReplyAsync("", false, builder.Build());
            }
        }
    }
    

    之后,我只需在我的模块文件夹中为我想要调整的每个命令创建一个新的类项。我是新手,也在学习。但是你可以在https://github.com/Thanory/Discordbot_Techxas 看到我正在创建的沙盒机器人和我用来到达那里的资源:

    【讨论】:

      猜你喜欢
      • 2014-04-21
      • 2019-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-14
      • 2021-08-20
      • 2021-01-24
      • 2017-09-20
      相关资源
      最近更新 更多