Advertisement
Guest User

Untitled

a guest
Jun 8th, 2016
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 26.88 KB | None | 0 0
  1. using System;
  2. using System.Web;
  3. using System.Net;
  4. using System.Text;
  5. using System.IO;
  6. using System.Threading;
  7. using System.Collections.Generic;
  8. using System.Security.Cryptography;
  9. using System.ComponentModel;
  10. using SteamKit2;
  11. using SteamTrade;
  12. using SteamKit2.Internal;
  13.  
  14. namespace SteamBot
  15. {
  16. public class Bot
  17. {
  18. public string BotControlClass;
  19. // If the bot is logged in fully or not. This is only set
  20. // when it is.
  21. public bool IsLoggedIn = false;
  22.  
  23. // The bot's display name. Changing this does not mean that
  24. // the bot's name will change.
  25. public string DisplayName { get; private set; }
  26.  
  27. // The response to all chat messages sent to it.
  28. public string ChatResponse;
  29.  
  30. // A list of SteamIDs that this bot recognizes as admins.
  31. public ulong[] Admins;
  32. public SteamFriends SteamFriends;
  33. public SteamClient SteamClient;
  34. public SteamTrading SteamTrade;
  35. public SteamUser SteamUser;
  36. public SteamGameCoordinator SteamGameCoordinator;
  37.  
  38. // The current trade; if the bot is not in a trade, this is
  39. // null.
  40. public Trade CurrentTrade;
  41.  
  42. public bool IsDebugMode = false;
  43.  
  44. // The log for the bot. This logs with the bot's display name.
  45. public Log log;
  46.  
  47. public delegate UserHandler UserHandlerCreator(Bot bot, SteamID id);
  48. public UserHandlerCreator CreateHandler;
  49. Dictionary<ulong, UserHandler> userHandlers = new Dictionary<ulong, UserHandler>();
  50.  
  51. List<SteamID> friends = new List<SteamID>();
  52.  
  53. // The maximum amount of time the bot will trade for.
  54. public int MaximumTradeTime { get; private set; }
  55.  
  56. // The maximum amount of time the bot will wait in between
  57. // trade actions.
  58. public int MaximiumActionGap { get; private set; }
  59.  
  60. //The current game that the bot is playing, for posterity.
  61. public int CurrentGame = 0;
  62.  
  63. // The Steam Web API key.
  64. string apiKey;
  65.  
  66. // The prefix put in the front of the bot's display name.
  67. string DisplayNamePrefix;
  68.  
  69. // Log level to use for this bot
  70. Log.LogLevel LogLevel;
  71.  
  72. // The number, in milliseconds, between polls for the trade.
  73. int TradePollingInterval;
  74.  
  75. public string MyLoginKey;
  76. string sessionId;
  77. string token;
  78. bool isprocess;
  79. public bool IsRunning = false;
  80.  
  81. public string AuthCode { get; set; }
  82.  
  83. SteamUser.LogOnDetails logOnDetails;
  84.  
  85. TradeManager tradeManager;
  86.  
  87. public Inventory MyInventory;
  88. public Inventory OtherInventory;
  89.  
  90. private BackgroundWorker backgroundWorker;
  91.  
  92. public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false, bool process = false)
  93. {
  94. logOnDetails = new SteamUser.LogOnDetails
  95. {
  96. Username = config.Username,
  97. Password = config.Password
  98. };
  99. DisplayName = config.DisplayName;
  100. ChatResponse = config.ChatResponse;
  101. MaximumTradeTime = config.MaximumTradeTime;
  102. MaximiumActionGap = config.MaximumActionGap;
  103. DisplayNamePrefix = config.DisplayNamePrefix;
  104. TradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval;
  105. Admins = config.Admins;
  106. this.apiKey = apiKey;
  107. this.isprocess = process;
  108. try
  109. {
  110. LogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true);
  111. }
  112. catch (ArgumentException)
  113. {
  114. Console.WriteLine("Invalid LogLevel provided in configuration. Defaulting to 'INFO'");
  115. LogLevel = Log.LogLevel.Info;
  116. }
  117. log = new Log (config.LogFile, this.DisplayName, LogLevel);
  118. CreateHandler = handlerCreator;
  119. BotControlClass = config.BotControlClass;
  120.  
  121. // Hacking around https
  122. ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;
  123.  
  124. log.Debug ("Initializing Steam Bot...");
  125. SteamClient = new SteamClient();
  126. SteamTrade = SteamClient.GetHandler<SteamTrading>();
  127. SteamUser = SteamClient.GetHandler<SteamUser>();
  128. SteamFriends = SteamClient.GetHandler<SteamFriends>();
  129. SteamGameCoordinator = SteamClient.GetHandler<SteamGameCoordinator>();
  130.  
  131. backgroundWorker = new BackgroundWorker { WorkerSupportsCancellation = true };
  132. backgroundWorker.DoWork += BackgroundWorkerOnDoWork;
  133. backgroundWorker.RunWorkerCompleted += BackgroundWorkerOnRunWorkerCompleted;
  134. backgroundWorker.RunWorkerAsync();
  135. }
  136.  
  137. /// <summary>
  138. /// Occurs when the bot needs the SteamGuard authentication code.
  139. /// </summary>
  140. /// <remarks>
  141. /// Return the code in <see cref="SteamGuardRequiredEventArgs.SteamGuard"/>
  142. /// </remarks>
  143. public event EventHandler<SteamGuardRequiredEventArgs> OnSteamGuardRequired;
  144.  
  145. /// <summary>
  146. /// Starts the callback thread and connects to Steam via SteamKit2.
  147. /// </summary>
  148. /// <remarks>
  149. /// THIS NEVER RETURNS.
  150. /// </remarks>
  151. /// <returns><c>true</c>. See remarks</returns>
  152. public bool StartBot()
  153. {
  154. IsRunning = true;
  155.  
  156. log.Info("Connecting...");
  157.  
  158. if (!backgroundWorker.IsBusy)
  159. // background worker is not running
  160. backgroundWorker.RunWorkerAsync();
  161.  
  162. SteamClient.Connect();
  163.  
  164. log.Success("Done Loading Bot!");
  165.  
  166. return true; // never get here
  167. }
  168.  
  169. /// <summary>
  170. /// Disconnect from the Steam network and stop the callback
  171. /// thread.
  172. /// </summary>
  173. public void StopBot()
  174. {
  175. IsRunning = false;
  176.  
  177. log.Debug("Trying to shut down bot thread.");
  178. SteamClient.Disconnect();
  179.  
  180. backgroundWorker.CancelAsync();
  181. }
  182.  
  183. /// <summary>
  184. /// Creates a new trade with the given partner.
  185. /// </summary>
  186. /// <returns>
  187. /// <c>true</c>, if trade was opened,
  188. /// <c>false</c> if there is another trade that must be closed first.
  189. /// </returns>
  190. public bool OpenTrade (SteamID other)
  191. {
  192. if (CurrentTrade != null)
  193. return false;
  194.  
  195. SteamTrade.Trade(other);
  196.  
  197. return true;
  198. }
  199.  
  200. /// <summary>
  201. /// Closes the current active trade.
  202. /// </summary>
  203. public void CloseTrade()
  204. {
  205. if (CurrentTrade == null)
  206. return;
  207.  
  208. UnsubscribeTrade (GetUserHandler (CurrentTrade.OtherSID), CurrentTrade);
  209.  
  210. tradeManager.StopTrade ();
  211.  
  212. CurrentTrade = null;
  213. }
  214.  
  215. void OnTradeTimeout(object sender, EventArgs args)
  216. {
  217. // ignore event params and just null out the trade.
  218. GetUserHandler (CurrentTrade.OtherSID).OnTradeTimeout();
  219. }
  220.  
  221. void OnTradeEnded (object sender, EventArgs e)
  222. {
  223. CloseTrade();
  224. }
  225.  
  226. public void HandleBotCommand(string command)
  227. {
  228. try
  229. {
  230. GetUserHandler(SteamClient.SteamID).OnBotCommand(command);
  231. }
  232. catch (ObjectDisposedException e)
  233. {
  234. // Writing to console because odds are the error was caused by a disposed log.
  235. Console.WriteLine(string.Format("Exception caught in BotCommand Thread: {0}", e));
  236. if (!this.IsRunning)
  237. {
  238. Console.WriteLine("The Bot is no longer running and could not write to the log. Try Starting this bot first.");
  239. }
  240. }
  241. catch (Exception e)
  242. {
  243. Console.WriteLine(string.Format("Exception caught in BotCommand Thread: {0}", e));
  244. }
  245. }
  246.  
  247. bool HandleTradeSessionStart (SteamID other)
  248. {
  249. if (CurrentTrade != null)
  250. return false;
  251.  
  252. try
  253. {
  254. tradeManager.InitializeTrade(SteamUser.SteamID, other);
  255. CurrentTrade = tradeManager.StartTrade (SteamUser.SteamID, other);
  256. }
  257. catch (SteamTrade.Exceptions.InventoryFetchException ie)
  258. {
  259. // we shouldn't get here because the inv checks are also
  260. // done in the TradeProposedCallback handler.
  261. string response = String.Empty;
  262.  
  263. if (ie.FailingSteamId.ConvertToUInt64() == other.ConvertToUInt64())
  264. {
  265. response = "Trade failed. Could not correctly fetch your backpack. Either the inventory is inaccessible or your backpack is private.";
  266. }
  267. else
  268. {
  269. response = "Trade failed. Could not correctly fetch my backpack.";
  270. }
  271.  
  272. SteamFriends.SendChatMessage(other,
  273. EChatEntryType.ChatMsg,
  274. response);
  275.  
  276. log.Info ("Bot sent other: " + response);
  277.  
  278. CurrentTrade = null;
  279. return false;
  280. }
  281.  
  282. CurrentTrade.OnClose += CloseTrade;
  283. SubscribeTrade (CurrentTrade, GetUserHandler (other));
  284.  
  285. return true;
  286. }
  287.  
  288. public void SetGamePlaying(int id)
  289. {
  290. var gamePlaying = new SteamKit2.ClientMsgProtobuf<CMsgClientGamesPlayed>(EMsg.ClientGamesPlayed);
  291.  
  292. if (id != 0)
  293. gamePlaying.Body.games_played.Add(new CMsgClientGamesPlayed.GamePlayed
  294. {
  295. game_id = new GameID(id),
  296. });
  297.  
  298. SteamClient.Send(gamePlaying);
  299.  
  300. CurrentGame = id;
  301. }
  302.  
  303. void HandleSteamMessage (CallbackMsg msg)
  304. {
  305. log.Debug(msg.ToString());
  306.  
  307. #region Login
  308. msg.Handle<SteamClient.ConnectedCallback> (callback =>
  309. {
  310. log.Debug ("Connection Callback: " + callback.Result);
  311.  
  312. if (callback.Result == EResult.OK)
  313. {
  314. UserLogOn();
  315. }
  316. else
  317. {
  318. log.Error ("Failed to connect to Steam Community, trying again...");
  319. SteamClient.Connect ();
  320. }
  321.  
  322. });
  323.  
  324. msg.Handle<SteamUser.LoggedOnCallback> (callback =>
  325. {
  326. log.Debug ("Logged On Callback: " + callback.Result);
  327.  
  328. if (callback.Result == EResult.OK)
  329. {
  330. MyLoginKey = callback.WebAPIUserNonce;
  331. }
  332. else
  333. {
  334. log.Error ("Login Error: " + callback.Result);
  335. }
  336.  
  337. if (callback.Result == EResult.AccountLogonDenied)
  338. {
  339. log.Interface ("This account is SteamGuard enabled. Enter the code via the `auth' command.");
  340.  
  341. // try to get the steamguard auth code from the event callback
  342. var eva = new SteamGuardRequiredEventArgs();
  343. FireOnSteamGuardRequired(eva);
  344. if (!String.IsNullOrEmpty(eva.SteamGuard))
  345. logOnDetails.AuthCode = eva.SteamGuard;
  346. else
  347. logOnDetails.AuthCode = Console.ReadLine();
  348. }
  349.  
  350. if (callback.Result == EResult.InvalidLoginAuthCode)
  351. {
  352. log.Interface("The given SteamGuard code was invalid. Try again using the `auth' command.");
  353. logOnDetails.AuthCode = Console.ReadLine();
  354. }
  355. });
  356.  
  357. msg.Handle<SteamUser.LoginKeyCallback> (callback =>
  358. {
  359. while (true)
  360. {
  361. bool authd = SteamWeb.Authenticate(callback, SteamClient, out sessionId, out token, MyLoginKey);
  362.  
  363. if (authd)
  364. {
  365. log.Success ("User Authenticated!");
  366.  
  367. tradeManager = new TradeManager(apiKey, sessionId, token);
  368. tradeManager.SetTradeTimeLimits(MaximumTradeTime, MaximiumActionGap, TradePollingInterval);
  369. tradeManager.OnTimeout += OnTradeTimeout;
  370. tradeManager.OnTradeEnded += OnTradeEnded;
  371. break;
  372. }
  373. else
  374. {
  375. log.Warn ("Authentication failed, retrying in 2s...");
  376. Thread.Sleep (2000);
  377. }
  378. }
  379.  
  380. if (Trade.CurrentSchema == null)
  381. {
  382. log.Info ("Downloading Schema...");
  383. Trade.CurrentSchema = Schema.FetchSchema (apiKey);
  384. log.Success ("Schema Downloaded!");
  385. }
  386.  
  387. SteamFriends.SetPersonaName (DisplayNamePrefix+DisplayName);
  388. SteamFriends.SetPersonaState (EPersonaState.Online);
  389.  
  390. log.Success ("Steam Bot Logged In Completely!");
  391.  
  392. IsLoggedIn = true;
  393.  
  394. GetUserHandler(SteamClient.SteamID).OnLoginCompleted();
  395. });
  396.  
  397. // handle a special JobCallback differently than the others
  398. if (msg.IsType<SteamClient.JobCallback<SteamUser.UpdateMachineAuthCallback>>())
  399. {
  400. msg.Handle<SteamClient.JobCallback<SteamUser.UpdateMachineAuthCallback>>(
  401. jobCallback => OnUpdateMachineAuthCallback(jobCallback.Callback, jobCallback.JobID)
  402. );
  403. }
  404. #endregion
  405.  
  406. #region Friends
  407. msg.Handle<SteamFriends.FriendsListCallback> (callback =>
  408. {
  409. foreach (SteamFriends.FriendsListCallback.Friend friend in callback.FriendList)
  410. {
  411. if (!friends.Contains(friend.SteamID))
  412. {
  413. friends.Add(friend.SteamID);
  414. if (friend.Relationship == EFriendRelationship.RequestRecipient &&
  415. GetUserHandler(friend.SteamID).OnFriendAdd())
  416. {
  417. SteamFriends.AddFriend(friend.SteamID);
  418. }
  419. }
  420. else
  421. {
  422. if (friend.Relationship == EFriendRelationship.None)
  423. {
  424. friends.Remove(friend.SteamID);
  425. GetUserHandler(friend.SteamID).OnFriendRemove();
  426. }
  427. }
  428. }
  429. });
  430.  
  431. msg.Handle<SteamFriends.FriendMsgCallback> (callback =>
  432. {
  433. EChatEntryType type = callback.EntryType;
  434.  
  435. if (callback.EntryType == EChatEntryType.ChatMsg ||
  436. callback.EntryType == EChatEntryType.Emote)
  437. {
  438. log.Info (String.Format ("Chat Message from {0}: {1}",
  439. SteamFriends.GetFriendPersonaName (callback.Sender),
  440. callback.Message
  441. ));
  442. GetUserHandler(callback.Sender).OnMessage(callback.Message, type);
  443. }
  444. });
  445. #endregion
  446.  
  447. #region Group Chat
  448. msg.Handle<SteamFriends.ChatMsgCallback>(callback =>
  449. {
  450. GetUserHandler(callback.ChatterID).OnChatRoomMessage(callback.ChatRoomID, callback.ChatterID, callback.Message);
  451. });
  452. #endregion
  453.  
  454. #region Trading
  455. msg.Handle<SteamTrading.SessionStartCallback> (callback =>
  456. {
  457. bool started = HandleTradeSessionStart (callback.OtherClient);
  458.  
  459. if (!started)
  460. log.Error ("Could not start the trade session.");
  461. else
  462. log.Debug ("SteamTrading.SessionStartCallback handled successfully. Trade Opened.");
  463. });
  464.  
  465. msg.Handle<SteamTrading.TradeProposedCallback> (callback =>
  466. {
  467. try
  468. {
  469. tradeManager.InitializeTrade(SteamUser.SteamID, callback.OtherClient);
  470. }
  471. catch (WebException we)
  472. {
  473. SteamFriends.SendChatMessage(callback.OtherClient,
  474. EChatEntryType.ChatMsg,
  475. "Trade error: " + we.Message);
  476.  
  477. SteamTrade.RespondToTrade(callback.TradeID, false);
  478. return;
  479. }
  480. catch (Exception)
  481. {
  482. SteamFriends.SendChatMessage(callback.OtherClient,
  483. EChatEntryType.ChatMsg,
  484. "Trade declined. Could not correctly fetch your backpack.");
  485.  
  486. SteamTrade.RespondToTrade(callback.TradeID, false);
  487. return;
  488. }
  489.  
  490. //if (tradeManager.OtherInventory.IsPrivate)
  491. //{
  492. // SteamFriends.SendChatMessage(callback.OtherClient,
  493. // EChatEntryType.ChatMsg,
  494. // "Trade declined. Your backpack cannot be private.");
  495.  
  496. // SteamTrade.RespondToTrade (callback.TradeID, false);
  497. // return;
  498. //}
  499.  
  500. if (CurrentTrade == null && GetUserHandler (callback.OtherClient).OnTradeRequest ())
  501. SteamTrade.RespondToTrade (callback.TradeID, true);
  502. else
  503. SteamTrade.RespondToTrade (callback.TradeID, false);
  504. });
  505.  
  506. msg.Handle<SteamTrading.TradeResultCallback> (callback =>
  507. {
  508. if (callback.Response == EEconTradeResponse.Accepted)
  509. {
  510. log.Debug ("Trade Status: " + callback.Response);
  511. log.Info ("Trade Accepted!");
  512. }
  513. else
  514. {
  515. log.Warn ("Trade failed: " + callback.Response);
  516. CloseTrade ();
  517. }
  518.  
  519. });
  520. #endregion
  521.  
  522. #region Disconnect
  523. msg.Handle<SteamUser.LoggedOffCallback> (callback =>
  524. {
  525. IsLoggedIn = false;
  526. log.Warn ("Logged Off: " + callback.Result);
  527. });
  528.  
  529. msg.Handle<SteamClient.DisconnectedCallback> (callback =>
  530. {
  531. IsLoggedIn = false;
  532. CloseTrade ();
  533. log.Warn ("Disconnected from Steam Network!");
  534. SteamClient.Connect ();
  535. });
  536. #endregion
  537. }
  538.  
  539. void UserLogOn()
  540. {
  541. // get sentry file which has the machine hw info saved
  542. // from when a steam guard code was entered
  543. Directory.CreateDirectory(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "sentryfiles"));
  544. FileInfo fi = new FileInfo(System.IO.Path.Combine("sentryfiles",String.Format("{0}.sentryfile", logOnDetails.Username)));
  545.  
  546. if (fi.Exists && fi.Length > 0)
  547. logOnDetails.SentryFileHash = SHAHash(File.ReadAllBytes(fi.FullName));
  548. else
  549. logOnDetails.SentryFileHash = null;
  550.  
  551. SteamUser.LogOn(logOnDetails);
  552. }
  553.  
  554. UserHandler GetUserHandler (SteamID sid)
  555. {
  556. if (!userHandlers.ContainsKey (sid))
  557. {
  558. userHandlers [sid.ConvertToUInt64 ()] = CreateHandler (this, sid);
  559. }
  560. return userHandlers [sid.ConvertToUInt64 ()];
  561. }
  562.  
  563. static byte [] SHAHash (byte[] input)
  564. {
  565. SHA1Managed sha = new SHA1Managed();
  566.  
  567. byte[] output = sha.ComputeHash( input );
  568.  
  569. sha.Clear();
  570.  
  571. return output;
  572. }
  573.  
  574. void OnUpdateMachineAuthCallback (SteamUser.UpdateMachineAuthCallback machineAuth, JobID jobId)
  575. {
  576. byte[] hash = SHAHash (machineAuth.Data);
  577.  
  578. Directory.CreateDirectory(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "sentryfiles"));
  579.  
  580. File.WriteAllBytes (System.IO.Path.Combine("sentryfiles", String.Format("{0}.sentryfile", logOnDetails.Username)), machineAuth.Data);
  581.  
  582. var authResponse = new SteamUser.MachineAuthDetails
  583. {
  584. BytesWritten = machineAuth.BytesToWrite,
  585. FileName = machineAuth.FileName,
  586. FileSize = machineAuth.BytesToWrite,
  587. Offset = machineAuth.Offset,
  588.  
  589. SentryFileHash = hash, // should be the sha1 hash of the sentry file we just wrote
  590.  
  591. OneTimePassword = machineAuth.OneTimePassword, // not sure on this one yet, since we've had no examples of steam using OTPs
  592.  
  593. LastError = 0, // result from win32 GetLastError
  594. Result = EResult.OK, // if everything went okay, otherwise ~who knows~
  595.  
  596. JobID = jobId, // so we respond to the correct server job
  597. };
  598.  
  599. // send off our response
  600. SteamUser.SendMachineAuthResponse (authResponse);
  601. }
  602.  
  603. /// <summary>
  604. /// Gets the bot's inventory and stores it in MyInventory.
  605. /// </summary>
  606. /// <example> This sample shows how to find items in the bot's inventory from a user handler.
  607. /// <code>
  608. /// Bot.GetInventory(); // Get the inventory first
  609. /// foreach (var item in Bot.MyInventory.Items)
  610. /// {
  611. /// if (item.Defindex == 5021)
  612. /// {
  613. /// // Bot has a key in its inventory
  614. /// }
  615. /// }
  616. /// </code>
  617. /// </example>
  618. public void GetInventory()
  619. {
  620. MyInventory = Inventory.FetchInventory(SteamUser.SteamID, apiKey);
  621. }
  622.  
  623. /// <summary>
  624. /// Gets the other user's inventory and stores it in OtherInventory.
  625. /// </summary>
  626. /// <param name="OtherSID">The SteamID of the other user</param>
  627. /// <example> This sample shows how to find items in the other user's inventory from a user handler.
  628. /// <code>
  629. /// Bot.GetOtherInventory(OtherSID); // Get the inventory first
  630. /// foreach (var item in Bot.OtherInventory.Items)
  631. /// {
  632. /// if (item.Defindex == 5021)
  633. /// {
  634. /// // User has a key in its inventory
  635. /// }
  636. /// }
  637. /// </code>
  638. /// </example>
  639. public void GetOtherInventory(SteamID OtherSID)
  640. {
  641. OtherInventory = Inventory.FetchInventory(OtherSID, apiKey);
  642. }
  643.  
  644. /// <summary>
  645. /// Subscribes all listeners of this to the trade.
  646. /// </summary>
  647. public void SubscribeTrade (Trade trade, UserHandler handler)
  648. {
  649. trade.OnClose += handler.OnTradeClose;
  650. trade.OnError += handler.OnTradeError;
  651. //trade.OnTimeout += OnTradeTimeout;
  652. trade.OnAfterInit += handler.OnTradeInit;
  653. trade.OnUserAddItem += handler.OnTradeAddItem;
  654. trade.OnUserRemoveItem += handler.OnTradeRemoveItem;
  655. trade.OnMessage += handler.OnTradeMessage;
  656. trade.OnUserSetReady += handler.OnTradeReady;
  657. trade.OnUserAccept += handler.OnTradeAccept;
  658. }
  659.  
  660. /// <summary>
  661. /// Unsubscribes all listeners of this from the current trade.
  662. /// </summary>
  663. public void UnsubscribeTrade (UserHandler handler, Trade trade)
  664. {
  665. trade.OnClose -= handler.OnTradeClose;
  666. trade.OnError -= handler.OnTradeError;
  667. //Trade.OnTimeout -= OnTradeTimeout;
  668. trade.OnAfterInit -= handler.OnTradeInit;
  669. trade.OnUserAddItem -= handler.OnTradeAddItem;
  670. trade.OnUserRemoveItem -= handler.OnTradeRemoveItem;
  671. trade.OnMessage -= handler.OnTradeMessage;
  672. trade.OnUserSetReady -= handler.OnTradeReady;
  673. trade.OnUserAccept -= handler.OnTradeAccept;
  674. }
  675.  
  676. #region Background Worker Methods
  677.  
  678. private void BackgroundWorkerOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs)
  679. {
  680. if (runWorkerCompletedEventArgs.Error != null)
  681. {
  682. Exception ex = runWorkerCompletedEventArgs.Error;
  683.  
  684. var s = string.Format("Unhandled exceptions in bot {0} callback thread: {1} {2}",
  685. DisplayName,
  686. Environment.NewLine,
  687. ex);
  688. log.Error(s);
  689.  
  690. log.Info("This bot died. Stopping it..");
  691. //backgroundWorker.RunWorkerAsync();
  692. //Thread.Sleep(10000);
  693. StopBot();
  694. //StartBot();
  695. }
  696.  
  697. log.Dispose();
  698. }
  699.  
  700. private void BackgroundWorkerOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
  701. {
  702. while (!backgroundWorker.CancellationPending)
  703. {
  704. CallbackMsg msg = SteamClient.WaitForCallback(true);
  705. HandleSteamMessage(msg);
  706. }
  707. }
  708.  
  709. #endregion Background Worker Methods
  710.  
  711. private void FireOnSteamGuardRequired(SteamGuardRequiredEventArgs e)
  712. {
  713. // Set to null in case this is another attempt
  714. this.AuthCode = null;
  715.  
  716. EventHandler<SteamGuardRequiredEventArgs> handler = OnSteamGuardRequired;
  717. if (handler != null)
  718. handler(this, e);
  719. else
  720. {
  721. while (true)
  722. {
  723. if (this.AuthCode != null)
  724. {
  725. e.SteamGuard = this.AuthCode;
  726. break;
  727. }
  728.  
  729. Thread.Sleep(5);
  730. }
  731. }
  732. }
  733. }
  734. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement