Kit de construcción para Discord Bot 🤖

Propósito de este plugin

Este plugin realiza varias funciones:

  1. Te permite alimentar un bot de Discord usando tu servidor Discourse para realizar tareas que vinculen ambos sistemas. Haz un fork de este repositorio y amplíalo con Ruby simple para crear todo tipo de funcionalidades para el bot.

  2. Funcionalidad existente que sirve como ejemplos y utilidad práctica:

  • Proporciona cierta publicación automática bidireccional de contenido que cumple ciertos criterios.
  • Comando para copiar mensajes de forma ad hoc a Discourse.
  • Comando para sincronizar la pertenencia a grupos con la pertenencia a roles de tu servidor de Discord con tu instancia de Discourse.

El plugin proporciona un esqueleto extensible sobre el cual podrías construir características adicionales. Se aceptan PRs para adiciones generalmente útiles.


\u003csup\u003eestos no son los dos comandos de sincronización, solo una ilustración de la interacción del bot que es posible. El segundo comando en la captura de pantalla fue obsoleto durante el desarrollo ;)\u003c/sup\u003e

Su configuración es necesariamente compleja, pero es excelente para los fanáticos de ambos sistemas que están dispuestos a invertir el tiempo en entender cómo funciona cada uno, al menos a nivel funcional y conceptual. Necesitas entender algunos de los fundamentos de cómo funciona la gestión de usuarios de Discourse y Discord para sacar el máximo provecho de este plugin.

Comandos del Bot

Hay cuatro comandos:

  1. Ping!
  2. !disckick
  3. !discsync
  4. !disccopy

Ping!

Para verificar si el bot está respondiendo, simplemente escribe “Ping!” y el bot debería responder con “:robot: : Pong!” - maravilloso, ¿verdad? :smiley: (esto es un poco de meme, por cierto!)

!disckick <nivel_mínimo_de_confianza: predeterminado 2>

Escribir esto expulsará a cualquier usuario que exista en tu Discourse pero con un Nivel de Confianza inferior al valor proporcionado. El valor predeterminado si no proporcionas uno es 2.

ej.:

!discsync <limpiar: predeterminado false, visibilidad_mínima: predeterminado 0, incluir grupos automatizados: predeterminado false>

Este comando intentará copiar todos los grupos a Roles en Discord que coincidan con los criterios proporcionados (o los predeterminados si no se proporcionan). Luego intentará poblar los roles según la pertenencia a Grupos en Discourse. Es una sincronización unidireccional únicamente. Nunca se modifica ningún dato de Discourse.

!disccopy <número_de_mensajes> <nombre_de_categoría_destino_opcional> <nombre_de_tópico_destino_opcional>

Te permite copiar el historial de mensajes de Discord a tu instancia de Discourse desde el chat de Discord. Esto puede manejar miles de mensajes de una sola vez (pero para ese volumen tomará tiempo).

Comunicación bidireccional

Estos son los ajustes

  • Puedes designar un Canal de Anuncios en Discord en la configuración del plugin.
  • Ahora puedes escribir en el Canal de Anuncios de Discord asignado y esto publicará tu mensaje en el Tópico de Discourse asignado en la configuración del plugin.
  • Puedes configurar una lista de Categorías en Discourse para publicar en el canal de Anuncios de tu Discord si alguien publica allí o agrega un nuevo Tópico (uno o ambos).
  • Copia automatizada de chat por mensaje, por canal a cualquier Categoría con el mismo nombre en Discourse: si el nombre del canal coincide con el nombre de la Categoría, copiará el mensaje a Discourse.

image

Además, he agregado un nuevo archivo para gestionar eventos de Discord compatibles con la API discordrb, siendo la lógica de Anuncios el primer ejemplo (siéntete libre de desarrollar nuevos y enviar un PR si son de utilidad general para la comunidad).

NB: Para cualquier mensaje copiado en Discourse desde Discord, el Usuario se mostrará correctamente si ese usuario ha iniciado sesión en Discourse usando el inicio de sesión con Discord (por lo que el Bot de Discord puede coincidir con los usuarios).

Estado de este plugin

Este es un plugin complejo de configurar. Eso fue bastante inevitable.

Sin embargo, es un juego de niños de usar una vez que todo está funcionando.

Considera el código como actualmente en Beta. Ha sido probado, incluso en Producción, pero es probable que contenga errores. Recomiendo probarlo primero en un servidor de Discord nuevo antes de aplicarlo a tu servidor principal de Discord en “Producción”, a menos que apenas estés comenzando.

Cualquier error es mucho más probable que afecte tu instancia de Discord que tu instancia de Discourse, porque no se realizan cambios en Discourse. Sin embargo, lo he escrito de una manera que significa que la mayoría de las cosas son recuperables y usualmente puedes simplemente repetir algo para solucionar un problema. Discourse se utiliza como maestro para la información de membresía y grupos, y estos datos se utilizan para actualizar la membresía y los Roles en tu servidor de Discord.

Instrucciones de configuración

Prerrequisitos

  1. un servidor de Discord en el que seas Administrador
  2. una Aplicación de Discord (ver abajo)
  3. un Bot de Discord (ver abajo)
  4. acceso root ssh a tu servidor Discourse
  5. actualizaciones en app.yml para instalar el plugin
  6. Todos los usuarios de tu Discourse necesitarán iniciar sesión usando el inicio de sesión OAuth de Discord que aparecerá en tu página de inicio de sesión una vez instalado el plugin.

Aplicación de Discord

Ve aquí y crea una aplicación:

Haz clic en “Nueva Aplicación”

Necesitarás crear un Bot y se verá algo así (déjalo no ‘público’):

Necesitarás autorizar al bot en el navegador, ver OAuth2 - Documentation - Discord

Una vez configurado el bot, copia el Token. Necesitarás ingresarlo en Discourse más tarde.

Cambios en app.yml

plugin

Solo necesitas un plugin para esto ahora que el Inicio de Sesión Social de Discord es nativo del núcleo de Discourse (¡guau :tada: )

Luego en el prompt ./launcher rebuild app como de costumbre.

Esto debería funcionar, sin problemas.

Puedes obtener algunos errores en la consola y en los registros que indican un fallo del bot en la primera compilación ya que aún no has ingresado las credenciales del bot en la interfaz frontal de la configuración de Discourse. (manejar esto de manera más elegante es una tarea pendiente, eliminaré esta parte cuando se haga). Sin embargo, no causará ningún daño y Discourse en sí funcionará con normalidad.

Una vez en tu área de administración de Discourse, ve a Configuración del Plugin y completa esto:

Obtendrás los IDs de la interfaz de Discord. Necesitarás activar el Modo Desarrollador para permitirte copiar estos IDs. En Discord, ve a tu Configuración - \u003e Apariencia - \u003e AVANZADO y habilita el Modo Desarrollador:

Luego puedes obtener los IDs desde la interfaz, ej.:

También necesitarás completar la configuración de OAuth de Discord. El ID de Cliente y el Secreto provienen de tu misma Aplicación de Discord.

Una vez que hayas configurado esto, vuelve a tu prompt raíz en Linux y escribe:

./launcher restart app

Si has configurado correctamente tus servidores de Discord y Discourse, deberías ver que el bot se une al servidor.

Si alguna vez el bot falla (se desconectará), necesitarás hacer lo mismo nuevamente para traerlo de vuelta. Una mayor independencia del bot del servidor principal de Discourse es una tarea pendiente. Dicho esto, he ejecutado un bot en Producción durante mucho tiempo y aún no ha fallado.

¿Próximos comandos?

Si tienes una idea para otro comando que aproveche el vínculo entre Discourse y Discord y crees que sería útil para la comunidad más amplia, házmelo saber en las respuestas y podemos explorar el potencial de implementarlo. NB: este bot no está destinado a realizar tareas fuera del alcance de Discourse.

Limitaciones

El objetivo principal de este plugin fue permitir al usuario crear un bot en su Discord que fuera alimentado por su servidor Discourse y pudiera realizar algunas funciones básicas de gestión de membresía. También proporciona una base para cualquier interacción adicional tipo bot entre los dos sistemas en el futuro. Parte de la motivación para usar bots es que son simplemente divertidos.

Los comandos del bot son ad hoc por su propia naturaleza.

Problemas conocidos

  • El bot iniciará una instancia de sí mismo si entras en una sesión de consola rails en el servidor. Esto hará que el bot parezca responder dos veces (pero en realidad ahora hay dos bots). En la consola rails simplemente detén el bot adicional escribiendo: ::DiscordBot::Bot.discord_bot.stop Esto ya no debería ser necesario.

  • El Robot es un poco parlanchín durante las actualizaciones de Discourse en ‘línea’ ya que sigue siendo reactivado durante el proceso de actualización. Esto se debe a encontrar una buena manera de ejecutar el bot en un proceso separado y gestionado en lugar de un hilo derivado del servidor web. Creo que todo esto es inofensivo, pero si la salida de los bots es solo a tu canal de administración en Discord, ¿realmente te importa? Esto debería estar casi resuelto ahora, con el bot anunciándose solo dos veces durante una reconstrucción.

Gracias

Hay varios patrocinadores a quienes agradecer por este plugin, lo cual me llevó mucho tiempo llegar a esta etapa, incluyendo a @Wedgebert, @FoohonPie. Gracias a Jeff por su generosa contribución. Gracias a @angus por todo el aliento y por gestionar el apoyo financiero.

El plugin fue inspirado por el trabajo que @Watercolor_Games realizó en una etapa anterior y depende del plugin de OAuth de Discord creado por @featheredtoast.

El plugin depende de la biblioteca Ruby discordrb semi-oficial respaldada por Discord y del trabajo fantástico que el equipo de Discord ha realizado para hacer accesible su sistema. Gracias a @Falco por ayudarme con una dependencia de una manera extremadamente receptiva.

Además, por supuesto, esto no sería posible sin el increíble ecosistema de plugins de Discourse (¡guau!)

Estado de estas instrucciones

Se mejorarán con el tiempo y agradezco los comentarios. Hay áreas que seguramente serán poco claras.

47 Me gusta
Discord<-> Discourse Selective Group Sync
Discord login and obtain discord roles in discourse
Discord and Discourse - Better Together | Blog
Convert Existing Plugin to do Discord to Discourse role/group sync
Slack Bot Construction Kit :robot:
2019: The Year in Review
Creat a user automatically when granted a Discord Role?
Discord Sync: sync a Discourse forum with a Discord server
Creating bot on discourse
Using "custom" ruby gems
Discourse Trust Levels for Discord
Discord is taking aim at Discourse. How does Discourse remain unique and stand out from the crowd?
Discord is taking aim at Discourse. How does Discourse remain unique and stand out from the crowd?
Copy + Pasting text from Discord into Discourse mangles paragraph breaks
Discord Role Badge Sync
Discord Bot: Topics not Posts
How do I go about making a very customized theme?
API feature request for additonal info about external accounts
Can anyone help me to add chat option of discord on forum?
How to Integrate/Sync Discord User MEE6 Points with Discourse Leaderboard?
LF Developer, Theme Creator, and Discord/Discourse Hero
Discord Sync: sync a Discourse forum with a Discord server
[PAID] Discourse/Discord integration needed (roles/user groups)
Can anyone help me to add chat option of discord on forum?
Discord and Discourse - Better Together | Blog
How to easily make Discourse bots?
Discourse to Discord bot possible?
Migrating from Discord to Discourse
Convert Existing Plugin to do Discord to Discourse role/group sync
Is migration from other chat apps supported?
Partially enable login option
Introducing Discourse Chat (BETA)
Which instant messenger do you use with Discourse?
Request widgetbot.io
Discord Sync: sync a Discourse forum with a Discord server

Hey I’m super interested in this.

Would the opposite be possible? I’d love a way to be able to create a Discourse setup for my Discord server. I’m not sure if there’s a Discord API event for roles being given but you could probably check when someone logs in with Discord or with CRON.

2 Me gusta

Yes, absolutely.

You could either build that as a bot command for ad hoc application, but with a repeat feature that reran the command after a period (nice but not very transparent and no way to individually manage these recurrences)

OR

As I alluded to above, have it scheduled as a job in Discourse as a sidekiq job. That might be a separate plugin (I actually started on the skeleton of that approach before moving to a bot only solution mainly because the ‘bot’ approach was kind of the Discord ‘thing’, fun and offered a unique approach and result), but if I can get Discourse to fire off bot commands then that’s moot (not yet had the chance to test that), and then we can write stuff once and have it work either way (nice!).

Both these solutions would rely on the same OAuth login though.

Whilst this is an excellent idea, it can’t be a priority for me at present because I have a lot of other client work at the moment I need to deliver, but if you wish to support such an extension, we can discuss offline on a PM and schedule it in.

4 Me gusta

It might be interesting to play around with, but I have nowhere near the skill level required to volunteer to develop/maintain an addon like this. I might make a messy fork at some time but I certainly don’t want my name on anything official. :slight_smile:

3 Me gusta

Absolutely get messy. It’s the only way to learn. :).

4 Me gusta

Minor bug fix deployed:

Got this during rebuild:

Bot is still offline. Triple checked everything and it’s all set up correctly. Not sure how to proceed now… Maybe I need to open a port on my server instance?

2 Me gusta

Thanks for testing this out and so soon after the update. Let me try to reproduce and I will revert. I did not change anything wrt to the port config.

2 Me gusta

No issues rebuilding here, Bot comes up fine … have you changed anything in your server config in between?

Your 400 Bad Request sounds like your server sent a corrupt or bad request to the Discord server and this was the response. This suggests it received it fine and was not blocked.

You can get this for:

  • malformed requests
  • lack of authorisation
  • exceeding rate limits

Unfortunately the error message doesn’t appear to help us determine which of these was the particular issue.

Presumably your Discourse is up? Check all the plugin settings are populated correctly.

Just to rule out a temporary gremlin run ./launcher restart app when you get chance … this will take your site down for a few seconds only (sorry about that!).

I see it runs the bot in the after_initialize block, so it will prevent migrations (and rebuilds) if the bot is misconfigured, or if Discord is down.

Maybe try to handle this exception and just log it?

5 Me gusta

It runs on a separate thread? So I expect that not to be an issue?

However this callback seems to run several times in a rebuild, so the main issue will be that a misconfigured bot could actually breach rate limits if authorisation fails too many times in quick succession. If that happens the account, in worse case, could be blocked for some time.

In any case, I’ll do a quick patch to do that with the current implementation to lessen the impact. Thanks for the suggestion.

UPDATE: @falco, this is done, e.g.:

image

3 Me gusta

First I want to say thank you for making this, once I can get it working its going to be a huge help for us managing our discourse and discord for a volunteer community.
I am running into a 400 error when trying to run this bot. Prior to this plugin being added we have been successfully using the official discord auth plugin and webhooks via the chat integration plugin. I’ve validated that those are both still working appropriately.

I created the bot within the same discord app I’d previously created authorized the bot within the discord server, it shows up in the member list as offline. Your documentation didn’t say what permission value to apply, but given most bots I’ve encountered for discord asked for it I went ahead and set it up with a permissions value of 8 for Administrator.

Within the discord server I then copied the ID of the Role it created, which was named after my app, and the id of the channel for admin text.I added the app Role to that channel with full rights, just to be sure, then added the IDs to discourse and restarted.

Unfortunately no matter what I try I’m getting a 400, I even tried a rebuild just to be sure.

3 Me gusta

Thank you, kind words. It was also enabled by the generosity of funders.

Yes, that’s great. It should have Admin.

This is the second report of this issue.

If you intentially remove the last char of the token in settings (remember what this is) do you get a 401 instead?

Let’s move this to PM because it might get messy :wink: (we can always post the solution here).

4 Me gusta

Just to post an update in case anyone else sees this, we’re actively looking into the issue but haven’t yet narrowed down the cause. I’d say if anyone else is running into this issue please say so would help to have others testing.

1 me gusta

This is now fixed. It was a weird one to track down.

Thanks to @ransim for raising and working with me to get to the bottom of it.

Huge thanks to the #ruby_discordrb gang on Discord API for their patient and instant help!

@neemiasvf

5 Me gusta

@merefield no problem,Your plugin is great.But I have encountered some problems now.
such this:

Discourse Sync:  Starting.  Please be patient, I'm rate limited to respect Discord services.
Discourse Sync:  Checking if there are any eligible groups for sync ...
Discourse Sync: 1 eligible group(s) were found
Discourse Sync:  Preparing list of users who also have a registered account on Discord ...
Discourse Sync:  Preparing list of groups that users who have a registered account on Discord belong to on Discourse ...
Discourse Sync: 0 eligible group(s) were found with Discord users
Discourse Sync:  No users were found in elibigle groups for sync using provided or default criteria!

my commond is : !discsync 4

and commond changed: !discsync false 5 false

Discourse Sync:  Starting.  Please be patient, I'm rate limited to respect Discord services.
Discourse Sync:  Checking if there are any eligible groups for sync ...
Discourse Sync: 10 eligible group(s) were found
Discourse Sync:  Preparing list of users who also have a registered account on Discord ...
Discourse Sync:  Preparing list of groups that users who have a registered account on Discord belong to on Discourse ...
1 me gusta

Hey @p0nda, sorry for slow reply.

If you include any parameters, you need to include all of them. It might be interpreting things strangely.

3 Me gusta

Unable to get the extended bot settings to show up? I have the changes to the app.yml and plugins installed. I have the OAuth setup working, but not the bot settings. Any ideas?

1 me gusta

The OAuth setting are there but no bot settings

1 me gusta

image
These

2 Me gusta