【发布时间】: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