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
通过GitHub的actions 自动采集节点 生成订阅信息

VmessActions 通过GitHub的actions 自动采集节点 自动生成订阅信息 订阅内容自动更新再仓库的 clash.yml 和 v2ray.txt 中 然后PC端/手机端根据自己的软件支持的格式,订阅对应的链接即可

skywolf627 372 Jan 04, 2023
A wordwolf bot with python

ワードウルフBot requirements.txtから依存ライブラリをインストールしてください discordのトークン/Google spread sheetのキー/Sheetの名前を.envに書き込んでください DISCORD_TOKEN SHEET_KEY SHEET_NAME また、.sh

Kato 2 Dec 11, 2022
Plazmix API wrapper for Python

An optimised, easy to use Plazmix API wrapper written in Python

Someone 2 Nov 16, 2021
A Python Program to determine Degree of Profanity of Tweets

tweetx tweetx is a program to detect racial slurs in Twitter Tweets. Racial Abuse on Twitter is becoming quite a serious issue in recent times. tweetx

Kartik Poojari 3 Nov 11, 2021
This is RequestTrackerBot and it used for tracking request made by user in a group

This is a Request Tracker Bot repo, It is for those who upload content like movies, anime, etc. It can be used for tracking request of content that your members asked for.

Abhijeet 27 Dec 29, 2022
A Discord bot made by QwertyIsCoding

QwertyBot QwertyBot A Discord bot made by QwertyIsCoding Explore the docs » View Demo . Report Bug . Request Feature About The Project This Discord bo

4 Oct 08, 2022
Remedy when Amazon ECR is not running basic scans for container CVEs.

Welcome to your CDK Python project! This is a blank project for Python development with CDK. The cdk.json file tells the CDK Toolkit how to execute yo

4n6ir 4 Nov 05, 2022
Python SDK for the Buycoins API.

This library provides easy access to the Buycoins API using the Python programming language. It provides all the feature of the API so that you don't need to interact with the API directly. This libr

Musa Rasheed 48 May 04, 2022
List of twitch bots n bigots

This is a collection of bot account names NamelistMASTER contains all the names we reccomend you ban in your channel Sometimes people get on that list

62 Sep 05, 2021
A telegram bot that messages you available vaccine appointments in the Veneto region

Serenissimo, domande frequenti Chi sei? Sono Alberto Granzotto, libero professionista a Berlino. Mi occupo di servizi software, privacy, decentralizza

vrde 31 Sep 30, 2022
Repository containing the project files for CEN4020's Team Utah.

inCollege-Team-Utah Repository containing the project files for CEN4020's Team Utah. Contributors: Deepak Putta Jose Ramirez Fuentes Jaason Raudales C

Keylin Sanchez 3 Jul 12, 2022
A python script fetches all your starred repositories from your GitHub account and clones them to your server so you will never lose important resources

A python script fetches all your starred repositories from your GitHub account and clones them to your server so you will never lose important resources

Ringo Hoffmann 27 Oct 01, 2022
This Is Advanced Version Of Old Radio Player, An Telegram Bot to Play Radio/Music in Channel or Group Voice Chats.

Telegram Radio Player V2 An Telegram Bot to Play Radio/Music in Channel or Group Voice Chats. This is also the source code of the bot which is being u

SAF ONE 81 Dec 03, 2022
📷 An Instagram bot written in Python using Selenium on Google Chrome

📷 An Instagram bot written in Python using Selenium on Google Chrome. It will go through posts in hashtag(s) and like and comment on them.

anniedotexe 47 Dec 19, 2022
Use Seaborn to visualize interpret the byte layout of Solana account types

solana-account-vis Use Seaborn to visually interpret the byte layout of Solana account types Usage from account_visualization import generate_account_

Jarry Xiao 15 Aug 25, 2022
Python script to harvest tweets with the Twitter API V2 Academic Research Product Track

Tweet harvester Python script to scrape, collect, and/or harvest tweets with the Twitter API V2 Academic Research Product Track. Important note: In or

Thomas Frissen 2 Nov 11, 2021
Soundcloud Music Downloader

Soundcloud Music Downloader Description This script is able to download music from SoundCloud and set id3tag to the downloaded music. Compatible with

Ronan 2.6k Jan 01, 2023
A Python Library to interface with Flickr REST API, OAuth & JSON Responses

Python-Flickr Python-Flickr is A Python library to interface with Flickr REST API & OAuth Features Photo Uploading Retrieve user information Common Fl

Mike Helmick 40 Sep 25, 2021
Torrent-Igruha SDK Python

Простой пример использования библиотеки: Устанавливаем библиотеку python -m

LORD_CODE 2 Jun 25, 2022
Mixcloud API wrapper for Python and Async IO

aiomixcloud Mixcloud API wrapper for Python and Async IO aiomixcloud is a wrapper library for the HTTP API of Mixcloud. It supports asynchronous opera

Aristotelis Mikropoulos 26 Dec 31, 2022