Interact with discourse from Python?

Hi everyone! Love discourse, it’s the backbone of our community.

We are an open source project with a strong presence on Github. We have a robot written in Python which manages our Github repositories and does things like merge pull requests automatically if they have been approved. Since we have a lot of repositories and not everyone follows every repository it would be awesome if the robot could post in the forums when a new project is created or when a pull request needs to be reviewed.

Can anyone point me in the direction of how I could best call the Discourse API from Python?

3 Me gusta

There is a python discourse api library that is a few years old:

https://github.com/tindie/pydiscourse

And a forked version that has been updated somewhat recently:

https://github.com/bennylope/pydiscourse

Hopefully the latter one will work for you.

Also this plugin may be of interest to you:

https://meta.discourse.org/t/the-github-linkback-plugin/66081

7 Me gusta

Thanks @blake! That is exactly the kind of thing I needed to get started.

I will report back with my successes.

2 Me gusta

I recently started a project for this, and am actively updating it. Currently working towards the next dot release:

https://github.com/samamorgan/discourse

10 Me gusta

Did it work out for you? I am trying this as well. I keep getting “DiscourseClientError: Payload Too Large”.

1 me gusta

I’m suddenly seeing this error too over the weekend when attempting to fetch a topic. This topic fetch code hasn’t changed in over a year, so something about the API must have changed. I’m investigating.

2 Me gusta

Payload Too Large is because of this change.

I don’t know about the project mentioned above, but here is the status for bennylope’s project. Maybe the same fix is needed on other wrappers as well.

https://github.com/bennylope/pydiscourse issue #38 fixes the problem, but the fixed version has not yet been pushed to pypi- https://github.com/bennylope/pydiscourse/issues/38. Waiting for github @bennylope to do it. So you can wait for pypi to be updated, or git pull master.

5 Me gusta

Thanks! This worked. I uninstalled pydiscourse, and used a local copy based on what you suggested. And now, it works!
I am trying to use Python’s Sentiment analyzer to get a sentiment analysis of the latest posts. I will keep you updated on how it goes.

1 me gusta

Is anybody else using this? Are you able to get more than 20 posts per topic using this?

1 me gusta

You probably need to use pagination. I haven’t tried this for posts specifically, but something like:

pagesize = 20
for page in range(100):
    client.posts(topic_id, limit=pagesize, offset=page*pagesize)
3 Me gusta

Sí, sé que esta es una publicación antigua, pero dado que es esencialmente lo que busco, no tiene sentido crear una nueva publicación cuando esta funciona, pero solo necesita actualizarse.

Si bien sé programar en muchos lenguajes de programación, lamento decir que Ruby no es uno de ellos. Me preguntaba si hay respuestas más nuevas o mejores a esta pregunta.

¿Interactuar con Discourse desde Python?


Como pregunta secundaria, ¿se pueden crear complementos y/o temas de Discourse usando Python?

1 me gusta

Temas, definitivamente no, eso es solo Javascript, CSS y HTML.

Complementos: Más o menos.

Puedes importar módulos de Python a un complemento de Discourse basado en Ruby (on Rails) y llamar a funciones de Python usando Pycall: GitHub - red-data-tools/pycall.rb: Calling Python functions from the Ruby language

Lo uso en producción para un propósito muy específico, ya que no existe un módulo equivalente mantenido en el ecosistema RoR, por lo que me evita tener que traducir y luego mantener todo ese código especializado en Ruby.

Funciona sorprendentemente bien.

Dicho esto, la base de ese complemento todavía está escrita en Ruby.

Te recomendaría que simplemente aprendieras Ruby on Rails también; realmente es un lenguaje muy agradable y, en mi opinión, el código es más agradable de leer que Python :slight_smile:

También debería tomarme el tiempo para aprender más Python si/cuando sea necesario.

Nota secundaria interesante: parte del código en Discourse Chatbot 🤖 que crea el comportamiento del agente se basó en un agente de Python llamado “Funkagent”, que primero traduje a Ruby on Rails (y luego modifiqué, mejoré). Por lo tanto, la traducción puede ser una opción, por supuesto, si tiene sentido hacerlo. En ese caso, tuvo sentido.

3 Me gusta

Gracias.

Esa es una respuesta razonable y una opción posible que mantendré sobre la mesa.

1 me gusta

Escribí varios scripts de importación antes de “aprender” realmente ruby. Dependiendo de lo que quieras hacer, podrías hacer más con tus habilidades actuales de lo que crees. Probablemente sea más fácil usar ruby que averiguar cómo usar otra cosa.

Sin embargo, si estás interactuando con la API, puedes usar el lenguaje que quieras.

5 Me gusta

Ruby está bellamente diseñada y es pan comido de aprender, en mi humilde opinión.

Ruby on Rails requiere un poco más de aprendizaje y, como framework que se basa en convenciones, puede ser complicado a veces, pero muy potente una vez que le coges el truco.

2 Me gusta

3 publicaciones se dividieron en un nuevo tema: ¿Qué tan difícil sería para los no programadores poder usar el bot de IA de Discourse AI para ayudarles a crear plugins y/o temas

Puedes echar un vistazo a GitHub - discourse/all-the-plugins para ver lo que es posible.

Elige algo que quieras hacer que parezca simple. Si quieres algo como cakeday que cambia la definición de un aniversario, entonces cakeday podría ser un buen lugar para empezar. Seleccionarías una cosa pequeña que quieras cambiar y harías las cosas un paso a la vez.

2 Me gusta

jaja, me estoy enseñando Ruby estos días, qué divertido. :exploding_head:

3 Me gusta