A Python library for the Discourse API

Overview

pydiscourse

Build Status Check out the Docs

A Python library for working with Discourse.

This is a fork of the original Tindie version. It was forked to include fixes, additional functionality, and to distribute a package on PyPI.

Goals

  • Exceptional documentation
  • Support all supported Python versions
  • Provide functional parity with the Discourse API, for the currently supported version of Discourse (something of a moving target)

The order here is important. The Discourse API is itself poorly documented so the level of documentation in the Python client is critical.

Installation

pip install pydiscourse

Examples

Create a client connection to a Discourse server:

from pydiscourse import DiscourseClient
client = DiscourseClient(
        'http://example.com',
        api_username='username',
        api_key='areallylongstringfromdiscourse')

Get info about a user:

user = client.user('eviltrout')
print user

user_topics = client.topics_by('johnsmith')
print user_topics

Create a new user:

user = client.create_user('The Black Knight', 'blacknight', '[email protected]', 'justafleshwound')

Implement SSO for Discourse with your Python server:

@login_required
def discourse_sso_view(request):
    payload = request.GET.get('sso')
    signature = request.GET.get('sig')
    nonce = sso_validate(payload, signature, SECRET)
    url = sso_redirect_url(nonce, SECRET, request.user.email, request.user.id, request.user.username)
    return redirect('http://discuss.example.com' + url)

Command line

To help experiment with the Discourse API, pydiscourse provides a simple command line client:

export DISCOURSE_API_KEY=your_master_key
pydiscoursecli --host-http://yourhost --api-user-system latest_topics
pydiscoursecli --host-http://yourhost --api-user-system topics_by johnsmith
pydiscoursecli --host-http://yourhost --api-user-system user eviltrout
Comments
  • pydiscourse.exceptions.DiscourseClientError: Payload Too Large

    pydiscourse.exceptions.DiscourseClientError: Payload Too Large

    Hi! I've been trying to get various methods from the library to work to no avail:

    from pydiscourse import DiscourseClient
    client = DiscourseClient(host='https://forums.mywebsite.com', api_username='username_of_admin', api_key='key')
    print(client.users())
    

    I get the same exception each time:

    Traceback (most recent call last):
      File "test_discourse.py", line 3, in <module>
        print(client.users())
      File "C:\Python37\lib\site-packages\pydiscourse\client.py", line 449, in users
        return self._get("/admin/users/list/{0}.json".format(filter), **kwargs)
      File "C:\Python37\lib\site-packages\pydiscourse\client.py", line 1298, in _get
        return self._request(GET, path, params=kwargs, override_request_kwargs=override_request_kwargs)
      File "C:\Python37\lib\site-packages\pydiscourse\client.py", line 1424, in _request
        raise DiscourseClientError(msg, response=response)
    pydiscourse.exceptions.DiscourseClientError: Payload Too Large
    

    Running pip freeze | grep discourse gives me pydiscourse==1.1.0. If I access the /admin/users/list/{0}.json endpoint directly in my browser I get the expected result, however, what seems to happen through the library is that an error HTML page is returned instead. Any pointers?

    opened by dkgv 8
  • pass params in data

    pass params in data

    Send request params in the request body instead of the query string. This avoid a pydiscourse.exceptions.DiscourseClientError: Request-URI Too Large error when updating large amounts of data.

    I tested this on update_post which is where I was running into this error but didn't test any additional methods.

    opened by jdorweiler 8
  • questions about accessing categories and topics via the api

    questions about accessing categories and topics via the api

    HI There @bennylope !! this tool is really fantastic. I"m playing around with it and trying to understand the discourse api. This:

    https://github.com/bennylope/pydiscourse/blob/master/pydiscourse/client.py#L481

    seems to be the way to grab a list of categories and topics.

    Questions For You

    1. How do i get a list of categories AND subcategories? i can get a list of categories using

    client.categories()

    But this doesn't return the subcategories from what i can tell.

    1. Id like to get a list of topics within each category. When i run client.category_topics(10) (10 is the ID for the category that i'm interested in) I get:

    DiscourseError: Invalid Response, expecting "application/json; charset=utf-8" got "text/html; charset=utf-8"

    i've played with providing it the slug and the category name and it doesn't seem to work

    just curious if you can help me sort this out. i'm happy to update docstrings and docs if i can figure this out if that is of interest / welcome!

    bug question 
    opened by lwasser 6
  • add watch_topic

    add watch_topic

    Summary of changes

    adds api call for: user gets notifications about a topic.

    Checklist

    • [x] Changes represent a discrete update
    • [x] Commit messages are meaningful and descriptive
    • [x] Changeset does not include any extraneous changes unrelated to the discrete change
    enhancement 
    opened by glanzel 5
  • Handle HTTP 429, rate limiting

    Handle HTTP 429, rate limiting

    Per the announcement on Discourse meta, global API rate limits have been introduced to the Discourse API. This change adds a new DiscourseRateLimitedError class and a retry mechanism on receipt of a 429.

    https://meta.discourse.org/t/global-rate-limits-in-discourse/78612

    Closes: #11

    I do have one question: Should the 'settings' (retry_{count,backof}) be defined somewhere easier to change?

    opened by goetzk 5
  • Discourse API throttling.

    Discourse API throttling.

    In the last month or so Discourse implemented API throttling.

    I don't have a lot of detail yet but I was told

    We recently added rate limiting to api calls which is why you are now running in to some issues. [...] You are allowed 60 requests per minute, so you shouldn’t have to slow things down too much.
    

    Are you open to building the throttling directly in to _request or would you prefer library users handled it individually? https://github.com/bennylope/pydiscourse/blob/master/pydiscourse/client.py#L1186

    At the moment an error along these lines is raised (this is what caused me to ask Discourse).

     pydiscourse.exceptions.DiscourseClientError: We have a daily limit on how many times that action can be taken. Please wait 5 seconds before trying again.
    

    thanks, kk

    opened by goetzk 5
  • Please merge features added by Alvaro Molina Alvarez

    Please merge features added by Alvaro Molina Alvarez

    Hi, I'm currently using your packages from pip (thanks!), but I've had to write a bunch of code to work around missing functionality - mainly related to json . Alvaro Molina Alvarez (@amolinaalvarez) has added a number of features including json support that I'm hoping you will be willing to merge. The diff is substantial but easy to follow and includes support for API calls currently not provided in your tree.

    https://github.com/bennylope/pydiscourse/compare/master...amolinaalvarez:master

    thanks, kk

    opened by goetzk 4
  • Bump pypi 1.1.3 ?

    Bump pypi 1.1.3 ?

    Hello!

    Thank you for this module.

    Is it possible to update the pypi version to include the latest change in master ? Notably, I would need the category_latest_topics.

    Thanks again!

    enhancement 
    opened by weber-s 3
  • Allow redirects for requests

    Allow redirects for requests

    Are you aware of any issues when supporting redirects from the Discourse server? In your call to requests.request() you explicitly set allow_redirects to False. This prevents topic lookup by path only (omitting the ID).

    I think a number of functions could make ID optional using the server redirect to resolve as needed.

    opened by gar1t 3
  • new release timeline?

    new release timeline?

    Hey there,

    v0.7.0 on PyPI is super-old, and there are a bunch of goodies in the master branch here I'd love to have access to. Any idea when there's a plan for an updated PyPI package?

    opened by benswift 3
  • SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:852)

    SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:852)

    I tried to follow the instructions provided to connect to my https website. It is failing with **SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:852) **

    Here is the sample code as per the instructions provided.

    from pydiscourse import DiscourseClient client = DiscourseClient( 'https://discuss.itversity.com', api_username='dgadiraju', api_key='api_key_with_single_user_and_global_permissions')

    question 
    opened by dgadiraju 2
  • Rate limit improvements

    Rate limit improvements

    Summary of changes

    Two changes here, happy to split if you would prefer.

    • First, with my Discourse instance (v2.8.13 on nginx, in case it makes a difference), I encountered rate-limited responses that did not have a Content-Type header. The first commit makes it so that the code takes these in stride.
    • The second commit includes information from the Discourse-Rate-Limit-Error-Code, which makes it easier to debug which limit is encountered. Also, logging happens before waiting, to provide feedback on what is happening.

    Checklist

    • [x] Changes represent a discrete update (-ish)
    • [x] Commit messages are meaningful and descriptive
    • [x] Changeset does not include any extraneous changes unrelated to the discrete change
    opened by inducer 0
  • Does not seem to fetch more than 20 posts per topic

    Does not seem to fetch more than 20 posts per topic

    Hi, So the client.posts(topic_id) function seems to fetch only the first 20 posts. Is there a way to get all the posts? My code (without the confidential data) is as below:

    client = DiscourseClient('http://example.com', api_username='username', api_key='areallylongstringfromdiscourse')

    print(len(client.posts(topic_id).get('post_stream').get('posts'))) - This prints out 20 and returns only 20 posts for all topics with > 20 posts. Where the number of posts is < 20, it prints out that correct number.

    help wanted question first time contributor opportunity 
    opened by gandharvbakshi 1
  • Users: Handle the case there are more than 100 results

    Users: Handle the case there are more than 100 results

    My apologies if it is already handled, but I didn't found how to do it in the code.

    When I want my discourse users, client.users() only gives me the first 100 users whereas I have more than 100.

    I've looked at the doc and it seems that the API doesn't tell that there are more users, but we can use the "page" param to get the next ones.

    I guess the solution would be to loop on the pages until the call gives an empty list as a result.

    I'll try to do a PR if I manage to find a solution.

    enhancement help wanted question 
    opened by werdeil 2
Releases(v1.3.0)
  • v1.3.0(Jul 29, 2022)

  • v1.2.0(Apr 18, 2022)

    What's Changed

    Adds support for Python 3.10, officially drops support for Python 2.7, 3.4, and 3.5.

    Also a bunch of new feature support from underappreciated contributors!

    • Update client.py by @kirstaylo in https://github.com/bennylope/pydiscourse/pull/40
    • Implement new routes by @gnuletik in https://github.com/bennylope/pydiscourse/pull/49
    • fix(errors): handle data-explorer responses by @gnuletik in https://github.com/bennylope/pydiscourse/pull/50
    • Add post_action_users to see who liked a post by @inducer in https://github.com/bennylope/pydiscourse/pull/53
    • Update supported Python versions by @bennylope in https://github.com/bennylope/pydiscourse/pull/54
    • Add option to fetch all categories including subcategories by @Sebastian2023 in https://github.com/bennylope/pydiscourse/pull/59
    • Fix getting category details by @Sebastian2023 in https://github.com/bennylope/pydiscourse/pull/58

    New Contributors

    • @kirstaylo made their first contribution in https://github.com/bennylope/pydiscourse/pull/40
    • @gnuletik made their first contribution in https://github.com/bennylope/pydiscourse/pull/49
    • @inducer made their first contribution in https://github.com/bennylope/pydiscourse/pull/53
    • @Sebastian2023 made their first contribution in https://github.com/bennylope/pydiscourse/pull/59

    Full Changelog: https://github.com/bennylope/pydiscourse/compare/v1.1.2...v1.2.0

    Source code(tar.gz)
    Source code(zip)
  • v1.1.2(Nov 10, 2020)

  • v1.1.1(Aug 18, 2020)

    This release contains fixes for a couple of bugs:

    • Fix call to get group info by name
    • Fix 413 response from Discourse due to empty dict passed as json
    Source code(tar.gz)
    Source code(zip)
  • v1.1.0(Aug 12, 2020)

    The first full release for some time includes the following enhancements over its predecessor 0.8:

    • Rate limiting and user activation
    • Replace parameterised auth with header auth
    • Add support for following redirects
    • Expanded methods for handling topics
    • Support for inviting users
    • Plus other changes to enhance features or maintain Discourse compatibility
    Source code(tar.gz)
    Source code(zip)
  • 0.7.0(Sep 9, 2016)

  • v0.3.0(Apr 8, 2016)

Owner
Ben Lopatin
I leverage synergies.
Ben Lopatin
Beyonic API Python official client library simplified examples using Flask, Django and Fast API.

Beyonic API Python official client library simplified examples using Flask, Django and Fast API.

Harun Mbaabu Mwenda 46 Sep 1, 2022
Python API wrapper library for Convex Value API

convex-value-python Python API wrapper library for Convex Value API. Further Links: Convex Value homepage @ConvexValue on Twitter JB on Twitter Authen

Aaron DeVera 2 May 11, 2022
This an API wrapper library for the OpenSea API written in Python 3.

OpenSea NFT API Python 3 wrapper This an API wrapper library for the OpenSea API written in Python 3. The library provides a simplified interface to f

Attila Tóth 159 Dec 26, 2022
Aio-binance-library - Async library for connecting to the Binance API on Python

aio-binance-library Async library for connecting to the Binance API on Python Th

GRinvest 10 Nov 21, 2022
PRAW, an acronym for "Python Reddit API Wrapper", is a python package that allows for simple access to Reddit's API.

PRAW: The Python Reddit API Wrapper PRAW, an acronym for "Python Reddit API Wrapper", is a Python package that allows for simple access to Reddit's AP

Python Reddit API Wrapper Development 3k Dec 29, 2022
PRAW, an acronym for "Python Reddit API Wrapper", is a python package that allows for simple access to Reddit's API.

PRAW: The Python Reddit API Wrapper PRAW, an acronym for "Python Reddit API Wrapper", is a Python package that allows for simple access to Reddit's AP

Python Reddit API Wrapper Development 3k Dec 29, 2022
WhatsApp Api Python - This documentation aims to exemplify the use of Moorse Whatsapp API in Python

WhatsApp API Python ChatBot Este repositório contém uma aplicação que se utiliza

Moorse.io 3 Jan 8, 2022
Official python API for Phish.AI public and private API to detect zero-day phishing websites

phish-ai-api Summary Official python API for Phish.AI public and private API to detect zero-day phishing websites How it Works (TLDR) Essentially we h

Phish.AI 168 May 17, 2022
Python API wrapper around Trello's API

A wrapper around the Trello API written in Python. Each Trello object is represented by a corresponding Python object. The attributes of these objects

Richard Kolkovich 904 Jan 2, 2023
A python to scratch API connector. Can fetch data from the API and send it back in cloud variables.

Scratch2py Scratch2py or S2py is a easy to use, versatile tool to communicate with the Scratch API Based of scratchclient by Raihan142857 Installation

null 20 Jun 18, 2022
Async ready API wrapper for Revolt API written in Python.

Mutiny Async ready API wrapper for Revolt API written in Python. Installation Python 3.9 or higher is required To install the library, you can just ru

null 16 Mar 29, 2022
🚀 An asynchronous python API wrapper meant to replace discord.py - Snappy discord api wrapper written with aiohttp & websockets

Pincer An asynchronous python API wrapper meant to replace discord.py ❗ The package is currently within the planning phase ?? Links |Join the discord

Pincer 125 Dec 26, 2022
wyscoutapi is an extremely basic API client for the Wyscout API (v2 & v3) for Python

wyscoutapi wyscoutapi is an extremely basic API client for the Wyscout API (v2 & v3). Usage Install with pip install wyscoutapi. To connect to the Wys

Ben Torvaney 11 Nov 22, 2022
A Python API wrapper for the Twitter API!

PyTweet PyTweet is an api wrapper made for twitter using twitter's api version 2! Installation Windows py3 -m pip install PyTweet Linux python -m pip

TheFarGG 1 Nov 19, 2022
A new coin listing alert bot using Python, Flask, MongoDB, Telegram API and Binance API

Bzzmans New Coin Listing Detection Bot Architecture About Project Work in progress. This bot basically gets new coin listings from Binance using Binan

Eyüp Barlas 21 May 31, 2022
YARSAW is an Async Python API Wrapper for the Random Stuff API.

Yet Another Random Stuff API Wrapper - YARSAW YARSAW is an Async Python API Wrapper for the Random Stuff API. This module makes it simpler for you to

Bruce 6 Mar 27, 2022
Python API Client for Twitter API v2

?? Python Client For Twitter API v2 ?? Why Twitter Stream ? Twitter-Stream.py a python API client for Twitter API v2 now supports FilteredStream, Samp

Twitivity 31 Nov 19, 2022
EpikCord.py - This is an API Wrapper for Discord's API for Python

EpikCord.py - This is an API Wrapper for Discord's API for Python! We've decided not to fork discord.py and start completely from scratch for a new, better structuring system!

EpikHost 28 Oct 10, 2022
A simple Python API wrapper for Cloudflare Stream's API.

python-cloudflare-stream A basic Python API wrapper for working with Cloudflare Stream. Arbington.com started off using Cloudflare Stream. We used the

Arbington 3 Sep 8, 2022