Kit di Costruzione per Discord Bot 🤖

Scopo di questo plugin

Questo plugin svolge diverse funzioni:

  1. Consente di far funzionare un bot Discord utilizzando il tuo server Discourse per collegare i due sistemi. Forka questo repository ed espandilo con semplici script Ruby per creare tutte le funzionalitĂ  di bot possibili.

  2. FunzionalitĂ  esistenti da utilizzare come esempi e utility utili:

  • Fornisce una pubblicazione automatica bidirezionale di contenuti che soddisfano determinati criteri.
  • Comando per copiare messaggi ad hoc su Discourse.
  • Comando per sincronizzare l’appartenenza ai gruppi con l’assegnazione dei ruoli sul tuo server Discord e la tua istanza Discourse.

Il plugin offre una struttura estensibile su cui puoi costruire funzionalitĂ  aggiuntive. Le PR per aggiunte generalmente utili sono benvenute.


questi non sono i due comandi di sincronizzazione, ma solo un’illustrazione dell’interazione del bot possibile. Il secondo comando nello screenshot è stato deprecato durante lo sviluppo :wink:

La configurazione è necessariamente complessa, ma è ottima per gli appassionati di entrambi i sistemi che sono disposti a dedicare tempo a comprendere il funzionamento di ciascun sistema, almeno a livello funzionale e concettuale. Per ottenere il massimo da questo plugin, è necessario comprendere alcuni fondamenti del funzionamento della gestione degli utenti di Discourse e Discord.

Comandi del Bot

Ci sono quattro comandi:

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

Ping!

Per verificare se il bot risponde, digita semplicemente “Ping!” e il bot dovrebbe rispondere con “:robot: : Pong!” - meraviglioso, vero? :smiley: (a proposito, questo è un meme!)

!disckick <min_trust_level: default 2>

Digitando questo comando, verrai espulso qualsiasi utente che esiste sul tuo Discourse ma con un Livello di Fiducia inferiore al valore fornito. Il valore predefinito, se non ne fornisci uno, è 2.

ad esempio:

!discsync <clean up: default false, min_visibility: default 0, include automated groups: default false>

Questo comando tenterà di copiare tutti i gruppi nei Ruoli di Discord che corrispondono ai criteri forniti (o ai valori predefiniti se non forniti). Successivamente, tenterà di popolare i ruoli in base all’appartenenza ai Gruppi su Discourse. È una sincronizzazione unidirezionale. Nessun dato di Discourse viene mai modificato.

!disccopy <number_of_messages> <optional_target_category_name> <optional_target_topic_name>

Consente di copiare la cronologia dei messaggi di Discord nella tua istanza Discourse direttamente dalla chat di Discord. Può gestire migliaia di messaggi in una sola volta (ma per tale volume richiederà del tempo).

Comunicazione bidirezionale

Ecco le impostazioni

  • Puoi designare un Canale Annunci su Discord nelle impostazioni del plugin.
  • Ora puoi digitare nel Canale Annunci di Discord assegnato e questo invierĂ  il tuo messaggio al tuo Argomento Discourse assegnato nelle impostazioni del plugin.
  • Puoi impostare un elenco di Categorie su Discourse per pubblicare nel canale Annunci del tuo Discord se qualcuno pubblica lĂŹ o aggiunge un nuovo Argomento (uno o entrambi).
  • Copia automatica della chat per messaggio, da canale a qualsiasi Categoria con lo stesso nome su Discourse: se il nome del canale corrisponde al nome della Categoria, il messaggio verrĂ  copiato su Discourse.

image

Inoltre, ho aggiunto un nuovo file per gestire gli eventi di Discord supportati dall’API discordrb, con la logica degli Annunci come primo esempio (sentiti libero di svilupparne di nuovi e inviare una PR se sono utili in generale alla comunità).

NB Per qualsiasi messaggio copiato su Discourse da Discord, l’Utente verrà mostrato correttamente se quell’utente ha effettuato l’accesso a Discourse utilizzando l’accesso con Discord (quindi il Bot Discord è in grado di abbinare gli utenti).

Stato di questo plugin

Questo è un plugin complesso da configurare. Era quasi inevitabile.

Tuttavia, è un gioco da ragazzi usarlo una volta che è tutto attivo e funzionante.

Considera il codice attualmente in Beta. È stato testato, anche in Produzione, ma potrebbe contenere bug. Consiglio di testarlo prima su un nuovo server Discord prima di applicarlo al tuo server Discord principale “Produzione”, a meno che tu non stia appena iniziando.

Qualsiasi bug è molto più probabile che disturbi la tua istanza Discord rispetto a quella di Discourse, poiché non vengono apportate modifiche a Discourse. Tuttavia, l’ho scritto in modo che la maggior parte delle cose sia recuperabile e puoi semplicemente ripetere un’azione per risolvere un problema, di solito. Discourse viene utilizzato come master per le informazioni di appartenenza e di gruppo e questi dati vengono utilizzati per aggiornare l’appartenenza e i Ruoli sul tuo server Discord.

Istruzioni per la configurazione

Prerequisiti

  1. Un server Discord su cui sei Amministratore
  2. Un’app Discord (vedi sotto)
  3. Un bot Discord (vedi sotto)
  4. Accesso SSH root al tuo server Discourse
  5. Aggiornamenti a app.yml per installare il plugin
  6. Tutti gli utenti del tuo Discourse dovranno effettuare l’accesso utilizzando il login OAuth di Discord che apparirà sulla tua pagina di accesso una volta installato il plugin.

App Discord

Vai qui e crea un’app:

Clicca su “New Application”

Dovrai creare un Bot e avrà un aspetto simile a questo (lascialo non ‘pubblico’):

Dovrai autorizzare il bot nel browser, vedi OAuth2 - Documentation - Discord

Una volta configurato il bot, copia il Token. Dovrai inserirlo in Discourse in seguito.

Modifiche a app.yml

plugin

Ora ti serve un solo plugin, dato che il Social Login di Discord è ora nativo nel core di Discourse (wooo :tada: )

Quindi al prompt esegui ./launcher rebuild app come al solito.

Questo dovrebbe funzionare, nessun problema.

Potresti ricevere alcuni errori nella console e nei log che indicano un fallimento del bot al primo build, poiché non hai ancora inserito le credenziali del bot nell’interfaccia delle impostazioni di Discourse. (gestire questo in modo più elegante è un compito da fare, cancellerò questa parte quando sarà completato). Tuttavia, non farà alcun danno e Discourse stesso funzionerà normalmente.

Una volta nell’area di amministrazione di Discourse, vai alle Impostazioni del Plugin e compila questi campi:

Otterrai gli ID dall’interfaccia di Discord. Dovrai attivare la Modalità Sviluppatore per permetterti di copiare questi ID. In Discord, vai alle tue Impostazioni → Aspetto → AVANZATO e abilita la Modalità Sviluppatore:

Puoi quindi ottenere gli ID dall’interfaccia, ad esempio:

Dovrai anche compilare le Impostazioni OAuth di Discord. L’ID Client e il Segreto provengono dalla tua stessa App Discord.

Una volta impostati questi, torna al prompt root in Linux e digita:

./launcher restart app

Se hai configurato correttamente i tuoi server Discord e Discourse, dovresti vedere il bot unirsi al server.

Se mai il bot si blocca (andrà offline), dovrai fare la stessa cosa per farlo tornare. Una maggiore indipendenza del bot dal server core di Discourse è un compito da fare. Detto questo, ho eseguito un bot in Produzione per molto tempo e non si è mai bloccato.

Comandi futuri?

Se hai un’idea per un altro comando che sfrutta il collegamento tra Discourse e Discord e che ritieni utile per la comunità più ampia, fammelo sapere nelle risposte e possiamo valutare la possibilità di implementarlo. NB questo bot non è inteso per eseguire attività al di fuori dell’ambito di Discourse.

Limitazioni

L’obiettivo principale di questo plugin era consentire all’utente di creare un bot sul proprio Discord che fosse alimentato dal proprio server Discourse e in grado di eseguire alcune funzioni di base di gestione dell’appartenenza. Fornisce anche una base per eventuali interazioni aggiuntive simili a bot tra i due sistemi per il futuro. Parte della motivazione per l’uso dei bot è che sono semplicemente divertenti.

I comandi del bot sono per loro natura ad hoc.

Problemi noti

  • Il bot avvierĂ  un’istanza di se stesso se entri in una sessione di console rails sul server. Questo farĂ  sĂŹ che il bot sembri rispondere due volte (ma in realtĂ  ora ci sono due bot). Nella console rails, fermare semplicemente il bot aggiuntivo digitando: ::DiscordBot::Bot.discord_bot.stop Ora non dovrebbe piĂš essere necessario!

  • Il Robot è un po’ loquace durante gli aggiornamenti di Discourse ‘online’ poichĂŠ continua a essere riattivato durante il processo di aggiornamento. Questo porta a trovare un buon modo per eseguire il bot in un processo separato e gestito invece che in un thread diramato dal webserver. Credo che tutto ciò sia innocuo, e se l’output dei bot è solo sul tuo canale amministrativo su Discord, ti importa davvero? Questo dovrebbe essere quasi risolto ora, con il bot che si annuncia solo due volte durante una ricostruzione.

Ringraziamenti

Ci sono diversi sostenitori da ringraziare per questo plugin, che mi ha richiesto molto tempo per arrivare a questo stadio, inclusi @Wedgebert, @FoohonPie. Grazie a Jeff per il suo generoso contributo. Grazie a @angus per tutto l’incoraggiamento e per aver gestito il supporto finanziario.

Il plugin è stato ispirato dal lavoro di @Watercolor_Games in una fase precedente e si basa sul plugin OAuth di Discord creato da @featheredtoast.

Il plugin si basa su la libreria Ruby discordrb semi-ufficiale supportata da Discord e sul lavoro fantastico svolto dal team di Discord per rendere il loro sistema accessibile. Grazie a @Falco per avermi aiutato con una dipendenza in modo estremamente reattivo.

Inoltre, naturalmente, questo non sarebbe stato possibile senza l’incredibile ecosistema di plugin di Discourse (woo!)

Stato di queste istruzioni

Saranno migliorate nel tempo e accolgo con favore i feedback. Ci sono aree che potrebbero risultare poco chiare.

47 Mi Piace
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 Mi Piace

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 Mi Piace

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 Mi Piace

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

4 Mi Piace

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 Mi Piace

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 Mi Piace

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 Mi Piace

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 Mi Piace

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 Mi Piace

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 Mi Piace

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 Mi Piace

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 Mi Piace

@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 Mi Piace

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 Mi Piace

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 Mi Piace

The OAuth setting are there but no bot settings

1 Mi Piace

image
These

2 Mi Piace