public DiscordClient() { _commands = new SlashCommandService(); _services = new ServiceCollection() .AddSingleton(socketClient) .AddSingleton(_commands) .BuildServiceProvider(); socketClient.Log += SocketClient_Log; _commands.Log += SocketClient_Log; socketClient.InteractionCreated += InteractionHandler; socketClient.Ready += RegisterCommand; // This is for dev purposes. // To avoid the situation in which you accidentally push your bot token to upstream, you can use // EnviromentVariables to store your key. botToken = Environment.GetEnvironmentVariable("DiscordSlashCommandsBotToken", EnvironmentVariableTarget.User); // Uncomment the next line of code to set the environment variable. // ------------------------------------------------------------------ // | WARNING! | // | | // | MAKE SURE TO DELETE YOUR TOKEN AFTER YOU HAVE SET THE VARIABLE | // | | // ------------------------------------------------------------------ //Environment.SetEnvironmentVariable("DiscordSlashCommandsBotToken", // "[YOUR TOKEN GOES HERE DELETE & COMMENT AFTER USE]", // EnvironmentVariableTarget.User); }
private static object GetMember(SlashCommandService commands, IServiceProvider services, Type memberType, TypeInfo ownerType) { if (memberType == typeof(SlashCommandService)) { return(commands); } if (memberType == typeof(IServiceProvider) || memberType == services.GetType()) { return(services); } var service = services.GetService(memberType); if (service != null) { return(service); } throw new InvalidOperationException($"Failed to create \"{ownerType.FullName}\", dependency \"{memberType.Name}\" was not found."); }
internal static Func <IServiceProvider, T> CreateBuilder <T>(TypeInfo typeInfo, SlashCommandService commands) { var constructor = GetConstructor(typeInfo); var parameters = constructor.GetParameters(); var properties = GetProperties(typeInfo); return((services) => { var args = new object[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { args[i] = GetMember(commands, services, parameters[i].ParameterType, typeInfo); } var obj = InvokeConstructor <T>(constructor, args, typeInfo); foreach (var property in properties) { property.SetValue(obj, GetMember(commands, services, property.PropertyType, typeInfo)); } return obj; }); }
internal static T CreateObject <T>(TypeInfo typeInfo, SlashCommandService commands, IServiceProvider services = null) => CreateBuilder <T>(typeInfo, commands)(services);