Go library for accessing the Reddit API.


go-reddit logo

Actions Status Go Report Card PkgGoDev

Overview

Featured in issues 327 and 347 of Golang Weekly 🎉

go-reddit is a Go client library for accessing the Reddit API.

You can view Reddit's official API documentation here.

Install

To get a specific version from the list of versions:

go get github.com/vartanbeno/go-reddit/[email protected]

Or for the latest version:

go get github.com/vartanbeno/go-reddit/v2

The repository structure for managing multiple major versions follows the one outlined here.

Usage

Make sure to have a Reddit app with a valid client id and secret. Here is a quick guide on how to create an app and get credentials.

package main

import "github.com/vartanbeno/go-reddit/v2/reddit"

func main() {
    credentials := reddit.Credentials{ID: "id", Secret: "secret", Username: "username", Password: "password"}
    client, _ := reddit.NewClient(credentials)
}

You can pass in a number of options to NewClient to further configure the client (see reddit/reddit-options.go). For example, to use a custom HTTP client:

httpClient := &http.Client{Timeout: time.Second * 30}
client, _ := reddit.NewClient(credentials, reddit.WithHTTPClient(httpClient))

Read-Only Mode

The DefaultClient method returns a valid, read-only client with limited access to the Reddit API, much like a logged out user. You can initialize your own and configure it further using options via NewReadonlyClient:

client, _ := reddit.NewReadonlyClient()

Examples

Configure the client from environment variables. When using this option, it's ok to pass an empty struct for the credentials.
client, _ := reddit.NewClient(reddit.Credentials{}, reddit.FromEnv)
Submit a comment.
comment, _, err := client.Comment.Submit(context.Background(), "t3_postid", "comment body")
if err != nil {
    return err
}
fmt.Printf("Comment permalink: %s\n", comment.Permalink)
Upvote a post.
_, err := client.Post.Upvote(context.Background(), "t3_postid")
if err != nil {
    return err
}
Get r/golang's top 5 posts of all time.
posts, _, err := client.Subreddit.TopPosts(context.Background(), "golang", &reddit.ListPostOptions{
    ListOptions: reddit.ListOptions{
        Limit: 5,
    },
    Time: "all",
})
if err != nil {
    return err
}
fmt.Printf("Received %d posts.\n", len(posts))

More examples are available in the examples folder.

Design

The package design is heavily inspired from Google's GitHub API client and DigitalOcean's API client.

Contributing

Contributions are welcome! For any bug reports/feature requests, feel free to open an issue or submit a pull request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Owner
Comments
  • undefined: `reddit.DefaultClient` and `reddit.NewDefaultClient`

    undefined: `reddit.DefaultClient` and `reddit.NewDefaultClient`

    For some reason I can't access these? Weird, cause reddit.NewClient works

    Steps to Reproduce

    Set up Project

    $ mkdir repro-go-reddit-bug
    $ cd repro-go-reddit-bug
    $ go mod init github.com/bbkane/repro-go-reddit-bug
    $ go get github.com/vartanbeno/go-reddit
    

    Contents of go.mod:

    $ cat go.mod
    module github.com/bbkane/repro-go-reddit-bug
    
    go 1.15
    
    require github.com/vartanbeno/go-reddit v1.0.0
    

    Add the following main.go:

    $ cat main.go
    package main
    
    import "github.com/vartanbeno/go-reddit/reddit"
    
    func main() {
    	_, _ = reddit.NewReadonlyClient()
    }
    

    Run Project, See Error

    $ go run main.go
    # command-line-arguments
    ./main.go:6:9: undefined: reddit.NewReadonlyClient
    

    Go Version

    $ go version
    go version go1.15.1 darwin/amd64
    
  • 401 Unauthorized

    401 Unauthorized

    I can't seem to get a basic auth going using Client ID, Client Secret, Username and Password. Any ideas why? I verified and I'm 100% sure I'm setting the right values.

  • Push release

    Push release

    It seems that go-reddit has progressed a lot since version 1.0.0, which is the version automatically downloaded when using go modules. Could you push another release? It has been over a 100 commits since 1.0.0 was release.

  • badger badger Blocked because of go-reddit and golang changes

    badger badger Blocked because of go-reddit and golang changes

    Howdy All y'all,

    I'm looking for a little help in how to avoid the "badger badger" or "Blocked" issue that comes when using a golang version > 16 with go-reddit. Here is some background information:

    • https://www.slurdge.org/post/2022-05-13-the-strange-case-of-golang-reddit-rss/
    • https://www.reddit.com/r/redditdev/comments/uncu00/go_golang_clients_getting_403_blocked_responses/

    I'm hoping that someone will lend me a hand crafting my normal call to this API:

    sr, _, err := reddit.DefaultClient().Subreddit.Get(ctx, subreddit)
    

    and turn off TLS.

    Any help you can provide is very much appreciated!

  • Add Subreddit Comment Support

    Add Subreddit Comment Support

    Changelog:

    • Added functions to subreddit.go to support fetching comments via Listing
    • Fetched some test-data from /r/golang/comments.json for basic unit test
      • Initially 100 comments, but reduced to 5
    • Added consumer method to stream.go to produce a stream of comments from a subreddit using this method
    • Copied post stream unit test logic to comment stream
  • Update README.md with link to go-reddit importers

    Update README.md with link to go-reddit importers

    In regards to https://github.com/vartanbeno/go-reddit/issues/7 : not a section but a sentence with a link :) . Full disclosure, this isn't entirely selfless - I'd like grabbit in front of more eyes, but I think it's a good idea for go-reddit too.

  • REQUEST: Add a

    REQUEST: Add a "projects using go-reddit" section

    I know of no easy way to find projects using other projects; it'd be neat to have a list -- even if not comprehensive -- of utilities using this library. Maybe you could open a wiki page and accept PRs against a project list?

  • Unable to download: package github.com/vartanbeno/go-reddit: no Go files in /home/<username>/go/src/github.com/vartanbeno/go-reddit

    Unable to download: package github.com/vartanbeno/go-reddit: no Go files in /home//go/src/github.com/vartanbeno/go-reddit

    Whenever I try to download go-reddit using the command go get github.com/vartanbeno/go-reddit, I get the following error: package github.com/vartanbeno/go-reddit: no Go files in /home/<username>/go/src/github.com/vartanbeno/go-reddit.

    I've tried about every fix that I can think of, including reinstalling go a couple times. I am running Ubuntu 20.04, GNU/Linux 5.4.0-58-generic. I am able to install other packages from Github.

  • Retriving user description / user subreddit

    Retriving user description / user subreddit

    I need to retrieve a user description, but I did not find anything in the docs about it. It would be nice feature.

    This is how its done in praw https://www.reddit.com/r/redditdev/comments/j3atzn/is_there_a_way_to_retrieve_description_of_a_user/

  • Add Subreddit Comment Support

    Add Subreddit Comment Support

    Changelog:

    • Added functions to subreddit.go to support fetching comments via Listing
    • Fetched some test-data from /r/golang/comments.json for basic unit test
      • Initially 100 comments, but reduced to 5
    • Added consumer method to stream.go to produce a stream of comments from a subreddit using this method
    • Copied post stream unit test logic to comment stream
  • 403 Forbidden

    403 Forbidden

    When I tried, the bellow code i got 403 error, Can any one tell me why this is happening and how can I fix this issue?

            package main
    
            import (
    	        "context"
    	        "fmt"
            
    	        "github.com/vartanbeno/go-reddit/v2/reddit"
            )
            
            func main() {
    	        ctx := context.Background()
    	        client, err := reddit.NewReadonlyClient()
            
    	        if err != nil {
    		        fmt.Println("Error from reddit.NewReadonlyClient()", err)
    	        }
    	        listOpts := &reddit.ListOptions{
    		        Limit: 10, // always 100, so we can filter out without extra logic; if this is ever > 100, use resp.After
    	        }
    	        data, res, err := client.Subreddit.HotPosts(ctx, "AnimalsBeingBros", listOpts)
            
    	        fmt.Println(data)
    	        fmt.Println(res)
    	        fmt.Println(err)
            
            }
    
  • searchpost params error

    searchpost params error

    if i want go subreddit: https://www.reddit.com/r/btc/search btc, all data.

    client.Subreddit.SearchPosts(ctx, "", "btc", &reddit.ListPostSearchOptions{
    			ListPostOptions: reddit.ListPostOptions{
    				ListOptions: reddit.ListOptions{
    					Limit: limit,
    					After: after,
    				},
    			},
    		})
    

    i got empty []. but in https://www.reddit.com/r/btc/search has datas.

  • OAuth: server response missing access token

    OAuth: server response missing access token

    Unluckily, #18 did not help me. 2FA is disabled, I triple checked my username/password/ID/secret but I still get the error

    Get "https://oauth.reddit.com/r/itookapicture/top?limit=1&t=today": oauth2: server response missing access_token
    
    click me to see the request that is sent
    {
       "Method":"GET",
       "URL":"*net/url.URL"{
          "Scheme":"https",
          "Opaque":"",
          "User":"*net/url.Userinfo nil",
          "Host":"oauth.reddit.com",
          "Path":"/r/itookapicture/top",
          "RawPath":"",
          "ForceQuery":false,
          "RawQuery":"limit=1&t=today",
          "Fragment":"",
          "RawFragment":""
       },
       "Proto":"HTTP/1.1",
       "ProtoMajor":1,
       "ProtoMinor":1,
       "Header":"net/http.Header"[
          "Content-Type":[
             "application/x-www-form-urlencoded"
          ],
          "Accept":[
             "application/json"
          ]
       ],
       "Body":"io.ReadCloser nil",
       "GetBody":"nil",
       "ContentLength":0,
       "TransferEncoding":[]"string len":0,
       "cap":0,
       "nil",
       "Close":false,
       "Host":"oauth.reddit.com",
       "Form":"net/url.Values nil",
       "PostForm":"net/url.Values nil",
       "MultipartForm":"*mime/multipart.Form nil",
       "Trailer":"net/http.Header nil",
       "RemoteAddr":"",
       "RequestURI":"",
       "TLS":"*crypto/tls.ConnectionState nil",
       "Cancel":"<-chan struct"{
          
       }"nil",
       "Response":"*net/http.Response nil",
       "ctx":context.Context(*context.emptyCtx) *0
    }
    

    I noticed that the User field is nil. Is that the intended behavior? I'm initializing the client like this:

    id := "xxxxxxxxxxxx"
    secret := "xxxxxxxxxxxx"
    user := "xxxxxxxxxxxx"
    password := "xxxxxxxxxxxx"
    credentials := reddit.Credentials{ID: id, Secret: secret, Username: user, Password: password}
    client, err := reddit.NewClient(credentials)
    if err != nil {
    	panic(err)
    }
    posts, _, err := client.Subreddit.TopPosts(context.Background(), "itookapicture", &reddit.ListPostOptions{
    	ListOptions: reddit.ListOptions{
    		Limit: 1,
    	},
    	Time: "today",
    })
    if err != nil {
    	panic(err)
    }
    

    I tried to track down where this error comes from and the call stack seems to be:

    reddit#Do:348
    reddit#DoRequestWithClient:437
    client#Do:593
    client#do:???
    

    but I have no clue where inside client#do the error happens (set breakpoints at every return but they don't trigger). Thus, I am not quite sure if this is caused by misuse on my end, an error in go-reddit or (rather unlikely) in client.go.

  • checksum 2.0.0 release changed

    checksum 2.0.0 release changed

    What happened to the 2.0.0 release?

    The checksum has changed. Has this release been compromised?

    https://github.com/marcofranssen/gothermostat/pull/121/checks?check_run_id=3717744193#step:5:6

An easy to use go program to download videos from Reddit.
An easy to use go program to download videos from Reddit.

Gettit Download videos from reddit from the command line. Use guide gettit -u post_url Example : gettit -u https://www.reddit.com/r/programminghorror/

Dec 30, 2022
Bulk image downloader for reddit.

rrip Program to bulk-download image from reddit subreddits. Features Set max size of file, max total size, minimum score etc.. Filter by post title or

Dec 25, 2022
Simple to do list API with Gin and Gorm (with Postgres)Simple to do list API with Gin and Gorm (with Postgres)

go-todo Simple to do list API with Gin and Gorm (with Postgres) Docker Clone this repository and run: docker-compose up You can then hit the followin

Aug 29, 2022
Go-api-cli - Small CLI to fetch data from an API sync and async

Async API Cli CLI to fetch data on "todos" from a given API in a number of ways.

Jan 13, 2022
Syno-cli - Synology unofficial API CLI and library

Synology CLI Unofficial wrapper over Synology API in Go. Focus on administrative

Jan 6, 2023
A tiny Go library + client for downloading Youtube videos. The library is capable of fetching Youtube video metadata, in addition to downloading videos.

A tiny Go library + client (command line Youtube video downloader) for downloading Youtube videos. The library is capable of fetching Youtube video metadata, in addition to downloading videos. If ffmpeg is available, client can extract MP3 audio from downloaded video files.

Oct 14, 2022
Simple and complete API for building command line applications in Go

Simple and complete API for building command line applications in Go Module cli provides a simple, fast and complete API for building command line app

Nov 23, 2022
Make any Go function into a API (FaaS)

faas Make any (Go) function into an API with one HTTP request. This is a FaaS: functions as a service. But, in actuality, its more of a FaaSSS: functi

Dec 30, 2022
cross platform command line tool to list, notify and book vaccine using cowin API

Command line tool to List and Book Vaccine cowin-cli is a simple cli tool to book vaccines and list centers using the COWIN API. It also supports auto

Mar 7, 2022
API con información de servicios del sistema de transporte público metropolitano de Santiago (Red y Metro)

APIs de Transporte Público en Santiago Saldo Bip! Permite obtener el saldo de una tarjeta Bip!, consultándolo en el sitio de RedBip!. Ejemplo: https:/

Nov 28, 2022
A client for managing authzed or any API-compatible system from your command line.

zed A client for managing authzed or any API-compatible system from your command line. Installation zed is currently packaged by as a head-only Homebr

Dec 31, 2022
Sample API made in Go

GoAPI-sample Sample API made in Go. Especially for those who want to develop API in Go and are beginners. Variables Endpoint Vars - /token - To genera

Sep 28, 2022
Go pkg and cli tool to sign Google Maps API URLs

gmapsign gmapsign is a Go pkg and cli tool to sign Google Maps API request URLs. This is required when using: A client ID with the web service APIs, M

Jul 4, 2022
A crunchyroll api integration in go with included cli

crunchyroll-go A Go library & cli for the undocumented crunchyroll api. You surely need a crunchyroll premium account to get full (api) access. CLI ??

Dec 18, 2022
Teardown API for Commandline Based Applications
Teardown API for Commandline Based Applications

Building go build -ldflags "-s -w" -o ./build/api.exe ./ Get the latest XML from https://www.teardowngame.com/modding/api.xml Commands help list searc

Mar 1, 2022
Simple CLI using spf13/cobra and Flink REST API

Flinkctl Flinkctl is a simple CLI written on Go using Cobra created to facilitate my team's daily basis work with multiple Flink clusters at Azion Tec

Aug 16, 2022
A simple CLI tool to use the _simulate API of elasticsearch to quickly test pipelines

elasticsearch-pipeline-tester A simple CLI tool to use the _simulate API of elasticsearch to quickly test pipelines usage: pipelinetester [<flags>] <p

Oct 19, 2021
A go cli makes it easy to get quotes from the Ted Lasso Quotes API

Ted Lasso Quotes CLI This cli makes it easy to get quotes from the Ted Lasso Quotes API Just clone the repo and build the binary for your distribution

Jun 15, 2022
Simple CLI util for running OCR on images through PERO OCR API

pero_ocr Simple CLI util for running OCR on images through PERO OCR API Usage: Usage of batch_pero_ocr: -c string cancel request with given

Dec 1, 2021