public StartupService(DiscordSocketClient client, IConfigurationRoot config, Discord.Commands.CommandService commands, IServiceProvider provider) { _client = client; _config = config; _commands = commands; _provider = provider; }
public async Task RunAsync(params string[] args) { _log = LogManager.GetCurrentClassLogger(); _log.Info("Starting NadekoBot v" + StatsService.BotVersion); //create client Client = new ShardedDiscordClient(new DiscordSocketConfig { AudioMode = Discord.Audio.AudioMode.Outgoing, MessageCacheSize = 10, LogLevel = LogSeverity.Warning, TotalShards = Credentials.TotalShards, ConnectionTimeout = int.MaxValue }); //initialize Services CommandService = new CommandService(); Localizer = new Localization(); Google = new GoogleApiService(); CommandHandler = new CommandHandler(Client, CommandService); Stats = new StatsService(Client, CommandHandler); //setup DI var depMap = new DependencyMap(); depMap.Add<ILocalization>(Localizer); depMap.Add<ShardedDiscordClient>(Client); depMap.Add<CommandService>(CommandService); depMap.Add<IGoogleApiService>(Google); //setup typereaders CommandService.AddTypeReader<PermissionAction>(new PermissionActionTypeReader()); CommandService.AddTypeReader<Command>(new CommandTypeReader()); CommandService.AddTypeReader<Module>(new ModuleTypeReader()); CommandService.AddTypeReader<IGuild>(new GuildTypeReader()); //connect await Client.LoginAsync(TokenType.Bot, Credentials.Token).ConfigureAwait(false); await Client.ConnectAsync().ConfigureAwait(false); await Client.DownloadAllUsersAsync().ConfigureAwait(false); _log.Info("Connected"); //load commands and prefixes using (var uow = DbHandler.UnitOfWork()) { ModulePrefixes = new ConcurrentDictionary<string, string>(uow.BotConfig.GetOrCreate().ModulePrefixes.ToDictionary(m => m.ModuleName, m => m.Prefix)); } // start handling messages received in commandhandler await CommandHandler.StartHandling().ConfigureAwait(false); await CommandService.LoadAssembly(this.GetType().GetTypeInfo().Assembly, depMap).ConfigureAwait(false); #if !GLOBAL_NADEKO await CommandService.Load(new Music(Localizer, CommandService, Client, Google)).ConfigureAwait(false); #endif Ready = true; Console.WriteLine(await Stats.Print().ConfigureAwait(false)); }
public CommandHandler(DiscordSocketClient client, Discord.Commands.CommandService commands, IServiceProvider provider) { _client = client; _commands = commands; _provider = provider; _client.MessageReceived += ClientOnMessageReceived; }
public StatsCollector(CommandService service) { this._service = service; _service.RanCommand += StatsCollector_RanCommand; //NadekoBot.client.MessageReceived += Client_MessageReceived; StartCollecting(); }
public Music(ILocalization loc, CommandService cmds, ShardedDiscordClient client, IGoogleApiService google) : base(loc, cmds, client) { //it can fail if its currenctly opened or doesn't exist. Either way i don't care try { Directory.Delete(MusicDataPath, true); } catch { } Directory.CreateDirectory(MusicDataPath); _google = google; }
public StatsCollector(CommandService service) { this._service = service; _service.CommandExecuted += StatsCollector_RanCommand; //NadekoBot.client.MessageReceived += Client_MessageReceived; StartCollecting(); Console.WriteLine("Logging enabled."); }
public Gambling(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client) { using (var uow = DbHandler.UnitOfWork()) { var conf = uow.BotConfig.GetOrCreate(); CurrencyName = conf.CurrencyName; CurrencySign = conf.CurrencySign; CurrencyPluralName = conf.CurrencyPluralName; } }
private NadekoStats() { _service = NadekoBot.client.Commands(); _client = NadekoBot.client; _statsSW = new Stopwatch(); _statsSW.Start(); _service.CommandExecuted += StatsCollector_RanCommand; StartCollecting(); Console.WriteLine("Logging enabled."); }
public DiscordModule(ILocalization loc, CommandService cmds, ShardedDiscordClient client) { string prefix; if (NadekoBot.ModulePrefixes.TryGetValue(this.GetType().Name, out prefix)) _prefix = prefix; else _prefix = "?missing_prefix?"; _l = loc; _commands = cmds; _client = client; _log = LogManager.GetCurrentClassLogger(); }
internal CommandBuilder(CommandService service, Command command, string prefix = "", string category = "", IEnumerable<IPermissionChecker> initialChecks = null) { _service = service; _command = command; _command.Category = category; _params = new List<CommandParameter>(); if (initialChecks != null) _checks = new List<IPermissionChecker>(initialChecks); else _checks = new List<IPermissionChecker>(); _prefix = prefix; _aliases = new List<string>(); _allowRequiredParams = true; _areParamsClosed = false; }
public CustomReactions(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client) { }
internal static Func <IServiceProvider, T> CreateBuilder <T>(TypeInfo typeInfo, CommandService commands) { ConstructorInfo constructor = GetConstructor(typeInfo); System.Reflection.ParameterInfo[] parameters = constructor.GetParameters(); PropertyInfo[] properties = GetProperties(typeInfo); return((services) => { object[] args = new object[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { args[i] = GetMember(commands, services, parameters[i].ParameterType, typeInfo); } T obj = InvokeConstructor <T>(constructor, args, typeInfo); foreach (PropertyInfo property in properties) { property.SetValue(obj, GetMember(commands, services, property.PropertyType, typeInfo)); } return obj; }); }
static void Main() { //load credentials from credentials.json bool loadTrello = false; try { creds = JsonConvert.DeserializeObject<Credentials>(File.ReadAllText("credentials.json")); botMention = creds.BotMention; if (string.IsNullOrWhiteSpace(creds.GoogleAPIKey)) { Console.WriteLine("No google api key found. You will not be able to use music and links won't be shortened."); } else { Console.WriteLine("Google API key provided."); GoogleAPIKey = creds.GoogleAPIKey; } if (string.IsNullOrWhiteSpace(creds.TrelloAppKey)) { Console.WriteLine("No trello appkey found. You will not be able to use trello commands."); } else { Console.WriteLine("Trello app key provided."); TrelloAppKey = creds.TrelloAppKey; loadTrello = true; } if (creds.ForwardMessages != true) Console.WriteLine("Not forwarding messages."); else { ForwardMessages = true; Console.WriteLine("Forwarding messages."); } if(string.IsNullOrWhiteSpace(creds.SoundCloudClientID)) Console.WriteLine("No soundcloud Client ID found. Soundcloud streaming is disabled."); else Console.WriteLine("SoundCloud streaming enabled."); OwnerID = creds.OwnerID; password = creds.Password; } catch (Exception ex) { Console.WriteLine($"Failed to load stuff from credentials.json, RTFM\n{ex.Message}"); Console.ReadKey(); return; } //create new discord client client = new DiscordClient(new DiscordConfigBuilder() { MessageCacheSize = 0, ConnectionTimeout = 60000, }); //create a command service var commandService = new CommandService(new CommandServiceConfigBuilder { AllowMentionPrefix = false, CustomPrefixHandler = m => 0, HelpMode = HelpMode.Disabled }); //reply to personal messages and forward if enabled. client.MessageReceived += Client_MessageReceived; //add command service var commands = client.Services.Add<CommandService>(commandService); //create module service var modules = client.Services.Add<ModuleService>(new ModuleService()); //add audio service var audio = client.Services.Add<AudioService>(new AudioService(new AudioServiceConfigBuilder() { Channels = 2, EnableEncryption = false, EnableMultiserver = true, Bitrate = 128, })); //install modules modules.Add(new Administration(), "Administration", ModuleFilter.None); modules.Add(new PermissionModule(), "Permissions", ModuleFilter.None); modules.Add(new Conversations(), "Conversations", ModuleFilter.None); modules.Add(new Gambling(), "Gambling", ModuleFilter.None); modules.Add(new Games(), "Games", ModuleFilter.None); modules.Add(new Music(), "Music", ModuleFilter.None); modules.Add(new Searches(), "Searches", ModuleFilter.None); if (loadTrello) modules.Add(new Trello(), "Trello", ModuleFilter.None); modules.Add(new NSFW(), "NSFW", ModuleFilter.None); //run the bot client.ExecuteAndWait(async () => { await client.Connect(creds.Username, creds.Password); Console.WriteLine("-----------------"); Console.WriteLine(NadekoStats.Instance.GetStats()); Console.WriteLine("-----------------"); try { OwnerPrivateChannel = await client.CreatePrivateChannel(OwnerID); } catch { Console.WriteLine("Failed creating private channel with the owner"); } Classes.Permissions.PermissionsHandler.Initialize(); client.ClientAPI.SendingRequest += (s, e) => { var request = e.Request as Discord.API.Client.Rest.SendMessageRequest; if (request != null) { if (string.IsNullOrWhiteSpace(request.Content)) e.Cancel = true; request.Content = request.Content.Replace("@everyone", "@everyοne"); } }; }); Console.WriteLine("Exiting..."); Console.ReadKey(); }
private static void BuildParameter(ParameterBuilder builder, System.Reflection.ParameterInfo paramInfo, int position, int count, CommandService service) { var attributes = paramInfo.GetCustomAttributes(); var paramType = paramInfo.ParameterType; builder.Name = paramInfo.Name; builder.IsOptional = paramInfo.IsOptional; builder.DefaultValue = paramInfo.HasDefaultValue ? paramInfo.DefaultValue : null; foreach (var attribute in attributes) { // TODO: C#7 type switch if (attribute is SummaryAttribute) { builder.Summary = (attribute as SummaryAttribute).Text; } else if (attribute is OverrideTypeReaderAttribute) { builder.TypeReader = GetTypeReader(service, paramType, (attribute as OverrideTypeReaderAttribute).TypeReader); } else if (attribute is ParameterPreconditionAttribute) { builder.AddPrecondition(attribute as ParameterPreconditionAttribute); } else if (attribute is ParamArrayAttribute) { builder.IsMultiple = true; paramType = paramType.GetElementType(); } else if (attribute is RemainderAttribute) { if (position != count - 1) { throw new InvalidOperationException("Remainder parameters must be the last parameter in a command."); } builder.IsRemainder = true; } } builder.ParameterType = paramType; if (builder.TypeReader == null) { var readers = service.GetTypeReaders(paramType); TypeReader reader = null; if (readers != null) { reader = readers.FirstOrDefault().Value; } else { reader = service.GetDefaultTypeReader(paramType); } builder.TypeReader = reader; } }
private static void BuildCommand(CommandBuilder builder, TypeInfo typeInfo, MethodInfo method, CommandService service, IServiceProvider serviceprovider) { var attributes = method.GetCustomAttributes(); foreach (var attribute in attributes) { switch (attribute) { case CommandAttribute command: builder.AddAliases(command.Text); builder.RunMode = command.RunMode; builder.Name = builder.Name ?? command.Text; break; case NameAttribute name: builder.Name = name.Text; break; case PriorityAttribute priority: builder.Priority = priority.Priority; break; case SummaryAttribute summary: builder.Summary = summary.Text; break; case RemarksAttribute remarks: builder.Remarks = remarks.Text; break; case AliasAttribute alias: builder.AddAliases(alias.Aliases); break; case PreconditionAttribute precondition: builder.AddPrecondition(precondition); break; default: builder.AddAttributes(attribute); break; } } if (builder.Name == null) { builder.Name = method.Name; } var parameters = method.GetParameters(); int pos = 0, count = parameters.Length; foreach (var paramInfo in parameters) { builder.AddParameter((parameter) => { BuildParameter(parameter, paramInfo, pos++, count, service, serviceprovider); }); } var createInstance = ReflectionUtils.CreateBuilder <IModuleBase>(typeInfo, service); async Task <IResult> ExecuteCallback(ICommandContext context, object[] args, IServiceProvider services, CommandInfo cmd) { var instance = createInstance(services); instance.SetContext(context); try { instance.BeforeExecute(cmd); var task = method.Invoke(instance, args) as Task ?? Task.Delay(0); if (task is Task <RuntimeResult> resultTask) { return(await resultTask.ConfigureAwait(false)); } else { await task.ConfigureAwait(false); return(ExecuteResult.FromSuccess()); } } finally { instance.AfterExecute(cmd); (instance as IDisposable)?.Dispose(); } } builder.Callback = ExecuteCallback; }
private static void BuildParameter(ParameterBuilder builder, System.Reflection.ParameterInfo paramInfo, int position, int count, CommandService service, IServiceProvider services) { var attributes = paramInfo.GetCustomAttributes(); var paramType = paramInfo.ParameterType; builder.Name = paramInfo.Name; builder.IsOptional = paramInfo.IsOptional; builder.DefaultValue = paramInfo.HasDefaultValue ? paramInfo.DefaultValue : null; foreach (var attribute in attributes) { switch (attribute) { case SummaryAttribute summary: builder.Summary = summary.Text; break; case OverrideTypeReaderAttribute typeReader: builder.TypeReader = GetTypeReader(service, paramType, typeReader.TypeReader, services); break; case ParamArrayAttribute _: builder.IsMultiple = true; paramType = paramType.GetElementType(); break; case ParameterPreconditionAttribute precon: builder.AddPrecondition(precon); break; case NameAttribute name: builder.Name = name.Text; break; case RemainderAttribute _: if (position != count - 1) { throw new InvalidOperationException($"Remainder parameters must be the last parameter in a command. Parameter: {paramInfo.Name} in {paramInfo.Member.DeclaringType.Name}.{paramInfo.Member.Name}"); } builder.IsRemainder = true; break; default: builder.AddAttributes(attribute); break; } } builder.ParameterType = paramType; if (builder.TypeReader == null) { builder.TypeReader = service.GetDefaultTypeReader(paramType) ?? service.GetTypeReaders(paramType)?.FirstOrDefault().Value; } }
private static void BuildModule(ModuleBuilder builder, TypeInfo typeInfo, CommandService service, IServiceProvider services) { var attributes = typeInfo.GetCustomAttributes(); builder.TypeInfo = typeInfo; foreach (var attribute in attributes) { switch (attribute) { case NameAttribute name: builder.Name = name.Text; break; case SummaryAttribute summary: builder.Summary = summary.Text; break; case RemarksAttribute remarks: builder.Remarks = remarks.Text; break; case AliasAttribute alias: builder.AddAliases(alias.Aliases); break; case GroupAttribute group: builder.Name = builder.Name ?? group.Prefix; builder.Group = group.Prefix; builder.AddAliases(group.Prefix); break; case PreconditionAttribute precondition: builder.AddPrecondition(precondition); break; default: builder.AddAttributes(attribute); break; } } //Check for unspecified info if (builder.Aliases.Count == 0) { builder.AddAliases(""); } if (builder.Name == null) { builder.Name = typeInfo.Name; } var validCommands = typeInfo.DeclaredMethods.Where(x => IsValidCommandDefinition(x)); foreach (var method in validCommands) { builder.AddCommand((command) => { BuildCommand(command, typeInfo, method, service, services); }); } }
public static async Task <IReadOnlyList <TypeInfo> > SearchAsync(Assembly assembly, CommandService service) { bool IsLoadableModule(TypeInfo info) { return(info.DeclaredMethods.Any(x => x.GetCustomAttribute <CommandAttribute>() != null) && info.GetCustomAttribute <DontAutoLoadAttribute>() == null); } var result = new List <TypeInfo>(); foreach (var typeInfo in assembly.DefinedTypes) { if (typeInfo.IsPublic || typeInfo.IsNestedPublic) { if (IsValidModuleDefinition(typeInfo) && !typeInfo.IsDefined(typeof(DontAutoLoadAttribute))) { result.Add(typeInfo); } } else if (IsLoadableModule(typeInfo)) { await service._cmdLogger.WarningAsync($"Class {typeInfo.FullName} is not public and cannot be loaded. To suppress this message, mark the class with {nameof(DontAutoLoadAttribute)}."); } } return(result); }
private static void BuildModule(ModuleBuilder builder, TypeInfo typeInfo, CommandService service, IServiceProvider services) { var attributes = typeInfo.GetCustomAttributes(); builder.TypeInfo = typeInfo; foreach (var attribute in attributes) { switch (attribute) { case NameAttribute name: builder.Name = name.Text; break; case SummaryAttribute summary: builder.Summary = summary.Text; break; case RemarksAttribute remarks: builder.Remarks = remarks.Text; break; case AliasAttribute alias: builder.AddAliases(alias.Aliases); break; case GroupAttribute group: builder.Name = builder.Name ?? group.Prefix; builder.Group = group.Prefix; builder.AddAliases(group.Prefix); break; case PreconditionAttribute precondition: builder.AddPrecondition(precondition); break; default: builder.AddAttributes(attribute); break; } } //Check for unspecified info if (builder.Aliases.Count == 0) { builder.AddAliases(""); } if (builder.Name == null) { builder.Name = typeInfo.Name; } // Get all methods (including from inherited members), that are valid commands var validCommands = typeInfo.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(IsValidCommandDefinition); foreach (var method in validCommands) { builder.AddCommand((command) => { BuildCommand(command, typeInfo, method, service, services); }); } }
public static Dictionary <Type, ModuleInfo> Build(IEnumerable <TypeInfo> validTypes, CommandService service) { /*if (!validTypes.Any()) * throw new InvalidOperationException("Could not find any valid modules from the given selection");*/ var topLevelGroups = validTypes.Where(x => x.DeclaringType == null); var subGroups = validTypes.Intersect(topLevelGroups); var builtTypes = new List <TypeInfo>(); var result = new Dictionary <Type, ModuleInfo>(); foreach (var typeInfo in topLevelGroups) { // TODO: This shouldn't be the case; may be safe to remove? if (result.ContainsKey(typeInfo.AsType())) { continue; } var module = new ModuleBuilder(service, null); BuildModule(module, typeInfo, service); BuildSubTypes(module, typeInfo.DeclaredNestedTypes, builtTypes, service); result[typeInfo.AsType()] = module.Build(service); } return(result); }
public static Dictionary <Type, ModuleInfo> Build(CommandService service, params TypeInfo[] validTypes) => Build(validTypes, service);
public Administration(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client) { NadekoBot.CommandHandler.CommandExecuted += DelMsgOnCmd_Handler; }
public static Task <Dictionary <Type, ModuleInfo> > BuildAsync(CommandService service, IServiceProvider services, params TypeInfo[] validTypes) => BuildAsync(validTypes, service, services);
static void Main() { //load credentials from credentials.json bool loadTrello = false; try { creds = JsonConvert.DeserializeObject<Credentials>(File.ReadAllText("credentials.json")); botMention = creds.BotMention; if (string.IsNullOrWhiteSpace(creds.GoogleAPIKey)) { Console.WriteLine("No google api key found. You will not be able to use music and links won't be shortened."); } else { Console.WriteLine("Google API key provided."); GoogleAPIKey = creds.GoogleAPIKey; } if (string.IsNullOrWhiteSpace(creds.TrelloAppKey)) { Console.WriteLine("No trello appkey found. You will not be able to use trello commands."); } else { Console.WriteLine("Trello app key provided."); TrelloAppKey = creds.TrelloAppKey; loadTrello = true; } if (creds.ForwardMessages != true) Console.WriteLine("Not forwarding messages."); else { ForwardMessages = true; Console.WriteLine("Forwarding messages."); } if (string.IsNullOrWhiteSpace(creds.ParseID) || string.IsNullOrWhiteSpace(creds.ParseKey)) { Console.WriteLine("Parse key and/or ID not found. Those are mandatory."); ParseActive = false; } else ParseActive = true; if(string.IsNullOrWhiteSpace(creds.OsuApiKey)) Console.WriteLine("No osu API key found. Osu functionality is disabled."); else Console.WriteLine("Osu enabled."); if(string.IsNullOrWhiteSpace(creds.SoundCloudClientID)) Console.WriteLine("No soundcloud Client ID found. Soundcloud streaming is disabled."); else Console.WriteLine("SoundCloud streaming enabled."); //init parse if (ParseActive) try { ParseClient.Initialize(creds.ParseID, creds.ParseKey); } catch (Exception) { Console.WriteLine("Parse exception. Probably wrong parse credentials."); } OwnerID = creds.OwnerID; password = creds.Password; } catch (Exception ex) { Console.WriteLine($"Failed to load stuff from credentials.json, RTFM\n{ex.Message}"); Console.ReadKey(); return; } //create new discord client client = new DiscordClient(); //create a command service var commandService = new CommandService(new CommandServiceConfig { CommandChar = null, HelpMode = HelpMode.Disable }); //reply to personal messages and forward if enabled. client.MessageReceived += Client_MessageReceived; //add command service var commands = client.Services.Add<CommandService>(commandService); //create module service var modules = client.Services.Add<ModuleService>(new ModuleService()); //add audio service var audio = client.Services.Add<AudioService>(new AudioService(new AudioServiceConfig() { Channels = 2, EnableEncryption = false, EnableMultiserver = true, Bitrate = 128, })); //install modules modules.Add(new Administration(), "Administration", ModuleFilter.None); modules.Add(new Conversations(), "Conversations", ModuleFilter.None); modules.Add(new Gambling(), "Gambling", ModuleFilter.None); modules.Add(new Games(), "Games", ModuleFilter.None); modules.Add(new Music(), "Music", ModuleFilter.None); modules.Add(new Searches(), "Searches", ModuleFilter.None); if (loadTrello) modules.Add(new Trello(), "Trello", ModuleFilter.None); //run the bot client.ExecuteAndWait(async () => { await client.Connect(creds.Username, creds.Password); Console.WriteLine("-----------------"); Console.WriteLine(NadekoStats.Instance.GetStats()); Console.WriteLine("-----------------"); foreach (var serv in client.Servers) { if ((OwnerUser = serv.GetUser(OwnerID)) != null) return; } client.ClientAPI.SendingRequest += (s, e) => { var request = e.Request as Discord.API.Client.Rest.SendMessageRequest; if (request != null) { if (string.IsNullOrWhiteSpace(request.Content)) e.Cancel = true; } }; }); Console.WriteLine("Exiting..."); Console.ReadKey(); }
public NSFW(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client) { }
internal CommandGroupBuilder(CommandService service, string prefix, IEnumerable<IPermissionChecker> initialChecks = null) { _service = service; _prefix = prefix; if (initialChecks != null) _checks = new List<IPermissionChecker>(initialChecks); else _checks = new List<IPermissionChecker>(); }
public Bot(DiscordClient client, CommandService commandService, IBotServices botServices) { _client = client; _commandService = commandService; _botServices = botServices; }
public Searches(ILocalization loc, CommandService cmds, ShardedDiscordClient client, IGoogleApiService youtube) : base(loc, cmds, client) { _google = youtube; }
private static void BuildCommand(CommandBuilder builder, TypeInfo typeInfo, MethodInfo method, CommandService service) { var attributes = method.GetCustomAttributes(); foreach (var attribute in attributes) { // TODO: C#7 type switch if (attribute is CommandAttribute) { var cmdAttr = attribute as CommandAttribute; builder.AddAliases(cmdAttr.Text); builder.RunMode = cmdAttr.RunMode; builder.Name = builder.Name ?? cmdAttr.Text; } else if (attribute is NameAttribute) { builder.Name = (attribute as NameAttribute).Text; } else if (attribute is PriorityAttribute) { builder.Priority = (attribute as PriorityAttribute).Priority; } else if (attribute is SummaryAttribute) { builder.Summary = (attribute as SummaryAttribute).Text; } else if (attribute is RemarksAttribute) { builder.Remarks = (attribute as RemarksAttribute).Text; } else if (attribute is AliasAttribute) { builder.AddAliases((attribute as AliasAttribute).Aliases); } else if (attribute is PreconditionAttribute) { builder.AddPrecondition(attribute as PreconditionAttribute); } } if (builder.Name == null) { builder.Name = method.Name; } var parameters = method.GetParameters(); int pos = 0, count = parameters.Length; foreach (var paramInfo in parameters) { builder.AddParameter((parameter) => { BuildParameter(parameter, paramInfo, pos++, count, service); }); } var createInstance = ReflectionUtils.CreateBuilder <IModuleBase>(typeInfo, service); builder.Callback = (ctx, args, map) => { var instance = createInstance(map); instance.SetContext(ctx); try { instance.BeforeExecute(); return(method.Invoke(instance, args) as Task ?? Task.Delay(0)); } finally { instance.AfterExecute(); (instance as IDisposable)?.Dispose(); } }; }
private static void Main() { Console.OutputEncoding = Encoding.Unicode; //var lines = File.ReadAllLines("data/input.txt"); //HashSet<dynamic> list = new HashSet<dynamic>(); //for (int i = 0; i < lines.Length; i += 3) { // dynamic obj = new JArray(); // obj.Text = lines[i]; // obj.Author = lines[i + 1]; // if (obj.Author.StartsWith("-")) // obj.Author = obj.Author.Substring(1, obj.Author.Length - 1).Trim(); // list.Add(obj); //} //File.WriteAllText("data/quotes.json", Newtonsoft.Json.JsonConvert.SerializeObject(list, Formatting.Indented)); //Console.ReadKey(); // generate credentials example so people can know about the changes i make try { File.WriteAllText("data/config_example.json", JsonConvert.SerializeObject(new Configuration(), Formatting.Indented)); if (!File.Exists("data/config.json")) File.Copy("data/config_example.json", "data/config.json"); File.WriteAllText("credentials_example.json", JsonConvert.SerializeObject(new Credentials(), Formatting.Indented)); } catch { Console.WriteLine("Failed writing credentials_example.json or data/config_example.json"); } try { Config = JsonConvert.DeserializeObject<Configuration>(File.ReadAllText("data/config.json")); Config.Quotes = JsonConvert.DeserializeObject<List<Quote>>(File.ReadAllText("data/quotes.json")); Config.PokemonTypes = JsonConvert.DeserializeObject<List<PokemonType>>(File.ReadAllText("data/PokemonTypes.json")); } catch (Exception ex) { Console.WriteLine("Failed loading configuration."); Console.WriteLine(ex); Console.ReadKey(); return; } try { //load credentials from credentials.json Creds = JsonConvert.DeserializeObject<Credentials>(File.ReadAllText("credentials.json")); } catch (Exception ex) { Console.WriteLine($"Failed to load stuff from credentials.json, RTFM\n{ex.Message}"); Console.ReadKey(); return; } //if password is not entered, prompt for password if (string.IsNullOrWhiteSpace(Creds.Password) && string.IsNullOrWhiteSpace(Creds.Token)) { Console.WriteLine("Password blank. Please enter your password:\n"); Creds.Password = Console.ReadLine(); } Console.WriteLine(string.IsNullOrWhiteSpace(Creds.GoogleAPIKey) ? "No google api key found. You will not be able to use music and links won't be shortened." : "Google API key provided."); Console.WriteLine(string.IsNullOrWhiteSpace(Creds.TrelloAppKey) ? "No trello appkey found. You will not be able to use trello commands." : "Trello app key provided."); Console.WriteLine(Config.ForwardMessages != true ? "Not forwarding messages." : "Forwarding private messages to owner."); Console.WriteLine(string.IsNullOrWhiteSpace(Creds.SoundCloudClientID) ? "No soundcloud Client ID found. Soundcloud streaming is disabled." : "SoundCloud streaming enabled."); BotMention = $"<@{Creds.BotId}>"; //create new discord client and log Client = new DiscordClient(new DiscordConfigBuilder() { MessageCacheSize = 10, ConnectionTimeout = 120000, LogLevel = LogSeverity.Warning, LogHandler = (s, e) => Console.WriteLine($"Severity: {e.Severity}" + $"Message: {e.Message}" + $"ExceptionMessage: {e.Exception?.Message ?? "-"}"), }); //create a command service var commandService = new CommandService(new CommandServiceConfigBuilder { AllowMentionPrefix = false, CustomPrefixHandler = m => 0, HelpMode = HelpMode.Disabled, ErrorHandler = async (s, e) => { if (e.ErrorType != CommandErrorType.BadPermissions) return; if (string.IsNullOrWhiteSpace(e.Exception?.Message)) return; try { await e.Channel.SendMessage(e.Exception.Message).ConfigureAwait(false); } catch { } } }); //reply to personal messages and forward if enabled. Client.MessageReceived += Client_MessageReceived; //add command service Client.AddService<CommandService>(commandService); //create module service var modules = Client.AddService<ModuleService>(new ModuleService()); //add audio service Client.AddService<AudioService>(new AudioService(new AudioServiceConfigBuilder() { Channels = 2, EnableEncryption = false, Bitrate = 128, })); //install modules modules.Add(new AdministrationModule(), "Administration", ModuleFilter.None); modules.Add(new HelpModule(), "Help", ModuleFilter.None); modules.Add(new PermissionModule(), "Permissions", ModuleFilter.None); modules.Add(new Conversations(), "Conversations", ModuleFilter.None); modules.Add(new GamblingModule(), "Gambling", ModuleFilter.None); modules.Add(new GamesModule(), "Games", ModuleFilter.None); modules.Add(new MusicModule(), "Music", ModuleFilter.None); modules.Add(new SearchesModule(), "Searches", ModuleFilter.None); modules.Add(new NSFWModule(), "NSFW", ModuleFilter.None); modules.Add(new ClashOfClansModule(), "ClashOfClans", ModuleFilter.None); modules.Add(new PokemonModule(), "Pokegame", ModuleFilter.None); modules.Add(new TranslatorModule(), "Translator", ModuleFilter.None); if (!string.IsNullOrWhiteSpace(Creds.TrelloAppKey)) modules.Add(new TrelloModule(), "Trello", ModuleFilter.None); //run the bot Client.ExecuteAndWait(async () => { try { if (string.IsNullOrWhiteSpace(Creds.Token)) await Client.Connect(Creds.Username, Creds.Password).ConfigureAwait(false); else { await Client.Connect(Creds.Token).ConfigureAwait(false); IsBot = true; } Console.WriteLine(NadekoBot.Client.CurrentUser.Id); } catch (Exception ex) { if (string.IsNullOrWhiteSpace(Creds.Token)) Console.WriteLine($"Probably wrong EMAIL or PASSWORD."); else Console.WriteLine($"Token is wrong. Don't set a token if you don't have an official BOT account."); Console.WriteLine(ex); Console.ReadKey(); return; } //await Task.Delay(90000).ConfigureAwait(false); Console.WriteLine("-----------------"); Console.WriteLine(await NadekoStats.Instance.GetStats().ConfigureAwait(false)); Console.WriteLine("-----------------"); try { OwnerPrivateChannel = await Client.CreatePrivateChannel(Creds.OwnerIds[0]).ConfigureAwait(false); } catch { Console.WriteLine("Failed creating private channel with the first owner listed in credentials.json"); } Client.ClientAPI.SendingRequest += (s, e) => { var request = e.Request as Discord.API.Client.Rest.SendMessageRequest; if (request == null) return; // meew0 is magic request.Content = request.Content?.Replace("@everyone", "@everyοne").Replace("@here", "@һere") ?? "_error_"; if (string.IsNullOrWhiteSpace(request.Content)) e.Cancel = true; }; PermissionsHandler.Initialize(); NadekoBot.Ready = true; }); Console.WriteLine("Exiting..."); Console.ReadKey(); }
public NamedArgumentTypeReader(CommandService commands) { _commands = commands; }
private static void Main() { Console.OutputEncoding = Encoding.Unicode; try { File.WriteAllText("data/config_example.json", JsonConvert.SerializeObject(new Configuration(), Formatting.Indented)); if (!File.Exists("data/config.json")) File.Copy("data/config_example.json", "data/config.json"); File.WriteAllText("credentials_example.json", JsonConvert.SerializeObject(new Credentials(), Formatting.Indented)); } catch { Console.WriteLine("Failed writing credentials_example.json or data/config_example.json"); } try { Config = JsonConvert.DeserializeObject<Configuration>(File.ReadAllText("data/config.json")); Config.Quotes = JsonConvert.DeserializeObject<List<Quote>>(File.ReadAllText("data/quotes.json")); Config.PokemonTypes = JsonConvert.DeserializeObject<List<PokemonType>>(File.ReadAllText("data/PokemonTypes.json")); } catch (Exception ex) { Console.WriteLine("Failed loading configuration."); Console.WriteLine(ex); Console.ReadKey(); return; } try { //load credentials from credentials.json Creds = JsonConvert.DeserializeObject<Credentials>(File.ReadAllText("credentials.json")); } catch (Exception ex) { Console.WriteLine($"Failed to load stuff from credentials.json, RTFM\n{ex.Message}"); Console.ReadKey(); return; } //if password is not entered, prompt for password if (string.IsNullOrWhiteSpace(Creds.Token)) { Console.WriteLine("Token blank. Please enter your bot's token:\n"); Creds.Token = Console.ReadLine(); } Console.WriteLine(string.IsNullOrWhiteSpace(Creds.GoogleAPIKey) ? "No google api key found. You will not be able to use music and links won't be shortened." : "Google API key provided."); Console.WriteLine(string.IsNullOrWhiteSpace(Creds.TrelloAppKey) ? "No trello appkey found. You will not be able to use trello commands." : "Trello app key provided."); Console.WriteLine(Config.ForwardMessages != true ? "Not forwarding messages." : "Forwarding private messages to owner."); Console.WriteLine(string.IsNullOrWhiteSpace(Creds.SoundCloudClientID) ? "No soundcloud Client ID found. Soundcloud streaming is disabled." : "SoundCloud streaming enabled."); Console.WriteLine(string.IsNullOrWhiteSpace(Creds.OsuAPIKey) ? "No osu! api key found. Song & top score lookups will not work. User lookups still available." : "osu! API key provided."); Console.WriteLine(string.IsNullOrWhiteSpace(Creds.DerpiAPIKey) ? "No Derpiboori api key found. Only searches useing the Default filter will work." : "Derpiboori API key provided."); BotMention = $"<@{Creds.BotId}>"; //create new discord client and log Client = new DiscordClient(new DiscordConfigBuilder() { MessageCacheSize = 10, ConnectionTimeout = int.MaxValue, LogLevel = LogSeverity.Warning, LogHandler = (s, e) => Console.WriteLine($"Severity: {e.Severity}" + $"ExceptionMessage: {e.Exception?.Message ?? "-"}" + $"Message: {e.Message}"), }); //create a command service var commandService = new CommandService(new CommandServiceConfigBuilder { AllowMentionPrefix = false, CustomPrefixHandler = m => 0, HelpMode = HelpMode.Disabled, ErrorHandler = async (s, e) => { if (e.ErrorType != CommandErrorType.BadPermissions) return; if (string.IsNullOrWhiteSpace(e.Exception?.Message)) return; try { await e.Channel.SendMessage(e.Exception.Message).ConfigureAwait(false); } catch { } } }); //add command service Client.AddService<CommandService>(commandService); //create module service var modules = Client.AddService<ModuleService>(new ModuleService()); //add audio service Client.AddService<AudioService>(new AudioService(new AudioServiceConfigBuilder() { Channels = 2, EnableEncryption = false, Bitrate = 128, })); //install modules modules.Add(new HelpModule(), "Help", ModuleFilter.None); modules.Add(new AdministrationModule(), "Administration", ModuleFilter.None); modules.Add(new UtilityModule(), "Utility", ModuleFilter.None); modules.Add(new PermissionModule(), "Permissions", ModuleFilter.None); modules.Add(new Conversations(), "Conversations", ModuleFilter.None); modules.Add(new GamblingModule(), "Gambling", ModuleFilter.None); modules.Add(new GamesModule(), "Games", ModuleFilter.None); #if !NADEKO_RELEASE modules.Add(new MusicModule(), "Music", ModuleFilter.None); #endif modules.Add(new SearchesModule(), "Searches", ModuleFilter.None); modules.Add(new NSFWModule(), "NSFW", ModuleFilter.None); modules.Add(new ClashOfClansModule(), "ClashOfClans", ModuleFilter.None); modules.Add(new PokemonModule(), "Pokegame", ModuleFilter.None); modules.Add(new TranslatorModule(), "Translator", ModuleFilter.None); modules.Add(new CustomReactionsModule(), "Customreactions", ModuleFilter.None); if (!string.IsNullOrWhiteSpace(Creds.TrelloAppKey)) modules.Add(new TrelloModule(), "Trello", ModuleFilter.None); //run the bot Client.ExecuteAndWait(async () => { await Task.Run(() => { Console.WriteLine("Specific config started initializing."); var x = SpecificConfigurations.Default; Console.WriteLine("Specific config done initializing."); }); await PermissionsHandler.Initialize(); try { await Client.Connect(Creds.Token, TokenType.Bot).ConfigureAwait(false); } catch (Exception ex) { Console.WriteLine($"Token is wrong. Don't set a token if you don't have an official BOT account."); Console.WriteLine(ex); Console.ReadKey(); return; } #if NADEKO_RELEASE await Task.Delay(300000).ConfigureAwait(false); #else await Task.Delay(1000).ConfigureAwait(false); #endif Console.WriteLine("-----------------"); Console.WriteLine(await NadekoStats.Instance.GetStats().ConfigureAwait(false)); Console.WriteLine("-----------------"); OwnerPrivateChannels = new List<Channel>(Creds.OwnerIds.Length); foreach (var id in Creds.OwnerIds) { try { OwnerPrivateChannels.Add(await Client.CreatePrivateChannel(id).ConfigureAwait(false)); } catch { Console.WriteLine($"Failed creating private channel with the owner {id} listed in credentials.json"); } } Client.ClientAPI.SendingRequest += (s, e) => { var request = e.Request as Discord.API.Client.Rest.SendMessageRequest; if (request == null) return; // meew0 is magic request.Content = request.Content?.Replace("@everyone", "@everyοne").Replace("@here", "@һere") ?? "_error_"; if (string.IsNullOrWhiteSpace(request.Content)) e.Cancel = true; }; #if NADEKO_RELEASE Client.ClientAPI.SentRequest += (s, e) => { Console.WriteLine($"[Request of type {e.Request.GetType()} sent in {e.Milliseconds}]"); var request = e.Request as Discord.API.Client.Rest.SendMessageRequest; if (request == null) return; Console.WriteLine($"[Content: { request.Content }"); }; #endif NadekoBot.Ready = true; NadekoBot.OnReady(); Console.WriteLine("Ready!"); //reply to personal messages and forward if enabled. Client.MessageReceived += Client_MessageReceived; }); Console.WriteLine("Exiting..."); Console.ReadKey(); }
internal static T CreateObject <T>(TypeInfo typeInfo, CommandService commands, IServiceProvider services = null) => CreateBuilder <T>(typeInfo, commands)(services);
public static async Task <Dictionary <Type, ModuleInfo> > BuildAsync(IEnumerable <TypeInfo> validTypes, CommandService service, IServiceProvider services) { /*if (!validTypes.Any()) * throw new InvalidOperationException("Could not find any valid modules from the given selection");*/ var topLevelGroups = validTypes.Where(x => x.DeclaringType == null || !IsValidModuleDefinition(x.DeclaringType.GetTypeInfo())); var builtTypes = new List <TypeInfo>(); var result = new Dictionary <Type, ModuleInfo>(); foreach (var typeInfo in topLevelGroups) { // TODO: This shouldn't be the case; may be safe to remove? if (result.ContainsKey(typeInfo.AsType())) { continue; } var module = new ModuleBuilder(service, null); BuildModule(module, typeInfo, service, services); BuildSubTypes(module, typeInfo.DeclaredNestedTypes, builtTypes, service, services); builtTypes.Add(typeInfo); result[typeInfo.AsType()] = module.Build(service, services); } await service._cmdLogger.DebugAsync($"Successfully built {builtTypes.Count} modules.").ConfigureAwait(false); return(result); }
public static Task <IReadOnlyCollection <CommandInfo> > GetExecutableCommandsAsync(this CommandService commandService, ICommandContext context, IServiceProvider provider) => GetExecutableCommandsAsync(commandService.Commands.ToArray(), context, provider);
static void Main() { //load credentials from credentials.json Credentials c; try { c = JsonConvert.DeserializeObject<Credentials>(File.ReadAllText("credentials.json")); botMention = c.BotMention; if (c.GoogleAPIKey == null || c.GoogleAPIKey == "") { Console.WriteLine("No google api key found. You will not be able to use music and links won't be shortened."); } else { GoogleAPIKey = c.GoogleAPIKey; } OwnerID = c.OwnerID; password = c.Password; } catch (Exception) { Console.WriteLine("Failed to load stuff from credentials.json, RTFM"); Console.ReadKey(); return; } //create new discord client client = new DiscordClient(); //create a command service var commandService = new CommandService(new CommandServiceConfig { CommandChar = null, HelpMode = HelpMode.Disable }); //init parse if (c.ParseKey != null && c.ParseID != null && c.ParseID != "" && c.ParseKey != "") { ParseClient.Initialize(c.ParseID, c.ParseKey); //monitor commands for logging stats_collector = new StatsCollector(commandService); } else { Console.WriteLine("Parse key and/or ID not found. Bot will not log."); } //add command service var commands = client.Services.Add<CommandService>(commandService); //create module service var modules = client.Services.Add<ModuleService>(new ModuleService()); //add audio service var audio = client.Services.Add<AudioService>(new AudioService(new AudioServiceConfig() { Channels = 2, EnableEncryption = false })); //install modules modules.Install(new Administration(), "Administration", FilterType.Unrestricted); modules.Install(new Conversations(), "Conversations", FilterType.Unrestricted); modules.Install(new Gambling(), "Gambling", FilterType.Unrestricted); modules.Install(new Games(), "Games", FilterType.Unrestricted); modules.Install(new Music(), "Music", FilterType.Unrestricted); modules.Install(new Searches(), "Searches", FilterType.Unrestricted); //run the bot client.Run(async () => { await client.Connect(c.Username, c.Password); Console.WriteLine("Connected!"); }); Console.WriteLine("Exiting..."); Console.ReadKey(); }
private static void BuildSubTypes(ModuleBuilder builder, IEnumerable <TypeInfo> subTypes, List <TypeInfo> builtTypes, CommandService service, IServiceProvider services) { foreach (var typeInfo in subTypes) { if (!IsValidModuleDefinition(typeInfo)) { continue; } if (builtTypes.Contains(typeInfo)) { continue; } builder.AddModule((module) => { BuildModule(module, typeInfo, service, services); BuildSubTypes(module, typeInfo.DeclaredNestedTypes, builtTypes, service, services); }); builtTypes.Add(typeInfo); } }
static void Main() { //load credentials from credentials.json Credentials c; try { c = JsonConvert.DeserializeObject<Credentials>(File.ReadAllText("credentials.json")); botMention = c.BotMention; if (c.ForwardMessages != true) Console.WriteLine("Not forwarding messages."); else { ForwardMessages = true; Console.WriteLine("Forwarding messages."); } OwnerID = c.OwnerID; password = c.Password; } catch (Exception ex) { Console.WriteLine("Failed to load stuff from credentials.json, RTFM"); Console.ReadKey(); return; } //create new discord client client = new DiscordClient(); //create a command service var commandService = new CommandService(new CommandServiceConfig { CommandChar = null, HelpMode = HelpMode.Disable }); //init parse if (c.ParseKey != null && c.ParseID != null && c.ParseID != "" && c.ParseKey != "") { ParseClient.Initialize(c.ParseID, c.ParseKey); //monitor commands for logging stats_collector = new StatsCollector(commandService); } else { Console.WriteLine("Parse key and/or ID not found. Logging disabled."); } //reply to personal messages and forward if enabled. client.MessageReceived += Client_MessageReceived; //add command service var commands = client.Services.Add<CommandService>(commandService); //count commands ran client.Commands().CommandExecuted += (s, e) => commandsRan++; //create module service var modules = client.Services.Add<ModuleService>(new ModuleService()); //add audio service var audio = client.Services.Add<AudioService>(new AudioService(new AudioServiceConfig() { Channels = 2, EnableEncryption = false, EnableMultiserver = true, Bitrate = 128, })); //install modules modules.Add(new Administration(), "Administration", ModuleFilter.None); //run the bot client.ExecuteAndWait(async () => { await client.Connect(c.Username, c.Password); Console.WriteLine("-----------------"); Console.WriteLine(GetStats()); Console.WriteLine("-----------------"); foreach (var serv in client.Servers) { if ((OwnerUser = serv.GetUser(OwnerID)) != null) return; } }); Console.WriteLine("Exiting..."); Console.ReadKey(); }
public CommandHandler(DiscordSocketClient client, Discord.Commands.CommandService cmd) { Client = client; Commands = cmd; InstallCommandsAsync(); }