Ejemplo n.º 1
0
        public Task <string> Blame(CommandMessage message)
        {
            if (message.Channel is SocketGuildChannel guildChannel)
            {
                List <IGuildUser> targets = new List <IGuildUser>();
                targets.Add(message.Author);

                foreach (SocketGuildUser tTarget in guildChannel.Guild.Users)
                {
                    if (CommandsService.GetPermissions(tTarget) != Permissions.Administrators)
                    {
                        continue;
                    }

                    targets.Add(tTarget);
                }

                Random     rnd    = new Random();
                int        val    = rnd.Next(targets.Count);
                IGuildUser target = targets[val];

                if (target.Id == Program.DiscordClient.CurrentUser.Id)
                {
                    return(Task.FromResult("This is my fault. =("));
                }

                return(Task.FromResult("This is your fault, " + target.GetName() + "."));
            }

            return(Task.FromResult("This is your fault, " + message.Author.GetName() + "."));
        }
Ejemplo n.º 2
0
        public async Task ClosePoll(CommandMessage message, ulong messageId)
        {
            if (!this.pollLookup.ContainsKey(messageId))
            {
                throw new UserException("I couldn't find that poll");
            }

            string pollId = this.pollLookup[messageId];
            Poll?  poll   = await this.pollDatabase.Load(pollId);

            if (poll == null)
            {
                throw new Exception("Poll missing from database: \"" + pollId + "\"");
            }

            if (CommandsService.GetPermissions(message.Author) == Permissions.Everyone)
            {
                if (poll.Author != message.Author.Id)
                {
                    throw new UserException("I'm sorry, only the polls author, or an administrator can do that.");
                }
            }

            await poll.Close();

            this.pollLookup.Remove(poll.MessageId);
            await this.pollDatabase.Delete(poll);

            await poll.UpdateMessage();
        }
Ejemplo n.º 3
0
        public RocketChat(string serverUrl)
        {
            IRestClient            restClient            = new RestClient(serverUrl);
            IJsonSerializer        jsonSerializer        = new JsonSerializer();
            IAuthHelper            authHelper            = new AuthHelper();
            IRestClientService     restClientService     = new RestClientService(authHelper, restClient, jsonSerializer);
            IFileRestClientService fileRestClientService = new FileRestClientService(authHelper, restClient, jsonSerializer);
            IAuthenticationService authService           = new AuthenticationService(authHelper, restClientService);
            IChannelsService       channelsService       = new ChannelsService(restClientService);
            IGroupsService         groupsService         = new GroupsService(restClientService);
            IUsersService          usersService          = new UsersService(restClientService);
            IChatService           chatService           = new ChatService(restClientService);
            IRoomService           roomService           = new RoomService(restClientService);
            IAssetsService         assetsService         = new AssetsService(restClientService);
            IAutoTranslateService  autoTranslateService  = new AutoTranslateService(restClientService);
            ICommandsService       commandsService       = new CommandsService(restClientService);
            IEmojisService         emojisService         = new EmojisService(restClientService, fileRestClientService);

            Api = new RocketChatApi(
                chatService,
                usersService,
                groupsService,
                channelsService,
                authService,
                roomService,
                assetsService,
                autoTranslateService,
                commandsService,
                emojisService);
        }
Ejemplo n.º 4
0
        public async Task <string> DeleteQuote(CommandMessage message, IUser user, int quoteId)
        {
            if (message.Author != user && CommandsService.GetPermissions(message.Author) != Permissions.Administrators)
            {
                throw new UserException("You don't have permission to do that.");
            }

            Dictionary <string, object> filters = new Dictionary <string, object>
            {
                { "UserId", user.Id },
                { "GuildId", message.Guild.Id },
                { "QuoteId", quoteId },
            };

            List <Quote> allQuotes = await this.quoteDb.LoadAll(filters);

            if (allQuotes.Count <= 0)
            {
                throw new UserException("I couldn't find that quote from that user.");
            }

            foreach (Quote quote in allQuotes)
            {
                await this.quoteDb.Delete(quote);
            }

            return("Quote deleted!");
        }
Ejemplo n.º 5
0
        public void EndTrade(CustomerInfo customer, bool succeed = false)
        {
            _loggerService.Log("Trade succeed with " + CurrentCustomer.Nickname);
            CurrentCustomer = null;
            CommandsService.KickFormParty(customer);
            if (succeed)
            {
                Win32.ChatCommand($"@{customer.Nickname} ty gl");
                CompletedTrades.Add(customer);
                _loggerService.Log("Trade comlete sucessfully");
            }
            else
            {
                _loggerService.Log($"Trade failed with {customer.Nickname}");
            }

            Customers.Remove(customer);

            if (!_StashHelper.OpenStash())
            {
                _loggerService.Log("Stash not found. I cant clean inventory after trade.");
            }
            else
            {
                if (succeed)
                {
                }
                else
                {
                    PutItemBack(customer);
                }
            }
            _InTrade = false;
        }
        static async Task Main(string[] args)
        {
            // register to unhandled exceptions handling
            // this allows logging exceptions that were not handled with a try-catch block
            AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;

            // optional: create a logger factory
            ILoggerFactory logFactory = CreateLoggerFactory();
            // optional: enable DI - add logger factory to it as well
            IServiceCollection services = new ServiceCollection()
                                          .AddSingleton <ILoggerFactory>(logFactory);

            // create client and listen to events we're interested in
            _client = new WolfClient(logFactory.CreateLogger <WolfClient>());
            _client.AddMessageListener <WelcomeEvent>(OnWelcome);        // these 2 callbacks are invoked if received message is a WolfEvent (first callback)

            // initialize commands system
            CommandsOptions options = new CommandsOptions()
            {
                Prefix          = "!",                      // set prefix
                RequirePrefix   = PrefixRequirement.Always, // make prefix always required - can also for example require it in group only
                CaseSensitivity = false                     // make commands case insensitive
            };
            CommandsService commands = new CommandsService(_client, options, logFactory.CreateLogger <CommandsService>(), services.BuildServiceProvider());
            await commands.StartAsync();                    // calling StartAsync causes reload of all commands

            // start connection and prevent the application from closing
            await _client.ConnectAsync();

            await Task.Delay(-1);
        }
Ejemplo n.º 7
0
        public async Task ShowInventory(CommandMessage message)
        {
            // Shop items
            List <ShopItem> items = new List <ShopItem>();

            User user = await UserService.GetUser(message.Author);

            EmbedBuilder embed = new EmbedBuilder();

            embed.Title = message.Author.GetName() + "'s Inventory";
            embed.Color = Color.Blue;

            StringBuilder desc = new StringBuilder();

            if (user.Inventory.Count == 0)
            {
                desc.AppendLine("Nothing to show here. Visit our shop, _kupo!_");
            }
            else
            {
                // Load shop items
                items = await ShopItemDatabase.LoadAll(new Dictionary <string, object>()
                {
                    { "GuildId", message.Guild.Id },
                });

                // Restrict items to only held
                items = items.Where(x => user.Inventory.ContainsKey(x.Name)).ToList();

                foreach (KeyValuePair <string, int> item in user.Inventory)
                {
                    desc.AppendLine(item.Value + "x - " + item.Key);
                }
            }

            desc.AppendLine(Utils.Characters.Tab);

            embed.Description = desc.ToString();

            string prefix = CommandsService.GetPrefix(message.Guild.Id);

            embed.WithFooter("Use " + prefix + "shop to see items to buy. Select a reaction to redeem.");

            RestUserMessage userMessage = await message.Channel.SendMessageAsync(embed : embed.Build(), messageReference : message.MessageReference);

            // Add reacts
            await userMessage.AddReactionsAsync(items.Select(x => x.ReactionEmote).ToArray());

            // Handle reacts
            Program.DiscordClient.ReactionAdded += this.OnReactionAddedInventory;

            // Add to active windows
            this.activeInventoryWindows.Add(userMessage.Id, DateTime.Now);

            // Clear reacts
            _ = Task.Run(async() => await this.StopInventoryListener(userMessage));
        }
Ejemplo n.º 8
0
 public TelegramCallbackHandler(TelegramBotClient botClient, CommandsService commandsService,
                                IMapper mapper,
                                IEnumerable <ISender> senders)
 {
     _botClient       = botClient;
     _commandsService = commandsService;
     _mapper          = mapper;
     _sender          = senders.First(x => x.ConsumerType == ConsumerType.Telegram);
 }
Ejemplo n.º 9
0
        private void RequestTrade()
        {
            _InTrade       = true;
            TradinngThread = new Thread(() =>
            {
                if (Win32.GetActiveWindowTitle() != "Path of Exile")
                {
                    Win32.PoE_MainWindow();
                }

                if (CurrentCustomer == null)
                {
                    Thread.CurrentThread.Abort();
                    return;
                }

                // check if im invited
                if (!AcceptTradeRequest())
                {
                    // Send trade request
                    SendTradeRequest();
                }
                // Move items to trade window
                while (!IsTradeStarted())
                {
                    Thread.Sleep(100);
                }

                if (!PutItems())
                {
                    _InTrade = false;
                    // TODO add actio to end trade if cant put items
                    Win32.ChatCommand($"@{CurrentCustomer.Nickname} Item gone, sorry");
                    CommandsService.KickFormParty(CurrentCustomer);
                    Thread.CurrentThread.Abort();
                    return;
                }

                // validate until cancel or ok
                bool IsNotPaidYet = true;
                while (IsNotPaidYet)
                {
                    IsNotPaidYet = !CheckTradeCurrency();
                }
                // accept trade
                while (!AccepTrade())
                {
                    Thread.Sleep(100);
                }
                Thread.CurrentThread.Abort();
            });
            TradinngThread.SetApartmentState(ApartmentState.STA);
            TradinngThread.Start();
        }
Ejemplo n.º 10
0
        private bool CheckTradeCurrency()
        {
            if (Win32.GetActiveWindowTitle() != "Path of Exile")
            {
                Win32.PoE_MainWindow();
            }

            Item        currency;
            List <Item> lCurrency  = new List <Item>();
            double      totalChaos = 0;

            Bitmap cell;
            Bitmap template = new Bitmap($"Assets/{Properties.Settings.Default.UI_Fragments}/empty_cel2.png");

            Win32.MoveTo(0, 0);
            Thread.Sleep(100);

            for (int i = 0; i < 12; i++)
            {
                for (int j = 0; j < 5; j++)
                {
                    int xInit = x_trade + (tab_width * i) - i / 2;
                    int yInit = y_trade + (tab_height * j) - j / 2;
                    cell = ScreenCapture.CaptureRectangle(xInit, yInit, tab_width, tab_height);
                    if (!OpenCV_Service.Match(cell, template, 0.80f))
                    {
                        Win32.MoveTo(xInit + (tab_width / 2), yInit + (tab_height / 2));
                        Thread.Sleep(100);

                        string clip = CommandsService.CtrlC_PoE();
                        currency = _ItemService.GetCurrency(clip);

                        if (currency != null)
                        {
                            lCurrency.Add(currency);
                            totalChaos += currency.Price.Cost;
                        }
                    }
                }
            }

            // validate price
            if (CurrentCustomer != null)
            {
                // Check value

                if (CurrentCustomer.Chaos_Price < totalChaos)
                {
                    return(true);
                }
            }
            return(false);
        }
Ejemplo n.º 11
0
        public async Task ViewContentCreators(CommandMessage message)
        {
            // Load streamers
            List <ContentCreator> streamers = await ContentCreatorDatabase.LoadAll(new Dictionary <string, object> {
                { "DiscordGuildId", message.Guild.Id }
            });

            EmbedBuilder embed = new EmbedBuilder()
                                 .WithTitle("Content Creators");

            // Add thumbnail
            embed.AddThumbnail(message.Guild.IconUrl);

            if (streamers == null || streamers.Count == 0)
            {
                // TODO: Add YT when implemented
                string prefix = CommandsService.GetPrefix(message.Guild.Id);
                embed.Description = $"No streamers found!\nUsers can add themselves with {prefix}ICreatorTwitch or {prefix}ICreatorYoutube command";
            }
            else
            {
                StringBuilder desc = new StringBuilder();

                foreach (ContentCreator streamer in streamers)
                {
                    desc.Append($"{FC.Utils.DiscordMarkdownUtils.BulletPoint} {streamer.GuildNickName} | ");

                    if (streamer.Twitch != null)
                    {
                        desc.Append($"Twitch: {streamer.Twitch.Link}");
                    }

                    if (streamer.Youtube != null)
                    {
                        if (streamer.Twitch != null)
                        {
                            desc.Append(" | ");
                        }

                        desc.Append($"Youtube: {streamer.Youtube.Link}");
                    }

                    desc.AppendLine();
                }

                embed.Description = desc.ToString();
            }

            // Send Embed
            await message.Channel.SendMessageAsync(embed : embed.Build(), messageReference : message.MessageReference);
        }
Ejemplo n.º 12
0
 public VkCallbackHandler(CommandsService commandsService,
                          BotDbContext db,
                          IVkApi vkApi,
                          IEnumerable <ISender> senders,
                          IOptions <VkOptions> options,
                          IMapper mapper)
 {
     _commandsService = commandsService;
     _db      = db;
     _vkApi   = vkApi;
     _sender  = senders.First(x => x.ConsumerType == ConsumerType.Vkontakte);
     _mapper  = mapper;
     _options = options.Value;
     _logger  = Log.ForContext <VkCallbackHandler>();
 }
Ejemplo n.º 13
0
        public void ConsoleService()
        {
            string command        = "";
            var    commandService = new CommandsService();

            //Console Interface
            while (true)
            {
                Console.WriteLine();
                Console.Write("W.A.P -->: ");
                command = Console.ReadLine();
                commandService.CheckCommand(command);
            }
            ;
        }
Ejemplo n.º 14
0
    private CommandsService GetService()
    {
        var service = new CommandsService(GetTextCommands(), GetKeyboardCommands(), ApplicationContext);

        return(service);

        IEnumerable <IKeyboardCommand> GetKeyboardCommands()
        {
            return(new IKeyboardCommand[] { new MailingKeyboardCommand(), new ScheduleKeyboardCommand() });
        }

        IEnumerable <ITextCommand> GetTextCommands()
        {
            return(new ITextCommand[] { new HelpCommand(), new StartCommand(), new FakeAdminCommand() });
        }
    }
Ejemplo n.º 15
0
        public static Task <Embed> GetHelp(CommandMessage message, string?command = null)
        {
            StringBuilder builder     = new StringBuilder();
            Permissions   permissions = CommandsService.GetPermissions(message.Author);

            if (command == null)
            {
                command = message.Command;
            }

            builder.AppendLine(GetHelp(message.Guild, command, permissions));

            EmbedBuilder embed = new EmbedBuilder();

            embed.Description = builder.ToString();

            if (string.IsNullOrEmpty(embed.Description))
            {
                throw new UserException("I'm sorry, you don't have permission to use that command.");
            }

            return(Task.FromResult(embed.Build()));
        }
Ejemplo n.º 16
0
        private static string?GetHelp(IGuild guild, string commandStr, Permissions permissions)
        {
            StringBuilder  builder  = new StringBuilder();
            List <Command> commands = CommandsService.GetCommands(commandStr);

            int count = 0;

            foreach (Command command in commands)
            {
                // Don't show commands users cannot access
                if (command.Permission > permissions)
                {
                    continue;
                }

                count++;
            }

            if (count <= 0)
            {
                return(null);
            }

            builder.Append("__");
            ////builder.Append(CommandsService.CommandPrefix);
            builder.Append(commandStr);
            builder.AppendLine("__");

            foreach (Command command in commands)
            {
                // Don't show commands users cannot access
                if (command.Permission > permissions)
                {
                    continue;
                }

                builder.Append(Utils.Characters.Tab);
                builder.Append(command.Permission);
                builder.Append(" - *");
                builder.Append(command.Help);
                builder.AppendLine("*");

                List <ParameterInfo> parameters = command.GetNeededParams();

                builder.Append("**");
                builder.Append(Utils.Characters.Tab);
                builder.Append(CommandsService.GetPrefix(guild));
                builder.Append(commandStr);
                builder.Append(" ");

                for (int i = 0; i < parameters.Count; i++)
                {
                    if (i != 0)
                    {
                        builder.Append(" ");
                    }

                    builder.Append(GetParam(parameters[i], command.RequiresQuotes));
                }

                builder.Append("**");
                builder.AppendLine();
                builder.AppendLine();
            }

            return(builder.ToString());
        }
Ejemplo n.º 17
0
        private static Embed GetHelp(IGuild guild, Permissions permissions, int startIndex, out int page)
        {
            // Get all help commands
            IEnumerable <HelpCommand> helpCommands = CommandsService.GetGroupedHelpCommands()
                                                     .Where(x => x.Permission <= permissions);

            int numberOfPages = 0;
            int pagesForGroup = 0;

            foreach (IGrouping <CommandCategory, HelpCommand> group in helpCommands.GroupBy(x => x.CommandCategory))
            {
                pagesForGroup  = (int)Math.Ceiling((decimal)group.Count() / PageSize);
                numberOfPages += pagesForGroup;

                // Create spacer commands
                int spacerCommandsRequired = (PageSize * pagesForGroup) - group.Count();
                for (int i = 0; i < spacerCommandsRequired; i++)
                {
                    helpCommands = helpCommands.Append(new HelpCommand("Spacer", group.Key, string.Empty, Permissions.Everyone));
                }
            }

            helpCommands = helpCommands.OrderBy(x => x.CommandCategory)
                           .ThenBy(x => x.CommandName)
                           .AsEnumerable();

            // page is 0-indexed
            page = startIndex + 1;

            // If page is greater than last page, wrap to start
            if (page > numberOfPages)
            {
                page       = 1;
                startIndex = 0;
            }

            // Moving to last page
            if (startIndex == -1)
            {
                page = numberOfPages;

                helpCommands = helpCommands.TakeLast(PageSize);

                startIndex = 0;
            }

            // Restrict to page size
            helpCommands = helpCommands.Skip(startIndex * PageSize).Take(PageSize);

            // Start Embed
            EmbedBuilder  embed   = new EmbedBuilder();
            StringBuilder builder = new StringBuilder();

            // Category name
            embed.Title = helpCommands.FirstOrDefault().CommandCategory.ToDisplayString() + " Commands";

            // Iterate commands
            foreach (HelpCommand category in helpCommands)
            {
                if (category.CommandName.ToLower() == "spacer")
                {
                    continue;
                }

                builder.Append("**" + category.CommandName + "**");
                builder.Append(" - ");

                if (category.CommandCount > 1)
                {
                    builder.Append("*+" + category.CommandCount + "* - ");
                }

                builder.Append(category.Help);
                builder.AppendLine();

                if (category.CommandShortcuts.Count > 0)
                {
                    builder.Append("Shortcut: ");
                    foreach (string shortcutString in category.CommandShortcuts)
                    {
                        builder.Append(shortcutString + ", ");
                    }

                    builder.Remove(builder.Length - 2, 2);

                    builder.AppendLine();
                }

                builder.AppendLine();
            }

            builder.AppendLine();

            string prefix = CommandsService.GetPrefix(guild);

            embed.WithThumbnailUrl("https://cdn.discordapp.com/attachments/825936704023691284/828491389838426121/think3.png")
            .WithDescription(builder.ToString())
            .WithAuthor(string.Format("Page {0} of {1}", page, numberOfPages))
            .WithFooter("To get more information on a command, look it up directly, like \"" + prefix + "help time\" or \"" + prefix + "et ?\"");

            // Return page to 0-index
            page -= 1;

            return(embed.Build());
        }
Ejemplo n.º 18
0
        public async Task <bool> Help(CommandMessage message)
        {
            Permissions permissions = CommandsService.GetPermissions(message.Author);

            return(await GetHelp(message, permissions));
        }
Ejemplo n.º 19
0
        public static async Task <bool> GetHelp(CommandMessage message, Permissions permissions)
        {
            EmbedBuilder  embed   = new EmbedBuilder();
            StringBuilder builder = new StringBuilder();

            List <string> commandStrings = new List <string>(CommandsService.GetCommands());

            commandStrings.Sort();

            int commandCount = 0;

            foreach (string commandString in commandStrings)
            {
                if (commandString == "help")
                {
                    continue;
                }

                int            count    = 0;
                List <Command> commands = CommandsService.GetCommands(commandString);
                foreach (Command command in commands)
                {
                    if (command.Permission > permissions)
                    {
                        continue;
                    }

                    count++;
                }

                if (count <= 0)
                {
                    continue;
                }

                builder.Append("__");
                builder.Append(commandString);
                builder.Append("__ - *+");
                builder.Append(count);
                builder.Append("* - ");
                builder.Append(commands[0].Help);
                builder.AppendLine();

                commandCount++;

                if (commandCount >= 20)
                {
                    embed             = new EmbedBuilder();
                    embed.Description = builder.ToString();
                    await message.Channel.SendMessageAsync(null, false, embed.Build());

                    builder.Clear();
                    commandCount = 0;
                }
            }

            builder.AppendLine();
            builder.AppendLine();
            builder.AppendLine("To get more information on a command, look it up directly, like `" + CommandsService.GetPrefix(message.Guild) + "help \"time\"` or `" + CommandsService.GetPrefix(message.Guild) + "et ?`");

            embed             = new EmbedBuilder();
            embed.Description = builder.ToString();
            await message.Channel.SendMessageAsync(null, false, embed.Build());

            return(true);
        }
Ejemplo n.º 20
0
        static void Main(string[] args)
        {
            IDisplay        display       = new ConsoleDisplay();
            IHandler        handler       = new RssHandlerService();
            IConfigManager  configManager = new JsonConfigManager();
            IRssManager     rssManager    = new RssManager(configManager);
            var             loggerFactory = new LoggerFactory();
            CommandsService commands      = new CommandsService(rssManager, loggerFactory.CreateLogger <CommandsService>(), handler);
            bool            exit          = true;

            Console.WriteLine("Введите help для просмотра доступных комманд.");
            do
            {
                string   command          = Console.ReadLine();
                string[] commandFragments = command.Split(" ");
                string   result           = "";
                switch (commandFragments[0])
                {
                case "pull":
                    result = commands.Pull();
                    display.Display(result);
                    break;

                case "list":
                    var list = commands.List();
                    foreach (var rss in list)
                    {
                        foreach (var article in rss)
                        {
                            display.Display(article);
                        }
                    }
                    break;

                case "remove":
                    result = commands.Remove();
                    display.Display(result);
                    break;

                case "exit":
                    exit = false;
                    break;

                case "clear":
                    Console.Clear();
                    break;

                case "add":
                    result = commands.Add(commandFragments[1]);
                    display.Display(result);
                    break;

                case "help":
                    Console.WriteLine("pull\tЧитает RSS ленты из файла настроек, скачивает их и сохраняет на локальный диск." +
                                      "\nlist\tЧитает скаченные локально RSS ленты и отображает их элементы." +
                                      "\nremove\tУдаляет все скаченные RSS ленты." +
                                      "\nadd\tДобавляет RSS ленту в список для загрузки." +
                                      "\nclear\tОчисщает консоль." +
                                      "\nexit\tВыйти из программы."); break;

                default: Console.WriteLine("Error executing command."); break;
                }
            } while (exit);
        }
Ejemplo n.º 21
0
 private void TradeRequest(object sender, TradeArgs e)
 {
     Customers.Add(e.customer);
     CommandsService.InviteCustomer(e.customer);
     _loggerService.Log("Trade registered " + e.customer.Nickname);
 }
Ejemplo n.º 22
0
        private bool CheckCurrency()
        {
            // TODO create new check currency which check currencys with control + c and checks name and stack size
            List <Position> found_positions = null;

            List <Currency_ExRate> main_currs = new List <Currency_ExRate>();

            //set main currencies

            main_currs.Add(CurrentCustomer.Currency);

            if (CurrentCustomer.Currency.Name != "chaos orb")
            {
                main_currs.Add(_CurrenciesService.GetCurrencyByName("chaos"));
            }

            if (CurrentCustomer.Currency.Name != "divine orb")
            {
                main_currs.Add(_CurrenciesService.GetCurrencyByName("divine"));
            }

            if (CurrentCustomer.Currency.Name != "exalted orb")
            {
                main_currs.Add(_CurrenciesService.GetCurrencyByName("exalted"));
            }

            if (CurrentCustomer.Currency.Name != "orb of alchemy")
            {
                main_currs.Add(_CurrenciesService.GetCurrencyByName("alchemy"));
            }

            if (CurrentCustomer.Currency.Name == "exalted orb")
            {
                //Win32.ChatCommand($"@{CurrentCustomer.Nickname} exalted orb = {_CurrenciesService.GetCurrencyByName("exalted").ChaosEquivalent}");

                main_currs.Add(_CurrenciesService.GetCurrencyByName("exalted"));
            }

            Bitmap screen_shot = null;

            int x_trade = 220;
            int y_trade = 140;

            for (int i = 0; i < 30; i++)
            {
                double price = 0;

                foreach (Currency_ExRate cur in main_currs)
                {
                    if (!System.IO.File.Exists(cur.ImageName))
                    {
                        continue;
                    }
                    Win32.MoveTo(0, 0);

                    Thread.Sleep(100);

                    screen_shot = ScreenCapture.CaptureRectangle(x_trade, y_trade, 465, 200);

                    found_positions = OpenCV_Service.FindCurrencies(screen_shot, cur.ImageName, 0.6);

                    foreach (Position pos in found_positions)
                    {
                        Win32.MoveTo(x_trade + pos.Left + pos.Width / 2, y_trade + pos.Top + pos.Height / 2);

                        Thread.Sleep(100);

                        string ctrlc = CommandsService.CtrlC_PoE();
                        // TODO fix this currency stack count
                        var curbyname = _CurrenciesService.GetCurrencyByName(CommandsService.GetNameItem_PoE(ctrlc));

                        if (curbyname == null)
                        {
                            price += CommandsService.GetSizeInStack(ctrlc) * cur.ChaosEquivalent;
                        }

                        else
                        {
                            price += CommandsService.GetSizeInStack(ctrlc) * curbyname.ChaosEquivalent;
                        }


                        screen_shot.Dispose();
                    }

                    if (price >= CurrentCustomer.Chaos_Price && price != 0)
                    {
                        break;
                    }
                }

                _loggerService.Log("Bid price (in chaos) = " + price + " Necessary (in chaos) = " + CurrentCustomer.Chaos_Price);

                if (price >= CurrentCustomer.Chaos_Price)
                {
                    _loggerService.Log("I want accept trade");

                    screen_shot = ScreenCapture.CaptureRectangle(200, 575, 130, 40);

                    Position pos = OpenCV_Service.FindObject(screen_shot, $"Assets/{Properties.Settings.Default.UI_Fragments}/accept_tradewindow.png");

                    if (pos.IsVisible)
                    {
                        Win32.MoveTo(210 + pos.Left + pos.Width / 2, 580 + pos.Top + pos.Height / 2);

                        Thread.Sleep(100);

                        Win32.DoMouseClick();

                        screen_shot.Dispose();

                        var timer = DateTime.Now + new TimeSpan(0, 0, 5);

                        while (CurrentCustomer.TradeStatus != CustomerInfo.TradeStatuses.ACCEPTED)
                        {
                            if (CurrentCustomer.TradeStatus == CustomerInfo.TradeStatuses.CANCELED)
                            {
                                return(false);
                            }

                            if (DateTime.Now > timer)
                            {
                                break;
                            }
                        }

                        if (CurrentCustomer.TradeStatus == CustomerInfo.TradeStatuses.ACCEPTED)
                        {
                            return(true);
                        }

                        else
                        {
                            continue;
                        }
                    }
                }
                else
                {
                    screen_shot.Dispose();
                }

                Thread.Sleep(500);
            }

            Win32.SendKeyInPoE("{ESC}");

            return(false);
        }
Ejemplo n.º 23
0
        private bool GetProduct()
        {
            int x_inventory = 925;
            int y_inventory = 440;
            int offset      = 37;

            Bitmap screen_shot;

            for (int j = 0; j < 12; j++)
            {
                for (int i = 0; i < 5; i++)
                {
                    Win32.MoveTo(x_inventory + offset * j, y_inventory + 175);

                    Thread.Sleep(100);

                    screen_shot = ScreenCapture.CaptureRectangle(x_inventory - 30 + offset * j, y_inventory - 30 + offset * i, 60, 60);

                    Position pos = OpenCV_Service.FindObject(screen_shot, $"Assets/{Properties.Settings.Default.UI_Fragments}/empty_cel.png", 0.4);

                    if (pos != null && !pos.IsVisible)
                    {
                        Clipboard.Clear();

                        string ss = null;

                        Thread.Sleep(100);

                        Win32.MoveTo(x_inventory + offset * j, y_inventory + offset * i);

                        var time = DateTime.Now + new TimeSpan(0, 0, 5);

                        while (ss == null)
                        {
                            Win32.SendKeyInPoE("^c");
                            ss = Win32.GetText();

                            if (time < DateTime.Now)
                            {
                                ss = "empty_string";
                            }
                        }

                        if (ss == "empty_string")
                        {
                            continue;
                        }

                        if (CurrentCustomer.Product.Contains(CommandsService.GetNameItem_PoE(ss)))
                        {
                            _loggerService.Log($"{ss} is found in inventory");

                            Win32.CtrlMouseClick();

                            screen_shot.Dispose();

                            return(true);
                        }
                    }
                    screen_shot.Dispose();
                }
            }
            Win32.SendKeyInPoE("{ESC}");

            Win32.ChatCommand("@" + CurrentCustomer.Nickname + " I sold it, sry");

            return(false);
        }
Ejemplo n.º 24
0
        private async Task OnReactionAdded(Cacheable <IUserMessage, ulong> incomingMessage, ISocketMessageChannel channel, SocketReaction reaction)
        {
            try
            {
                // Don't react to your own reacts!
                if (reaction.UserId == Program.DiscordClient.CurrentUser.Id)
                {
                    return;
                }

                // Only handle reacts to help embed
                if (!activeHelpEmbeds.ContainsKey(incomingMessage.Id))
                {
                    return;
                }

                ActiveHelp helpWindow = activeHelpEmbeds[incomingMessage.Id];
                helpWindow.LastInteractedWith = DateTime.Now;

                // Only handle reacts from the original user, remove the reaction
                if (helpWindow.UserId != reaction.UserId)
                {
                    IUserMessage message = await incomingMessage.DownloadAsync();

                    await message.RemoveReactionAsync(reaction.Emote, reaction.User.Value);

                    return;
                }

                // Only handle relevant reacts
                if (!HelpEmotes.Contains(reaction.Emote))
                {
                    IUserMessage message = await incomingMessage.DownloadAsync();

                    await message.RemoveReactionAsync(reaction.Emote, reaction.User.Value);

                    return;
                }

                if (channel is SocketGuildChannel guildChannel)
                {
                    IUserMessage message = await incomingMessage.DownloadAsync();

                    await message.RemoveReactionAsync(reaction.Emote, reaction.User.Value);

                    // Adjust current page
                    if (reaction.Emote.Equals(First))
                    {
                        helpWindow.CurrentPage = 0;
                    }
                    else if (reaction.Emote.Equals(Previous))
                    {
                        helpWindow.CurrentPage -= 1;
                    }
                    else if (reaction.Emote.Equals(Next))
                    {
                        helpWindow.CurrentPage += 1;
                    }
                    else if (reaction.Emote.Equals(Last))
                    {
                        helpWindow.CurrentPage = -1;
                    }

                    Permissions permissions = CommandsService.GetPermissions(message.GetAuthor());

                    int   currentPage = helpWindow.CurrentPage;
                    Embed embed       = GetHelp(message.GetGuild(), permissions, helpWindow.CurrentPage, out currentPage);

                    // Update current page
                    helpWindow.CurrentPage = currentPage;

                    await message.ModifyAsync(x => x.Embed = embed);
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
            }
        }
Ejemplo n.º 25
0
        public bool PutItems()
        {
            int x_inventory = 925;
            int y_inventory = 440;
            int offset      = 37;

            var customer = CurrentCustomer;

            int TotalAmount = 0;

            List <Cell> skip = new List <Cell>();

            for (int j = 0; j < 12; j++)
            {
                for (int i = 0; i < 5; i++)
                {
                    if (skip.Find(cel => cel.Left == i && cel.Top == j) != null)
                    {
                        continue;
                    }

                    Win32.MoveTo(x_inventory + offset * j, +175);

                    Thread.Sleep(100);

                    var screen_shot = ScreenCapture.CaptureRectangle(x_inventory - 30 + offset * j, y_inventory - 30 + offset * i, 60, 60);

                    var pos = OpenCV_Service.FindObject(screen_shot, $"Assets/{Properties.Settings.Default.UI_Fragments}/empty_cel.png", 0.5);

                    if (!pos.IsVisible)
                    {
                        Win32.MoveTo(x_inventory + offset * j, y_inventory + offset * i);

                        var item_info = CommandsService.CtrlC_PoE();

                        string name = CommandsService.GetNameItem_PoE_Pro(item_info);

                        if (name != customer.Product)
                        {
                            continue;
                        }

                        int SizeInStack = CommandsService.GetStackSize_PoE_Pro(item_info);

                        TotalAmount += SizeInStack;

                        if (name.Contains("Resonator"))
                        {
                            if (name.Contains("Potent"))
                            {
                                skip.Add(new Cell(i, j + 1));
                            }

                            if (name.Contains("Prime") || name.Contains("Powerful"))
                            {
                                skip.Add(new Cell(i, j + 1));
                                skip.Add(new Cell(i + 1, j + 1));
                                skip.Add(new Cell(i + 1, j));
                            }
                        }

                        Win32.CtrlMouseClick();

                        Thread.Sleep(250);

                        if (TotalAmount >= customer.NumberProducts)
                        {
                            screen_shot.Dispose();

                            _loggerService.Log($"I put {TotalAmount} items in trade window");

                            return(true);
                        }
                    }

                    screen_shot.Dispose();
                }
            }
            Win32.SendKeyInPoE("{ESC}");

            Win32.ChatCommand("@" + CurrentCustomer.Nickname + " i sold it, sry");

            return(false);
        }
Ejemplo n.º 26
0
 public ServiceBase()
 {
     CommandsService.BindCommands(this);
 }