private void OnUnitSpellCastSucceeded(object obj, LuaEventArgs args)
 {
     try
     {
         if ((string)args.Args[0] == "player" && (uint)((double)args.Args[4]) == Entry)
         {
             // confirm last recipe
             if (Casted + 1 == CalculatedRepeat)
             {
                 Confimed = true;
             }
             if (RepeatType != RepeatCalculationType.Craftable)
             {
                 Casted++;
             }
             ProfessionbuddyBot.Instance.UpdateMaterials();
             if (MainForm.IsValid)
             {
                 MainForm.Instance.RefreshTradeSkillTabs();
                 MainForm.Instance.RefreshActionTree(typeof(CastSpellAction));
             }
         }
     }
     catch (Exception ex)
     {
         PBLog.Warn(ex.ToString());
     }
 }
示例#2
0
 protected async override Task Run()
 {
     try
     {
         try
         {
             await Action(this);
         }
         catch (Exception ex)
         {
             if (ex.GetType() != typeof(ThreadAbortException))
             {
                 PBLog.Warn("{0}:({1})\n{2}", Strings["Action_CustomAction_Name"], Code, ex);
             }
         }
         IsDone = true;
     }
     catch (Exception ex)
     {
         if (ex.GetType() != typeof(ThreadAbortException))
         {
             PBLog.Warn("There was an exception while executing a CustomAction\n{0}", ex);
         }
     }
 }
        protected async override Task Run()
        {
            if (_sub == null && !SubRoutineComposite.GetSubRoutineMyName(SubRoutineName, out _sub))
            {
                PBLog.Warn("{0}: {1}.", ProfessionbuddyBot.Instance.Strings["Error_SubroutineNotFound"], SubRoutineName);
                IsDone = true;
                return;
            }

            using (SubRoutineComposite.Activate(_sub))
            {
                try
                {
                    if (_sub.IsDone)
                    {
                        _sub.Reset();
                    }
                    await _sub;
                }
                finally
                {
                    IsDone = _sub.IsDone;
                }
            }
        }
示例#4
0
        private List <AuctionEntry> BuildScanItemList()
        {
            var tmpItemlist = new List <AuctionEntry>();

            if (UseCategory)
            {
                var itemList =
                    StyxWoW.Me.BagItems.Where(
                        i =>
                        !i.IsSoulbound && !i.IsConjured && !i.IsDisabled && !i.IsGiftWrapped && i.ItemInfo.ItemClass == Category &&
                        SubCategoryCheck(i)).ToList();
                foreach (var item in itemList)
                {
                    // skip tradeskill tools. If tools need to be mailed then they should be selected by ID
                    if (ProfessionbuddyBot.Instance.TradeskillTools.Contains(item.Entry))
                    {
                        continue;
                    }
                    // don't add same item id multiple times.
                    if (tmpItemlist.Any(ae => ae.Id == item.Entry))
                    {
                        continue;
                    }
                    // skip items with less than 'StackSize amount in bag if not posting partial stacks.
                    if (!PostPartialStacks && Helpers.InbagCount(item.Entry) < StackSize)
                    {
                        continue;
                    }
                    tmpItemlist.Add(new AuctionEntry(item.Name, item.Entry, 0, 0));
                }
            }
            else
            {
                string[] entries = ItemID.Split(',');
                if (entries.Length > 0)
                {
                    foreach (string entry in entries)
                    {
                        uint itemID;
                        if (!uint.TryParse(entry.Trim(), out itemID))
                        {
                            PBLog.Warn(Strings["Error_NotAValidItemEntry"], entry.Trim());
                            continue;
                        }
                        List <WoWItem> itemList = StyxWoW.Me.BagItems.Where(i => !i.IsSoulbound && !i.IsConjured && i.Entry == itemID).ToList();
                        if (!itemList.Any() || !PostPartialStacks && itemList.Count < StackSize)
                        {
                            continue;
                        }
                        tmpItemlist.Add(new AuctionEntry(itemList[0].Name, itemList[0].Entry, 0, 0));
                    }
                }
                else
                {
                    PBLog.Warn(Strings["Error_NoItemEntries"]);
                    IsDone = true;
                }
            }
            return(tmpItemlist);
        }
示例#5
0
        private List <uint> BuildItemList()
        {
            var idList = new List <uint>();

            string[] entries = ItemID.Split(',');
            if (entries.Length > 0)
            {
                foreach (string entry in entries)
                {
                    uint itemID;
                    if (!uint.TryParse(entry.Trim(), out itemID))
                    {
                        PBLog.Warn(Strings["Error_NotAValidItemEntry"], entry.Trim());
                        continue;
                    }
                    idList.Add(itemID);
                }
            }
            else
            {
                PBLog.Warn(Strings["Error_NoItemEntries"]);
                IsDone = true;
            }
            return(idList);
        }
示例#6
0
        protected override async Task Run()
        {
            if (MoveType != MoveToType.Location)
            {
                _loc = GetLocationFromType(MoveType, Entry);
                if (_loc == WoWPoint.Zero)
                {
                    if (_locationDb == WoWPoint.Zero)
                    {
                        _locationDb = GetLocationFromDB(MoveType, Entry);
                    }
                    _loc = _locationDb;
                }
                if (_loc == WoWPoint.Zero)
                {
                    PBLog.Warn(Strings["Error_UnableToFindLocationFromDB"]);
                    IsDone = true;
                    return;
                }
            }
            if (Entry > 0 && (!StyxWoW.Me.GotTarget || StyxWoW.Me.CurrentTarget.Entry != Entry))
            {
                WoWUnit unit = ObjectManager.GetObjectsOfType <WoWUnit>(true).FirstOrDefault(u => u.Entry == Entry);
                if (unit != null)
                {
                    unit.Target();
                }
            }
            float speed = StyxWoW.Me.MovementInfo.CurrentSpeed;

            Navigator.PathPrecision = speed > 7 ? (SpeedModifer * speed) / 7f : SpeedModifer;
            if (StyxWoW.Me.Location.Distance(_loc) > 4.5)
            {
                if (Pathing == NavigationType.ClickToMove)
                {
                    WoWMovement.ClickToMove(_loc);
                }
                else
                {
                    Util.MoveTo(_loc);
                }
            }
            else
            {
                if (!_concludingSw.IsRunning)
                {
                    _concludingSw.Start();
                }
                else if (_concludingSw.ElapsedMilliseconds >= 2000)
                {
                    IsDone = true;
                    PBLog.Log("MoveTo Action completed for type {0}", MoveType);
                    _concludingSw.Stop();
                    _concludingSw.Reset();
                }
            }
        }
示例#7
0
        protected async override Task Run()
        {
            try
            {
                if (
                    Lua.GetReturnVal <int>(
                        "if AuctionFrame and AuctionFrame:IsVisible() == 1 then return 1 else return 0 end ", 0) ==
                    0)
                {
                    MoveToAh();
                }
                else if (
                    Lua.GetReturnVal <int>(
                        "if CanSendAuctionQuery('owner') == 1 then return 1 else return 0 end ", 0) == 1)
                {
                    if (_toScanItemList == null)
                    {
                        _toScanItemList   = BuildScanItemList();
                        _toCancelItemList = new List <AuctionEntry>();
                    }

                    if (_toScanItemList.Count > 0)
                    {
                        AuctionEntry ae       = _toScanItemList[0];
                        bool         scanDone = ScanAh(ref ae);
                        _toScanItemList[0] = ae;                 // update
                        if (scanDone)
                        {
                            _toCancelItemList.Add(ae);
                            _toScanItemList.RemoveAt(0);
                        }
                        if (_toScanItemList.Count == 0)
                        {
                            ProfessionbuddyBot.Debug("Finished scanning for items");
                        }
                    }
                    else
                    {
                        if (_toCancelItemList.Count == 0)
                        {
                            _toScanItemList = null;
                            IsDone          = true;
                            return;
                        }
                        if (CancelAuction(_toCancelItemList[0]))
                        {
                            _toCancelItemList.RemoveAt(0);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                PBLog.Warn(ex.ToString());
            }
        }
示例#8
0
        private List <AuctionEntry> BuildScanItemList()
        {
            var tmpItemlist = new List <AuctionEntry>();
            Dictionary <uint, string> myAucs = GetMyAuctions();

            if (UseCategory)
            {
                using (StyxWoW.Memory.AcquireFrame())
                {
                    foreach (var aucKV in myAucs)
                    {
                        ItemInfo info = ItemInfo.FromId(aucKV.Key);
                        if (info != null)
                        {
                            if (info.ItemClass == Category && SubCategoryCheck(info.SubClassId))
                            {
                                tmpItemlist.Add(new AuctionEntry(aucKV.Value, aucKV.Key, 0, 0));
                            }
                        }
                        else
                        {
                            PBLog.Warn("item cache of {0} is null", aucKV.Value);
                        }
                    }
                }
            }
            else
            {
                if (ItemID == "0" || ItemID == "")
                {
                    tmpItemlist.AddRange(myAucs.Select(kv => new AuctionEntry(kv.Value, kv.Key, 0, 0)));
                }
                else
                {
                    string[] entries = ItemID.Split(',');
                    if (entries.Length > 0)
                    {
                        foreach (string entry in entries)
                        {
                            uint itemID;
                            if (!uint.TryParse(entry.Trim(), out itemID))
                            {
                                PBLog.Warn(Strings["Error_NotAValidItemEntry"], entry.Trim());
                                continue;
                            }
                            if (myAucs.ContainsKey(itemID))
                            {
                                tmpItemlist.Add(new AuctionEntry(myAucs[itemID], itemID, 0, 0));
                            }
                        }
                    }
                }
            }
            return(tmpItemlist);
        }
示例#9
0
        private Dictionary <uint, int> BuildItemList()
        {
            var itemList = new Dictionary <uint, int>();
            IEnumerable <WoWItem> tmpItemlist = from item in Me.BagItems
                                                where !item.IsConjured && !item.IsSoulbound && !item.IsDisabled
                                                select item;

            if (UseCategory)
            {
                foreach (WoWItem item in tmpItemlist)
                {
                    if (item.ItemInfo.ItemClass == Category &&
                        SubCategoryCheck(item) && !itemList.ContainsKey(item.Entry))
                    {
                        itemList.Add(
                            item.Entry,
                            Deposit == DepositWithdrawAmount.Amount
                                                                ? Amount
                                                                : Util.GetCarriedItemCount(item.Entry));
                    }
                }
            }
            else
            {
                string[] entries = ItemID.Split(',');
                if (entries.Length > 0)
                {
                    foreach (string entry in entries)
                    {
                        uint itemID;
                        if (!uint.TryParse(entry.Trim(), out itemID))
                        {
                            PBLog.Warn(Strings["Error_NotAValidItemEntry"], entry.Trim());
                            continue;
                        }
                        itemList.Add(
                            itemID,
                            Deposit == DepositWithdrawAmount.Amount
                                                                ? Amount
                                                                : Util.GetCarriedItemCount(itemID));
                    }
                }
                else
                {
                    PBLog.Warn(Strings["Error_NoItemEntries"]);
                    IsDone = true;
                }
            }
            return(itemList);
        }
示例#10
0
 protected bool CanRun()
 {
     try
     {
         return(CanRunDelegate(this));
     }
     catch (Exception ex)
     {
         if (ex.GetType() != typeof(ThreadAbortException))
         {
             PBLog.Warn("{0}\nErr:{1}", Title, ex);
         }
         return(false);
     }
 }
示例#11
0
        protected override async Task Run()
        {
            try
            {
                if (_changeBotTimer == null)
                {
                    _changeBotTimer = new WaitTimer(TimeSpan.FromSeconds(10));
                    _changeBotTimer.Reset();
                    _bot = Util.GetBotByName(BotName);
                    if (_bot != null)
                    {
                        if (ProfessionbuddyBot.Instance.SecondaryBot == _bot)
                        {
                            IsDone = true;
                            return;
                        }
                        ProfessionbuddyBot.ChangeSecondaryBot(BotName);
                    }
                }
            }
            finally
            {
                // Wait until bot change completes or fails
                if (_bot == null ||
                    _changeBotTimer != null && (_changeBotTimer.IsFinished || ProfessionbuddyBot.Instance.SecondaryBot == _bot))
                {
                    IsDone          = true;
                    _changeBotTimer = null;
                }
            }

            if (IsDone)
            {
                if (_bot == null)
                {
                    PBLog.Warn("No bot with name: {0} could be found", BotName);
                }
                else if (ProfessionbuddyBot.Instance.SecondaryBot == _bot)
                {
                    PBLog.Log("Successfuly changed secondary bot to: {0}", BotName);
                }
                else
                {
                    PBLog.Warn("Unable to switch secondary bot to: {0}", BotName);
                }
            }
        }
示例#12
0
        private async Task OpenMailbox()
        {
            WoWPoint      movetoPoint = _loc;
            WoWGameObject mailbox;

            if (AutoFindMailBox || movetoPoint == WoWPoint.Zero)
            {
                mailbox =
                    ObjectManager.GetObjectsOfType <WoWGameObject>().Where(
                        o => o.SubType == WoWGameObjectType.Mailbox && o.CanUse())
                    .OrderBy(o => o.DistanceSqr).FirstOrDefault();
            }
            else
            {
                mailbox =
                    ObjectManager.GetObjectsOfType <WoWGameObject>().Where(
                        o => o.SubType == WoWGameObjectType.Mailbox &&
                        o.Location.Distance(_loc) < 10 && o.CanUse())
                    .OrderBy(o => o.DistanceSqr).FirstOrDefault();
            }
            if (mailbox != null)
            {
                movetoPoint = mailbox.Location;
            }

            if (movetoPoint == WoWPoint.Zero)
            {
                PBLog.Warn(Strings["Error_UnableToFindMailbox"]);
                return;
            }

            if (mailbox == null || !mailbox.WithinInteractRange)
            {
                await CommonCoroutines.MoveTo(movetoPoint);

                return;
            }

            if (Me.IsMoving)
            {
                await CommonCoroutines.StopMoving();
            }
            mailbox.Interact();
        }
示例#13
0
        private void MoveToAh()
        {
            WoWPoint movetoPoint = _loc;
            WoWUnit  auctioneer;

            if (AutoFindAh || movetoPoint == WoWPoint.Zero)
            {
                auctioneer =
                    ObjectManager.GetObjectsOfType <WoWUnit>()
                    .Where(o => o.IsAuctioneer && o.IsAlive)
                    .OrderBy(o => o.Distance)
                    .FirstOrDefault();
            }
            else
            {
                auctioneer =
                    ObjectManager.GetObjectsOfType <WoWUnit>()
                    .Where(o => o.IsAuctioneer && o.Location.Distance(_loc) < 5)
                    .OrderBy(o => o.Distance)
                    .FirstOrDefault();
            }
            if (auctioneer != null)
            {
                movetoPoint = WoWMathHelper.CalculatePointFrom(Me.Location, auctioneer.Location, 3);
            }
            else if (movetoPoint == WoWPoint.Zero)
            {
                movetoPoint = MoveToAction.GetLocationFromDB(MoveToAction.MoveToType.NearestAH, 0);
            }
            if (movetoPoint == WoWPoint.Zero)
            {
                PBLog.Warn(Strings["Error_UnableToFindAuctioneer"]);
            }
            if (movetoPoint.Distance(StyxWoW.Me.Location) > 4.5)
            {
                Util.MoveTo(movetoPoint);
            }
            else if (auctioneer != null)
            {
                auctioneer.Interact();
            }
        }
示例#14
0
        protected async override Task Run()
        {
            try
            {
                if (!SubRoutineComposite.GetSubRoutineMyName(SubRoutineName, out _sub))
                {
                    PBLog.Warn("{0}: {1}.", ProfessionbuddyBot.Instance.Strings["Error_SubroutineNotFound"], SubRoutineName);
                    return;
                }

                _treeHookStub = new ActionRunCoroutine(ctx => SubRoutineExecutor());
                TreeHooks.Instance.InsertHook(TreeHookName, 0, _treeHookStub);
                BotEvents.Profile.OnNewOuterProfileLoaded += ProfileOnOnNewOuterProfileLoaded;
                BotEvents.OnBotStopped += BotEvents_OnBotStopped;
                PBLog.Debug("Attached the '{0}' SubRoutine to the {1} TreeHook", SubRoutineName, TreeHookName);
            }
            finally
            {
                _ranonce = true;
            }
        }
        private Dictionary <uint, int> BuildItemList()
        {
            var items = new Dictionary <uint, int>();

            switch (GetItemfromBankType)
            {
            case BankWithdrawlItemType.SpecificItem:
                //List<uint> idList = new List<uint>();
                string[] entries = ItemID.Split(',');
                if (entries.Length > 0)
                {
                    foreach (string entry in entries)
                    {
                        uint itemID;
                        if (!uint.TryParse(entry.Trim(), out itemID))
                        {
                            PBLog.Warn(Strings["Error_NotAValidItemEntry"], entry.Trim());
                            continue;
                        }
                        if (WithdrawAdditively)
                        {
                            items.Add(itemID, Withdraw == DepositWithdrawAmount.All ? int.MaxValue : Amount);
                        }
                        else
                        {
                            items.Add(itemID, Amount - Util.GetCarriedItemCount(itemID));
                        }
                    }
                }
                break;

            case BankWithdrawlItemType.Materials:
                foreach (var kv in PB.MaterialList)
                {
                    items.Add(kv.Key, kv.Value);
                }
                break;
            }
            return(items);
        }
示例#16
0
        private void MoveToBanker()
        {
            WoWPoint  movetoPoint = _loc;
            WoWObject bank        = GetLocalBanker();

            if (bank != null)
            {
                movetoPoint = WoWMathHelper.CalculatePointFrom(Me.Location, bank.Location, 4);
            }
            // search the database
            else if (movetoPoint == WoWPoint.Zero)
            {
                movetoPoint = MoveToAction.GetLocationFromDB(
                    Bank == BankType.Personal
                                                ? MoveToAction.MoveToType.NearestBanker
                                                : MoveToAction.MoveToType.NearestGB,
                    NpcEntry);
            }
            if (movetoPoint == WoWPoint.Zero)
            {
                IsDone = true;
                PBLog.Warn("Unable to find bank");
            }
            if (movetoPoint.Distance(StyxWoW.Me.Location) > 4)
            {
                Util.MoveTo(movetoPoint);
            }
            // since there are many personal bank replacement addons I can't just check if frame is open and be generic.. using events isn't reliable
            else if (bank != null)
            {
                bank.Interact();
            }
            else
            {
                IsDone = true;
                PBLog.Warn(Strings["Error_UnableToFindBank"]);
            }
        }
示例#17
0
 protected async override Task Run()
 {
     if (!_timeout.IsRunning)
     {
         _timeout.Start();
     }
     try
     {
         if (_timeout.ElapsedMilliseconds >= Timeout || CanRunDelegate(this))
         {
             _timeout.Reset();
             ProfessionbuddyBot.Debug("Wait for {0} or until {1} Completed", TimeSpan.FromMilliseconds(Timeout), Condition);
             IsDone = true;
         }
     }
     catch (Exception ex)
     {
         if (ex.GetType() != typeof(ThreadAbortException))
         {
             PBLog.Warn("{0}:({1})\n{2}", Strings["Action_WaitAction_Name"], Condition, ex);
         }
     }
 }
示例#18
0
        protected override async Task Run()
        {
            if (MerchantFrame.Instance == null || !MerchantFrame.Instance.IsVisible)
            {
                WoWPoint movetoPoint = _loc;
                WoWUnit  unit        = ObjectManager.GetObjectsOfType <WoWUnit>().Where(o => o.Entry == NpcEntry).
                                       OrderBy(o => o.Distance).FirstOrDefault();
                if (unit != null)
                {
                    movetoPoint = WoWMathHelper.CalculatePointFrom(Me.Location, unit.Location, 3);
                }
                else if (movetoPoint == WoWPoint.Zero)
                {
                    movetoPoint = MoveToAction.GetLocationFromDB(MoveToAction.MoveToType.NpcByID, NpcEntry);
                }
                if (movetoPoint != WoWPoint.Zero && StyxWoW.Me.Location.Distance(movetoPoint) > 4.5)
                {
                    Util.MoveTo(movetoPoint);
                }
                else if (unit != null)
                {
                    unit.Target();
                    unit.Interact();
                }
                if (GossipFrame.Instance != null && GossipFrame.Instance.IsVisible &&
                    GossipFrame.Instance.GossipOptionEntries != null)
                {
                    foreach (GossipEntry ge in GossipFrame.Instance.GossipOptionEntries)
                    {
                        if (ge.Type == GossipEntry.GossipEntryType.Vendor)
                        {
                            GossipFrame.Instance.SelectGossipOption(ge.Index);
                            break;
                        }
                    }
                }
            }
            else
            {
                // check if we have merchant frame open at correct NPC
                if (NpcEntry > 0 && Me.GotTarget && Me.CurrentTarget.Entry != NpcEntry)
                {
                    MerchantFrame.Instance.Close();
                    return;
                }
                if (!_concludingSw.IsRunning)
                {
                    if (BuyItemType == BuyItemActionType.SpecificItem)
                    {
                        var      idList  = new List <uint>();
                        string[] entries = ItemID.Split(',');
                        if (entries.Length > 0)
                        {
                            foreach (string entry in entries)
                            {
                                uint itemID;
                                if (!uint.TryParse(entry.Trim(), out itemID))
                                {
                                    PBLog.Warn(Strings["Error_NotAValidItemEntry"], entry.Trim());
                                    continue;
                                }
                                idList.Add(itemID);
                            }
                        }
                        else
                        {
                            PBLog.Warn(Strings["Error_NoItemEntries"]);
                            IsDone = true;
                            return;
                        }
                        foreach (uint id in idList)
                        {
                            int count = !BuyAdditively?Math.Max(Count - Util.GetCarriedItemCount(id), 0) : Count;

                            if (count > 0)
                            {
                                BuyItem(id, (uint)count);
                            }
                        }
                    }
                    else if (BuyItemType == BuyItemActionType.Material)
                    {
                        foreach (var kv in ProfessionbuddyBot.Instance.MaterialList)
                        {
                            // only buy items if we don't have enough in bags...
                            int amount = kv.Value - (int)Ingredient.GetInBagItemCount(kv.Key);
                            if (amount > 0)
                            {
                                BuyItem(kv.Key, (uint)amount);
                            }
                        }
                    }
                    _concludingSw.Start();
                }
                if (_concludingSw.ElapsedMilliseconds >= 2000)
                {
                    PBLog.Log("BuyItemAction Completed");
                    IsDone = true;
                }
            }
        }
示例#19
0
        public static Type CompileAndLoad()
        {
            CompilerResults results;

            using (var provider = new CSharpCodeProvider(
                       new Dictionary <string, string>
            {
                { "CompilerVersion", "v4.0" },
            }))
            {
                var options = new CompilerParameters();
                foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
                {
                    if (!asm.GetName().Name.Contains(ProfessionbuddyBot.Instance.Name) && !asm.IsDynamic)
                    {
                        options.ReferencedAssemblies.Add(asm.Location);
                    }
                }

                options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);

                // disabled due to a bug in 2.0.0.3956;
                //options.GenerateInMemory = true;
                options.GenerateExecutable      = false;
                options.TempFiles               = new TempFileCollection(TempFolder, false);
                options.IncludeDebugInformation = false;
                options.OutputAssembly          = string.Format("{0}\\CodeAssembly{1:N}.dll", TempFolder, Guid.NewGuid());
                options.CompilerOptions         = "/optimize /nowarn:1998";
                CsharpStringBuilder             = new StringBuilder();
                CsharpStringBuilder.Append(Prefix);
                // Line numbers are used to identify actions that genorated compile errors.
                int currentLine = CsharpStringBuilder.ToString().Count(c => c == '\n') + 1;
                // genorate CanRun Methods
                foreach (var met in Declarations)
                {
                    CsharpStringBuilder.AppendFormat("{0}\n", met.Value.Code.Replace(Environment.NewLine, ""));
                    met.Value.CodeLineNumber = currentLine++;
                }
                foreach (var met in NoneDeclarations)
                {
                    switch (met.Value.CodeType)
                    {
                    case CsharpCodeType.BoolExpression:
                        CsharpStringBuilder.AppendFormat(
                            "public bool {0} (object instance){{return {1};}}\n",
                            met.Key,
                            met.Value.Code.Replace(Environment.NewLine, ""));
                        break;

                    case CsharpCodeType.Statements:
                        CsharpStringBuilder.AppendFormat(
                            "public void {0} (object instance){{{1}}}\n",
                            met.Key,
                            met.Value.Code.Replace(Environment.NewLine, ""));
                        break;

                    case CsharpCodeType.Coroutine:
                        CsharpStringBuilder.AppendFormat(
                            "public async Task {0} (object instance){{{1}}}\n",
                            met.Key,
                            met.Value.Code.Replace(Environment.NewLine, ""));
                        break;

                    default:
                        Type retType = ((IDynamicProperty)met.Value).ReturnType;
                        CsharpStringBuilder.AppendFormat(
                            "public {0} {1} (object instance){{return ({0}){2};}}\n",
                            retType.Name,
                            met.Key,
                            met.Value.Code.Replace(Environment.NewLine, ""));
                        break;
                    }
                    met.Value.CodeLineNumber = currentLine++;
                }
                CsharpStringBuilder.Append(Postfix);

                results = provider.CompileAssemblyFromSource(
                    options,
                    CsharpStringBuilder.ToString());
            }

            List <IPBComponent> compositesToRefreshList =
                CsharpCodeDict.Where(c => !string.IsNullOrEmpty(c.Value.CompileError))
                .Select(c => c.Value.AttachedComponent)
                .Distinct()
                .ToList();

            // clear all previous compile errors
            foreach (var code in CsharpCodeDict.Values)
            {
                code.CompileError = string.Empty;
                var dynamicProperty = code as IDynamicProperty;
                if (dynamicProperty == null)
                {
                    continue;
                }
                dynamicProperty.AttachedComposite.HasErrors = false;
            }

            if (results.Errors.HasErrors)
            {
                if (results.Errors.Count > 0)
                {
                    foreach (CompilerError error in results.Errors)
                    {
                        IDynamicallyCompiledCode icsc = CsharpCodeDict.Values.FirstOrDefault(c => c.CodeLineNumber == error.Line);
                        var dynamicProperty           = icsc as IDynamicProperty;

                        if (icsc != null)
                        {
                            if (dynamicProperty != null)
                            {
                                PBLog.Warn(
                                    "{0}->{1}\nCompile Error : {2}\n",
                                    icsc.AttachedComponent.Name,
                                    dynamicProperty.Name,
                                    error.ErrorText);
                                dynamicProperty.AttachedComposite.HasErrors = true;
                            }
                            else
                            {
                                PBLog.Warn("{0}\nCompile Error : {1}\n", icsc.AttachedComponent.Title, error.ErrorText);
                            }
                            if (!compositesToRefreshList.Contains(icsc.AttachedComponent))
                            {
                                compositesToRefreshList.Add(icsc.AttachedComponent);
                            }
                            icsc.CompileError = error.ErrorText;
                        }
                        else
                        {
                            PBLog.Warn("Unable to link action that produced Error: {0}", error.ErrorText);
                        }
                    }
                }
            }

            if (MainForm.IsValid)
            {
                foreach (var pbComposite in compositesToRefreshList)
                {
                    MainForm.Instance.RefreshActionTree(pbComposite);
                }
                MainForm.Instance.ActionGrid.Refresh();
            }

            CodeIsModified = false;
            return(results.Errors.HasErrors ? null : results.CompiledAssembly.GetType("CodeDriver"));
        }
示例#20
0
        private Dictionary <uint, int> BuildItemList()
        {
            var itemList = new Dictionary <uint, int>();
            IEnumerable <WoWItem> tmpItemlist = from item in Me.BagItems
                                                where !item.IsConjured && !item.IsSoulbound && !item.IsDisabled
                                                select item;

            switch (ItemSelection)
            {
            case ItemSelectionType.Category:
                foreach (WoWItem item in tmpItemlist)
                {
                    // skip tradeskill tools. If tools need to be mailed then they should be selected by ID
                    if (ProfessionbuddyBot.Instance.TradeskillTools.Contains(item.Entry))
                    {
                        continue;
                    }
                    if (item.ItemInfo.ItemClass == Category &&
                        SubCategoryCheck(item) && !itemList.ContainsKey(item.Entry))
                    {
                        itemList.Add(
                            item.Entry,
                            Mail == DepositWithdrawAmount.Amount
                                                                        ? Amount
                                                                        : Util.GetCarriedItemCount(item.Entry));
                    }
                }
                break;

            case ItemSelectionType.IDs:
                string[] entries = ItemID.Split(',');
                if (entries.Length > 0)
                {
                    foreach (string entry in entries)
                    {
                        uint itemID;
                        if (!uint.TryParse(entry.Trim(), out itemID))
                        {
                            PBLog.Warn(Strings["Error_NotAValidItemEntry"], entry.Trim());
                            continue;
                        }
                        itemList.Add(
                            itemID,
                            Mail == DepositWithdrawAmount.Amount
                                                                        ? Amount
                                                                        : Util.GetCarriedItemCount(itemID));
                    }
                }
                else
                {
                    PBLog.Warn("No ItemIDs are specified");
                    IsDone = true;
                }
                break;

            case ItemSelectionType.Quality:
                foreach (WoWItem item in tmpItemlist)
                {
                    // skip tradeskill tools. If tools need to be mailed then they should be selected by ID
                    if (ProfessionbuddyBot.Instance.TradeskillTools.Contains(item.Entry))
                    {
                        continue;
                    }
                    if (item.Quality == ItemQuality)
                    {
                        itemList.Add(
                            item.Entry,
                            Mail == DepositWithdrawAmount.Amount
                                                                        ? Amount
                                                                        : Util.GetCarriedItemCount(item.Entry));
                    }
                }
                break;
            }
            return(itemList);
        }
示例#21
0
        protected override async Task Run()
        {
            if (!_timeoutSW.IsRunning)
            {
                _timeoutSW.Start();
            }

            if (_timeoutSW.ElapsedMilliseconds > 300000)
            {
                IsDone = true;
            }

            if (MailFrame.Instance == null || !MailFrame.Instance.IsVisible)
            {
                WoWPoint movetoPoint = _loc;
                if (AutoFindMailBox || movetoPoint == WoWPoint.Zero)
                {
                    _mailbox =
                        ObjectManager.GetObjectsOfType <WoWGameObject>().Where(
                            o => o.SubType == WoWGameObjectType.Mailbox && o.CanUse())
                        .OrderBy(o => o.DistanceSqr).FirstOrDefault();
                }
                else
                {
                    _mailbox =
                        ObjectManager.GetObjectsOfType <WoWGameObject>().Where(
                            o => o.SubType == WoWGameObjectType.Mailbox &&
                            o.Location.Distance(_loc) < 10 && o.CanUse())
                        .OrderBy(o => o.DistanceSqr).FirstOrDefault();
                }
                if (_mailbox != null)
                {
                    movetoPoint = _mailbox.Location;
                }
                if (movetoPoint == WoWPoint.Zero)
                {
                    PBLog.Warn(Strings["Error_UnableToFindMailbox"]);
                    return;
                }

                if (_mailbox == null || !_mailbox.WithinInteractRange)
                {
                    Util.MoveTo(movetoPoint);
                }
                else if (_mailbox != null)
                {
                    if (Me.IsMoving)
                    {
                        WoWMovement.MoveStop();
                    }
                    _mailbox.Interact();
                }
                return;
            }
            // mail frame is open.
            if (_idList == null)
            {
                _idList = BuildItemList();
            }
            if (!_refreshInboxSW.IsRunning)
            {
                _refreshInboxSW.Start();
            }
            if (!_waitForContentToShowSW.IsRunning)
            {
                _waitForContentToShowSW.Start();
            }
            if (_waitForContentToShowSW.ElapsedMilliseconds < 3000)
            {
                return;
            }

            if (!_concludingSW.IsRunning)
            {
                if (_refreshInboxSW.ElapsedMilliseconds < 64000)
                {
                    if (MinFreeBagSlots > 0 && Me.FreeNormalBagSlots - MinFreeBagSlots <= 4)
                    {
                        if (!_throttleSW.IsRunning)
                        {
                            _throttleSW.Start();
                        }
                        if (_throttleSW.ElapsedMilliseconds < 4000 - (Me.FreeNormalBagSlots - MinFreeBagSlots) * 1000)
                        {
                            return;
                        }
                        _throttleSW.Reset();
                        _throttleSW.Start();
                    }
                    if (GetMailType == GetMailActionType.AllItems)
                    {
                        string lua = string.Format(MailFormat, CheckNewMail ? 1 : 0, MaxCODAmount.TotalCopper);
                        if (Me.FreeNormalBagSlots <= MinFreeBagSlots || Lua.GetReturnValues(lua)[0] == "1")
                        {
                            _concludingSW.Start();
                        }
                    }
                    else
                    {
                        if (_idList.Count > 0 && Me.FreeNormalBagSlots > MinFreeBagSlots)
                        {
                            string lua = string.Format(MailByIdFormat, _idList[0], CheckNewMail ? 1 : 0, MaxCODAmount.TotalCopper);

                            if (Lua.GetReturnValues(lua)[0] == "1")
                            {
                                _idList.RemoveAt(0);
                            }
                        }
                        else
                        {
                            _concludingSW.Start();
                        }
                    }
                }
                else
                {
                    _refreshInboxSW.Reset();
                    MailFrame.Instance.Close();
                }
            }
            if (_concludingSW.ElapsedMilliseconds > 2000)
            {
                IsDone = true;
            }
            if (IsDone)
            {
                PBLog.Log("Mail retrieval of items:{0} finished", GetMailType);
            }
        }
示例#22
0
        private List <BuyItemEntry> BuildItemList()
        {
            var list   = new List <BuyItemEntry>();
            var idList = new List <uint>();

            string[] entries = ItemID.Split(',');
            if (entries.Length > 0)
            {
                foreach (string entry in entries)
                {
                    uint itemID;
                    if (!uint.TryParse(entry.Trim(), out itemID))
                    {
                        PBLog.Warn(Strings["Error_NotAValidItemEntry"], entry.Trim());
                        continue;
                    }
                    idList.Add(itemID);
                }
            }
            else
            {
                PBLog.Warn(Strings["Error_NoItemEntries"]);
                IsDone = true;
            }

            switch (ItemListType)
            {
            case ItemType.Item:
                list.AddRange(
                    from id in idList
                    let amount = !BuyAdditively ? Amount - Util.GetCarriedItemCount(id) : Amount
                                 where amount > 0
                                 select new BuyItemEntry {
                    BuyAmount = (uint)amount, Id = id
                });
                break;

            case ItemType.MaterialList:
                list.AddRange(
                    PB.MaterialList.Select(kv => new BuyItemEntry {
                    Id = kv.Key, BuyAmount = (uint)kv.Value
                }));
                break;

            case ItemType.RecipeMats:
                list.AddRange(from id in idList
                              select(from tradeskill in PB.TradeSkillList
                                     where tradeskill.KnownRecipes.ContainsKey(id)
                                     select tradeskill.KnownRecipes[id]).FirstOrDefault()
                              into recipe
                              where recipe != null
                              from ingred in recipe.Ingredients
                              let toBuyAmount =
                                  (int)((ingred.Required * Amount) - Ingredient.GetInBagItemCount(ingred.ID))
                                  where toBuyAmount > 0
                                  select new BuyItemEntry {
                    Id = ingred.ID, BuyAmount = (uint)toBuyAmount
                });
                break;
            }
            return(list);
        }
示例#23
0
        protected async override Task Run()
        {
            if (Me.IsFlying && await CommonCoroutines.Dismount("Crafting an item"))
            {
                return;
            }

            if (!IsRecipe)
            {
                CheckTradeskillList();
            }

            if (Casted >= CalculatedRepeat)
            {
                Finished();
                return;
            }

            // can't make recipe so stop trying.
            if (IsRecipe && Recipe.CanRepeatNum2 <= 0)
            {
                Finished("Not enough material.");
                return;
            }

            if (Me.IsCasting && Me.CastingSpellId != Entry)
            {
                SpellManager.StopCasting();
            }

            // we should confirm the last recipe in list so we don't make an axtra
            if (Casted + 1 < CalculatedRepeat || (Casted + 1 == CalculatedRepeat &&
                                                  (Confimed || !_spamControl.IsRunning ||
                                                   (_spamControl.ElapsedMilliseconds >=
                                                    (_recastTime + (_recastTime / 2)) + _waitTime &&
                                                    !StyxWoW.Me.IsCasting))))
            {
                if (!_spamControl.IsRunning || Me.IsCasting && Me.CurrentCastTimeLeft <= TimeSpan.FromMilliseconds(250) ||
                    (!StyxWoW.Me.IsCasting && _spamControl.ElapsedMilliseconds >= _waitTime))
                {
                    if (StyxWoW.Me.IsMoving)
                    {
                        WoWMovement.MoveStop();
                    }
                    if (!QueueIsRunning)
                    {
                        Lua.Events.AttachEvent("UNIT_SPELLCAST_SUCCEEDED", OnUnitSpellCastSucceeded);
                        QueueIsRunning      = true;
                        TreeRoot.StatusText = string.Format("Casting: {0}",
                                                            IsRecipe
                                                                                                                                ? Recipe.Name
                                                                                                                                : Entry.ToString());
                    }
                    WoWSpell spell = WoWSpell.FromId((int)Entry.Value);
                    if (spell == null)
                    {
                        PBLog.Warn("{0}: {1}", Strings["Error_UnableToFindSpellWithEntry"], Entry.Value.ToString(CultureInfo.InvariantCulture));
                        return;
                    }

                    _recastTime = spell.CastTime;
                    ProfessionbuddyBot.Debug("Casting {0}, recast :{1}", spell.Name, _recastTime);
                    if (CastOnItem)
                    {
                        WoWItem item = TargetedItem;
                        if (item != null)
                        {
                            spell.CastOnItem(item);
                        }
                        else
                        {
                            PBLog.Warn(
                                "{0}: {1}",
                                Strings["Error_UnableToFindItemToCastOn"],
                                IsRecipe
                                                                        ? Recipe.Name
                                                                        : Entry.Value.ToString(CultureInfo.InvariantCulture));
                            IsDone = true;
                        }
                    }
                    else
                    {
                        spell.Cast();
                    }
                    _waitTime = Util.WowWorldLatency * 3 + 50;
                    Confimed  = false;
                    _spamControl.Reset();
                    _spamControl.Start();
                }
            }
        }
        protected async override Task Run()
        {
            if (_loadingProfile)
            {
                return;
            }

            var absPath = GetAbsolutePath();

            bool emptyProfile = string.IsNullOrEmpty(Path);

            if (IsLocal)
            {
                // check if profile is already loaded.
                if (!string.IsNullOrEmpty(ProfileManager.XmlLocation) &&
                    ProfileManager.XmlLocation.Equals(absPath, StringComparison.CurrentCultureIgnoreCase))
                {
                    IsDone = true;
                    return;
                }
                // check if profile exists
                if (!emptyProfile && !File.Exists(absPath))
                {
                    PBLog.Warn("{0}: {1}", ProfessionbuddyBot.Instance.Strings["Error_UnableToFindProfile"], Path);
                    IsDone = true;
                    return;
                }
            }

            ProfessionbuddyBot.Debug(
                "Loading Profile: {0}, previous profile was {1}",
                emptyProfile ? "(Empty Profile)" : Path,
                ProfileManager.XmlLocation ?? "[No Profile]");

            var path = emptyProfile || !IsLocal ? Path : absPath;

            Util.ExecuteActionWhileBotIsStopped(
                () =>
            {
                try
                {
                    if (string.IsNullOrEmpty(path))
                    {
                        ProfileManager.LoadEmpty();
                    }
                    else if (!IsLocal)
                    {
                        var req   = WebRequest.Create(path);
                        req.Proxy = null;
                        using (WebResponse res = req.GetResponse())
                        {
                            using (var stream = res.GetResponseStream())
                            {
                                ProfileManager.LoadNew(stream);
                            }
                        }
                    }
                    else if (File.Exists(path))
                    {
                        ProfileManager.LoadNew(path);
                    }
                    IsDone = true;
                    ProfessionbuddyBot.Debug("Successfully loaded profile:{0}", emptyProfile ? "(Empty Profile)" : Path);
                }
                catch (Exception ex)
                {
                    // if ex is not null there was a problem loading profile.
                    ProfessionbuddyBot.Fatal("Failed to load profile.\n{0}", ex);
                }
            },
                "Loading a new profile");
            _loadingProfile = true;
        }
示例#25
0
        public bool Load()
        {
            var absPath = AbsolutePath;

            if (IsLocal && !string.IsNullOrEmpty(ProfileManager.XmlLocation) &&
                ProfileManager.XmlLocation.Equals(absPath, StringComparison.CurrentCultureIgnoreCase))
            {
                return(false);
            }
            try
            {
                // Logging.Write("Cava: {0}", "something");

                PBLog.Debug(
                    "CAVAPB Loading Profile :{0}, previous profile was {1}",
                    Path,
                    ProfileManager.XmlLocation ?? "[No Profile]");
                if (string.IsNullOrEmpty(Path))
                {
                    ProfileManager.LoadEmpty();
                }
                else if (!IsLocal)
                {
                    if (Path.Contains("cavaprofessions"))
                    {
                        var pathtocavasettings = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                                        string.Format(@"Settings\CavaPlugin\Main-Settings.xml"));
                        var servertouse = Getdata(pathtocavasettings, "UseServer");
                        if (servertouse == "0")
                        {
                            Path = "https://cavaprofiles.net/index.php/profiles/profiles-list/" + Path;
                            var url = string.Format("https://cavaprofiles.net/index.php?user={0}&passw={1}",
                                                    Getdata(pathtocavasettings, "CpLogin"), Decrypt(Getdata(pathtocavasettings, "CpPassword")));
                            var request = (HttpWebRequest)WebRequest.Create(url);
                            request.AllowAutoRedirect = false;
                            request.CookieContainer   = new CookieContainer();
                            var response = (HttpWebResponse)request.GetResponse();
                            var cookies  = request.CookieContainer;
                            response.Close();
                            try
                            {
                                request =
                                    (HttpWebRequest)
                                    WebRequest.Create(Path + "/file");
                                request.AllowAutoRedirect = false;
                                request.CookieContainer   = cookies;
                                response = (HttpWebResponse)request.GetResponse();
                                var    data = response.GetResponseStream();
                                string html;
                                // ReSharper disable once AssignNullToNotNullAttribute
                                using (var sr = new StreamReader(data))
                                {
                                    html = sr.ReadToEnd();
                                }
                                response.Close();
                                var profilepath =
                                    new MemoryStream(
                                        Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(Convert.FromBase64String(html))));
                                ProfileManager.LoadNew(profilepath);
                            }
                            catch (Exception ex)
                            {
                                PBLog.Warn(
                                    "CAVAPB Does not have access to Profile {0}. Please check if you have Profession access Error code: {1}",
                                    Path, ex);
                                return(false);
                            }
                        }
                        else
                        {
                            Path = "https://cavaprofiles.org/index.php/cavapages/profiles/profiles-list/" + Path;
                            var url = string.Format("https://cavaprofiles.org/index.php?user={0}&passw={1}",
                                                    Getdata(pathtocavasettings, "CpLogin"), Decrypt(Getdata(pathtocavasettings, "CpPassword")));
                            var request = (HttpWebRequest)WebRequest.Create(url);
                            request.AllowAutoRedirect = false;
                            request.CookieContainer   = new CookieContainer();
                            var response = (HttpWebResponse)request.GetResponse();
                            var cookies  = request.CookieContainer;
                            response.Close();
                            try
                            {
                                request =
                                    (HttpWebRequest)
                                    WebRequest.Create(Path + "/file");
                                request.AllowAutoRedirect = false;
                                request.CookieContainer   = cookies;
                                response = (HttpWebResponse)request.GetResponse();
                                var    data = response.GetResponseStream();
                                string html;
                                // ReSharper disable once AssignNullToNotNullAttribute
                                using (var sr = new StreamReader(data))
                                {
                                    html = sr.ReadToEnd();
                                }
                                response.Close();
                                var profilepath =
                                    new MemoryStream(
                                        Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(Convert.FromBase64String(html))));
                                ProfileManager.LoadNew(profilepath);
                            }
                            catch (Exception ex)
                            {
                                PBLog.Warn(
                                    "CAVAPB Does not have access to Profile {0}. Please check if you have Profession access Error code: {1}",
                                    Path, ex);
                                return(false);
                            }
                        }
                    }
                    else
                    {
                        var req = WebRequest.Create(Path);
                        req.Proxy = null;
                        using (WebResponse res = req.GetResponse())
                        {
                            using (var stream = res.GetResponseStream())
                            {
                                ProfileManager.LoadNew(stream);
                            }
                        }
                    }
                }
                else if (File.Exists(absPath))
                {
                    ProfileManager.LoadNew(absPath);
                }
                else
                {
                    PBLog.Warn("{0}: {1}", "CAVAPB Unable to find profile", Path);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                PBLog.Warn("CAVAPB {0}", ex);
                return(false);
            }
            return(true);
        }
示例#26
0
        /// <summary>
        ///     Switches to a different character on same account
        /// </summary>
        /// <param name="character"></param>
        /// <param name="server"></param>
        /// <param name="botName">Name of bot to use on that character. The bot class type name will also work.</param>
        public static void SwitchCharacter(string character, string server, string botName)
        {
            if (_isSwitchingToons)
            {
                PBLog.Log("Already switching characters");
                return;
            }
            string loginLua = string.Format(LoginLua, character, server);

            _isSwitchingToons = true;
            // reset all actions
            ProfessionbuddyBot.Instance.IsRunning = false;
            ProfessionbuddyBot.Instance.Reset();

            Application.Current.Dispatcher.BeginInvoke(
                new Action(
                    () =>
            {
                Lua.DoString("Logout()");

                new Thread(
                    () =>
                {
                    while (StyxWoW.IsInGame)
                    {
                        Thread.Sleep(2000);
                    }
                    while (!StyxWoW.IsInGame)
                    {
                        Lua.DoString(loginLua);
                        Thread.Sleep(2000);
                    }
                    BotBase bot = Util.GetBotByName(botName);
                    if (bot != null)
                    {
                        if (ProfessionbuddyBot.Instance.SecondaryBot.Name != bot.Name)
                        {
                            ProfessionbuddyBot.Instance.SecondaryBot = bot;
                        }
                        if (!bot.Initialized)
                        {
                            bot.DoInitialize();
                        }
                        if (ProfessionBuddySettings.Instance.LastBotBase != bot.Name)
                        {
                            ProfessionBuddySettings.Instance.LastBotBase = bot.Name;
                            ProfessionBuddySettings.Instance.Save();
                        }
                    }
                    else
                    {
                        PBLog.Warn("Could not find bot with name {0}", botName);
                    }
                    TreeRoot.Start();
                    ProfessionbuddyBot.Instance.OnTradeSkillsLoaded += ProfessionbuddyBot.Instance.Professionbuddy_OnTradeSkillsLoaded;
                    ProfessionbuddyBot.Instance.LoadTradeSkills();
                    _isSwitchingToons = false;
                    ProfessionbuddyBot.Instance.IsRunning = true;
                })
                {
                    IsBackground = true
                }.Start();
            }));
            TreeRoot.Stop();
        }
示例#27
0
        protected override async Task Run()
        {
            if (MerchantFrame.Instance == null || !MerchantFrame.Instance.IsVisible)
            {
                WoWPoint movetoPoint = _loc;
                if (_entry == 0)
                {
                    _entry = NpcEntry;
                }
                if (_entry == 0)
                {
                    MoveToAction.GetLocationFromDB(MoveToAction.MoveToType.NearestVendor, 0);
                    NpcResult npcResults = NpcQueries.GetNearestNpc(
                        StyxWoW.Me.MapId,
                        StyxWoW.Me.Location,
                        UnitNPCFlags.Vendor);
                    _entry      = (uint)npcResults.Entry;
                    movetoPoint = npcResults.Location;
                }
                WoWUnit unit = ObjectManager.GetObjectsOfType <WoWUnit>().Where(o => o.Entry == _entry).
                               OrderBy(o => o.Distance).FirstOrDefault();
                if (unit != null)
                {
                    movetoPoint = unit.Location;
                }
                else if (movetoPoint == WoWPoint.Zero)
                {
                    movetoPoint = MoveToAction.GetLocationFromDB(MoveToAction.MoveToType.NpcByID, NpcEntry);
                }
                if (movetoPoint != WoWPoint.Zero && StyxWoW.Me.Location.Distance(movetoPoint) > 4.5)
                {
                    Util.MoveTo(movetoPoint);
                }
                else if (unit != null)
                {
                    unit.Target();
                    unit.Interact();
                }

                if (GossipFrame.Instance != null && GossipFrame.Instance.IsVisible &&
                    GossipFrame.Instance.GossipOptionEntries != null)
                {
                    foreach (GossipEntry ge in GossipFrame.Instance.GossipOptionEntries)
                    {
                        if (ge.Type == GossipEntry.GossipEntryType.Vendor)
                        {
                            GossipFrame.Instance.SelectGossipOption(ge.Index);
                            return;
                        }
                    }
                }
            }
            else
            {
                if (SellItemType == SellItemActionType.Specific)
                {
                    var      idList  = new List <uint>();
                    string[] entries = ItemID.Split(',');
                    if (entries.Length > 0)
                    {
                        foreach (string entry in entries)
                        {
                            uint itemID;
                            if (!uint.TryParse(entry.Trim(), out itemID))
                            {
                                PBLog.Warn(Strings["Error_NotAValidItemEntry"], entry.Trim());
                                continue;
                            }
                            idList.Add(itemID);
                        }
                    }
                    else
                    {
                        PBLog.Warn(Strings["Error_NoItemEntries"]);
                        IsDone = true;
                        return;
                    }
                    List <WoWItem> itemList = StyxWoW.Me.BagItems.Where(u => idList.Contains(u.Entry)).
                                              Take(Sell == DepositWithdrawAmount.All ? int.MaxValue : Count).ToList();
                    using (StyxWoW.Memory.AcquireFrame())
                    {
                        foreach (WoWItem item in itemList)
                        {
                            item.UseContainerItem();
                        }
                    }
                }
                else
                {
                    List <WoWItem>        itemList  = null;
                    IEnumerable <WoWItem> itemQuery = from item in Me.BagItems
                                                      where !ProtectedItemsManager.Contains(item.Entry) &&
                                                      !ProfessionbuddyBot.Instance.TradeskillTools.Contains(item.Entry)
                                                      select item;
                    switch (SellItemType)
                    {
                    case SellItemActionType.Greys:
                        itemList = itemQuery.Where(i => i.Quality == WoWItemQuality.Poor).ToList();
                        break;

                    case SellItemActionType.Whites:
                        itemList = itemQuery.Where(i => i.Quality == WoWItemQuality.Common).ToList();
                        break;

                    case SellItemActionType.Greens:
                        itemList = itemQuery.Where(i => i.Quality == WoWItemQuality.Uncommon).ToList();
                        break;

                    case SellItemActionType.Blues:
                        itemList = itemQuery.Where(i => i.Quality == WoWItemQuality.Rare).ToList();
                        break;
                    }
                    if (itemList != null)
                    {
                        using (StyxWoW.Memory.AcquireFrame())
                        {
                            foreach (WoWItem item in itemList)
                            {
                                item.UseContainerItem();
                            }
                        }
                    }
                }
                PBLog.Log("SellItemAction Completed for {0}", ItemID);
                IsDone = true;
            }
        }
示例#28
0
        protected override async Task Run()
        {
            if (!_interactTimer.IsFinished)
            {
                return;
            }

            if (!TrainerFrame.Instance.IsVisible || !StyxWoW.Me.GotTarget || StyxWoW.Me.CurrentTarget.Entry != NpcEntry)
            {
                WoWPoint movetoPoint = _loc;
                WoWUnit  unit        = ObjectManager.GetObjectsOfType <WoWUnit>().Where(o => o.Entry == NpcEntry).
                                       OrderBy(o => o.Distance).FirstOrDefault();

                if (unit != null)
                {
                    movetoPoint = unit.Location;
                }
                else if (movetoPoint == WoWPoint.Zero)
                {
                    movetoPoint = MoveToAction.GetLocationFromDB(MoveToAction.MoveToType.NpcByID, NpcEntry);
                }

                if (movetoPoint != WoWPoint.Zero && StyxWoW.Me.Location.Distance(movetoPoint) > 4.5)
                {
                    Util.MoveTo(movetoPoint);
                    return;
                }

                if (GossipFrame.Instance.IsVisible)
                {
                    foreach (GossipEntry ge in GossipFrame.Instance.GossipOptionEntries)
                    {
                        if (ge.Type == GossipEntry.GossipEntryType.Trainer)
                        {
                            GossipFrame.Instance.SelectGossipOption(ge.Index);
                            return;
                        }
                    }
                    PBLog.Warn("NPC does not provide a train gossip option");
                    // we should not continue at this point.
                    TreeRoot.Stop();
                    return;
                }

                if (Me.IsMoving)
                {
                    WoWMovement.MoveStop();
                    return;
                }

                if (unit != null)
                {
                    if (Me.CurrentTargetGuid != unit.Guid)
                    {
                        unit.Target();
                        return;
                    }
                    _interactTimer.Reset();
                    unit.Interact();
                }

                return;
            }

            if (_trainWaitTimer.IsFinished)
            {
                using (StyxWoW.Memory.AcquireFrame())
                {
                    Lua.DoString("SetTrainerServiceTypeFilter('available', 1)");
                    // check if there is any abilities to that need training.
                    var numOfAvailableAbilities =
                        Lua.GetReturnVal <int>(
                            "local a=0 for n=GetNumTrainerServices(),1,-1 do if select(3,GetTrainerServiceInfo(n)) == 'available' then a=a+1 end end return a ",
                            0);
                    if (numOfAvailableAbilities == 0)
                    {
                        IsDone = true;
                        PBLog.Log("Done training");
                        return;
                    }
                    Lua.DoString("BuyTrainerService(0) ");
                    _trainWaitTimer.Reset();
                }
            }
        }