Snowflake is a unique identifier format used by Discord, Twitter (now X) and other platforms. This library provides tools for parsing Discord snowflake IDs.
Snowflake is a 64-bit integer without sign (in Go, this is a uint64 type). Snowflake bits are separated into groups:
[000000100111000100000110010110101100000100][00001][00000][000010011001]
64 22 17 12 0
Where:
- Bits 0-12 is a sequence (incremented for every generated ID on process);
- Bits 12-17 is a internal process ID;
- Bits 17-22 is a internal worker ID;
- Bits 22-64 is a number of milliseconds since Discord epoch.
Type this command in your terminal to install:
$ go get github.com/gophercord/snowflake
Simple gophercord/snowflake usage example. You may like to see the .examples directory for more examples (TODO).
package main
import (
"fmt"
"github.com/gophercord/snowflake"
)
func main() {
var err error
// Creating new snowflake from uint64
s := snowflake.Snowflake(1363292549053284505)
// Accessing snowflake attributes
fmt.Println(
"Created at:", s.Time(),
"\n Seconds:", s.Unix(),
"\n Milliseconds:", s.UnixMilli(),
"\nWorker ID:", s.WorkerID(),
"\nProcess ID:", s.ProcessID(),
"\nSequence:", s.Sequence(),
"\n==============================",
)
// You can parse a snowflake from a string, JSON, or a [time.Time]
// Parsing new snowflake ID from a string
//
// NOTE: The string must contain only digits without any signs (because Snowflake is a
// uint64 type)
s2, _ := snowflake.ParseString("10")
fmt.Println("parsed from string:", s2)
// Parsing new snowflake ID from JSON
s3, _ := snowflake.ParseJSON([]byte(`"134"`))
s4, _ := snowflake.ParseJSON([]byte("134")) // unquoted integer
fmt.Println("parsed from JSON:", s3, s4)
// You can deny unquoted integers in JSON (by default, unquoted integers are allowed)
snowflake.AllowUnquoted = false
_, err = snowflake.ParseJSON([]byte("42"))
fmt.Println("JSON parse error:", err)
// The error is not nil, because unquoted integers are not allowed
// Allow unquoted integers
snowflake.AllowUnquoted = true
_, err = snowflake.ParseJSON([]byte("42"))
fmt.Println("JSON parse error:", err)
// The error is nil because unquoted integers are now allowed
}
This software is licensed under the MIT License. For more information, see LICENSE.