├── .gitignore ├── COPYRIGHT ├── LICENSE ├── README.md ├── config ├── locales │ ├── server.de.yml │ └── server.en.yml └── settings.yml ├── lib ├── bot.rb ├── bot_commands.rb ├── discord_events_handlers.rb ├── discourse_events_handlers.rb ├── engine.rb └── utils.rb └── plugin.rb /.gitignore: -------------------------------------------------------------------------------- 1 | gems 2 | -------------------------------------------------------------------------------- /COPYRIGHT: -------------------------------------------------------------------------------- 1 | All code in this repository is Copyright 2019 by Robert Barrow. 2 | 3 | This program is free software; you can redistribute it and/or modify 4 | it under the terms of the GNU General Public License as published by 5 | the Free Software Foundation; either version 2 of the License, or (at 6 | your option) any later version. 7 | 8 | This program is distributed in the hope that it will be useful, but 9 | WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 10 | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 11 | for more details. 12 | 13 | You should have received a copy of the GNU General Public License 14 | along with this program as the file LICENSE.txt; if not, please see 15 | http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # discourse-discord-bot 2 | A Discord bot that runs on your Discourse server to link the two servers. 3 | 4 | [Read more about this project, a Discourse plugin, here](https://meta.discourse.org/t/discord-bot-run-one-on-your-discourse-server-keep-things-in-sync/122530) 5 | -------------------------------------------------------------------------------- /config/locales/server.de.yml: -------------------------------------------------------------------------------- 1 | en: 2 | site_settings: 3 | discord_bot_enabled: Discourse Discord Bot Plugin aktivieren 4 | discord_bot_token: Gebe hier den Discord Bot TOKEN ein 5 | discord_bot_admin_channel_id: Die ID des Admin Text Channels auf Discord 6 | discord_bot_admin_role_id: 'Die ID deiner Admin-Rolle auf Discord, für die Befehle erlaubt sind' 7 | discord_bot_announcement_channel_id: Die ID deines Discord-Ankündigungskanals 8 | discord_bot_discourse_announcement_topic_id: >- 9 | Die ID deines Discourse-Ankündigungsthemas (wenn die automatische 10 | Synchronisierung des Discord-Kanals aktiviert ist und eine passende 11 | Kategorie gefunden wurde, wird dies unterdrückt) 12 | discord_bot_auto_channel_sync: >- 13 | Chat-Synchronisation auf gleichnamigen Kanälen/Kategorien aktivieren (hat 14 | Vorrang vor Discourse Announcement Topic) 15 | discord_bot_message_copy_topic_size_limit: >- 16 | Kopie des Nachrichtenverlaufs: Anzahl der Discord-Nachrichten pro 17 | Diskursthema 18 | discord_bot_message_copy_default_category: >- 19 | Wenn keine Kategorie angegeben wurde und der Name des Kanals nicht mit 20 | einer Discourse-Kategorie übereinstimmt, wird diese Kategorie zum Einfügen 21 | von Themen verwendet 22 | discord_bot_message_copy_convert_discord_mentions_to_usernames: >- 23 | Erwähnungen in Discord-Nachrichten in Discourse- oder Discord-Nutzernamen 24 | umwandeln 25 | discord_bot_message_copy_ignore_bot_messages: Ignoriere Nachrichten von Bot und kopiere nicht rüber 26 | discord_bot_post_announcement_categories: Neue Posts hier im Ankündigungskanal ankündigen 27 | discord_bot_topic_announcement_categories: Kündige neue Themen hier im Ankündigungskanal an 28 | discord_bot_rate_limit_delay: >- 29 | Die Verzögerung in Sekunden, in der Befehle an Discord geschickt werden, 30 | um die Rate Limits einzuhalten 31 | discord_bot_unknown_user_proxy_account: >- 32 | Benutzername des Accounts, der zum Posten verwendet werden soll, wenn der 33 | Discord-Benutzer der Discourse-Instanz unbekannt ist 34 | discord_bot: 35 | discord_events: 36 | auto_message_copy: 37 | default_topic_title: 'Discord #%{channel_name} Nachrichten' 38 | commands: 39 | rate_limit_breached: 'Warte, Kuh(Mädchen/Junge/Person), Ratengrenze erreicht!' 40 | no_matching_category: Keine passende Kategorie in Discourse! 41 | disccopy: 42 | description: Kopiere den gesamten Nachrichtenverlauf in die gleichnamige Kategorie 43 | discourse_topic_title: '#%{channel} Nachrichten von Discord' 44 | link_to_discord: >- 45 | (Dieses Thema bezieht sich auf die [Discord-Unterhaltung 46 | hier](%{link_to_discord})) 47 | no_category_specified: >- 48 | Es wurde keine Zielkategorie angegeben, also wird versucht, den 49 | aktuellen Kanalnamen zu verwenden, um eine Discourse-Kategorie zu 50 | finden, oder es wird die Standardkategorie verwendet. 51 | success: 52 | found_matching_discourse_category: 'Erfolg: Passende Discourse Kategorie gefunden: "%{name}"' 53 | found_matching_discourse_topic: 'Erfolg: Passendes Discourse-Thema gefunden' 54 | final_outcome: >- 55 | Erfolg: Über %{count} der vergangenen Nachrichten in Discourse 56 | kopiert! 57 | link: 'Erfolg: Das Thema des Discourse findest du unter %{url}' 58 | error: 59 | must_specify_message_number: >- 60 | FEHLER: Außerhalb eines Threads musst du die Anzahl der zu 61 | kopierenden Nachrichten angeben! 62 | must_specify_message_number_as_integer: 'FEHLER: Die Anzahl der Nachrichten muss eine ganze Zahl sein!' 63 | unable_to_find_discourse_category: >- 64 | FEHLER: Keine passende Discourse-Kategorie gefunden, Abbruch des 65 | Befehls! Achte darauf, Leerzeichen im Namen durch _ zu ersetzen und 66 | die Groß- und Kleinschreibung anzupassen. 67 | unable_to_find_discourse_topic: >- 68 | FEHLER: Kein passendes Diskursthema in der Zielkategorie gefunden, 69 | wird neu erstellt! 70 | unable_to_determine_topic_id: >- 71 | FEHLER: Es kann keine passende Themen Id für Discourse ermittelt 72 | werden! 73 | disccopythread: 74 | description: Kopiere diesen Thread in ein neues Thema auf Discourse 75 | disckick: 76 | description: >- 77 | Benutzer blockieren, deren Vertrauenslevel unter einer bestimmten Zahl 78 | liegt -------------------------------------------------------------------------------- /config/locales/server.en.yml: -------------------------------------------------------------------------------- 1 | en: 2 | site_settings: 3 | discord_bot_enabled: "Enable the Discourse Discord bot plugin" 4 | discord_bot_token: "Enter your bot TOKEN from Discord here" 5 | discord_bot_admin_channel_id: "The id of your admin text channel on Discord" 6 | discord_bot_admin_role_id: "The id of your admin role on Discord for which commands are permitted" 7 | discord_bot_announcement_channel_id: "The id of your Discord announcement channel" 8 | discord_bot_discourse_announcement_topic_id: "The id of your Discourse Announcement Topic (if discord auto channel sync is enabled and matching Category found this is suppressed)" 9 | discord_bot_auto_channel_sync: "Enable chat sync on identically named channels/Categories (takes precedence over Discourse Announcement Topic)" 10 | discord_bot_message_copy_topic_size_limit: "Message history copy: number of Discord messages per Discourse Topic" 11 | discord_bot_message_copy_default_category: "If no Category specified and Channel name doesn't match a Discourse Category use this Category to paste Topics" 12 | discord_bot_message_copy_convert_discord_mentions_to_usernames: "Convert mentions within Discord messages to Discourse or Discord usernames" 13 | discord_bot_message_copy_ignore_bot_messages: "Ignore messages by bot and do not copy over" 14 | discord_bot_post_announcement_categories: "Announce new Posts in here within the announcements channel" 15 | discord_bot_topic_announcement_categories: "Announce new Topics in here within the announcements channel" 16 | discord_bot_topic_announcement_delay_seconds: "Announce new Topics: the delay in seconds" 17 | discord_bot_rate_limit_delay: "The delay in seconds between sending commands to Discord so we don't annihilate rate limits" 18 | discord_bot_unknown_user_proxy_account: "Username of account to be used for posting if Discord User is unknown to Discourse instance" 19 | discord_bot: 20 | discord_events: 21 | auto_message_copy: 22 | default_topic_title: "Discord #%{channel_name} messages" 23 | embed: "[%{title}](%{url})\n\n%{description}\n\n%{thumbnail_url}" 24 | discourse_events: 25 | announce_new_post: "There's a new Post in the '%{posted_category_name}' Category on Discourse: %{url}" 26 | announce_new_topic: "There's a new Topic in the '%{posted_category_name}' Category on Discourse: %{url}" 27 | commands: 28 | rate_limit_breached: "Hold on cow(girl/boy/person), rate limit hit!" 29 | no_matching_category: "No matching Category in Discourse!" 30 | disccopy: 31 | description: "Copy across message history to Category of same name" 32 | discourse_topic_title: "#%{channel} messages from Discord" 33 | discourse_topic_contents: "%{channel}" 34 | mention_prefix: "discord_%{discord_username}" 35 | link_to_discord: "\n\n(This Topic relates to the [Discord conversation here](%{link_to_discord}))" 36 | no_category_specified: "No target Category specified, so attempting to use current channel name to match a Discourse Category or will use Default Category." 37 | success: 38 | found_matching_discourse_category: "Success: Found matching Discourse Category: \"%{name}\"" 39 | found_matching_discourse_topic: "Success: Found matching Discourse Topic" 40 | final_outcome: "Success: Copied over %{count} past messages to Discourse!" 41 | link: "Success: The Discourse Topic can be found at %{url}" 42 | error: 43 | general_error: "ERROR: occurred, aborting command!: %{error}" 44 | must_specify_message_number: "ERROR: Outside of a Thread you must specify number of messages to be copied!" 45 | must_specify_message_number_as_integer: "ERROR: Number of messages must be an integer!" 46 | unable_to_find_discourse_category: "ERROR: Unable to find matching Discourse Category, aborting command! Be sure to substitute _ for spaces in name and match case." 47 | unable_to_find_discourse_topic: "ERROR: Unable to find matching Discourse Topic in target Category, will create new!" 48 | unable_to_determine_topic_id: "ERROR: Unable to determine a suitable Topic Id for Discourse!" 49 | disccopythread: 50 | description: "Copy this thread to a new Topic on Discourse" 51 | disckick: 52 | description: "Block users whose trust level is below a certain integer on discourse" -------------------------------------------------------------------------------- /config/settings.yml: -------------------------------------------------------------------------------- 1 | plugins: 2 | discord_bot_enabled: 3 | default: true 4 | client: false 5 | discord_bot_token: 6 | default: '' 7 | client: false 8 | discord_bot_admin_channel_id: 9 | default: '' 10 | client: false 11 | discord_bot_admin_role_id: 12 | default: '' 13 | client: false 14 | discord_bot_announcement_channel_id: 15 | default: '' 16 | client: false 17 | discord_bot_discourse_announcement_topic_id: 18 | default: '' 19 | client: false 20 | discord_bot_post_announcement_categories: 21 | client: false 22 | default: '' 23 | type: category_list 24 | discord_bot_topic_announcement_categories: 25 | client: false 26 | default: '' 27 | type: category_list 28 | discord_bot_topic_announcement_delay_seconds: 29 | default: 5 30 | client: false 31 | discord_bot_auto_channel_sync: 32 | default: false 33 | client: false 34 | discord_bot_message_copy_topic_size_limit: 35 | default: 100 36 | client: false 37 | discord_bot_message_copy_default_category: 38 | client: false 39 | default: '' 40 | type: category_list 41 | discord_bot_message_copy_convert_discord_mentions_to_usernames: 42 | client: false 43 | default: true 44 | discord_bot_message_copy_ignore_bot_messages: 45 | client: false 46 | default: true 47 | discord_bot_unknown_user_proxy_account: 48 | client: false 49 | type: username 50 | default: system 51 | discord_bot_rate_limit_delay: 52 | default: 2 53 | client: false 54 | -------------------------------------------------------------------------------- /lib/bot.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | # Discord bot class 3 | class ::DiscordBot::Bot 4 | 5 | @@DiscordBot = nil 6 | 7 | def self.init 8 | @@DiscordBot = Discordrb::Commands::CommandBot.new token: SiteSetting.discord_bot_token, prefix: '!' 9 | 10 | admin_channel_id = SiteSetting.discord_bot_admin_channel_id 11 | @@DiscordBot.ready do |event| 12 | puts "Logged in as #{@@DiscordBot.profile.username} (ID:#{@@DiscordBot.profile.id}) | #{@@DiscordBot.servers.size} servers" 13 | @@DiscordBot.send_message(admin_channel_id, "The Discourse admin bot has started his shift!") 14 | end 15 | 16 | @@DiscordBot 17 | end 18 | 19 | def self.discord_bot 20 | @@DiscordBot 21 | end 22 | 23 | def self.run_bot 24 | bot = self.init 25 | 26 | unless bot.nil? 27 | ::DiscordBot::DiscourseEventsHandlers.hook_events 28 | bot.include!(::DiscordBot::DiscordEventsHandlers::TransmitAnnouncement) 29 | ::DiscordBot::BotCommands.manage_discord_commands(bot) 30 | end 31 | end 32 | end 33 | -------------------------------------------------------------------------------- /lib/bot_commands.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | module ::DiscordBot::BotCommands 3 | 4 | HISTORY_CHUNK_LIMIT = 100 5 | 6 | THREAD_TYPES = [ 7 | Discordrb::Channel::TYPES[:news_thread], 8 | Discordrb::Channel::TYPES[:public_thread], 9 | Discordrb::Channel::TYPES[:private_thread] 10 | ].freeze 11 | 12 | def self.manage_discord_commands(bot) 13 | bot.bucket :admin_tasks, limit: 3, time_span: 60, delay: 10 14 | 15 | # '!disccopy' - a command to copy message history to Topics in Discourse 16 | 17 | bot.command(:disccopy, min_args: 0, max_args: 3, bucket: :admin_tasks, rate_limit_message: I18n.t("discord_bot.commands.rate_limit_breached"), required_roles: [SiteSetting.discord_bot_admin_role_id], description: I18n.t("disccopy.description")) do |event, number_of_past_messages, target_category, target_topic| 18 | token = event.bot.token.split(' ')[1] 19 | RailsMultisite::ConnectionManagement.each_connection do 20 | next if token != SiteSetting.discord_bot_token 21 | past_messages = [] 22 | 23 | if !THREAD_TYPES.include?(event.channel.type) 24 | if !(number_of_past_messages.to_i > 0) 25 | event.respond I18n.t("discord_bot.commands.disccopy.error.must_specify_message_number") 26 | break 27 | end 28 | else 29 | if !number_of_past_messages.blank? && !(number_of_past_messages.to_i > 0) 30 | event.respond I18n.t("discord_bot.commands.disccopy.error.must_specify_message_number_as_integer") 31 | break 32 | end 33 | end 34 | 35 | number_of_past_messages = number_of_past_messages || HISTORY_CHUNK_LIMIT 36 | if number_of_past_messages.to_i <= HISTORY_CHUNK_LIMIT 37 | past_messages = event.channel.history(number_of_past_messages.to_i, event.message.id) 38 | else 39 | number_of_messages_retrieved = 0 40 | last_id = event.message.id 41 | while number_of_messages_retrieved < number_of_past_messages.to_i 42 | retrieve_this_time = number_of_past_messages.to_i - number_of_messages_retrieved > HISTORY_CHUNK_LIMIT ? HISTORY_CHUNK_LIMIT : number_of_past_messages.to_i - number_of_messages_retrieved 43 | past_messages = event.channel.history(retrieve_this_time, last_id) 44 | last_id = past_messages.last.id.to_i 45 | number_of_messages_retrieved += retrieve_this_time 46 | end 47 | end 48 | 49 | # if beginning of thread, strip the first message and replace it with its parent message that kicked off the thread (ugh!) 50 | if past_messages.last.content.blank? && THREAD_TYPES.include?(event.channel.type) 51 | past_messages = past_messages[0..past_messages.length-2] << event.bot.channel(event.channel.parent_id).message(event.channel.id) 52 | end 53 | 54 | destination_topic = nil 55 | if target_category.nil? 56 | destination_category = Category.find_by(name: event.message.channel.name) || Category.find_by(id: SiteSetting.discord_bot_message_copy_default_category) 57 | event.respond I18n.t("discord_bot.commands.disccopy.no_category_specified") 58 | else 59 | target_category = target_category.gsub /_/, ' ' 60 | destination_category = Category.find_by(name: target_category) 61 | end 62 | if destination_category 63 | event.respond I18n.t("discord_bot.commands.disccopy.success.found_matching_discourse_category", name: destination_category.name) 64 | else 65 | event.respond I18n.t("discord_bot.commands.disccopy.error.unable_to_find_discourse_category") 66 | break 67 | end 68 | unless target_topic.nil? 69 | target_topic = target_topic.gsub /_/, ' ' 70 | destination_topic = Topic.find_by(title: target_topic, category_id: destination_category.id) 71 | if destination_topic 72 | event.respond I18n.t("discord_bot.commands.disccopy.success.found_matching_discourse_topic") 73 | else 74 | event.respond I18n.t("discord_bot.commands.disccopy.error.unable_to_find_discourse_topic") 75 | end 76 | end 77 | system_user = User.find_by(username: SiteSetting.discord_bot_unknown_user_proxy_account) || User.find_by(id: -1) 78 | 79 | total_copied_messages = 0 80 | current_topic_id = nil 81 | bot_user_id = Base64.decode64(bot.token.split(" ")[1].split(".")[0]).to_i 82 | 83 | past_messages.reverse.in_groups_of(SiteSetting.discord_bot_message_copy_topic_size_limit.to_i).each_with_index do |message_batch, index| 84 | message_batch.each_with_index do |pm, topic_index| 85 | next if pm.nil? 86 | next if SiteSetting.discord_bot_message_copy_ignore_bot_messages && pm.author.id == bot_user_id 87 | 88 | posting_user, raw = ::DiscordBot::Utils.prepare_post(pm) 89 | 90 | if topic_index == 0 && destination_topic.nil? 91 | raw = raw.blank? ? I18n.t("discord_bot.commands.disccopy.discourse_topic_contents", channel: event.channel.name) : raw 92 | # because of structure of Discord if we are copying thread we want the link on second message, ugh! 93 | if THREAD_TYPES.include?(event.channel.type) && message_batch.length > 1 94 | link_to_discord = message_batch[1].link 95 | else 96 | link_to_discord = pm.link 97 | end 98 | 99 | raw = raw + I18n.t("discord_bot.commands.disccopy.link_to_discord", link_to_discord: link_to_discord) 100 | new_post = PostCreator.create!(posting_user, title: I18n.t("discord_bot.commands.disccopy.discourse_topic_title", channel: event.channel.name) + (past_messages.count <= SiteSetting.discord_bot_message_copy_topic_size_limit ? "" : " #{index + 1}") , raw: raw, category: destination_category.id, skip_validations: true) 101 | total_copied_messages += 1 102 | current_topic_id = new_post.topic.id 103 | elsif !destination_topic.nil? || !current_topic_id.nil? 104 | if current_topic_id.nil? 105 | current_topic_id = destination_topic.id 106 | end 107 | new_post = PostCreator.create!(posting_user, raw: raw, topic_id: current_topic_id, skip_validations: true) 108 | total_copied_messages += 1 109 | else 110 | event.respond I18n.t("discord_bot.commands.disccopy.error.unable_to_determine_topic_id") 111 | end 112 | end 113 | end 114 | event.respond I18n.t("discord_bot.commands.disccopy.success.final_outcome", count: total_copied_messages) 115 | url = "https://#{Discourse.current_hostname}/t/slug/#{current_topic_id.to_s}" 116 | event.respond I18n.t("discord_bot.commands.disccopy.success.link", url: url) 117 | end 118 | rescue => e 119 | event.respond I18n.t("discord_bot.commands.disccopy.error.general_error", error: e) 120 | Rails.logger.error("Discord Bot: There was a problem: #{e}") 121 | end 122 | 123 | # '!disckick' - a command to kick members beneath a certain trust level on Discourse 124 | 125 | bot.command(:disckick, min_args: 0, max_args: 1, bucket: :admin_tasks, rate_limit_message: I18n.t("discord_bot.commands.rate_limit_breached"), required_roles: [SiteSetting.discord_bot_admin_role_id], description: I18n.t("disckick.description")) do |event, min_trust_level| 126 | token = event.bot.token.split(' ')[1] 127 | RailsMultisite::ConnectionManagement.each_connection do 128 | next if token != SiteSetting.discord_bot_token 129 | 130 | if !min_trust_level then min_trust_level = 3 end 131 | 132 | discordusers = [] 133 | 134 | event.respond "Discourse Kick: Starting. Minimum Trust Level = #{min_trust_level.to_s}" 135 | event.respond "Discourse Kick: Starting. Please be patient, I'm rate limited to respect Discord services." 136 | event.respond "Discourse Kick: Preparing list of users who also have a registered account on Discord ..." 137 | 138 | builder = DB.build("select * from user_associated_accounts /*where*/") 139 | builder.where("provider_name = :provider_name", provider_name: "discord") 140 | builder.query.each do |t| 141 | discordusers << { discord_user_id: t.user_id, provider_uid: t.provider_uid } 142 | end 143 | 144 | event.respond "Discourse Kick: Determining user trust levels ..." 145 | 146 | discordusers.each do |user| 147 | trustuser = User.find_by(id: user[:discord_user_id]) 148 | user[:trust_level] = trustuser[:trust_level] 149 | end 150 | 151 | event.respond "Discourse Kick: Compiling list of untrusted users ..." 152 | 153 | untrusted_users = discordusers.select do |user| 154 | user[:trust_level].to_i < min_trust_level.to_i 155 | end 156 | 157 | bot_profile = bot.profile.on(event.server) 158 | can_do_the_magic_dance = bot_profile.permission?(:kick_members) 159 | 160 | if can_do_the_magic_dance == true 161 | 162 | ut_count = untrusted_users.count 163 | 164 | if ut_count > 0 165 | untrusted_users.each_with_index do |user, index| 166 | user_id = user[:provider_uid] 167 | event.server.kick(user_id.to_s, "Kicked for not having sufficient trust level on the linked Discourse site") 168 | event.respond "Discourse Kick: [#{index + 1}/#{ut_count}] <@#{user_id.to_s}> has been kicked for having insufficient trust level on the linked Discourse site" 169 | sleep(SiteSetting.discord_bot_rate_limit_delay) 170 | rescue => e 171 | event.respond 'Discourse Kick: The user you are trying to kick has a role higher than/equal to me.' 172 | bot.send_message(SiteSetting.discord_bot_admin_channel_id, "ERROR on server #{event.server.name} (ID: #{event.server.id}) for command `^kick`, `#{e}`") 173 | end 174 | else 175 | event.respond 'Discourse Kick: Great news! There were no users below the specified or default trust level!' 176 | end 177 | else 178 | event.respond 'Discourse Kick: Sorry, but I do not have the "Kick Members" permission' 179 | end 180 | event.respond "Discourse Kick: I'm done with the dirty work!" 181 | end 182 | end 183 | 184 | # '!discsync' - a command to pull all the groups that Discord using members are a member of and set them up on Discord inc. adding those Roles to users accordingly 185 | 186 | bot.command(:discsync, min_args: 0, max_args: 3, bucket: :admin_tasks, rate_limit_message: I18n.t("discord_bot.commands.rate_limit_breached"), required_roles: [SiteSetting.discord_bot_admin_role_id], description: 'Block users whose trust level is below a certain integer on discourse') do |event, clean_house, max_group_visibility, include_automated_groups| 187 | token = event.bot.token.split(' ')[1] 188 | RailsMultisite::ConnectionManagement.each_connection do 189 | next if token != SiteSetting.discord_bot_token 190 | 191 | if !clean_house then clean_house = false end 192 | if !max_group_visibility then max_group_visibility = 0 end 193 | if !include_automated_groups then include_automated_groups_args = false end 194 | 195 | discord_users = [] 196 | eligible_discourse_groups = [] 197 | discourse_groups = [] 198 | discord_roles = [] 199 | ug_list = [] 200 | 201 | event.respond "Discourse Sync: Starting. Please be patient, I'm rate limited to respect Discord services." 202 | event.respond "Discourse Sync: Checking if there are any eligible groups for sync ..." 203 | 204 | eligiblegroupbuilder = DB.build("select id from groups /*where*/") 205 | eligiblegroupbuilder.where("visibility_level <= :visibility", visibility: max_group_visibility.to_i) 206 | unless include_automated_groups.to_s.downcase == "true" then eligiblegroupbuilder.where("automatic = false") end 207 | 208 | event.respond "Discourse Sync: #{eligiblegroupbuilder.query.count} eligible group(s) were found" 209 | 210 | if eligiblegroupbuilder.query.count == 0 211 | event.respond "Discourse Sync: No eligible groups for sync using provided or default criteria!" 212 | else 213 | 214 | eligiblegroupbuilder.query.each do |g| 215 | eligible_discourse_groups << g.id 216 | end 217 | 218 | event.respond "Discourse Sync: Preparing list of users who also have a registered account on Discord ..." 219 | 220 | builder = DB.build("select * from user_associated_accounts /*where*/") 221 | builder.where("provider_name = :provider_name", provider_name: "discord") 222 | builder.query.each do |t| 223 | discord_users << { discourse_user_id: t.user_id, discord_uid: t.provider_uid } 224 | end 225 | 226 | event.respond "Discourse Sync: Preparing list of groups that users who have a registered account on Discord belong to on Discourse ..." 227 | 228 | discord_users.each do |user| 229 | groupbuilder = DB.build("select group_id from group_users /*where*/") 230 | groupbuilder.where("user_id = :user_id", user_id: user[:discourse_user_id]) 231 | groupbuilder.query.each do |g| 232 | if eligible_discourse_groups.include? g.group_id 233 | discourse_groups |= [discourse_group_id: g.group_id] 234 | ug_entry = { discourse_user_id: user[:discourse_user_id], discord_uid: user[:discord_uid], discourse_group_id: g.group_id } 235 | ug_list << ug_entry 236 | end 237 | end 238 | userbuilder = DB.build("select username from users /*where*/ limit 1") 239 | userbuilder.where("id = :user_id", user_id: user[:discourse_user_id]) 240 | userbuilder.query.each do |un| 241 | ug_list.each do |ug| 242 | if ug[:discourse_user_id] == user[:discourse_user_id] 243 | ug[:discourse_username] = un.username 244 | end 245 | end 246 | end 247 | end 248 | 249 | event.respond "Discourse Sync: #{discourse_groups.length} eligible group(s) were found with Discord users" 250 | 251 | if discourse_groups.length == 0 252 | event.respond "Discourse Sync: No users were found in elibigle groups for sync using provided or default criteria!" 253 | else 254 | 255 | event.respond "Discourse Sync: Retrieving list of roles from Discord server ..." 256 | 257 | event.server.roles.each do |r| 258 | discord_roles << { name: r.name, id: r.id } 259 | end 260 | 261 | discourse_groups.each do |g| 262 | builder = DB.build("select name from groups /*where*/ limit 1") 263 | builder.where("id = :group_id", group_id: g[:discourse_group_id]) 264 | builder.query.each do |n| 265 | g[:discourse_name] = n.name 266 | end 267 | end 268 | 269 | if clean_house.to_s.downcase == "true" 270 | 271 | event.respond "Discourse Sync: Deleting existing mapping roles ..." 272 | 273 | discourse_groups_count = discourse_groups.count 274 | 275 | discourse_groups.each_with_index do |g, index| 276 | 277 | event.respond "Discourse Sync: [#{index + 1}/#{discourse_groups_count}] Attempting to delete Role" 278 | 279 | if !discord_roles.detect { |r| r[:name] == g[:discourse_name] }.nil? 280 | role_id = discord_roles.detect { |r| r[:name] == g[:discourse_name] }[:id] 281 | else 282 | role_id = nil 283 | end 284 | 285 | unless role_id.nil? 286 | begin 287 | event.server.role(role_id).delete("Discourse Sync Cleanup") 288 | event.respond "Discourse Sync: Role '#{g[:discourse_name]}' deleted as part of cleanup" 289 | sleep(SiteSetting.discord_bot_rate_limit_delay) 290 | rescue => e 291 | event.respond 'Discourse Sync: I dont appear to have rights to do this though!' 292 | bot.send_message(SiteSetting.discord_bot_admin_channel_id, "ERROR on server #{event.server.name} (ID: #{event.server.id}) for command `^role deletion`, `#{e}`") 293 | end 294 | end 295 | end 296 | end 297 | 298 | event.respond "Discourse Sync: Creating missing Roles on Discord server ..." 299 | 300 | discord_roles = [] 301 | 302 | event.server.roles.each do |r| 303 | discord_roles << { name: r.name, id: r.id } 304 | end 305 | 306 | discourse_groups_count = discourse_groups.count 307 | 308 | discourse_groups.each_with_index do |g, index| 309 | 310 | event.respond "Discourse Sync: [#{index + 1}/#{discourse_groups_count}] Attempting to create Role for #{g[:discourse_name]}" 311 | 312 | if !discord_roles.any? { |hash| hash[:name] == g[:discourse_name] } 313 | begin 314 | event.server.create_role(name: g[:discourse_name]) 315 | event.respond "Discourse Sync: Role '#{g[:discourse_name]}' created!" 316 | rescue => e 317 | event.respond 'Discourse Sync: I dont appear to have rights to create Roles!' 318 | bot.send_message(SiteSetting.discord_bot_admin_channel_id, "ERROR on server #{event.server.name} (ID: #{event.server.id}) for command `^role create`, `#{e}`") 319 | end 320 | else 321 | event.respond "Discourse Sync: Role '#{g[:discourse_name]}' already exists!" 322 | end 323 | 324 | sleep(SiteSetting.discord_bot_rate_limit_delay) 325 | end 326 | 327 | discord_roles = [] 328 | 329 | event.server.roles.each do |r| 330 | discord_roles << { name: r.name, id: r.id } 331 | end 332 | 333 | event.respond "Discourse Sync: Building user role mapping ..." 334 | 335 | ug_list.each do |ug| 336 | entrybuilder = DB.build("select name from groups /*where*/ limit 1") 337 | entrybuilder.where("id = :group_id", group_id: ug[:discourse_group_id]) 338 | 339 | entrybuilder.query.each do |n| 340 | ug[:discourse_group_name] = n.name 341 | end 342 | 343 | discord_roles.each do |dr| 344 | if dr[:name] == ug[:discourse_group_name] 345 | ug[:discord_group_id] = dr[:id] 346 | end 347 | end 348 | end 349 | 350 | event.respond "Discourse Sync: Adding users to roles ..." 351 | 352 | ug_count = ug_list.count 353 | ug_list.each_with_index do |ug, index| 354 | event.respond "Discourse Sync: [#{index + 1}/#{ug_count}] Adding member '#{ug[:discourse_username]}' to '#{ug[:discourse_group_name]}'" 355 | event.server.member(ug[:discord_uid]).add_role(ug[:discord_group_id]) 356 | sleep(SiteSetting.discord_bot_rate_limit_delay) 357 | rescue => e 358 | event.respond 'Discourse Sync: I dont appear to have rights to do this though!' 359 | bot.send_message(SiteSetting.discord_bot_admin_channel_id, "ERROR on server #{event.server.name} (ID: #{event.server.id}) for command `^add_role`, `#{e}`") 360 | end 361 | 362 | event.respond "Discourse Sync: DONE!" 363 | end 364 | end 365 | end 366 | end 367 | 368 | bot.message(with_text: 'Ping!') do |event| 369 | token = event.bot.token.split(' ')[1] 370 | RailsMultisite::ConnectionManagement.each_connection do 371 | next if token != SiteSetting.discord_bot_token 372 | event.respond 'Pong!' 373 | end 374 | end 375 | 376 | bot.run 377 | end 378 | end 379 | -------------------------------------------------------------------------------- /lib/discord_events_handlers.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | module ::DiscordBot::DiscordEventsHandlers 3 | # Copy message to Discourse 4 | module TransmitAnnouncement 5 | extend Discordrb::EventContainer 6 | message do |event| 7 | 8 | RailsMultisite::ConnectionManagement.each_connection do 9 | next if !SiteSetting.discord_bot_auto_channel_sync && SiteSetting.discord_bot_discourse_announcement_topic_id.blank && 10 | (event.message.channel.id.to_s != SiteSetting.discord_bot_announcement_channel_id) 11 | 12 | posting_user, raw = ::DiscordBot::Utils.prepare_post(event.message) 13 | 14 | if !raw.blank? 15 | if SiteSetting.discord_bot_auto_channel_sync 16 | matching_category = Category.find_by(name: event.message.channel.name) 17 | unless matching_category.nil? 18 | if !(target_topic = Topic.find_by(title: I18n.t("discord_bot.discord_events.auto_message_copy.default_topic_title", channel_name: matching_category.name))).nil? 19 | new_post = PostCreator.create!(posting_user, raw: raw, topic_id: target_topic.id, skip_validations: true) 20 | else 21 | new_post = PostCreator.create!(posting_user, title: I18n.t("discord_bot.discord_events.auto_message_copy.default_topic_title", channel_name: matching_category.name), raw: raw, category: matching_category.id, skip_validations: true) 22 | end 23 | return 24 | end 25 | end 26 | if !SiteSetting.discord_bot_discourse_announcement_topic_id.blank? && (event.message.channel.id == SiteSetting.discord_bot_announcement_channel_id.to_i) 27 | # Copy the message to the assigned Discourse announcement Topic if assigned in plugin settings 28 | discourse_announcement_topic = Topic.find_by(id: SiteSetting.discord_bot_discourse_announcement_topic_id.to_i) 29 | unless discourse_announcement_topic.nil? 30 | new_post = PostCreator.create!(posting_user, raw: raw, topic_id: discourse_announcement_topic.id, skip_validations: true) 31 | end 32 | end 33 | end 34 | end 35 | end 36 | end 37 | end 38 | -------------------------------------------------------------------------------- /lib/discourse_events_handlers.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | module ::DiscordBot::DiscourseEventsHandlers 3 | def self.hook_events 4 | DiscourseEvent.on(:post_created) do |post| 5 | if post.id > 0 && post.topic.archetype != 'private_message' && !::DiscordBot::Bot.discord_bot.nil? then 6 | post_listening_categories = SiteSetting.discord_bot_post_announcement_categories.split('|') 7 | topic_listening_categories = SiteSetting.discord_bot_topic_announcement_categories.split('|') 8 | posted_category = post.topic.category.id 9 | posted_category_name = Category.find_by(id: posted_category).name 10 | if post_listening_categories.include?(posted_category.to_s) then 11 | message = I18n.t("discord_bot.discourse_events.announce_new_post", posted_category_name: posted_category_name, url: Discourse.base_url + post.url) 12 | ::DiscordBot::Bot.discord_bot.send_message(SiteSetting.discord_bot_announcement_channel_id, message) 13 | else 14 | if topic_listening_categories.include?(posted_category.to_s) && post.post_number = 1 then 15 | sleep(SiteSetting.discord_bot_topic_announcement_delay_seconds) 16 | message = I18n.t("discord_bot.discourse_events.announce_new_topic", posted_category_name: posted_category_name, url: Discourse.base_url + post.url) 17 | ::DiscordBot::Bot.discord_bot.send_message(SiteSetting.discord_bot_announcement_channel_id, message) 18 | end 19 | end 20 | end 21 | end 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /lib/engine.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | module ::DiscordBot 3 | class Engine < ::Rails::Engine 4 | engine_name "discord_bot" 5 | isolate_namespace DiscordBot 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /lib/utils.rb: -------------------------------------------------------------------------------- 1 | module ::DiscordBot::Utils 2 | include ActionView::Helpers::DateHelper 3 | 4 | module_function 5 | 6 | def prepare_post(pm) 7 | 8 | raw = pm.to_s 9 | embed = pm.embeds[0] 10 | 11 | # embed 12 | if !raw.blank? 13 | raw = convert_timestamps(raw) 14 | raw = format_youtube_links(raw) 15 | #mentions 16 | if SiteSetting.discord_bot_message_copy_convert_discord_mentions_to_usernames 17 | raw = convert_mentions(raw) 18 | end 19 | elsif !embed.blank? 20 | url = embed.url 21 | thumbnail_url = embed.thumbnail&.url || embed.image&.url || embed.video&.url || "" 22 | description = embed.description 23 | title = embed.title 24 | raw = I18n.t("discord_bot.discord_events.auto_message_copy.embed", url: url, description: description, title: title, thumbnail_url: thumbnail_url) 25 | end 26 | 27 | # attachments 28 | pm.attachments.each do |attachment| 29 | if attachment.content_type.include?("image") 30 | raw = !raw.blank? ? raw + "\n\n" + attachment.url : attachment.url 31 | else 32 | raw = !raw.blank? ? raw + "\n\n#{attachment.filename}" : "#{attachment.filename}" 33 | end 34 | end 35 | 36 | # associated author 37 | associated_user = UserAssociatedAccount.find_by(provider_uid: pm.author.id, provider_name: 'discord') 38 | proxy_account = User.find_by(name: SiteSetting.discord_bot_unknown_user_proxy_account) 39 | 40 | if associated_user.nil? 41 | posting_user = proxy_account.nil? ? system_user : proxy_account 42 | else 43 | posting_user = User.find_by(id: associated_user.user_id) 44 | end 45 | 46 | return posting_user, raw 47 | end 48 | 49 | def convert_timestamps(text) 50 | # Define a hash mapping format types to strftime patterns 51 | format_map = { 52 | 't' => "%-I:%M %p", # Short time, e.g., "6:00 PM" 53 | 'T' => "%-I:%M:%S %p", # Long time, e.g., "6:00:00 PM" 54 | 'd' => "%m/%d/%Y", # Short date, e.g., "02/10/2024" 55 | 'D' => "%B %-d, %Y", # Long date, e.g., "October 2, 2024" 56 | 'f' => "%B %-d, %Y %-I:%M %p", # Long date and short time, e.g., "October 2, 2024 6:00 PM" 57 | 'F' => "%A, %B %-d, %Y %-I:%M %p" # Full date and time, e.g., "Wednesday, October 2, 2024 6:00 PM" 58 | } 59 | 60 | # Regular expression to match the pattern 61 | text.gsub(//) do |match| 62 | # Extract the timestamp and the format type 63 | timestamp = $1.to_i 64 | format_type = $2 65 | time = Time.at(timestamp) 66 | 67 | # Check if it's a relative time ('R') format 68 | if format_type == 'R' 69 | # Get the relative time and check if it's in the future or past 70 | relative_time = time_ago_in_words(time) 71 | if time > Time.now 72 | "in #{relative_time}" 73 | else 74 | "#{relative_time} ago" 75 | end 76 | else 77 | # Convert the timestamp to Time and format it according to the specified format type 78 | time.strftime(format_map[format_type]) 79 | end 80 | end 81 | end 82 | 83 | def convert_mentions(text) 84 | text.gsub(/\B[<]@\d+[>]/) do |instance| 85 | provider_uid = instance[2..19] 86 | associated_user = UserAssociatedAccount.find_by(provider_uid: provider_uid, provider_name: 'discord') 87 | 88 | if associated_user.nil? 89 | discord_username = event.bot.user(provider_uid).username 90 | I18n.t("discord_bot.commands.disccopy.mention_prefix", discord_username: discord_username) + instance[21..] 91 | else 92 | mentioned_user = User.find_by(id: associated_user.user_id) 93 | "@" + mentioned_user.username + instance[21..] 94 | end 95 | end 96 | end 97 | 98 | def format_youtube_links(text) 99 | # Regular expression to match YouTube URLs 100 | youtube_regex = %r{(https?://(?:www\.)?(?:youtube\.com|youtu\.be)/[^\s]+)} 101 | 102 | # Use gsub to find and format YouTube links with two new lines before and after 103 | text.gsub(youtube_regex) { |match| "\n\n#{match}\n\n" } 104 | end 105 | end -------------------------------------------------------------------------------- /plugin.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | # name: discourse-discord-bot 3 | # about: Integrate Discord Bots with Discourse 4 | # version: 0.3.27 5 | # authors: Robert Barrow 6 | # url: https://github.com/merefield/discourse-discord-bot 7 | 8 | 9 | libdir = File.join(File.dirname(__FILE__), "vendor/discordrb/lib") 10 | 11 | $LOAD_PATH.unshift(libdir) unless $LOAD_PATH.include?(libdir) 12 | 13 | gem 'event_emitter', '0.2.6' 14 | gem 'websocket', '1.2.11' 15 | gem 'websocket-client-simple', '0.3.0' 16 | gem 'opus-ruby', '1.0.1', { require: false } 17 | gem 'netrc', '0.11.0' 18 | gem 'mime-types-data', '3.2025.0507', { require: false } 19 | gem 'mime-types', '3.7.0', { require: false } 20 | gem 'domain_name', '0.5.20180417' 21 | gem 'http-cookie', '1.0.3' 22 | gem 'http-accept', '1.7.0', { require: false } 23 | gem 'rest-client', '2.1.0.rc1' 24 | 25 | gem 'discordrb-webhooks', '3.5.0', { require: false } 26 | gem 'discordrb', '3.5.0' 27 | 28 | enabled_site_setting :discord_bot_enabled 29 | 30 | after_initialize do 31 | 32 | %w[ 33 | ../lib/engine.rb 34 | ../lib/bot.rb 35 | ../lib/utils.rb 36 | ../lib/bot_commands.rb 37 | ../lib/discourse_events_handlers.rb 38 | ../lib/discord_events_handlers.rb 39 | ].each do |path| 40 | load File.expand_path(path, __FILE__) 41 | end 42 | 43 | def start_thread(db) 44 | if Discourse.running_in_rack? 45 | bot_thread = Thread.new do 46 | begin 47 | RailsMultisite::ConnectionManagement.establish_connection(db: db) 48 | ::DiscordBot::Bot.run_bot 49 | STDERR.puts '---------------------------------------------------' 50 | STDERR.puts 'Bot should now be spawned, say "Ping!" on Discord!' 51 | STDERR.puts '---------------------------------------------------' 52 | STDERR.puts '(------- If not check logs ---------)' 53 | rescue Exception => ex 54 | Rails.logger.error("Discord Bot: There was a problem: #{ex}") 55 | end 56 | end 57 | end 58 | end 59 | 60 | db_threads = {} 61 | RailsMultisite::ConnectionManagement.each_connection do 62 | next unless SiteSetting.discord_bot_enabled && ! SiteSetting.discord_bot_token.empty? 63 | db = RailsMultisite::ConnectionManagement.current_db 64 | db_threads[db] = start_thread(db) 65 | end 66 | 67 | DiscourseEvent.on(:site_setting_changed) do |name| 68 | if ["discord_bot_enabled", "discord_bot_token"].include? (name) 69 | db = RailsMultisite::ConnectionManagement.current_db 70 | if db_threads.has_key?(db) 71 | db_threads[db].kill 72 | end 73 | db_threads[db] = start_thread(db) 74 | end 75 | end 76 | end 77 | --------------------------------------------------------------------------------