Example #1
0
        public ShowTrade_Web(SteamID OtherSID)
        {
            InitializeComponent();

            extendedWebBrowser1.UserAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11";
            extendedWebBrowser1.Navigate(trade_url, null, null, "Cookies: " + Trade.cookies.GetCookieHeader(new Uri(trade_url)) + Environment.NewLine);
        }
 private bool Respond(SteamID toID, string message, bool room)
 {
     string pattern = @"\<title\b[^>]*\>\s*(?<Title>[\s\S]*?)\</title\>";
     Uri uriResult;
     string[] splitmes = message.Split(' ');
     for (int i = 0; i < splitmes.Length; i++)
     {
         try
         {
             bool result = Uri.TryCreate(splitmes[i], UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
             if (result)
             {
                 using (WebClient client = new WebClient())
                 {
                     string body = client.DownloadString(splitmes[i]);
                     string title = Regex.Match(body, pattern, RegexOptions.IgnoreCase).Groups["Title"].Value;
                     if (title != null)
                     {
                         SendMessageAfterDelay(toID, title.ToString(), room);
                         return true;
                     }
                 }
             }
             else
             {
                 return false;
             }
         }
         catch (WebException e)
         {
             Log.Instance.Error(e.StackTrace);
         }
     }
     return false;
 }
        public UI()
        {
            InitializeComponent();
            this.FormClosed += new FormClosedEventHandler(stopGSListen);

            settings = grabSid();

            if (settings.Length.Equals(0))
            {
                MessageBox.Show("Please paste your SteamID into the steamid.txt file created in the folder this program is in and restart the program.");
                Environment.Exit(0);
            }
            else
            {
                sid = settings[0];

                //Set custom colors
                if (settings.Length > 1)
                {
                    if (settings.Length.Equals(7))
                    {
                        string u, v, w, x, y, z;

                        u = settings[1];
                        v = settings[2];
                        w = settings[3];
                        x = settings[4];
                        y = settings[5];
                        z = settings[6];

                        setColors(u, v, w, x, y, z);
                    }
                    else
                    {
                        MessageBox.Show("In order to use custom colors, you muse serparate two sets of RGB values in the config.txt file like so:\n\n" +
                            "<steamid> <R> <G> <B> <R> <G> <B>\n\n" +
                            "All values must be within 0-255 and must be separated by spaces. The first set of values are for background color and the second set are for stat counter color. En example configuration would look like the following:\n\n" +
                            "STEAM_0:0:1234 64 64 64 0 192 0");
                    }
                }

                s = new SteamID(sid.Trim());

                if (s.IsValid)
                {
                    gsl = new GameStateListener(3000);
                    gsl.NewGameState += new NewGameStateHandler(OnNewGameState);
                    if (!gsl.Start())
                    {
                        Environment.Exit(0);
                    }
                    Console.WriteLine("Listening...");
                }
                else
                {
                    MessageBox.Show("INVALID STEAMID PROVIDED\n\nSteamID must be in regular SteamID format. EX: STEAM_0:0:39990");
                    Environment.Exit(0);
                }
            }
        }
Example #4
0
        public void SetFromSteam3StringCorrectParse()
        {
            SteamID sidUser = new SteamID();
            sidUser.SetFromSteam3String( "[U:1:123]" );
            Assert.Equal( 123u, sidUser.AccountID );
            Assert.Equal( EUniverse.Public, sidUser.AccountUniverse );
            Assert.Equal( 1u, sidUser.AccountInstance );
            Assert.Equal( EAccountType.Individual, sidUser.AccountType );

            SteamID sidAnonGSUser = new SteamID();
            sidAnonGSUser.SetFromSteam3String( "[A:1:123:456]" );
            Assert.Equal (123u, sidAnonGSUser.AccountID );
            Assert.Equal( EUniverse.Public, sidAnonGSUser.AccountUniverse );
            Assert.Equal( 456u, sidAnonGSUser.AccountInstance );
            Assert.Equal( EAccountType.AnonGameServer, sidAnonGSUser.AccountType );

            SteamID sidLobby = new SteamID();
            sidLobby.SetFromSteam3String( "[L:1:123]" );
            Assert.Equal( 123u, sidLobby.AccountID );
            Assert.Equal( EUniverse.Public, sidLobby.AccountUniverse );
            Assert.True( ( ( SteamID.ChatInstanceFlags )sidLobby.AccountInstance ).HasFlag( SteamID.ChatInstanceFlags.Lobby ) );
            Assert.Equal( EAccountType.Chat, sidLobby.AccountType );

            SteamID sidClanChat = new SteamID();
            sidClanChat.SetFromSteam3String( "[c:1:123]" );
            Assert.Equal( 123u, sidClanChat.AccountID );
            Assert.Equal(EUniverse.Public, sidClanChat.AccountUniverse);
            Assert.True( ( ( SteamID.ChatInstanceFlags )sidClanChat.AccountInstance ).HasFlag( SteamID.ChatInstanceFlags.Clan ) );
            Assert.Equal( EAccountType.Chat, sidClanChat.AccountType );
        }
Example #5
0
        private static void Main(string[] args)
        {
            Console.Title = "===== BOT Anthony =====";
            Console.WriteLine("Ctrl + C quits m8");

            config = JsonConvert.DeserializeObject<Config>(File.ReadAllText("config.json"));

            AdminName = new SteamID(config.AdminID);

            swearWords = config.Swears;

            Console.WriteLine("[BOT] Loaded JSON configuration file sucessfully!");
            
            if (config != null)
            {
                Console.WriteLine("[Authentication] Grabbing username and password from file...");
                usrName = config.Username;
                usrPass = config.Password;
                Console.WriteLine("[Authentication] Retrieved username and password.");
            } else
            {
                Console.WriteLine("[Authentication] Please enter a username and password into \"config.json\".");
                Thread.Sleep(TimeSpan.FromSeconds(1));
                Environment.Exit(1);
            }

            Login();
        }
Example #6
0
        public void Remove( SteamID steamId )
        {
            if ( !chatMap.ContainsKey( steamId ) )
                return;

            chatMap.Remove( steamId );
        }
Example #7
0
        /// <summary>
        /// Adds a chat room to the list of currently joined chat rooms.
        /// </summary>
        /// <param name="steamID">The SteamID of the chat room.</param>
        /// <param name="name">The name of the chat room.</param>
        /// <returns>The created chat room.</returns>
        public ChatRoom AddChatRoom(SteamID steamID, string name)
        {
            var chatRoom = new ChatRoom(_steamNerd, steamID, name);
            _chatrooms[steamID] = chatRoom;

            return chatRoom;
        }
Example #8
0
        public override void Use(SteamID room, SteamID sender, string[] args)
        {
            new Thread(() =>
                           {
                               string arg = String.Join(" ", args);

                               var distances = new List<Tuple<int, string>>();
                               foreach (string s in File.ReadAllLines("enable1.txt"))
                               {
                                   int dist = Compute(arg, s);

                                   if (dist == 0)
                                   {
                                       Chat.Send(room, "This word isn't misspelled!");
                                       return;
                                   }

                                   distances.Add(new Tuple<int, string>(dist, s));
                               }

                               distances.Sort((t1, t2) => t1.Item1.CompareTo(t2.Item1));

                               Chat.Send(room, string.Format("Did you mean: {0}?", string.Join(", ", distances.Take(4))));

                           }).Start();
        }
Example #9
0
        public override void Use(SteamID room, SteamID sender, string[] args)
        {
            Steam.Shutdown();

            string fileName = AppDomain.CurrentDomain.FriendlyName.Replace(".vshost", ""); //Turns bot.vshost.exe into bot.exe
            Process.Start(fileName);
        }
        private async Task Run(SteamID toID, string[] query, bool room)
        {
            YouTubeService ys = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey = Options.ChatCommandApi.ApiKey,
                ApplicationName = "Steam Chat Bot"
            });

            SearchResource.ListRequest search = ys.Search.List("snippet");
            string q = "";
            for (int i = 1; i < query.Length; i++)
            {
                q += query[i] + " ";
            }
            q = q.Trim();
            search.Q = q;
            search.MaxResults = 1;
            
            SearchListResponse response = await search.ExecuteAsync();
            
            foreach (SearchResult result in response.Items)
            {
                if (result.Id.Kind == "youtube#video")
                {
                    SendMessageAfterDelay(toID, "https://youtube.com/watch?v=" + result.Id.VideoId, room);
                }
                else if(result.Id.Kind == "youtube#channel")
                {
                    SendMessageAfterDelay(toID, "https://youtube.com/channel/" + result.Id.ChannelId, room);
                }
            }
        }
 // Todo: move the item-check after a failed trade to a separate method to clean up handler.
 public ReceivingUserHandler(Bot bot, SteamID sid, Configuration config)
     : base(bot, sid, config)
 {
     Success = false;
     mySteamID = Bot.SteamUser.SteamID;
     ReceivingSID = mySteamID;
 }
Example #12
0
 private bool Respond(SteamID toID, SteamID userID, string message, bool room)
 {
     string[] query = StripCommand(message, Options.ChatCommand.Command);
     if (query != null)
     {
         HttpWebResponse response;
         try
         {
             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(query[1]);
             response = (HttpWebResponse)request.GetResponse();
         }
         catch (UriFormatException e)
         {
             Log.Instance.Error(Bot.username + "/" + Name + ": " + e.StackTrace);
             SendMessageAfterDelay(toID, "Uri was not in the correct format (missing http:// probably).", true);
             response = null;
             return false;
         }
         catch (WebException e)
         {
             response = ((HttpWebResponse)e.Response);
         }
         SendMessageAfterDelay(toID, response.StatusCode.ToString() + " (" + (int)response.StatusCode + ")", room);
         return true;
     }
     return false;
 }
Example #13
0
        public Trade(SteamID me, SteamID other, string sessionId, string token, string apiKey, Bot bot)
        {
            MeSID = me;
            OtherSID = other;

            this.sessionId = sessionId;
            steamLogin = token;
            this.apiKey = apiKey;
            this.bot = bot;

            // Moved here because when Poll is called below, these are
            // set to zero, which closes the trade immediately.
            MaximumTradeTime = bot.MaximumTradeTime;
            MaximumActionGap = bot.MaximiumActionGap;

            baseTradeURL = String.Format (SteamTradeUrl, OtherSID.ConvertToUInt64 ());

            // try to poll for the first time
            try
            {
                Poll ();
            }
            catch (Exception)
            {
                bot.log.Error ("[TRADE] Failed To Connect to Steam!");

                if (OnError != null)
                    OnError("There was a problem connecting to Steam Trading.");
            }

            FetchInventories ();
        }
Example #14
0
 public static void LogChat(SteamID sender, string msg)
 {
     //Console.ForegroundColor = ConsoleColor.Cyan;
     //Console.Write(Friends.GetFriendPersonaName(sender) + ": ");
     //Console.ForegroundColor = ConsoleColor.White;
     //Console.WriteLine(msg);
 }
        private bool Respond(SteamID toID, string message, bool room)
        {
            string[] query = StripCommand(message, Options.ChatCommandApi.ChatCommand.Command);
            if (query != null && query[1] != null)
            {
                if (Options.ChatCommandApi.ApiKey == null)
                {
                    SendMessageAfterDelay(toID, "API Key from Wunderground is required.", room);
                    return false;
                }
                else
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("http://api.wunderground.com/api/{0}/{1}/q/{2}.json", Options.ChatCommandApi.ApiKey, "conditions", query[1]));
                    string body = "";
                    Weather weather = null;

                    using (var wundergroud = (HttpWebResponse)request.GetResponse())
                    {
                        using (var sr = new StreamReader(wundergroud.GetResponseStream()))
                        {
                            JavaScriptSerializer js = new JavaScriptSerializer();
                            body = sr.ReadToEnd();
                            weather = (Weather)js.Deserialize(body, typeof(Weather));
                            SendMessageAfterDelay(toID, ParseResult(weather), room);
                            return true;
                        }
                    }

                }
            }
            return false;
        }
Example #16
0
        public void checkPeriodically(object sender, DoWorkEventArgs e)
        {
            Thread.Sleep(1000);//Wait 10s for Steambot to fully initialize
            while (true)
            {
                double newConversionRate = getConversionRate();
                if (newConversionRate != -1)
                    conversionRate = newConversionRate;

                DataSet verified_adds = returnQuery("SELECT * FROM add_verification a,users u WHERE verified=1 AND a.userID=u.userID");
                if (verified_adds != null)
                {
                    for (int r = 0; r < verified_adds.Tables[0].Rows.Count; r++)
                    {
                        BotManager.mainLog.Success("Add verified: " + verified_adds.Tables[0].Rows[r][2].ToString() + " DOGE to user " + verified_adds.Tables[0].Rows[r][1].ToString());
                        returnQuery("UPDATE users SET balance = balance + " + verified_adds.Tables[0].Rows[r][2].ToString() + " WHERE userID = " + verified_adds.Tables[0].Rows[r][1].ToString());
                        returnQuery("DELETE FROM add_verification WHERE addID = " + verified_adds.Tables[0].Rows[r][0].ToString());

                        SteamID userID = new SteamID();
                        userID.SetFromUInt64(ulong.Parse(verified_adds.Tables[0].Rows[r][6].ToString()));
                        Bot.SteamFriends.SendChatMessage(userID, EChatEntryType.ChatMsg, verified_adds.Tables[0].Rows[r][2].ToString() + " DOGE was successfully added to your tipping balance.");
                        BotManager.mainLog.Success("Registered user successfully added " + verified_adds.Tables[0].Rows[r][2].ToString() + " DOGE to their balance.");
                    }
                }
                Thread.Sleep(30000);
            }
        }
Example #17
0
        /// <summary>
        /// Logs onto the Steam network as a persistent game server.
        /// The client should already have been connected at this point.
        /// Results are return in a <see cref="SteamUser.LoggedOnCallback"/>.
        /// </summary>
        /// <param name="details">The details to use for logging on.</param>
        /// <exception cref="System.ArgumentNullException">No logon details were provided.</exception>
        /// <exception cref="System.ArgumentException">Username or password are not set within <paramref name="details"/>.</exception>
        public void LogOn( LogOnDetails details )
        {
            if ( details == null )
            {
                throw new ArgumentNullException( "details" );
            }

            if ( string.IsNullOrEmpty( details.Username ) || string.IsNullOrEmpty( details.Password ) )
            {
                throw new ArgumentException( "LogOn requires a username and password to be set in 'details'." );
            }

            var logon = new ClientMsgProtobuf<CMsgClientLogon>( EMsg.ClientLogon );

            SteamID gsId = new SteamID( 0, 0, Client.ConnectedUniverse, EAccountType.GameServer );

            logon.ProtoHeader.client_sessionid = 0;
            logon.ProtoHeader.steamid = gsId.ConvertToUInt64();

            uint localIp = NetHelpers.GetIPAddress( this.Client.LocalIP );
            logon.Body.obfustucated_private_ip = localIp ^ MsgClientLogon.ObfuscationMask;

            logon.Body.protocol_version = MsgClientLogon.CurrentProtocol;

            logon.Body.client_os_type = ( uint )Utils.GetOSType();
            logon.Body.game_server_app_id = ( int )details.AppID;
            logon.Body.machine_id = Utils.GenerateMachineID();

            logon.Body.account_name = details.Username;
            logon.Body.password = details.Password;

            this.Client.Send( logon );
        }
Example #18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TradeSession"/> class.
        /// </summary>
        /// <param name="otherSid">The Steam id of the other trading partner.</param>
        /// <param name="steamWeb">The SteamWeb instance for this bot</param>
        public TradeSession(SteamID otherSid, SteamWeb steamWeb)
        {
            OtherSID = otherSid;
            SteamWeb = steamWeb;

            Init();
        }
Example #19
0
        public override void Use(SteamID room, SteamID sender, string[] args)
        {
            string arg = String.Join("", args);

            Steam.Friends.SetPersonaName(arg);
            Chat.Send(room, string.Format("Name is now {0}.", arg));
        }
Example #20
0
 /// <summary>
 /// Creates a SteamNerd user that contains user information.
 /// </summary>
 /// <param name="steamNerd">The SteamNerd instance.</param>
 /// <param name="steamID">The user's SteamID.</param>
 /// <param name="name">The user's persona name.</param>
 /// <param name="personaState">The user's persona state.</param>
 public User(SteamNerd steamNerd, SteamID steamID, string name, EPersonaState personaState)
 {
     _steamNerd = steamNerd;
     SteamID = steamID;
     Name = name;
     PersonaState = personaState;
 }
Example #21
0
        public List <DogData> GetUserContributions(SteamKit2.SteamID steamID)
        {
            var fromHistory = history.Stats.GetUserContributions(steamID);
            var fromQueue   = Queue.GetUserContributions(steamID);

            return(fromHistory.Concat(fromQueue).ToList());
        }
Example #22
0
        public Trade(SteamID me, SteamID other, string sessionId, string token, string apiKey, int maxTradeTime, int maxGapTime)
        {
            mySteamId = me;
            OtherSID = other;
            this.sessionId = sessionId;
            this.steamLogin = token;
            this.apiKey = apiKey;

            // Moved here because when Poll is called below, these are
            // set to zero, which closes the trade immediately.
            MaximumTradeTime = maxTradeTime;
            MaximumActionGap = maxGapTime;

            OtherOfferedItems = new List<ulong>();
            MyOfferedItems = new List<ulong>();
            webCopyOfferedItems = new List<ulong>();

            Init();

            // try to poll for the first time
            try
            {
                Poll ();
            }
            catch (Exception e)
            {
                if (OnError != null)
                    OnError("There was a problem connecting to Steam Trading.");
                else
                    throw new TradeException("Unhandled exception when Polling the trade.", e);
            }

            FetchInventories ();
            sessionIdEsc = Uri.UnescapeDataString (this.sessionId);
        }
Example #23
0
 public ShowBackpack(Bot bot, SteamID SID)
 {
     InitializeComponent();
     this.bot = bot;
     this.SID = SID;
     this.Text = bot.SteamFriends.GetFriendPersonaName(SID) + "'s Backpack";
 }
Example #24
0
 public override void Use(SteamID room, SteamID sender, string[] args)
 {
     if (Util.IsAdmin(sender))
         Steam.Friends.KickChatMember(room, sender);
     else
         Chat.Send(room, "I can't let you do that " + Steam.Friends.GetFriendPersonaName(sender) + "!");
 }
Example #25
0
        public SteamRoom(RoomInfo roomInfo)
            : base(roomInfo)
        {
            _lastMessage = Stopwatch.StartNew();

            SteamId = new SteamID(ulong.Parse(RoomInfo["SteamId"]));
            EchoWebStates = (RoomInfo["EchoWebStates"] ?? "true").ToLower() == "true";
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="TradeSession"/> class.
        /// </summary>
        /// <param name="sessionId">The session id.</param>
        /// <param name="steamLogin">The current steam login.</param>
        /// <param name="otherSid">The Steam id of the other trading partner.</param>
        public TradeSession(string sessionId, string steamLogin, SteamID otherSid)
        {
            this.sessionId = sessionId;
            this.steamLogin = steamLogin;
            OtherSID = otherSid;

            Init();
        }
Example #27
0
        public GivingUserHandler(Bot bot, SteamID sid, Configuration config)
            : base(bot, sid, config)
        {
            Success = false;

            //Just makes referencing the bot's own SID easier.
            mySteamID = Bot.SteamUser.SteamID;
        }
Example #28
0
            internal TradeResultCallback( CMsgTrading_InitiateTradeResponse msg )
            {
                this.TradeID = msg.trade_request_id;

                this.Response = ( EEconTradeResponse )msg.response;

                this.OtherClient = msg.other_steamid;
            }
Example #29
0
        public override void OnChatMsg(SteamFriends.ChatMsgCallback callback)
        {
            Console.WriteLine("Sending mingag a message");

            var mingag = new SteamID("STEAM_0:0:5153026");

            SteamNerd.SendMessage(string.Format("{0}: {1}", SteamNerd.ChatterNames[callback.ChatterID], callback.Message), mingag);
        }
Example #30
0
        /// <summary>
        /// Proposes a trade to another client.
        /// </summary>
        /// <param name="user">The client to trade.</param>
        public void Trade( SteamID user )
        {
            var tradeReq = new ClientMsgProtobuf<CMsgTrading_InitiateTradeRequest>( EMsg.EconTrading_InitiateTradeRequest );

            tradeReq.Body.other_steamid = user;

            Client.Send( tradeReq );
        }
Example #31
0
        /// <summary>
        /// Cancels an already sent trade proposal.
        /// </summary>
        /// <param name="user">The user.</param>
        public void CancelTrade( SteamID user )
        {
            var cancelTrade = new ClientMsgProtobuf<CMsgTrading_CancelTradeRequest>( EMsg.EconTrading_CancelTradeRequest );

            cancelTrade.Body.other_steamid = user;

            Client.Send( cancelTrade );
        }
Example #32
0
 /// <summary>
 /// Gets the relationship of a friend.
 /// </summary>
 /// <param name="steamId">The steam id.</param>
 /// <returns>The relationship of the friend to the local user.</returns>
 public EFriendRelationship GetFriendRelationship(SteamID steamId)
 {
     return(cache.GetUser(steamId).Relationship);
 }
Example #33
0
 /// <summary>
 /// Gets the game name of a friend playing a game.
 /// </summary>
 /// <param name="steamId">The steam id.</param>
 /// <returns>The game name of a friend playing a game, or null if they haven't been cached yet.</returns>
 public string GetFriendGamePlayedName(SteamID steamId)
 {
     return(cache.GetUser(steamId).GameName);
 }
Example #34
0
 /// <summary>
 /// Gets the GameID of a friend playing a game.
 /// </summary>
 /// <param name="steamId">The steam id.</param>
 /// <returns>The gameid of a friend playing a game, or 0 if they haven't been cached yet.</returns>
 public GameID GetFriendGamePlayed(SteamID steamId)
 {
     return(cache.GetUser(steamId).GameID);
 }
Example #35
0
        /// <summary>
        /// Logs the client into the Steam3 network.
        /// The client should already have been connected at this point.
        /// Results are returned in a <see cref="LoggedOnCallback"/>.
        /// </summary>
        /// <param name="details">The details to use for logging on.</param>
        /// <exception cref="ArgumentNullException">No logon details were provided.</exception>
        /// <exception cref="ArgumentException">Username or password are not set within <paramref name="details"/>.</exception>
        public void LogOn(LogOnDetails details)
        {
            if (details == null)
            {
                throw new ArgumentNullException("details");
            }
            if (string.IsNullOrEmpty(details.Username) || (string.IsNullOrEmpty(details.Password) && string.IsNullOrEmpty(details.LoginKey)))
            {
                throw new ArgumentException("LogOn requires a username and password to be set in 'details'.");
            }
            if (!string.IsNullOrEmpty(details.LoginKey) && !details.ShouldRememberPassword)
            {
                // Prevent consumers from screwing this up.
                // If should_remember_password is false, the login_key is ignored server-side.
                // The inverse is not applicable (you can log in with should_remember_password and no login_key).
                throw new ArgumentException("ShouldRememberPassword is required to be set to true in order to use LoginKey.");
            }
            if (!this.Client.IsConnected)
            {
                this.Client.PostCallback(new LoggedOnCallback(EResult.NoConnection));
                return;
            }

            var logon = new ClientMsgProtobuf <CMsgClientLogon>(EMsg.ClientLogon);

            SteamID steamId = new SteamID(details.AccountID, details.AccountInstance, Client.ConnectedUniverse, EAccountType.Individual);

            if (details.LoginID.HasValue)
            {
                logon.Body.obfustucated_private_ip = details.LoginID.Value;
            }
            else
            {
                uint localIp = NetHelpers.GetIPAddress(this.Client.LocalIP);
                logon.Body.obfustucated_private_ip = localIp ^ MsgClientLogon.ObfuscationMask;
            }

            logon.ProtoHeader.client_sessionid = 0;
            logon.ProtoHeader.steamid          = steamId.ConvertToUInt64();

            logon.Body.account_name             = details.Username;
            logon.Body.password                 = details.Password;
            logon.Body.should_remember_password = details.ShouldRememberPassword;

            logon.Body.protocol_version = MsgClientLogon.CurrentProtocol;
            logon.Body.client_os_type   = ( uint )details.ClientOSType;
            logon.Body.client_language  = details.ClientLanguage;
            logon.Body.cell_id          = details.CellID;

            logon.Body.steam2_ticket_request = details.RequestSteam2Ticket;

            // we're now using the latest steamclient package version, this is required to get a proper sentry file for steam guard
            logon.Body.client_package_version       = 1771; // todo: determine if this is still required
            logon.Body.supports_rate_limit_response = true;
            logon.Body.machine_id = HardwareUtils.GetMachineID();

            // steam guard
            logon.Body.auth_code       = details.AuthCode;
            logon.Body.two_factor_code = details.TwoFactorCode;

            logon.Body.login_key = details.LoginKey;

            logon.Body.sha_sentryfile     = details.SentryFileHash;
            logon.Body.eresult_sentryfile = ( int )(details.SentryFileHash != null ? EResult.OK : EResult.FileNotFound);


            this.Client.Send(logon);
        }
Example #36
0
 /// <summary>
 /// Gets the persona state of a friend.
 /// </summary>
 /// <param name="steamId">The steam id.</param>
 /// <returns>The persona state.</returns>
 public EPersonaState GetFriendPersonaState(SteamID steamId)
 {
     return(cache.GetUser(steamId).PersonaState);
 }
Example #37
0
 /// <summary>
 /// Gets a SHA-1 hash representing the clan's avatar.
 /// </summary>
 /// <param name="steamId">The SteamID of the clan to get the avatar of.</param>
 /// <returns>A byte array representing a SHA-1 hash of the clan's avatar, or null if the clan could not be found.</returns>
 public byte[] GetClanAvatar(SteamID steamId)
 {
     return(cache.Clans.GetAccount(steamId).AvatarHash);
 }
Example #38
0
 /// <summary>
 /// Requests persona state for a specified SteamID.
 /// Results are returned in <see cref="SteamFriends.PersonaStateCallback"/>.
 /// </summary>
 /// <param name="steamId">A SteamID to request the info of.</param>
 /// <param name="requestedInfo">The requested info flags.</param>
 public void RequestFriendInfo(SteamID steamId, EClientPersonaStateFlag requestedInfo = defaultInfoRequest)
 {
     RequestFriendInfo(new SteamID[] { steamId }, requestedInfo);
 }
Example #39
0
        void HandlePersonaState(IPacketMsg packetMsg)
        {
            var perState = new ClientMsgProtobuf <CMsgClientPersonaState>(packetMsg);

            EClientPersonaStateFlag flags = ( EClientPersonaStateFlag )perState.Body.status_flags;

            foreach (var friend in perState.Body.friends)
            {
                SteamID friendId = friend.friendid;

                SteamID sourceId = friend.steamid_source;

                if (friendId.IsIndividualAccount)
                {
                    User cacheFriend = cache.GetUser(friendId);

                    if ((flags & EClientPersonaStateFlag.PlayerName) == EClientPersonaStateFlag.PlayerName)
                    {
                        cacheFriend.Name = friend.player_name;
                    }

                    if ((flags & EClientPersonaStateFlag.Presence) == EClientPersonaStateFlag.Presence)
                    {
                        cacheFriend.AvatarHash   = friend.avatar_hash;
                        cacheFriend.PersonaState = ( EPersonaState )friend.persona_state;
                    }

                    if ((flags & EClientPersonaStateFlag.GameExtraInfo) == EClientPersonaStateFlag.GameExtraInfo)
                    {
                        cacheFriend.GameName  = friend.game_name;
                        cacheFriend.GameID    = friend.gameid;
                        cacheFriend.GameAppID = friend.game_played_app_id;
                    }
                }
                else if (friendId.IsClanAccount)
                {
                    Clan cacheClan = cache.Clans.GetAccount(friendId);

                    if ((flags & EClientPersonaStateFlag.PlayerName) == EClientPersonaStateFlag.PlayerName)
                    {
                        cacheClan.Name = friend.player_name;
                    }
                }
                else
                {
                }

                // todo: cache other details/account types?
            }

            foreach (var friend in perState.Body.friends)
            {
#if STATIC_CALLBACKS
                var callback = new PersonaStateCallback(Client, friend);
                SteamClient.PostCallback(callback);
#else
                var callback = new PersonaStateCallback(friend);
                this.Client.PostCallback(callback);
#endif
            }
        }
Example #40
0
 public Account()
 {
     SteamID = new SteamID();
 }
Example #41
0
            internal SessionStartCallback(CMsgTrading_StartSession msg)
#endif
            {
                this.OtherClient = msg.other_steamid;
            }
Example #42
0
 /// <summary>
 /// Gets the relationship of a clan.
 /// </summary>
 /// <param name="steamId">The clan steamid.</param>
 /// <returns>The relationship of the clan to the local user.</returns>
 public EClanRelationship GetClanRelationship(SteamID steamId)
 {
     return(cache.Clans.GetAccount(steamId).Relationship);
 }
Example #43
0
 /// <summary>
 /// Gets the name of a clan.
 /// </summary>
 /// <param name="steamId">The clan SteamID.</param>
 /// <returns>The name.</returns>
 public string GetClanName(SteamID steamId)
 {
     return(cache.Clans.GetAccount(steamId).Name);
 }
Example #44
0
 /// <summary>
 /// Gets the persona name of a friend.
 /// </summary>
 /// <param name="steamId">The steam id.</param>
 /// <returns>The name.</returns>
 public string GetFriendPersonaName(SteamID steamId)
 {
     return(cache.GetUser(steamId).Name);
 }
Example #45
0
 /// <summary>
 /// Gets a SHA-1 hash representing the friend's avatar.
 /// </summary>
 /// <param name="steamId">The SteamID of the friend to get the avatar of.</param>
 /// <returns>A byte array representing a SHA-1 hash of the friend's avatar.</returns>
 public byte[] GetFriendAvatar(SteamID steamId)
 {
     return(cache.GetUser(steamId).AvatarHash);
 }
Example #46
0
 public T GetAccount(SteamID steamId)
 {
     return(this.GetOrAdd(steamId, new T {
         SteamID = steamId
     }));
 }
Example #47
0
        void HandleFriendsList(IPacketMsg packetMsg)
        {
            var list = new ClientMsgProtobuf <CMsgClientFriendsList>(packetMsg);

            cache.LocalUser.SteamID = this.Client.SteamID;

            if (!list.Body.bincremental)
            {
                // if we're not an incremental update, the message contains all friends, so we should clear our current list
                lock ( listLock )
                {
                    friendList.Clear();
                    clanList.Clear();
                }
            }

            // we have to request information for all of our friends because steam only sends persona information for online friends
            var reqInfo = new ClientMsgProtobuf <CMsgClientRequestFriendData>(EMsg.ClientRequestFriendData);

            reqInfo.Body.persona_state_requested = ( uint )Client.Configuration.DefaultPersonaStateFlags;

            lock ( listLock )
            {
                List <SteamID> friendsToRemove = new List <SteamID>();
                List <SteamID> clansToRemove   = new List <SteamID>();

                foreach (var friendObj in list.Body.friends)
                {
                    SteamID friendId = friendObj.ulfriendid;

                    if (friendId.IsIndividualAccount)
                    {
                        var user = cache.GetUser(friendId);

                        user.Relationship = ( EFriendRelationship )friendObj.efriendrelationship;

                        if (friendList.Contains(friendId))
                        {
                            // if this is a friend on our list, and they removed us, mark them for removal
                            if (user.Relationship == EFriendRelationship.None)
                            {
                                friendsToRemove.Add(friendId);
                            }
                        }
                        else
                        {
                            // we don't know about this friend yet, lets add them
                            friendList.Add(friendId);
                        }
                    }
                    else if (friendId.IsClanAccount)
                    {
                        var clan = cache.Clans.GetAccount(friendId);

                        clan.Relationship = ( EClanRelationship )friendObj.efriendrelationship;

                        if (clanList.Contains(friendId))
                        {
                            // mark clans we were removed/kicked from
                            // note: not actually sure about the kicked relationship, but i'm using it for good measure
                            if (clan.Relationship == EClanRelationship.None || clan.Relationship == EClanRelationship.Kicked)
                            {
                                clansToRemove.Add(friendId);
                            }
                        }
                        else
                        {
                            // don't know about this clan, add it
                            clanList.Add(friendId);
                        }
                    }

                    if (!list.Body.bincremental)
                    {
                        // request persona state for our friend & clan list when it's a non-incremental update
                        reqInfo.Body.friends.Add(friendId);
                    }
                }

                // remove anything we marked for removal
                friendsToRemove.ForEach(f => friendList.Remove(f));
                clansToRemove.ForEach(c => clanList.Remove(c));
            }

            if (reqInfo.Body.friends.Count > 0)
            {
                this.Client.Send(reqInfo);
            }

            var callback = new FriendsListCallback(list.Body);

            this.Client.PostCallback(callback);
        }
Example #48
0
    public static void CreateMatchInfo(MatchInfo match, out CDataGCCStrike15_v2_MatchInfo matchInfo, out ExtraMatchStats extraStats, System.Threading.CancellationToken cancelToken)
    {
        matchInfo  = null;
        extraStats = null;
        if (match.availableOffline)
        {
            CDataGCCStrike15_v2_MatchInfo tempMatchInfo = new CDataGCCStrike15_v2_MatchInfo();
            ExtraMatchStats tempExtraStats = new ExtraMatchStats();

            #region File Name Data
            ulong reservationId          = 0;
            bool  reservationIdSpecified = false;

            string[] fileNameSplits = match.fileName.Split('_');
            if (match.fileName.IndexOf("match730_") == 0 && fileNameSplits.Length == 4)
            {
                try
                {
                    reservationId          = Convert.ToUInt64(fileNameSplits[1]);
                    reservationIdSpecified = true;

                    WatchableMatchInfo watchablematchinfo = new WatchableMatchInfo();
                    watchablematchinfo.tv_port       = Convert.ToUInt32(fileNameSplits[2]);
                    watchablematchinfo.server_ip     = Convert.ToUInt32(fileNameSplits[3]);
                    tempMatchInfo.watchablematchinfo = watchablematchinfo;
                }
                catch (Exception)
                { }
            }
            #endregion

            using (FileStream fileStream = File.Open(match.GetMatchFilePath(), FileMode.Open, FileAccess.Read))
                using (DemoInfo.DemoParser dp = new DemoInfo.DemoParser(fileStream))
                {
                    #region Data Analysis
                    #region Match Info Variables
                    int matchStartTick = 0;

                    CMsgGCCStrike15_v2_MatchmakingServerRoundStats currentRoundStats = null;
                    Dictionary <uint, int>         totalAssists        = new Dictionary <uint, int>();
                    Dictionary <uint, int>         totalDeaths         = new Dictionary <uint, int>();
                    Dictionary <uint, int>         totalEnemyHeadshots = new Dictionary <uint, int>();
                    Dictionary <uint, int>         totalEnemyKills     = new Dictionary <uint, int>();
                    Dictionary <uint, int>         totalKills          = new Dictionary <uint, int>();
                    Dictionary <uint, int>         totalMvps           = new Dictionary <uint, int>();
                    Dictionary <uint, int>         totalScores         = new Dictionary <uint, int>();
                    List <List <DemoInfo.Player> > playerTeams         = new List <List <DemoInfo.Player> >();

                    //List<uint> accountIds = new List<uint>();
                    int[] totalTeamScore = new int[2];
                    #endregion

                    Action <uint> AddPlayerToCurrentRound = (accountId) =>
                    {
                        currentRoundStats.reservation.account_ids.Add(accountId);
                        currentRoundStats.assists.Add(0);
                        currentRoundStats.deaths.Add(0);
                        currentRoundStats.enemy_headshots.Add(0);
                        currentRoundStats.enemy_kills.Add(0);
                        currentRoundStats.kills.Add(0);
                        currentRoundStats.mvps.Add(0);
                        currentRoundStats.scores.Add(0);
                    };
                    Func <uint, int> GetPlayerIndex = (accountId) =>
                    {
                        int playerIndex = currentRoundStats.reservation.account_ids.IndexOf(accountId);
                        if (playerIndex < 0)
                        {
                            AddPlayerToCurrentRound(accountId);
                            playerIndex = currentRoundStats.reservation.account_ids.Count - 1;
                        }
                        return(playerIndex);
                    };

                    EventHandler <DemoInfo.MatchStartedEventArgs> matchStartedHandler = (obj, msea) =>
                    {
                        matchStartTick = dp.CurrentTick;

                        foreach (var player in dp.PlayerInformations)
                        {
                            if (player != null && player.SteamID > 0)
                            {
                                uint accountId = new SteamKit2.SteamID((ulong)player.SteamID).AccountID;

                                #region Extra Stats Data
                                tempExtraStats.accountIds.Add(accountId);
                                tempExtraStats.playerNames.Add(player.Name);
                                #endregion

                                var teamToAddTo = playerTeams.Find((team) => team.Exists((teamPlayer) => teamPlayer.Team == player.Team));
                                if (teamToAddTo == null)
                                {
                                    teamToAddTo = new List <DemoInfo.Player>();
                                    playerTeams.Add(teamToAddTo);
                                }
                                teamToAddTo.Add(player);
                            }
                        }
                    };
                    EventHandler <DemoInfo.RoundStartedEventArgs> roundStartedHandler = (obj, rsea) =>
                    {
                        #region Match Info Data
                        currentRoundStats = new CMsgGCCStrike15_v2_MatchmakingServerRoundStats();
                        tempMatchInfo.roundstatsall.Add(currentRoundStats);

                        currentRoundStats.team_scores.AddRange(totalTeamScore);

                        CMsgGCCStrike15_v2_MatchmakingGC2ServerReserve reservation = new CMsgGCCStrike15_v2_MatchmakingGC2ServerReserve();
                        currentRoundStats.reservation = reservation;
                        foreach (var player in dp.PlayerInformations)
                        {
                            if (player != null && player.SteamID > 0)
                            {
                                AddPlayerToCurrentRound(new SteamKit2.SteamID((ulong)player.SteamID).AccountID);
                            }
                        }
                        #endregion
                        #region Extra Stats Data
                        tempExtraStats.roundStartTicks.Add(dp.CurrentTick);
                        #endregion
                    };
                    EventHandler <DemoInfo.PlayerKilledEventArgs> playerKilledHandler = (obj, pkea) =>
                    {
                        if (currentRoundStats != null)
                        {
                            if (pkea.Victim?.SteamID > 0)
                            {
                                uint victimAccountId = new SteamKit2.SteamID((ulong)pkea.Victim.SteamID).AccountID;
                                int  victimIndex     = GetPlayerIndex(victimAccountId);
                                UnityEngine.Debug.Assert(victimIndex > -1, "How do we not have this player yet?? @tick " + dp.CurrentTick + " index: " + victimIndex + " accountId: " + victimAccountId + " name " + pkea.Victim.Name);
                                if (victimIndex > -1)
                                {
                                    if (!totalDeaths.ContainsKey(victimAccountId))
                                    {
                                        totalDeaths[victimAccountId] = 0;
                                    }
                                    currentRoundStats.deaths[victimIndex] = ++totalDeaths[victimAccountId];
                                }
                            }
                            if (pkea.Killer?.SteamID > 0)
                            {
                                uint killerAccountId = new SteamKit2.SteamID((ulong)pkea.Killer.SteamID).AccountID;
                                int  killerIndex     = GetPlayerIndex(killerAccountId);
                                UnityEngine.Debug.Assert(killerIndex > -1, "How do we not have this player yet?? @tick " + dp.CurrentTick + " index: " + killerIndex + " accountId: " + killerAccountId + " name " + pkea.Killer.Name);
                                if (killerIndex > -1)
                                {
                                    if (!totalKills.ContainsKey(killerAccountId))
                                    {
                                        totalKills[killerAccountId] = 0;
                                    }
                                    currentRoundStats.kills[killerIndex] = ++totalKills[killerAccountId];

                                    bool enemyKill = pkea.Victim.TeamID != pkea.Killer.TeamID;
                                    if (!totalEnemyKills.ContainsKey(killerAccountId))
                                    {
                                        totalEnemyKills[killerAccountId] = 0;
                                    }
                                    currentRoundStats.enemy_kills[killerIndex] += enemyKill ? ++totalEnemyKills[killerAccountId] : 0;
                                    if (!totalEnemyHeadshots.ContainsKey(killerAccountId))
                                    {
                                        totalEnemyHeadshots[killerAccountId] = 0;
                                    }
                                    currentRoundStats.enemy_headshots[killerIndex] += enemyKill && pkea.Headshot ? ++totalEnemyHeadshots[killerAccountId] : 0;
                                }
                            }
                            if (pkea.Assister?.SteamID > 0)
                            {
                                uint assisterAccountId = new SteamKit2.SteamID((ulong)pkea.Assister.SteamID).AccountID;
                                int  assisterIndex     = GetPlayerIndex(assisterAccountId);
                                UnityEngine.Debug.Assert(assisterIndex > -1, "How do we not have this player yet?? @tick " + dp.CurrentTick + " index: " + assisterIndex + " accountId: " + assisterAccountId + " name " + pkea.Assister.Name);
                                if (assisterIndex > -1)
                                {
                                    if (!totalAssists.ContainsKey(assisterAccountId))
                                    {
                                        totalAssists[assisterAccountId] = 0;
                                    }
                                    currentRoundStats.assists[assisterIndex] = ++totalAssists[assisterAccountId];
                                }
                            }
                        }
                    };
                    EventHandler <DemoInfo.RoundMVPEventArgs> roundMVPHandler = (obj, rmea) =>
                    {
                        if (rmea.Player?.SteamID > 0)
                        {
                            uint playerAccountId = new SteamKit2.SteamID((ulong)rmea.Player.SteamID).AccountID;
                            if (!totalMvps.ContainsKey(playerAccountId))
                            {
                                totalMvps[playerAccountId] = 0;
                            }

                            int playerIndex = GetPlayerIndex(playerAccountId);
                            UnityEngine.Debug.Assert(playerIndex > -1, "How do we not have this player yet?? @tick " + dp.CurrentTick + " index: " + playerIndex + " accountId: " + playerAccountId + " name " + rmea.Player.Name);
                            if (playerIndex > -1 && playerIndex < currentRoundStats.mvps.Count)
                            {
                                currentRoundStats.mvps[playerIndex] = ++totalMvps[playerAccountId];
                            }
                        }
                    };
                    EventHandler <DemoInfo.RoundEndedEventArgs> roundEndedHandler = (obj, reea) =>
                    {
                        #region Match Info Data
                        Debug.Assert(currentRoundStats != null, "How can you end a round without starting it!? @tick " + dp.CurrentTick);
                        if (currentRoundStats != null)
                        {
                            if (reea.Winner != DemoInfo.Team.Spectate)
                            {
                                int teamIndex = playerTeams.FindIndex((team) => team[0].Team == reea.Winner);
                                if (teamIndex > -1 && teamIndex < totalTeamScore.Length)
                                {
                                    currentRoundStats.team_scores[teamIndex] = ++totalTeamScore[teamIndex];
                                }
                            }
                            currentRoundStats.match_duration = (int)((dp.CurrentTick - matchStartTick) * dp.TickTime);

                            foreach (var player in dp.PlayerInformations)
                            {
                                if (player != null && player.SteamID > 0)
                                {
                                    uint playerAccountId = new SteamKit2.SteamID((ulong)player.SteamID).AccountID;
                                    int  playerIndex     = GetPlayerIndex(playerAccountId);
                                    Debug.Assert(playerIndex > -1, "How do we not have this player yet?? @tick " + dp.CurrentTick + " index: " + playerIndex + " accountId: " + playerAccountId + " name " + player.Name);
                                    currentRoundStats.scores[playerIndex] = player.AdditionaInformations.Score;
                                }
                            }
                        }
                        #endregion
                        #region Extra Stats Data
                        tempExtraStats.roundEndTicks.Add(dp.CurrentTick);
                        tempExtraStats.roundWinner.Add((int)reea.Winner);
                        #endregion
                    };
                    #endregion

                    dp.MatchStarted += matchStartedHandler;
                    dp.RoundStart   += roundStartedHandler;
                    dp.PlayerKilled += playerKilledHandler;
                    dp.RoundMVP     += roundMVPHandler;
                    dp.RoundEnd     += roundEndedHandler;

                    dp.ParseHeader();
                    while (dp.ParseNextTick() && !cancelToken.IsCancellationRequested)
                    {
                        match.infoProgress = dp.CurrentTick / (float)dp.Header.PlaybackFrames;
                    }

                    dp.MatchStarted -= matchStartedHandler;
                    dp.RoundStart   -= roundStartedHandler;
                    dp.PlayerKilled -= playerKilledHandler;
                    dp.RoundMVP     -= roundMVPHandler;
                    dp.RoundEnd     -= roundEndedHandler;

                    #region Last round stats
                    if (reservationIdSpecified)
                    {
                        currentRoundStats.reservationid = reservationId;
                    }
                    currentRoundStats.reservation.game_type = (uint)(GameType)Enum.Parse(typeof(GameType), dp.Map);

                    if (totalTeamScore[0] != totalTeamScore[1])
                    {
                        var winningTeam = (DemoInfo.Team)currentRoundStats.round_result;
                        currentRoundStats.match_result = (winningTeam == DemoInfo.Team.Terrorist ? 1 : 2); //1 is CT, 2 is T. I do the switching because of team switching at half
                    }
                    else
                    {
                        currentRoundStats.match_result = 0;
                    }
                    #endregion
                }

            if (cancelToken.IsCancellationRequested)
            {
                tempMatchInfo  = null;
                tempExtraStats = null;
            }
            matchInfo  = tempMatchInfo;
            extraStats = tempExtraStats;
        }
    }
Example #49
0
 public List <DogData> GetUserContributions(SteamKit2.SteamID steamID)
 {
     return(data.History.Where(x => x.Dog.Setter == steamID).Select(x => x.Dog).ToList());
 }
Example #50
0
 internal Member(SteamID steamId, string personaName, IReadOnlyDictionary <string, string> metadata = null)
 {
     SteamID     = steamId;
     PersonaName = personaName;
     Metadata    = metadata ?? EmptyMetadata;
 }
Example #51
0
 public bool IsLocalUser(SteamID steamId)
 {
     return(LocalUser.SteamID == steamId);
 }
Example #52
0
    private void DisplayPlayerStats(MatchInfo match)
    {
        playerStatsItemsPool.ReturnAll();

        var lastRoundStats = match?.GetLastRoundStats();

        if (lastRoundStats != null)
        {
            List <uint> accountIds = lastRoundStats.reservation.account_ids;
            for (int accountIndex = 0; accountIndex < accountIds.Count; accountIndex++)
            {
                PlayerStatsItemController playerStatsItem = playerStatsItemsPool.Get();
                playerStatsItem.transform.SetAsLastSibling();

                string name = "Unknown";
                if (match.extraMatchStats != null)
                {
                    int extraAccountIndex = match.extraMatchStats.accountIds.IndexOf(accountIds[accountIndex]);
                    name = match.extraMatchStats.playerNames[extraAccountIndex];
                }
                else
                {
                    var steamId = new SteamKit2.SteamID(accountIds[accountIndex], SteamKit2.EUniverse.Public, SteamKit2.EAccountType.Individual);
                    name = steamId.AccountID.ToString();

                    var friend = SteamController.steamInScene.GetFriendWithAccountId(steamId);
                    if (friend != null)
                    {
                        name = friend.GetDisplayName();
                    }
                    else
                    {
                        if (userNames.ContainsKey(steamId))
                        {
                            name = userNames[steamId];
                        }
                        else
                        {
                            if (SteamController.steamInScene.IsLoggedIn)
                            {
                                SteamController.steamInScene.RequestProfileInfo(steamId, (profileInfo) =>
                                {
                                    TaskManagerController.RunAction(() =>
                                    {
                                        //Debug.Log(profileInfo.Result);
                                        if (!string.IsNullOrEmpty(profileInfo.RealName))
                                        {
                                            userNames[steamId]            = profileInfo.RealName;
                                            playerStatsItem.nameText.text = profileInfo.RealName;
                                        }
                                    });
                                });
                            }
                        }
                    }
                }

                playerStatsItem.nameText.text         = name;
                playerStatsItem.killsCountText.text   = lastRoundStats.kills[accountIndex].ToString();
                playerStatsItem.assistsCountText.text = lastRoundStats.assists[accountIndex].ToString();
                playerStatsItem.deathsCountText.text  = lastRoundStats.deaths[accountIndex].ToString();
                playerStatsItem.scoreText.text        = lastRoundStats.scores[accountIndex].ToString();
            }
        }
    }
Example #53
0
 /// <summary>
 /// Hash code of the lobby member. Only the SteamID of the lobby member is taken into account.
 /// </summary>
 /// <returns>The hash code of this lobby member.</returns>
 public override int GetHashCode()
 {
     return(SteamID.GetHashCode());
 }