Facepunch.Steamworks

repository·master·Indexed 25 days ago

https://github.com/facepunch/facepunch.steamworks

A C# wrapper for the Steamworks API designed for Unity developers. It provides idiomatic access to Steam client and server initialization, user and friend information, achievements, Workshop item querying and downloading, Steam Cloud storage, inventory management, and authentication. It includes the ServerInfo struct for managing game server metadata, tags, and favorites/history lists.

Tokens
1.9K
Snippets
6
Records
13
Agent score
37%

What's inside Facepunch.Steamworks

  1. Initialize a Steam Server

    master

    To create a dedicated server, use SteamServer.Init with a SteamServerInit configuration object. This allows you to specify the game name, ports, and security settings.

    var serverInit = new SteamServerInit( "gmod", "Garry Mode" )
    {
        GamePort = 28015,
        Secure = true,
        QueryPort = 28016
    };
    
    try
    {
        Steamworks.SteamServer.Init( 4000, serverInit );
    }
    catch ( System.Exception )
    {
        // Couldn't init for some reason (dll errors, blocked ports)
    }
  2. Initialize a Steam Client

    master

    To use Facepunch.Steamworks, you must first initialize the SteamClient. Replace the integer with your specific game's AppID. You should not call any other Steam functions before initialization. When the game closes, call SteamClient.Shutdown() to clean up.

    using Steamworks;
    
    try 
    {
        SteamClient.Init( 4000 );
    }
    catch ( System.Exception e )
    {
        // Couldn't init for some reason (steam is closed etc)
    }
    
    // When closing the game:
    SteamClient.Shutdown();
  3. Handle Steam Inventory

    master

    Access item definitions via SteamInventory.Definitions or GetDefinitionsWithPricesAsync(). To retrieve a user's items, use SteamInventory.GetItems(). Note that the result is disposable and should be used within a using block.

    // Get items for sale
    var defs = await SteamInventory.GetDefinitionsWithPricesAsync();
    
    // Get user items
    var result = await SteamInventory.GetItems();
    using ( result )
    {
        var items = result?.GetItems( bWithProperties );
        foreach ( InventoryItem item in items )
        {
            Console.WriteLine( $"{item.Id} / {item.Quantity} / {item.Def.Name} " );
        }
    }
  4. Manage Steam Achievements

    master

    You can iterate through all available achievements via SteamUserStats.Achievements and unlock them by creating an Achievement object with the achievement's name and calling .Trigger().

    // List achievements
    foreach ( var a in SteamUserStats.Achievements )
    {
        Console.WriteLine( $"{a.Name} ({a.State})" );
    }
    
    // Unlock an achievement
    var ach = new Achievement( "GM_PLAYED_WITH_GARRY" );
    ach.Trigger();
  5. Query and download Workshop items

    master

    Use SteamUGC.Download(id) to download a specific item. For querying, use the Ugc namespace to build queries (e.g., Ugc.Query.All) with filters like .WithTag() and execute them using .GetPageAsync(pageNumber).

    // Download by ID
    SteamUGC.Download( 1717844711 );
    
    // Query items
    var q = Ugc.Query.All
                    .WithTag( "Fun" )
                    .WithTag( "Movie" )
                    .MatchAllTags();
    
    var result = await q.GetPageAsync( 1 );
    
    foreach ( Ugc.Item entry in result.Value.Entries )
    {
        Console.WriteLine( $"{entry.Title}" );
    }
  6. Implement Steam Authentication

    master

    Authentication involves a client generating a ticket via SteamUser.GetAuthSessionTicket() and a server validating it. Servers can listen to SteamServer.OnValidateAuthTicketResponse or manually call SteamServer.BeginAuthSession(ticketData, clientSteamId) to verify a user.

    // Client side
    var ticket = SteamUser.GetAuthSessionTicket();
    
    // Server side listener
    SteamServer.OnValidateAuthTicketResponse += ( steamid, ownerid, rsponse ) =>
    {
        if ( rsponse == AuthResponse.OK )
            TellUserTheyCanBeOnServer( steamid );
        else
            KickUser( steamid );
    };
    
    // Server side manual validation
    if ( !SteamServer.BeginAuthSession( ticketData, clientSteamId ) )
    {
        KickUser( clientSteamId );
    }
    
    // Cancel ticket
    ticket.Cancel();
  7. Manage Steam Favorites and History with ServerInfo

    master

    You can add or remove a server from the user's Steam Favorites or History lists directly via the ServerInfo instance:

    • AddToFavourites(): Adds the server to the user's favorites list.
    • RemoveFromFavourites(): Removes the server from the favorites list.
    • AddToHistory(): Adds the server to the history list (or updates the last played time if already present).
    • RemoveFromHistory(): Removes the server from the history list.
  8. ServerInfo Properties Reference

    master

    The following properties are available on the ServerInfo struct:

    PropertyTypeDescription
    NamestringThe name of the server
    PingintThe server ping
    GameDirstringThe game directory
    MapstringThe current map
    DescriptionstringThe server description
    AppIduintThe Steam App ID
    PlayersintCurrent number of players
    MaxPlayersintMaximum player capacity
    BotPlayersintNumber of bot players
    PasswordedboolWhether the server is password protected
    SecureboolWhether the server is secure
    LastTimePlayeduintTimestamp of last play time
    VersionintThe server version
    TagStringstringComma-separated string of tags
    Tagsstring[]Array of individual tags
    SteamIdulongThe Steam ID of the server
    AddressRawuintThe raw IP address
    AddressIPAddressThe IP address object
    ConnectionPortintThe connection port
    QueryPortintThe query port