public BotModule(IServiceProvider serviceProvider) : base(serviceProvider) { _serviceProvider = serviceProvider; _commandHandlerService = serviceProvider.GetRequiredService <CommandHandlerService>(); _unitsService = serviceProvider.GetRequiredService <UnitsService>(); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { var uiapp = commandData.Application; var app = uiapp.Application; App = app; var uidoc = uiapp.ActiveUIDocument; var doc = uidoc.Document; var sel = uidoc.Selection; var acview = doc.ActiveView; app.DocumentChanged += OnDocumentChanged; uiapp.Idling += OnIdling; floor = sel.PickObject(ObjectType.Element, doc.GetSelectionFilter(m => m is Floor)).GetElement(doc) as Floor; #if Revit2019 CommandHandlerService.invokeCommandHandler("ID_OBJECTS_PROJECT_CURVE"); #endif #if Revit2016 //调用postablecommand var commandid = RevitCommandId.LookupPostableCommandId(PostableCommand.ModelLine); uiapp.PostCommand(commandid); #endif return(Result.Succeeded); }
internal async Task ConnectAsync(DiscordBotConfig config) { Log.Information("Initializing connection."); _commandHandler = new CommandHandlerService(_client, _logger, config, _service, _serviceProvider); _messageHandler = new MessageHandlerService(_client, _logger, config, _levelingService, _userAccountRepository); _userEventsHandler = new UserEventsHandlerService(_client, _logger, config, _userAccountRepository); _client.Log += _logger.Log; _client.Ready += ReadyAsync; if (config.Token == null || config.Token == "") { throw new ArgumentNullException("Token", "Discord Bot Token is empty!"); } if (config.CmdPrefix == null || config.CmdPrefix == "") { throw new ArgumentNullException("cmdPrefix", "Discord Bot cmdPrefix is empty!"); } await _client.LoginAsync(TokenType.Bot, config.Token); await _client.StartAsync(); await _commandHandler.InitializeAsync(); _messageHandler.Initialize(); _userEventsHandler.Initialize(); await Task.Delay(-1); }
public EmojiButler(DiscordSocketClient client, CommandHandlerService commandHandler, DiscordEmojiService discordEmoji, EmojiButlerConfiguration configuration) { this.client = client; this.discordEmoji = discordEmoji; this.commandHandler = commandHandler; this.configuration = configuration; }
public void CommandHandler_GivenCommands_ReturnCorrectRoverPosition(string[] input, string expectedRoverPosition) { CommandHandlerService commandHandlerService = new CommandHandlerService(); List <Rover> rovers = commandHandlerService.ParseCommands(input); Assert.Equal(rovers.First().GetRoverPositionDetailedString(), expectedRoverPosition); }
public void CommandHandler_GivenCommandParameters_ReturnCorrectRoverPositions(string[] input, string[] expectedRoverPositions) { Application.CommandHandlerService commandHandlerService = new CommandHandlerService(); List <Rover> rovers = commandHandlerService.ParseCommands(input); Assert.Equal(rovers.Select(c => c.GetRoverPositionDetailedString()).ToArray(), expectedRoverPositions); }
public void CommandHandler_GivenWrongPleateuCommands_ReturnInvalidOperationException() { CommandHandlerService commandHandlerService = new CommandHandlerService(); var input = new string[] { "5 5", "5 5 N", "MM" }; Action act = () => commandHandlerService.ParseCommands(input); Assert.Throws <InvalidOperationException>(act); }
public EventHookupTestState(XElement workspaceElement) : base(workspaceElement, null, false) { CommandHandlerService t = (CommandHandlerService)Workspace.GetService <ICommandHandlerServiceFactory>().GetService(Workspace.Documents.Single().TextBuffer); var field = t.GetType().GetField("_commandHandlers", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance); var handlers = (IEnumerable <Lazy <ICommandHandler, OrderableContentTypeMetadata> >)field.GetValue(t); _commandHandler = handlers.Single(h => h.Value is EventHookupCommandHandler).Value as EventHookupCommandHandler; _testSessionHookupMutex = new Mutex(false); _commandHandler.TESTSessionHookupMutex = _testSessionHookupMutex; }
private async Task Client_Ready() { AddonLoader.Load(Client); Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); List <Type> commandClasses = new List <Type>(); foreach (Assembly assembly in assemblies) { commandClasses.AddRange(assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(ModuleBase)) && !t.IsAbstract).ToList()); } checkNewUserEntries(); StatusNotifierService.InitializeService(Me); MusicCommands.Initialize(Client); RoleManagerService.InitializeHandler(Client, BotConfiguration); ApiRequestService.Initialize(BotConfiguration); UserManagerService.InitializeHandler(Client); await CommandHandlerService.InitializeHandler(Client, BotConfiguration, commandClasses, prefixDictionary, !CredentialManager.OptionalSettings.Contains("CleverApi")); CacheService.InitializeHandler(); VoiceRewardService.InitializeHandler(Client, BotConfiguration, !CredentialManager.OptionalSettings.Contains("CleverApi")); switch (startValue) { case 0: //shutdown break; case 1: //restarting await Me.SendMessageAsync("I have restored and restarted successfully."); break; case 2: //updating //check if an update is nessasarry await Me.SendMessageAsync("I at all the new features and restarted successfully."); break; default: break; } if (!CredentialManager.OptionalSettings.Contains("WeatherApiKey")) { if (!CredentialManager.OptionalSettings.Contains("WeatherPlace")) { MoodDictionary.InitializeMoodDictionary(Client, BotConfiguration); await MoodHandlerService.InitializeHandler(Client, BotConfiguration); } WeatherSubscriptionService.InitializeWeatherSub(Client, BotConfiguration); } }
async Task InitializeServices() { var services = ConfigureServices(); _config = await services.GetRequiredService <Configuration>().BuildConfig().ConfigureAwait(false); _client = services.GetRequiredService <DiscordSocketClient>(); _cmdHandler = services.GetRequiredService <CommandHandlerService>(); await _cmdHandler.InitializeAsync().ConfigureAwait(false); _logger = services.GetRequiredService <LoggingService>(); _reliabilityService = services.GetRequiredService <ReliabilityService>(); }
/// <summary> /// 指定Revit命令Id,调用内部命令. /// </summary> public bool Invoke(string cmdId) { if (ExternalCommandHelper.CanExecute(cmdId)) { ExternalCommandHelper.executeExternalCommand(cmdId); return(true); } else if (CommandHandlerService.canExecute(cmdId)) { CommandHandlerService.invokeCommandHandler(cmdId); return(true); } else { return(false); } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { var uidoc = commandData.Application.ActiveUIDocument; var doc = uidoc.Document; var sel = uidoc.Selection; var dim = sel.PickObject(ObjectType.Element, doc.GetSelectionFilter(m => m is Dimension)) .GetElement(doc) as Dimension; sel.SetElementIds(new List <ElementId>() { dim.Id }); CommandHandlerService.invokeCommandHandler("ID_FLIP_DIMENSION_DIRECTION"); return(Result.Succeeded); }
public SpinTheWheelBot(CommandLineOptions options) { _services = CreateServiceProvider(options); _logger = _services.GetRequiredService <LoggingService>(); _managementService = _services.GetRequiredService <ManagementService>(); // Log the starting message _logger.Log(LoggingService.LogLevel.INFO, "Starting SpinTheWheelBot..."); // Load services _client = _services.GetRequiredService <DiscordSocketClient>(); _commandHandlerService = _services.GetRequiredService <CommandHandlerService>(); // Load cfg _managementService.LoadConfigFile(options.CfgFile); _logger.RegisterClient(_client); _client.Ready += Ready; }
static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Debug) .CreateLogger(); try { var commandText = @"5 5 1 2 N LMLMLMLMM 3 3 E MMRMMRMRRM"; CommandHandlerService s = new CommandHandlerService(); Console.WriteLine(s.ParseCommands(commandText.Split(Environment.NewLine)).Select(c => c.GetRoverPositionDetailedString()).ToArray()); } catch (Exception) { throw; } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { var uidoc = commandData.Application.ActiveUIDocument; var sel = uidoc.Selection; var eleId = sel.PickObject(ObjectType.Element, uidoc.Document.GetSelectionFilter(m => { return(m.Category.Id == new ElementId(BuiltInCategory.OST_Viewers)); })).ElementId; string commandId = "ID_SECTION_GAP"; sel.SetElementIds(new List <ElementId>() { eleId }); CommandHandlerService.invokeCommandHandler(commandId); return(Result.Succeeded); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { var uidoc = commandData.Application.ActiveUIDocument; var sel = uidoc.Selection; var doc = uidoc.Document; var acview = doc.ActiveView as ViewSection; var ele = sel.PickObject(ObjectType.Element); sel.SetElementIds(new List <ElementId>() { ele.ElementId }); //选中剖面符号 CommandHandlerService.invokeCommandHandler("ID_SECTION_GAP"); //打断剖面符号 sel.SetElementIds(new List <ElementId>()); return(Result.Succeeded); }
public async Task CheckPrice(string name) { ////create a generic text format //TextInfo textInfo = new CultureInfo("en-US", false).TextInfo; ////normalize text input //string normInput = textInfo.ToTitleCase(name); string lowerName = name.ToLower(); string normInput = lowerName.First().ToString().ToUpper() + lowerName.Substring(1); string itemUrl = normInput.Replace(" ", "_"); IMessage searchMessage = Context.Message.Channel.SendMessageAsync("Searching for item....").Result; //use api service instead using (WebClient wc = new WebClient()) { string id = null; var json = wc.DownloadString("https://rsbuddy.com/exchange/summary.json"); JObject jsonIdFinder = JObject.Parse(json); JObject jsonItem = null; string json2 = null; Dictionary <string, int> itemNameComparison = new Dictionary <string, int>(); bool hasBreaked = false; //make foreach smaller. need to overthink the code body of foreach foreach (var item in jsonIdFinder) { //fill dictionary with item names string dataItemName = (string)jsonIdFinder[item.Key]["name"]; if (!itemNameComparison.ContainsKey(dataItemName)) { itemNameComparison.Add(dataItemName, CommandHandlerService.CalcLevenshteinDistance(dataItemName, normInput)); } //check if the item is equal to the input if (normInput == dataItemName && !hasBreaked) { EmbedBuilder rsEmbed = new EmbedBuilder(); var parentKey = item.Value.AncestorsAndSelf() .FirstOrDefault(k => k != null); id = (string)parentKey["id"]; //for some reason the official api has not every item. check the response try { json2 = wc.DownloadString($"https://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item={id}"); } catch (Exception) { json2 = null; } if (json2 == null) { jsonItem = new JObject(); rsEmbed .WithTitle("Oldschool Runescape Grand Exchange Price Check") .WithDescription("Check current prices of items in the grand exchange") .WithColor(new Color((uint)Convert.ToInt32(CommandHandlerService.MessageAuthor.EmbedColor, 16))) .WithTimestamp(DateTime.Now) .WithThumbnailUrl($"https://oldschool.runescape.wiki/images/thumb/7/72/{itemUrl}_detail.png/130px-Dragon_longsword_detail.png?7052f") .WithFooter(NET.DataAccess.File.FileAccess.GENERIC_FOOTER, NET.DataAccess.File.FileAccess.GENERIC_THUMBNAIL_URL) .AddField("Name", (string)jsonIdFinder[item.Key]["name"], true) .AddField("Member-Item", (string)jsonIdFinder[item.Key]["members"] == "true" ? "\u2705" : "\u274E", true) .AddField("Buying Price", (string)jsonIdFinder[item.Key]["buy_average"] + " gp", true) .AddField("Selling Price", (string)jsonIdFinder[item.Key]["sell_average"] + " gp", true) .AddField("Further Reading", $"https://oldschool.runescape.wiki/w/{itemUrl}"); } else { jsonItem = JObject.Parse(json2); rsEmbed .WithTitle("Oldschool Runescape Grand Exchange Price Check") .WithDescription("Check current prices of items in the grand exchange") .WithColor(new Color((uint)Convert.ToInt32(CommandHandlerService.MessageAuthor.EmbedColor, 16))) .WithTimestamp(DateTime.Now) .WithThumbnailUrl($"https://oldschool.runescape.wiki/images/thumb/7/72/{itemUrl}_detail.png/130px-Dragon_longsword_detail.png?7052f") .WithFooter(NET.DataAccess.File.FileAccess.GENERIC_FOOTER, NET.DataAccess.File.FileAccess.GENERIC_THUMBNAIL_URL) .AddField("Name", (string)jsonItem["item"]["name"], true) .AddField("Type", (string)jsonItem["item"]["type"], true) .AddField("Description", (string)jsonItem["item"]["description"], true) .AddField("Member-Item", (string)jsonItem["item"]["members"] == "true" ? "\u2705" : "\u274E", true) .AddField("Current Value", (string)jsonItem["item"]["current"]["price"] + " gp") .AddField("Buying Price", (string)jsonIdFinder[item.Key]["buy_average"] + " gp", true) .AddField("Selling Price", (string)jsonIdFinder[item.Key]["sell_average"] + " gp", true) .AddField("30 Days Price Trend", (string)jsonItem["item"]["day30"]["change"]) .AddField("90 Days Price Trend", (string)jsonItem["item"]["day90"]["change"]) .AddField("180 Days Price Trend", (string)jsonItem["item"]["day180"]["change"]) .AddField("Further Reading", $"https://oldschool.runescape.wiki/w/{itemUrl}"); } await searchMessage.DeleteAsync(); await Context.Message.Channel.SendMessageAsync(embed : rsEmbed.Build()); hasBreaked = true; } else { continue; } } if (jsonItem == null) { //if item wasnt found, give the user an item, which may be correct int minValue = itemNameComparison.Values.Min(); string result = itemNameComparison.Where(v => v.Value == minValue).FirstOrDefault().Key; await searchMessage.DeleteAsync(); await Context.Message.Channel.SendMessageAsync($"Item not found... But do you mean {result}?"); } } }
public InfoSubmodule(IServiceProvider serviceProvider) : base(serviceProvider) { _commandHandlerService = serviceProvider.GetRequiredService <CommandHandlerService>(); }
private async Task Client_Ready() { IServiceProvider services = new ServiceCollection() .AddSingleton(Client) .AddSingleton <CleverbotApiHandler>() .AddSingleton <ColornamesApiHandler>() .AddSingleton <KonachanApiHandler>() .AddSingleton <WeatherApiHandler>() .AddSingleton <WikipediaApiHandler>() .AddSingleton(CredentialManager) .BuildServiceProvider(); AddonLoader.Load(Client); Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); List <Type> commandClasses = new List <Type>(); foreach (Assembly assembly in assemblies) { commandClasses.AddRange(assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(ModuleBase)) && !t.IsAbstract).ToList()); } VoiceRewardService.InitializeHandler(Client, BotConfiguration, !CredentialManager.OptionalSettings.Contains("CleverApi")); checkNewUserEntries(); StatusNotifierService.InitializeService(Me); MusicCommands.Initialize(Client); RoleManagerService.InitializeHandler(Client, BotConfiguration); UserManagerService.InitializeHandler(Client, fileLogger); await CommandHandlerService.InitializeHandler(Client, BotConfiguration, commandClasses, prefixDictionary, !CredentialManager.OptionalSettings.Contains("CleverApi"), fileLogger, services); CacheService.InitializeHandler(); switch (startValue) { case 0: //shutdown break; case 1: //restarting await Me.SendMessageAsync("I have restored and restarted successfully."); break; case 2: //updating //check if an update is nessasarry await Me.SendMessageAsync("I at all the new features and restarted successfully."); break; default: break; } if (!CredentialManager.OptionalSettings.Contains("WeatherApiKey")) { if (!CredentialManager.OptionalSettings.Contains("WeatherPlace")) { MoodDictionary.InitializeMoodDictionary(Client, BotConfiguration); await MoodHandlerService.InitializeHandler(Client, BotConfiguration, services.GetRequiredService <WeatherApiHandler>(), fileLogger); } WeatherSubscriptionService.InitializeWeatherSub(Client, BotConfiguration, services.GetRequiredService <WeatherApiHandler>()); } consoleLogger.Info($"Addons loaded: {AddonLoader.LoadedAddonsCount}"); consoleLogger.Info($"User loaded: {DatabaseAccess.Instance.Users.Count}"); consoleLogger.Info($"Registered guilds: {Client.Guilds.Count}"); consoleLogger.Info($"Bot start up time: {(DateTime.Now - startTime).TotalSeconds} s"); }
public HelpModule(IServiceProvider serviceProvider) : base(serviceProvider) { _commandHandlerService = serviceProvider.GetRequiredService <CommandHandlerService>(); _commandService = serviceProvider.GetRequiredService <CommandService>(); }
public CustomCommandModule(DatabaseContext database, CommandHandlerService commandService) { _database = database; _commandService = commandService.Commands; }