Advertisement
Guest User

Untitled

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