Skip to content

Commit

Permalink
πŸŽ‰ Initialize
Browse files Browse the repository at this point in the history
  • Loading branch information
barbarbar338 committed Jul 22, 2021
0 parents commit 1833495
Show file tree
Hide file tree
Showing 7 changed files with 972 additions and 0 deletions.
674 changes: 674 additions & 0 deletions LICENSE

Large diffs are not rendered by default.

102 changes: 102 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
[![stars](https://img.shields.io/github/stars/barbarbar338/go-lanyard?color=yellow&logo=github&style=for-the-badge)](https://github.com/barbarbar338/go-lanyard)
[![license](https://img.shields.io/github/license/barbarbar338/go-lanyard?logo=github&style=for-the-badge)](https://github.com/barbarbar338/go-lanyard)
[![supportServer](https://img.shields.io/discord/711995199945179187?color=7289DA&label=Support&logo=discord&style=for-the-badge)](https://discord.gg/BjEJFwh)
[![forks](https://img.shields.io/github/forks/barbarbar338/go-lanyard?color=green&logo=github&style=for-the-badge)](https://github.com/barbarbar338/go-lanyard)
[![issues](https://img.shields.io/github/issues/barbarbar338/go-lanyard?color=red&logo=github&style=for-the-badge)](https://github.com/barbarbar338/go-lanyard)

# πŸš€ Go Lanyard

Use Lanyard API easily in your Go app!

# πŸ“¦ Installation

- Initialize your project (`go mod init example.com/example`)
- Add package (`go get github.com/barbarbar338/go-lanyard`)

# πŸ€“ Usage

Using without websocket:

```golang
package main

import (
"fmt"
)

func main() {
// User ID here πŸ‘‡
res := FetchUser("331846231514939392")

// handle presence data here
fmt.Println(res.Data.DiscordStatus)
}
```

Using with websocket:

```golang
package main

import (
"fmt"
"os"
"os/signal"
"syscall"

"github.com/barbarbar338/go-lanyard"
)

func main() {
// User ID here πŸ‘‡
ws := lanyard.CreateWS("331846231514939392", func(data *LanyardData) {

// handle presence data here
fmt.Println(data.DiscordStatus)
})

sc := make(chan os.Signal, 1)
signal.Notify(
sc,
syscall.SIGINT,
syscall.SIGTERM,
os.Interrupt,
)
<-sc

fmt.Println("Closing client.")

// destroy ws before exit
ws.Destroy()
}
```

# πŸ“„ License

Copyright © 2021 [Barış DEMİRCİ](https://github.com/barbarbar338).

Distributed under the [GPL-3.0](https://www.gnu.org/licenses/gpl-3.0.html) License. See `LICENSE` for more information.

# 🧦 Contributing

Feel free to use GitHub's features.

1. Fork the Project
2. Create your Feature Branch (`git checkout -b feature/my-feature`)
3. Commit your Changes (`git commit -m 'my awesome feature my-feature'`)
4. Push to the Branch (`git push origin feature/my-feature`)
5. Open a Pull Request

# πŸ”₯ Show your support

Give a ⭐️ if this project helped you!

# πŸ“ž Contact

- Mail: [email protected]
- Discord: https://discord.gg/BjEJFwh
- Instagram: https://www.instagram.com/ben_baris.d/

# ✨ Special Thanks

- [Phineas](https://github.com/Phineas) - Creator of [Lanyard API](https://github.com/Phineas/lanyard)
5 changes: 5 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module github.com/barbarbar338/go-lanyard

go 1.16

require github.com/sacOO7/gowebsocket v0.0.0-20210515122958-9396f1a71e23
6 changes: 6 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/sacOO7/go-logger v0.0.0-20180719173527-9ac9add5a50d h1:5T+fbRuQbpi+WZtB2yfuu59r00F6T2HV/zGYrwX8nvE=
github.com/sacOO7/go-logger v0.0.0-20180719173527-9ac9add5a50d/go.mod h1:L5EJe2k8GwpBoGXDRLAEs58R239jpZuE7NNEtW+T7oo=
github.com/sacOO7/gowebsocket v0.0.0-20210515122958-9396f1a71e23 h1:yjnkNJTpQPCx10KF1jypuIhAVc6EYn2M9lJgwSTHQYs=
github.com/sacOO7/gowebsocket v0.0.0-20210515122958-9396f1a71e23/go.mod h1:h00QywbM5Le22ESUiI8Yz2/9TVGD8eAz/cAk55Kcz/E=
34 changes: 34 additions & 0 deletions rest.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package lanyard

import (
"encoding/json"
"io"
"net/http"
)


const (
API_URL = "https://api.lanyard.rest/v1/users/"
)

func FetchUser(userId string) LanyardResponse {
resp, err := http.Get(API_URL + userId)

if err != nil {
panic(err)
}

body, err := io.ReadAll(resp.Body)
if err != nil {
panic(err)
}

var data LanyardResponse

err = json.Unmarshal(body, &data)
if err != nil {
panic(err)
}

return data
}
80 changes: 80 additions & 0 deletions types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package lanyard

// I'm not entirely sure if these are correct. You can review and open a PR before using it.
// Go port of https://github.com/barbarbar338/react-use-lanyard/blob/main/src/types.ts
type LanyardResponse struct {
Success bool `json:"success"`
Data *LanyardData `json:"data"`
Error *LanyardError `json:"error"`
}

type LanyardWSResponse struct {
Op int `json:"op"`
Seq int `json:"seq"`
T string `json:"t"`
D *LanyardData `json:"d"`
}


type LanyardData struct {
Spotify Spotify `json:"spotify"`
ListeningToSpotify bool `json:"listening_to_spotify"`
DiscordUser DiscordUser `json:"discord_user"`
DiscordStatus string `json:"discord_status"`
Activities []Activity `json:"activities"`
ActiveOnDiscordMobile bool `json:"active_on_discord_mobile"`
ActiveOnDiscordDesktop bool `json:"active_on_discord_desktop"`
}

type LanyardError struct {
Message string `json:"message"`
Code string `json:"code"`
}

type Spotify struct {
TrackId string `json:"track_id"`
Timestamps Timestamps `json:"timestamps"`
Song string `json:"song"`
Artist string `json:"artist"`
Album string `json:"album"`
AlbumArtUrl string `json:"album_art_url"`
}

type Timestamps struct {
Start int `json:"start"`
End int `json:"end"`
}

type Activity struct {
Type int `json:"type"`
State string `json:"state"`
Name string `json:"name"`
Id string `json:"id"`
Emoji *Emoji `json:"emoji"`
CreatedAt int `json:"created_at"`
ApplicationId string `json:"application_id"`
Timestamps *Timestamps `json:"timestamps"`
SessionId string `json:"session_id"`
Details *string `json:"details"`
Buttons *[]string `json:"buttons"`
Assets *Assets `json:"assets"`
}

type Assets struct {
SmallText string `json:"small_text"`
SmallImage string `json:"small_image"`
LargeText string `json:"large_text"`
LargeImage string `json:"large_image"`
}

type Emoji struct {
Name string `json:"name"`
}

type DiscordUser struct {
Id string `json:"id"`
Username string `json:"username"`
Avatar string `json:"avatar"`
Discriminator string `json:"discriminator"`
PublicFlags int `json:"public_flags"`
}
71 changes: 71 additions & 0 deletions websocket.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package lanyard

import (
"encoding/json"
"log"
"strings"
"time"

"github.com/sacOO7/gowebsocket"
)

const (
WS_URL = "wss://api.lanyard.rest/socket"
PING_PERIOD = 30 * time.Second
)

type WSClient struct {
socket gowebsocket.Socket
ticker *time.Ticker
}

func (client WSClient) Destroy() {
if client.ticker != nil {
client.ticker.Stop()
}
client.socket.Close()
}

func (client WSClient) ping() {
client.ticker = time.NewTicker(PING_PERIOD)
defer client.ticker.Stop()

for ; ; <-client.ticker.C {
client.socket.SendText("{\"op\":3}")
}
}

func CreateWS(userId string, presenceUpdate func(data *LanyardData)) WSClient {
client := WSClient {
socket: gowebsocket.New(WS_URL),
}

client.socket.OnConnected = func(socket gowebsocket.Socket) {
client.socket.SendText("{\"op\":2,\"d\":{\"subscribe_to_id\":\"" + userId + "\"}}")
go client.ping()
};

client.socket.OnConnectError = func(err error, socket gowebsocket.Socket) {
log.Println("An error occured while connecting to Lanyard websocket server", err)
client.Destroy()
};

client.socket.OnTextMessage = func(message string, socket gowebsocket.Socket) {
if strings.Contains(message, "heartbeat_interval") {
return
}

var data LanyardWSResponse
err := json.Unmarshal([]byte(message), &data)
if err != nil {
client.Destroy()
return
}

presenceUpdate(data.D)
};

client.socket.Connect()

return client
}

0 comments on commit 1833495

Please sign in to comment.