Beispiel #1
0
        /// <summary>
        /// Starts the callback thread and connects to Steam via SteamKit2.
        /// </summary>
        /// <remarks>
        /// THIS NEVER RETURNS.
        /// </remarks>
        /// <returns><c>true</c>. See remarks</returns>
        public bool RestartBot()
        {
            if (IsRunning)
            {
                return(false);
            }

            log = new Log(LogFile, this.DisplayName, LogLevel);

            // Hacking around https
            ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;

            log.Debug("Initializing Steam Bot...");
            SteamClient          = new SteamClient();
            SteamTrade           = SteamClient.GetHandler <SteamTrading>();
            SteamUser            = SteamClient.GetHandler <SteamUser>();
            SteamFriends         = SteamClient.GetHandler <SteamFriends>();
            SteamGameCoordinator = SteamClient.GetHandler <SteamGameCoordinator>();

            backgroundWorker = new BackgroundWorker {
                WorkerSupportsCancellation = true
            };
            backgroundWorker.DoWork             += BackgroundWorkerOnDoWork;
            backgroundWorker.RunWorkerCompleted += BackgroundWorkerOnRunWorkerCompleted;
            backgroundWorker.RunWorkerAsync();
            log.Info("Connecting...");

            SteamClient.Connect();

            IsRunning = true;

            log.Info("Done Loading Bot!");

            return(true); // never get here
        }
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false, bool process = false)
        {
            logOnDetails = new SteamUser.LogOnDetails
            {
                Username = config.Username,
                Password = config.Password
            };
            DisplayName          = config.DisplayName;
            MaximumTradeTime     = config.MaximumTradeTime;
            MaximiumActionGap    = config.MaximumActionGap;
            DisplayNamePrefix    = config.DisplayNamePrefix;
            TradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval;
            Admins           = config.Admins;
            BackpackUrl      = config.Backpack;
            sNumberTradeFile = config.TradeNumberSaveFile;
            this.apiKey      = apiKey;
            this.isprocess   = process;
            try
            {
                LogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true);
            }
            catch (ArgumentException)
            {
                Console.WriteLine("Invalid LogLevel provided in configuration. Defaulting to 'INFO'");
                LogLevel = Log.LogLevel.Info;
            }
            log             = new Log(config.LogFile, this.DisplayName, LogLevel);
            CreateHandler   = handlerCreator;
            BotControlClass = config.BotControlClass;

            // Hacking around https
            ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;
            dReserved = new Dictionary <ulong, SteamID>();
            dDonated  = new Dictionary <ulong, SteamID>();
            log.Debug("Initializing Steam Bot...");
            SteamClient          = new SteamClient();
            SteamTrade           = SteamClient.GetHandler <SteamTrading>();
            SteamUser            = SteamClient.GetHandler <SteamUser>();
            SteamFriends         = SteamClient.GetHandler <SteamFriends>();
            SteamGameCoordinator = SteamClient.GetHandler <SteamGameCoordinator>();
            craftHandler         = new CraftingHandler(this);
            informHandler        = new InformHandler(this, BotControlClass.Substring(9));
            AdvertiseHandler     = new AdvertiseHandler(this, BotControlClass.Substring(9), clsFunctions.BotGroup);
            backgroundWorker     = new BackgroundWorker {
                WorkerSupportsCancellation = true
            };

            if (!Directory.Exists(FriendsFolder))
            {
                Directory.CreateDirectory(FriendsFolder);
            }


            this.FriendActivity                  = FriendActivity.LoadFriendActivity(FriendsFolder + logOnDetails.Username + ".json");
            backgroundWorker.DoWork             += BackgroundWorkerOnDoWork;
            backgroundWorker.RunWorkerCompleted += BackgroundWorkerOnRunWorkerCompleted;
            backgroundWorker.RunWorkerAsync();
        }
Beispiel #3
0
 public void Initialize(bool useUDP)
 {
     SteamClient  = new SteamClient(useUDP ? ProtocolType.Udp : ProtocolType.Tcp);
     SteamFriends = SteamClient.GetHandler <SteamFriends>();
     SteamUser    = SteamClient.GetHandler <SteamUser>();
     SteamTrading = SteamClient.GetHandler <SteamTrading>();
     SteamWeb     = SteamClient.GetHandler <SteamWeb>();
     SteamGC      = SteamClient.GetHandler <SteamGameCoordinator>();
 }
Beispiel #4
0
        public BotControlForm(Configuration.BotInfo config, string apiKey, bool debug = false)
        {
            InitializeComponent();


            foreach (EPersonaState state in Enum.GetValues(typeof(EPersonaState)))
            {
                this.cbxPersonaState.Items.Add(state);
            }


            SetStatus("Setting variables...");

            logOnDetails = new SteamUser.LogOnDetails
            {
                Username = config.Username,
                Password = config.Password
            };
            DisplayName          = config.DisplayName;
            ChatResponse         = config.ChatResponse;
            MaximumTradeTime     = config.MaximumTradeTime;
            MaximiumActionGap    = config.MaximumActionGap;
            DisplayNamePrefix    = config.DisplayNamePrefix;
            TradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval;
            Admins      = config.Admins;
            this.apiKey = apiKey;
            try
            {
                LogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true);
            }
            catch (ArgumentException)
            {
                Console.WriteLine("Invalid LogLevel provided in configuration. Defaulting to 'INFO'");
                LogLevel = Log.LogLevel.Info;
            }
            log = new Log(config.LogFile, this.DisplayName, LogLevel);
            //CreateHandler = handlerCreator;
            BotControlClass = config.BotControlClass;

            // Hacking around https
            ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;


            SteamClient  = new SteamClient();
            SteamTrade   = SteamClient.GetHandler <SteamTrading>();
            SteamUser    = SteamClient.GetHandler <SteamUser>();
            SteamFriends = SteamClient.GetHandler <SteamFriends>();

            SetStatus("Connecting to Steam...");

            SteamClient.Connect();

            masterThread = new Thread(this.pollSteam);
            masterThread.Start();
        }
Beispiel #5
0
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false, bool process = false)
        {
            logOnDetails = new SteamUser.LogOnDetails
            {
                Username = config.Username,
                Password = config.Password
            };
            DisplayName          = config.DisplayName;
            ChatResponse         = config.ChatResponse;
            MaximumTradeTime     = config.MaximumTradeTime;
            MaximiumActionGap    = config.MaximumActionGap;
            DisplayNamePrefix    = config.DisplayNamePrefix;
            TradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval;
            SchemaLang           = config.SchemaLang != null && config.SchemaLang.Length == 2 ? config.SchemaLang.ToLower() : "en";
            Admins         = config.Admins;
            this.ApiKey    = !String.IsNullOrEmpty(config.ApiKey) ? config.ApiKey : apiKey;
            this.isprocess = process;

            try
            {
                LogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true);
            }
            catch (ArgumentException)
            {
                Console.WriteLine("Invalid LogLevel provided in configuration. Defaulting to 'INFO'");
                LogLevel = Log.LogLevel.Info;
            }
            log             = new Log(config.LogFile, this.DisplayName, LogLevel);
            CreateHandler   = handlerCreator;
            BotControlClass = config.BotControlClass;
            SteamWeb        = new SteamWeb();

            // Hacking around https
            ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;

            log.Debug("Initializing Steam Bot...");
            SteamClient = new SteamClient();
            SteamClient.AddHandler(new SteamNotifications());
            SteamTrade           = SteamClient.GetHandler <SteamTrading>();
            SteamUser            = SteamClient.GetHandler <SteamUser>();
            SteamFriends         = SteamClient.GetHandler <SteamFriends>();
            SteamGameCoordinator = SteamClient.GetHandler <SteamGameCoordinator>();
            SteamNotifications   = SteamClient.GetHandler <SteamNotifications>();

            backgroundWorker = new BackgroundWorker {
                WorkerSupportsCancellation = true
            };
            backgroundWorker.DoWork             += BackgroundWorkerOnDoWork;
            backgroundWorker.RunWorkerCompleted += BackgroundWorkerOnRunWorkerCompleted;
            backgroundWorker.RunWorkerAsync();
        }
Beispiel #6
0
        void ProcessTradeEvents()
        {
            // If we are not running a trade and are not waiting for the response
            // of a pending trade request, then we should dequeue a new trade.

            bool hasTrade         = CurrentTrade != null || PendingTradeRequest != null;
            bool hasPendingTrades = PendingTrades.Count > 0;

            if (!hasTrade && hasPendingTrades)
            {
                PendingTradeRequest = PendingTrades.Dequeue();
                SteamTrading.RequestTrade(PendingTradeRequest.Target);
                PendingTradeTimer.Change(PendingTradeTimeout, TimeSpan.FromTicks(-1));
            }

            ProcessCurrentTrade();
        }
Beispiel #7
0
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, Interface gui, bool debug = false)
        {
            while (Interface.loginClicked == false)
            {
                // Wait for user to login
            }

            logOnDetails = new SteamUser.LogOnDetails
            {
                Username = Interface.username,
                Password = Interface.password
            };
            Admins      = new ulong[1];
            Admins[0]   = 123456789;
            this.apiKey = apiKey;
            LogLevel    = Log.LogLevel.Info;
            //log = new Log(config.LogFile, this.DisplayName, LogLevel);
            CreateHandler   = handlerCreator;
            BotControlClass = config.BotControlClass;

            // Hacking around https
            ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;

            ////log.Debug("Initializing Steam Bot...");
            SteamClient  = new SteamClient();
            SteamTrade   = SteamClient.GetHandler <SteamTrading>();
            SteamUser    = SteamClient.GetHandler <SteamUser>();
            SteamFriends = SteamClient.GetHandler <SteamFriends>();
            gui.UpdateLog("\r\nConnecting, please wait...");
            ////log.Info("Connecting...");
            SteamClient.Connect();

            Thread CallbackThread = new Thread(() => // Callback Handling
            {
                while (true)
                {
                    CallbackMsg msg = SteamClient.WaitForCallback(true);

                    HandleSteamMessage(msg, gui);
                }
            });

            CallbackThread.Start();
            ////log.Success("Done Loading Bot!");
            CallbackThread.Join();
        }
Beispiel #8
0
        static void SteamLogin()
        {
            steamClient = new SteamClient();

            #region callbacks
            manager = new CallbackManager(steamClient);
            manager.Subscribe <SteamClient.ConnectedCallback>(OnConnected);
            manager.Subscribe <SteamClient.DisconnectedCallback>(OnDisconnected);
            manager.Subscribe <SteamUser.LoggedOnCallback>(OnLoggedOn);
            manager.Subscribe <SteamUser.UpdateMachineAuthCallback>(UpdateMachineAuthCallback); // If steam guard auth succeeded
            manager.Subscribe <SteamUser.AccountInfoCallback>(OnAccountInfo);
            manager.Subscribe <SteamUser.LoggedOffCallback>(OnLoggedOff);
            manager.Subscribe <SteamFriends.FriendMsgCallback>(OnChatMessage);
            manager.Subscribe <SteamFriends.FriendAddedCallback>(OnFriendAdded);
            manager.Subscribe <SteamFriends.FriendsListCallback>(OnFriendsList);
            manager.Subscribe <SteamGameCoordinator.MessageCallback>(OnGCMessage);
            #endregion

            #region Handlers
            steamUser            = steamClient.GetHandler <SteamUser>();
            steamFriends         = steamClient.GetHandler <SteamFriends>();
            steamCloud           = steamClient.GetHandler <SteamCloud>();
            steamGameServer      = steamClient.GetHandler <SteamGameServer>();
            steamMasterServer    = steamClient.GetHandler <SteamMasterServer>();
            steamGameCoordinator = steamClient.GetHandler <SteamGameCoordinator>();
            steamScreenshots     = steamClient.GetHandler <SteamScreenshots>();
            steamTrading         = steamClient.GetHandler <SteamTrading>();
            steamUFM             = steamClient.GetHandler <SteamUnifiedMessages>();
            steamUserStats       = steamClient.GetHandler <SteamUserStats>();
            steamWorkShop        = steamClient.GetHandler <SteamWorkshop>();
            #endregion

            isRunning = true;

            Console.Title = "Steam Bot - Connecting...";

            steamClient.Connect();

            while (isRunning)
            {
                manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
            }
            Console.ReadKey();
        }
Beispiel #9
0
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false, bool process = false)
        {
            userHandlers = new Dictionary <SteamID, UserHandler>();
            logOnDetails = new SteamUser.LogOnDetails
            {
                Username = config.Username,
                Password = config.Password
            };
            DisplayName          = config.DisplayName;
            ChatResponse         = config.ChatResponse;
            MaximumTradeTime     = config.MaximumTradeTime;
            MaximumActionGap     = config.MaximumActionGap;
            DisplayNamePrefix    = config.DisplayNamePrefix;
            tradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval;
            schemaLang           = config.SchemaLang != null && config.SchemaLang.Length == 2 ? config.SchemaLang.ToLower() : "en";
            Admins     = config.Admins;
            ApiKey     = !String.IsNullOrEmpty(config.ApiKey) ? config.ApiKey : apiKey;
            isProccess = process;
            try
            {
                if (config.LogLevel != null)
                {
                    consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true);
                    Console.WriteLine(@"(Console) LogLevel configuration parameter used in bot {0} is depreciated and may be removed in future versions. Please use ConsoleLogLevel instead.", DisplayName);
                }
                else
                {
                    consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.ConsoleLogLevel, true);
                }
            }
            catch (ArgumentException)
            {
                Console.WriteLine(@"(Console) ConsoleLogLevel invalid or unspecified for bot {0}. Defaulting to ""Info""", DisplayName);
                consoleLogLevel = Log.LogLevel.Info;
            }

            try
            {
                fileLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.FileLogLevel, true);
            }
            catch (ArgumentException)
            {
                Console.WriteLine(@"(Console) FileLogLevel invalid or unspecified for bot {0}. Defaulting to ""Info""", DisplayName);
                fileLogLevel = Log.LogLevel.Info;
            }

            logFile = config.LogFile;
            CreateLog();
            createHandler   = handlerCreator;
            BotControlClass = config.BotControlClass;
            SteamWeb        = new SteamWeb();

            // Hacking around https
            ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;

            Log.Debug("Initializing Steam Bot...");
            SteamClient = new SteamClient();
            SteamClient.AddHandler(new SteamNotifications());
            SteamTrade           = SteamClient.GetHandler <SteamTrading>();
            SteamUser            = SteamClient.GetHandler <SteamUser>();
            SteamFriends         = SteamClient.GetHandler <SteamFriends>();
            SteamGameCoordinator = SteamClient.GetHandler <SteamGameCoordinator>();
            SteamNotifications   = SteamClient.GetHandler <SteamNotifications>();

            botThread = new BackgroundWorker {
                WorkerSupportsCancellation = true
            };
            botThread.DoWork             += BackgroundWorkerOnDoWork;
            botThread.RunWorkerCompleted += BackgroundWorkerOnRunWorkerCompleted;
            botThread.RunWorkerAsync();
        }
Beispiel #10
0
        public Bot(Configuration.BotInfo config, Log log, string apiKey, UserHandlerCreator handlerCreator, Login _login, bool debug = false)
        {
            this.main    = _login;
            logOnDetails = new SteamUser.LogOnDetails
            {
                Username = _login.Username,
                Password = _login.Password
            };
            ChatResponse         = "";
            TradePollingInterval = 50;
            Admins      = new ulong[1];
            Admins[0]   = 123456789;
            this.apiKey = apiKey;
            try
            {
                LogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), "Debug", true);
            }
            catch (ArgumentException)
            {
                Console.WriteLine("Invalid LogLevel provided in configuration. Defaulting to 'INFO'");
                LogLevel = Log.LogLevel.Info;
            }
            this.log        = log;
            CreateHandler   = handlerCreator;
            BotControlClass = "SteamBot.SimpleUserHandler";

            // Hacking around https
            ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;

            log.Debug("Initializing Steam account...");
            main.Invoke((Action)(() =>
            {
                main.label_status.Text = "Initializing Steam account...";
            }));
            SteamClient  = new SteamClient();
            SteamTrade   = SteamClient.GetHandler <SteamTrading>();
            SteamUser    = SteamClient.GetHandler <SteamUser>();
            SteamFriends = SteamClient.GetHandler <SteamFriends>();
            log.Info("Connecting...");
            main.Invoke((Action)(() =>
            {
                main.label_status.Text = "Connecting to Steam...";
            }));
            SteamClient.Connect();

            Thread CallbackThread = new Thread(() => // Callback Handling
            {
                while (true)
                {
                    CallbackMsg msg = SteamClient.WaitForCallback(true);

                    HandleSteamMessage(msg);
                }
            });

            CallbackThread.Start();
            CallbackThread.Join();
            log.Success("Done loading account!");
            main.Invoke((Action)(() =>
            {
                main.label_status.Text = "Done loading account!";
            }));
        }
Beispiel #11
0
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false,
                   bool process = false)
        {
            userHandlers = new Dictionary <SteamID, UserHandler>();
            logOnDetails = new SteamUser.LogOnDetails
            {
                Username = config.Username,
                Password = _sec_RetrievePassword(config.Username)
            };
            DisplayName           = config.DisplayName;
            ChatResponse          = config.ChatResponse;
            MaximumTradeTime      = config.MaximumTradeTime;
            MaximumActionGap      = config.MaximumActionGap;
            DisplayNamePrefix     = config.DisplayNamePrefix;
            _tradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval;
            schemaLang            = config.SchemaLang != null ? config.SchemaLang : "en_US";
            Admins     = config.Admins;
            ApiKey     = !string.IsNullOrEmpty(config.ApiKey) ? config.ApiKey : apiKey;
            isProccess = process;
            try
            {
                if (config.LogLevel != null)
                {
                    consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true);
                    Console.WriteLine("(Console) LogLevel configuration parameter used in bot {0} is depreciated and may be " +
                                      "removed in future versions. Please use ConsoleLogLevel instead.", DisplayName);
                }
                else
                {
                    consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.ConsoleLogLevel, true);
                }
            }
            catch (ArgumentException)
            {
                Console.WriteLine("(Console) ConsoleLogLevel invalid or unspecified for bot {0}. Defaulting to 'Info'", DisplayName);
                consoleLogLevel = Log.LogLevel.Info;
            }

            try
            {
                fileLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.FileLogLevel, true);
            }
            catch (ArgumentException)
            {
                Console.WriteLine("(Console) FileLogLevel invalid or unspecified for bot {0}. Defaulting to 'Info'", DisplayName);
                fileLogLevel = Log.LogLevel.Info;
            }

            logFile         = config.LogFile;
            Log             = new Log(logFile, DisplayName, consoleLogLevel, fileLogLevel);
            createHandler   = handlerCreator;
            BotControlClass = config.BotControlClass;
            SteamWeb        = new SteamWeb();

            Orders = OrderManager.Load(Log);

            // Hacking around https
            ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;

            Log.Debug("Initializing Steam Bot...");

            SteamClient = new SteamClient();
            SteamClient.AddHandler(new SteamNotifications());
            SteamTrade           = SteamClient.GetHandler <SteamTrading>();
            SteamUser            = SteamClient.GetHandler <SteamUser>();
            SteamFriends         = SteamClient.GetHandler <SteamFriends>();
            SteamGameCoordinator = SteamClient.GetHandler <SteamGameCoordinator>();
            SteamNotifications   = SteamClient.GetHandler <SteamNotifications>();

            CallbackMgr = new CallbackManager(SteamClient);

            EventMgr = new EventManager(this, CallbackMgr);

            botSteamThread = new BackgroundWorker {
                WorkerSupportsCancellation = true
            };
            botSteamThread.DoWork             += _backgroundWorkerOnDoWork;
            botSteamThread.RunWorkerCompleted += _backgroundWorkerOnRunWorkerCompleted;
            botSteamThread.RunWorkerAsync();

            heartBeatThread      = new Thread(HeartbeatLoop);
            heartBeatThread.Name = "bp.tf Heartbeat Thread: " + config.Username;
            heartBeatThread.Start();

            crafterThread      = new Thread(CrafterLoop);
            crafterThread.Name = "Crafting Loop Thread: " + config.Username;
            crafterThread.Start();
        }
Beispiel #12
0
        static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.DarkCyan;

            System.Console.Title = "TradeBot";
            System.Console.WriteLine("Welcome to TradeBot!\nCreated by Jessecar.\nTurn of Steam Guard before loggin in!\n\n");

            Console.ForegroundColor = ConsoleColor.White;

            printConsole("Steam Username:"******"jessecar96"; //Console.ReadLine();

            System.Console.WriteLine("Steam Password: "******"Sorry, could not connect to Steam.");
                    }
                    steamUser.LogOn(new SteamUser.LogOnDetails
                    {
                        Username = username,
                        Password = password,
                    });
                });


                //Login Callback
                msg.Handle <SteamUser.LoggedOnCallback>(callback =>
                {
                    if (callback.Result != EResult.OK)
                    {
                        printConsole("Incorrect username or Password. Make sure you have disabled steam guard!");
                    }
                    else
                    {
                        printConsole("Connected to Steam!\nWelcome " + steamUser.SteamID);
                        steamFriends.SetPersonaName("ChatBot Beta (Say hi)");
                        steamFriends.SetPersonaState((EPersonaState)6);
                    }
                });

                //Chat Messages
                msg.Handle <SteamFriends.FriendMsgCallback>(callback =>
                {
                    EChatEntryType type = callback.EntryType;



                    if (type == EChatEntryType.ChatMsg)
                    {
                        SteamID sid = callback.Sender;

                        if (!clients.Contains(callback.Sender))
                        {
                            printConsole("[New Client]" + callback.Sender, ConsoleColor.Magenta);
                            clients.Add(callback.Sender);

                            steamFriends.SendChatMessage(callback.Sender, EChatEntryType.ChatMsg, "Welcome to TradeBot created by Jessecar.  To see a list of commands type /help");
                        }

                        if (callback.Message.StartsWith("/"))
                        {
                            string message = callback.Message.Replace("/", "");

                            printConsole("[Command]" + callback.Sender + " (" + steamFriends.GetFriendPersonaName(callback.Sender) + "): " + message, ConsoleColor.Magenta);
                            //string[] args = .Split(" ");

                            string[] words = message.Split(new char[] { ' ' }, 2);

                            switch (words[0])
                            {
                            case "trade":
                                //Send a trade
                                trade.RequestTrade(callback.Sender);
                                printConsole("Trade requested by " + callback.Sender + " (" + steamFriends.GetFriendPersonaName(callback.Sender) + ")", ConsoleColor.Green);
                                steamFriends.SendChatMessage(callback.Sender, EChatEntryType.Emote, "initiated a trade request.");
                                break;

                            case "remove":
                                //Remove Friend
                                steamFriends.SendChatMessage(callback.Sender, EChatEntryType.ChatMsg, "Thank you for using the Steam TradeBot BETA.");
                                steamFriends.RemoveFriend(callback.Sender);
                                printConsole("[Friend] Friend Removed: " + callback.Sender + " (" + steamFriends.GetFriendPersonaName(callback.Sender) + ")", ConsoleColor.Yellow);
                                break;

                            case "status":
                                //get status (nothing)
                                steamFriends.SendChatMessage(callback.Sender, EChatEntryType.Emote, "is Online and working good.");
                                break;

                            case "hi":
                                steamFriends.SendChatMessage(callback.Sender, EChatEntryType.Emote, "says hello.");
                                break;

                            case "help":
                                steamFriends.SendChatMessage(callback.Sender, EChatEntryType.ChatMsg, "\nList Of Commands:\n/trade - Start a trade.\n/remove - Remove TradeBot from your friends.\n/hi - say hello");
                                break;

                            case "name":
                                if (checkAdmin(sid))
                                {
                                    steamFriends.SetPersonaName(words[1]);
                                }
                                break;

                            case "send":
                                string[] wrds = message.Split(new char[] { ' ' }, 3);

                                int index = int.Parse(wrds[1]);

                                if (index < clients.Count() && index >= 0)
                                {
                                    steamFriends.SendChatMessage(clients[index], EChatEntryType.ChatMsg, wrds[2]);
                                }
                                else
                                {
                                    steamFriends.SendChatMessage(callback.Sender, EChatEntryType.Emote, "Error: index out of bounds.");
                                }

                                break;

                            default:
                                printConsole("[Error]Unknown command from " + callback.Sender + ": " + callback.Message, ConsoleColor.Red);
                                steamFriends.SendChatMessage(callback.Sender, EChatEntryType.Emote, "doesn't know that command.");
                                break;
                            }
                        }
                        else
                        {
                            printConsole("[Chat][" + getIndex(sid) + "]" + callback.Sender + ": " + " (" + steamFriends.GetFriendPersonaName(callback.Sender) + ")" + callback.Message, ConsoleColor.Magenta);
                            if ((callback.Message != "hi" || callback.Message != "hello") && clients.Contains(callback.Sender))
                            {
                                steamFriends.SendChatMessage(callback.Sender, EChatEntryType.ChatMsg, "You Said: " + callback.Message);
                            }
                        }
                    }
                    else if (type == EChatEntryType.Emote)
                    {
                        printConsole("[Emote]" + callback.Sender + ": " + callback.Message, ConsoleColor.DarkMagenta);
                    }
                });

                msg.Handle <SteamTrading.TradeProposedCallback>(callback =>
                {
                    SteamID sid = callback.Other;
                    //trade.RespondTradeRequest(callback.TradeRequestId, sid, true);
                    //trade.HandleMsg((IPacketMsg)EMsg.EconTrading_InitiateTradeProposed);
                });

                msg.Handle <SteamTrading.TradeRequestCallback>(callback =>
                {
                    printConsole("[Trade] Trade Status with " + callback.Other + " (" + steamFriends.GetFriendPersonaName(callback.Other) + "): " + callback.Status.ToString(), ConsoleColor.Green);
                    if (callback.Status == ETradeStatus.Rejected)
                    {
                        printConsole("[Trade] Trade rejected by " + callback.Other + " (" + steamFriends.GetFriendPersonaName(callback.Other) + ")", ConsoleColor.DarkRed);
                        steamFriends.SendChatMessage(callback.Other, EChatEntryType.Emote, "detected that you rejected that trade.");
                    }
                    //trade.RespondTradeRequest(callback.TradeRequestId, callback.Other, true);
                });

                msg.Handle <SteamTrading.TradeStartSessionCallback>(callback =>
                {
                    //callback.Other
                });

                msg.Handle <SteamFriends.PersonaStateCallback>(callback =>
                {
                    if (callback.FriendID == steamUser.SteamID)
                    {
                        return;
                    }

                    EFriendRelationship relationship = steamFriends.GetFriendRelationship(callback.FriendID);
                    if (!(relationship == EFriendRelationship.RequestRecipient))
                    {
                        return;
                    }

                    printConsole("[Friend] Added Friend: " + callback.FriendID + "(" + steamFriends.GetFriendPersonaName(callback.FriendID) + ")", ConsoleColor.Yellow);
                    steamFriends.AddFriend(callback.FriendID);
                });
            }
        }
Beispiel #13
0
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false)
        {
            logOnDetails = new SteamUser.LogOnDetails
            {
                Username = config.Username,
                Password = config.Password
            };

            DisplayName          = config.DisplayName;
            ChatResponse         = config.ChatResponse;
            MaximumTradeTime     = config.MaximumTradeTime;
            MaximiumActionGap    = config.MaximumActionGap;
            DisplayNamePrefix    = config.DisplayNamePrefix;
            TradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval;
            Admins      = config.Admins;
            this.apiKey = apiKey;
            try
            {
                LogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true);
            }
            catch (ArgumentException)
            {
                Console.WriteLine("Invalid LogLevel provided in configuration. Defaulting to 'INFO'");
                LogLevel = Log.LogLevel.Info;
            }
            log           = new Log(config.LogFile, this.DisplayName, LogLevel);
            CreateHandler = handlerCreator;

            // Hacking around https
            ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;

            log.Debug("Initializing Steam Bot...");
            SteamClient  = new SteamClient();
            SteamTrade   = SteamClient.GetHandler <SteamTrading>();
            SteamUser    = SteamClient.GetHandler <SteamUser>();
            SteamFriends = SteamClient.GetHandler <SteamFriends>();
            log.Info("Connecting...");
            SteamClient.Connect();

            Thread CallbackThread = new Thread(() => // Callback Handling
            {
                while (true)
                {
                    CallbackMsg msg = SteamClient.WaitForCallback(true);

                    HandleSteamMessage(msg);
                }
            });

            new Thread(() => // Trade Polling if needed
            {
                while (true)
                {
                    Thread.Sleep(TradePollingInterval);
                    if (CurrentTrade != null)
                    {
                        try
                        {
                            CurrentTrade.Poll();

                            if (CurrentTrade != null &&
                                CurrentTrade.OtherUserCancelled)
                            {
                                log.Info("Other user cancelled the trade.");
                                CurrentTrade = null;
                            }
                        }
                        catch (Exception e)
                        {
                            log.Error("Error Polling Trade: " + e);
                            // ok then we should stop polling...
                            CurrentTrade = null;
                        }
                    }
                }
            }).Start();

            CallbackThread.Start();
            log.Success("Done Loading Bot!");
            CallbackThread.Join();
        }
Beispiel #14
0
        public static void Main(string[] args)
        {
            #region SteamRE Init
            AllArgs = args;

            //Hacking around https
            ServicePointManager.CertificatePolicy = new MainClass();

            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.WriteLine("\n\tSteamBot Beta\n\tCreated by Jessecar96.\n\n");
            Console.ForegroundColor = ConsoleColor.White;


            steamClient = new SteamClient();
            steamTrade  = steamClient.GetHandler <SteamTrading>();
            SteamUser steamUser = steamClient.GetHandler <SteamUser> ();
            steamFriends = steamClient.GetHandler <SteamFriends>();

            steamClient.Connect();
            #endregion


            while (true)
            {
                CallbackMsg msg = steamClient.WaitForCallback(true);

                //Console Debug
                printConsole(msg.ToString(), ConsoleColor.Blue, true);


                #region Logged Off Handler
                msg.Handle <SteamUser.LoggedOffCallback> (callback =>
                {
                    printConsole("Logged Off: " + callback.Result, ConsoleColor.Red);
                });
                #endregion


                #region Steam Disconnect Handler
                msg.Handle <SteamClient.DisconnectedCallback> (callback =>
                {
                    printConsole("Disconnected.", ConsoleColor.Red);
                });
                #endregion


                #region Steam Connect Handler

                /**
                 * --Steam Connection Callback
                 *
                 * It's not needed to modify this section
                 */

                msg.Handle <SteamClient.ConnectedCallback> (callback =>
                {
                    //Print Callback
                    printConsole("Steam Connected Callback: " + callback.Result, ConsoleColor.Cyan);

                    //Validate Result
                    if (callback.Result == EResult.OK)
                    {
                        //Get Steam Login Details
                        printConsole("Username: "******"Password: "******"Getting Web Cookies...", ConsoleColor.Yellow);

                        //Get Web Cookies
                        SteamWeb web = new SteamWeb();
                        WebCookies   = web.DoLogin(user, pass);

                        if (WebCookies != null)
                        {
                            printConsole("SteamWeb Cookies retrived.", ConsoleColor.Green);
                            //Do Login
                            steamUser.LogOn(new SteamUser.LogOnDetails {
                                Username = user,
                                Password = pass
                            });
                        }
                        else
                        {
                            printConsole("Error while getting SteamWeb Cookies.", ConsoleColor.Red);
                        }
                    }
                    else
                    {
                        //Failure
                        printConsole("Failed to Connect to steam.", ConsoleColor.Red);
                    }
                });
                #endregion


                #region Steam Login Handler
                //Logged in (or not)
                msg.Handle <SteamUser.LoggedOnCallback>(callback =>
                {
                    printConsole("Logged on callback: " + callback.Result, ConsoleColor.Cyan);

                    if (callback.Result != EResult.OK)
                    {
                        printConsole("Login Failed!", ConsoleColor.Red);
                    }
                    else
                    {
                        printConsole("Successfulyl Logged In!\nWelcome " + steamUser.SteamID, ConsoleColor.Green);

                        //Set community status
                        steamFriends.SetPersonaName(BotPersonaName);
                        steamFriends.SetPersonaState(BotPersonaState);
                    }
                });
                #endregion


                #region Steam Trade Start

                /**
                 *
                 * Steam Trading Handler
                 *
                 */
                msg.Handle <SteamTrading.TradeStartSessionCallback>(call =>
                {
                    //Trading
                    trade = null;
                    trade = new TradeSystem();
                    trade.initTrade(steamUser.SteamID, call.Other, WebCookies);
                });
                #endregion

                #region Trade Requested Handler
                //Don't modify this
                msg.Handle <SteamTrading.TradeProposedCallback>(thing =>
                {
                    //Trade Callback
                    printConsole("Trade Proposed Callback. Other: " + thing.Other + "\n");

                    //Accept It
                    steamTrade.RequestTrade(thing.Other);
                });
                #endregion

                msg.Handle <SteamFriends.PersonaStateCallback>(callback =>
                {
                    if (callback.FriendID == steamUser.SteamID)
                    {
                        return;
                    }

                    EFriendRelationship relationship = steamFriends.GetFriendRelationship(callback.FriendID);
                    if (!(relationship == EFriendRelationship.RequestRecipient))
                    {
                        return;
                    }


                    if (steamFriends.GetFriendRelationship(callback.FriendID) == EFriendRelationship.PendingInvitee)
                    {
                        printConsole("[Friend] Friend Request Pending: " + callback.FriendID + "(" + steamFriends.GetFriendPersonaName(callback.FriendID) + ") - Accepted", ConsoleColor.Yellow);
                        steamFriends.AddFriend(callback.FriendID);
                    }
                });


                #region Steam Chat Handler

                /**
                 *
                 * Steam Chat Handler
                 *
                 */
                msg.Handle <SteamFriends.FriendMsgCallback>(callback =>
                {
                    //Type (emote or chat)
                    EChatEntryType type = callback.EntryType;

                    if (type == EChatEntryType.ChatMsg)
                    {
                        //Message is a chat message

                        //Reply with the same message
                        steamFriends.SendChatMessage(callback.Sender, EChatEntryType.ChatMsg, callback.Message);

                        //Chat API coming soon
                    }
                    else if (type == EChatEntryType.Emote)
                    {
                        //Message is emote

                        //Do nothing yet
                    }
                });
                #endregion
            }     //end while loop
        }         //end Main method
Beispiel #15
0
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false)
        {
            logOnDetails = new SteamUser.LogOnDetails
            {
                Username = config.Username,
                Password = config.Password
            };
            DisplayName  = config.DisplayName;
            ChatResponse = config.ChatResponse;
            MaximumTradeTime = config.MaximumTradeTime;
            MaximiumActionGap = config.MaximumActionGap;
            DisplayNamePrefix = config.DisplayNamePrefix;
            TradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval;
            hatBuyPrice= config.HatBuyPrice;
            hatSellPrice= config.HatSellPrice;
            maxRequestTime= config.MaxRequestTime;
            craftHatSellPrice = config.CraftHatSellPrice;
            Admins       = config.Admins;
            this.apiKey  = apiKey;
            try
            {
                LogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true);
            }
            catch (ArgumentException)
            {
                Console.WriteLine("Invalid LogLevel provided in configuration. Defaulting to 'INFO'");
                LogLevel = Log.LogLevel.Info;
            }
            log          = new Log (config.LogFile, this.DisplayName, LogLevel);
            CreateHandler = handlerCreator;
            BotControlClass = config.BotControlClass;

            // Hacking around https
            ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;

            log.Debug ("Initializing Steam Bot...");
            SteamClient = new SteamClient();
            SteamTrade = SteamClient.GetHandler<SteamTrading>();
            SteamUser = SteamClient.GetHandler<SteamUser>();
            SteamFriends = SteamClient.GetHandler<SteamFriends>();
            log.Info ("Connecting...");
            SteamClient.Connect();
            
            Thread CallbackThread = new Thread(() => // Callback Handling
            {
                while (true)
                {
                    CallbackMsg msg = SteamClient.WaitForCallback (true);

                    HandleSteamMessage (msg);
                }
            });
            new Thread(() =>
                {
                    while (true)
                    {
                        Thread.Sleep(1000);
                        if (currentRequest.User != null)
                        {
                            DateTime RequestTimeout = RequestTime.AddSeconds(maxRequestTime);
                            int untilTradeTimeout = (int)Math.Round((RequestTimeout - DateTime.Now).TotalSeconds);
                            if (untilTradeTimeout <= 0 && (MySQL.getItem().User != null))
                            {
                                SteamFriends.SendChatMessage(currentRequest.User, EChatEntryType.ChatMsg, "Sorry, but your request took too long");
                                NewRequest(MySQL.RequestStatus.Timedout);
                                log.Warn("Request timedout");
                            }
                        }
                    }
                }).Start();
            CallbackThread.Start();
            log.Success ("Done Loading Bot!");
            CallbackThread.Join();
        }