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
A combination between python-flask, that fetch and send data from league client during champion select thanks to LCU

A combination between python-flask, that fetch data and send from league client during champion select thanks to LCU and compare picked champs to the gamesDataBase that we need to collect using my ot

Anas Hamrouni 1 Jan 19, 2022
Alcarin Tengwar - a Tengwar typeface designed to pair well with the Brill typeface

Alcarin Tengwar Alcarin Tengwar is a Tengwar typeface designed to pair well with

Toshi Omagari 23 Nov 02, 2022
NitroSniper - A discord nitro sniper, it uses 2 account tokens here's the explanation

Discord-Nitro-Sniper This is a discord nitro sniper, it uses 2 account tokens he

vanis / 1800 0 Jan 20, 2022
Cytotron - A unique discord bot like never before. Add it to your server to keep it active, motiviated, and amazing!!

Cytotron - Take your server to the next level Most of the details are in the website. Go to https://cytotron-bot.gq for more information. If that link

LeviathanProgramming 6 Jun 13, 2021
Unofficial Coinbase Python Library

Unofficial Coinbase Python Library Python Library for the Coinbase API for use with three legged oAuth2 and classic API key usage Version 0.3.0 Requir

George Sibble 104 Dec 01, 2022
Fetch information about a public Google document.

xeuledoc Fetch information about any public Google document. It's working on : Google Docs Google Spreadsheets Google Slides Google Drawning Google My

Malfrats Industries 655 Jan 03, 2023
Telegram Bot For Screenshot Generation.

Screenshotit_bot Telegram Bot For Screenshot Generation. Description An attempt to implement the screenshot generation of telegram files without downl

1 Nov 06, 2021
Chorok - High quality Discord music bot

Chorok - High quality Discord music bot Rewrite with dico Config guide

Chorok Opensource project 10 May 03, 2022
Drcom-pt-client - Drcom Pt version client with refresh timer

drcom-pt-client Drcom Pt version client with refresh timer Dr.com Pt版本客户端 可用于网页认

4 Nov 16, 2022
Analytics platform for Telegram Channels

Tele-Report Analytics platform for Telegram Channels 🚧 👷 Getting Started 1- Install redis and postgreSQL (it would be more generic in future, like u

2 Oct 11, 2022
A pypi package that helps in generating discord bots.

A pypi package that helps in generating discord bots.

KlevrHQ 3 Nov 17, 2021
Discord Custom Playing Status Redirecting

Discord-Custom-Playing-Status-Redirecting THINGS TO DO :- - Create an application from https://discord.com/developers/applications give it ur desired

WarLorD oP 1 Oct 30, 2021
And now, for the first time, you can send alerts via action from ArcSight ESM Console to the TheHive when Correlation Rules are triggered.

ArcSight Integration with TheHive And now, for the first time, you can send alerts via action from ArcSight ESM Console to the TheHive when Correlatio

Amir Hossein Zargaran 3 Jan 19, 2022
Python package for agilex robotics mobile base platform

This is Python API for Agilex Robotics Mobile base This is a python API for Can communication with Agilex Robotics Mobile base and controlling it. Sup

7 Sep 06, 2022
An API Wrapper for Gofile API

Gofile2 from gofile2 import Gofile g_a = Gofile() print(g_a.upload(file="/home/itz-fork/photo.png")) An API Wrapper for Gofile API. About API Gofile

I'm Not A Bot #Left_TG 16 Dec 10, 2022
A Open source Discord Token Grabber with several very useful features coded in python 3.9

Kiwee-Grabber A Open source Discord Token Grabber with several very useful features coded in python 3.9 This only works on any python 3.9 versions. re

Vesper 40 Jan 01, 2023
Python-random-quote - A file-based quote bot written in Python

Let's Write a Python Quote Bot! This repository will get you started with building a quote bot in Python. It's meant to be used along with the Learnin

amir mohammad fateh 1 Jan 02, 2022
Send notification to your telegram group/channel/private whenever a new video is uploaded on a youtube channel!

YouTube Feeds Bot. Send notification to your telegram group/channel/private whenever a new video is uploaded on a youtube channel! Variables BOT_TOKEN

Aditya 30 Dec 07, 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
PYthon Warframe Market API(pywmapi)

pywmapi PYthon Warframe Market API(pywmapi) API for warframe market, written in Python. For now, the implemented function is listed below: auth sign i

AyajiLin 7 Dec 11, 2022