Forráskód Böngészése

Merge branch 'master' of https://github.com/Markus-Rost/discord-wiki-bot

Markus-Rost 4 éve
szülő
commit
a6ebf24472

+ 1 - 8
dashboard/guilds.js

@@ -2,7 +2,7 @@ const cheerio = require('cheerio');
 const {defaultPermissions} = require('../util/default.json');
 const Lang = require('./i18n.js');
 const allLangs = Lang.allLangs().names;
-const {settingsData, addWidgets, createNotice} = require('./util.js');
+const {oauth, settingsData, addWidgets, createNotice} = require('./util.js');
 
 const forms = {
 	settings: require('./settings.js').get,
@@ -11,13 +11,6 @@ const forms = {
 	slash: require('./slash.js').get
 };
 
-const DiscordOauth2 = require('discord-oauth2');
-const oauth = new DiscordOauth2( {
-	clientId: process.env.bot,
-	clientSecret: process.env.secret,
-	redirectUri: process.env.dashboard
-} );
-
 const file = require('fs').readFileSync('./dashboard/index.html');
 
 /**

+ 17 - 1
dashboard/i18n/de.json

@@ -21,6 +21,7 @@
         "save": "Speichern",
         "selector": "Serverauswahl",
         "settings": "Einstellungen",
+        "slash": "Slash-Befehle",
         "support": "Support-Server",
         "theme-dark": "Nutze das dunkle Design",
         "theme-light": "Nutze das helle Design",
@@ -134,7 +135,7 @@
     },
     "rcscript": {
         "desc": "Dies sind die Letzte Änderungen-Webhooks für $1:",
-        "explanation": "<h2>Letzte Änderungen-Webhook</h2>\n<p>Wiki-Bot ist in der Lage einen Letzte Änderungen-Webhook basierend auf <a href=\"https://gitlab.com/piotrex43/RcGcDw\" target=\"_blank\">RcGcDw</a> auszuführen. Die letzten Änderungen können als kompakte Textnachrichten mit Inline-Links oder als Einbettungen mit Bearbeitungsmarkierungen und Kategorieänderungen angezeigt werden.</p>\n<p>Voraussetzungen um einen Letzte Änderungen-Webhook hinzuzufügen:</p>\n<ul>\n<li>Das Wiki benötigt mindestens <a href=\"https://www.mediawiki.org/wiki/MediaWiki_1.30\" target=\"_blank\">MediaWiki 1.30</a>.</li>\n<li>Die Systemnachricht <code>MediaWiki:Custom-RcGcDw</code> muss mit der Discord-Server-ID <code class=\"user-select\" id=\"server-id\"></code> übereinstimmen.</li>\n</ul>",
+        "explanation": "<h2>Letzte Änderungen-Webhook</h2>\n<p>Wiki-Bot ist in der Lage einen Letzte Änderungen-Webhook basierend auf <a href=\"https://gitlab.com/piotrex43/RcGcDw\" target=\"_blank\">RcGcDw</a> auszuführen. Die letzten Änderungen können als kompakte Textnachrichten mit Inline-Links oder als Einbettungen mit Bearbeitungsmarkierungen und Kategorieänderungen angezeigt werden.</p>\n<p>Voraussetzungen um einen Letzte Änderungen-Webhook hinzuzufügen:</p>\n<ul>\n<li>Das Wiki benötigt mindestens <a href=\"https://www.mediawiki.org/wiki/MediaWiki_1.30\" target=\"_blank\">MediaWiki 1.30</a>.</li>\n<li>Die Systemnachricht <code class=\"user-select\">MediaWiki:Custom-RcGcDw</code> muss mit der Discord-Server-ID <code class=\"user-select\" id=\"server-id\"></code> übereinstimmen.</li>\n</ul>",
         "form": {
             "channel": "Kanal:",
             "confirm": "Möchtest du wirklich den Letzte Änderungen-Webhook löschen?",
@@ -183,6 +184,21 @@
         },
         "new": "Neue Überschreibung"
     },
+    "slash": {
+        "desc": "Dies sind die Slash-Befehle für $1:",
+        "explanation": "<h2>Slash-Befehle</h2>\n<p>Die Nutzung von Slash-Befehlen kann pro Rolle beschränkt werden. Dies kannst du hier für die Slash-Befehle von Wiki-Bot tun.</p>",
+        "form": {
+            "add": "Hinzufügen",
+            "allow": "Erlaubt",
+            "default": "Standard",
+            "default_allow": "Standardmäßig kann dieser Befehl von allen genutzt werden.",
+            "default_deny": "Standardmäßig kann dieser Befehl von niemandem genutzt werden.",
+            "deny": "Verboten",
+            "entry": "Befehl $1",
+            "role": "Rolle:",
+            "select_role": "-- Wähle eine Rolle --"
+        }
+    },
     "verification": {
         "desc": "Dies sind die Verifizierungen für $1:",
         "explanation": "<h2>Wiki-Benutzer Verifizierung</h2>\n<p>Mit dem <code class=\"prefix\">verify &lt;Wiki-Benutzername&gt;</code>-Befehl können Discord-Benutzer sich selbst als ein bestimmter Wiki-Benutzer verifizieren mithilfe des Discord-Feldes auf deren Wiki-Profil. Falls der Benutzer übereinstimmt und Verifizierungen auf dem Server vorhanden sind, wird Wiki-Bot dem Benutzer die Rollen für alle Verifizierungs-Einträge geben, die der Benutzer erfüllt.</p>\n<p>Jeder Verifizierungs-Eintrag erlaubt mehrere Bedingungen, die der Wiki-Benutzer erreicht haben muss um die Verifizierung zu erfüllen:</p>\n<ul>\n<li>Kanal in dem der <code class=\"prefix\">verify</code>-Befehl genutzt werden muss.</li>\n<li>Discord-Rolle die vergeben wird, wenn der Benutzer die Verifizierung erfüllt.</li>\n<li>Mindestens benötigte Bearbeitungsanzahl auf dem Wiki um den Verifizierungs-Eintrag zu erfüllen.</li>\n<li>Benötigte Wiki-Benutzergruppe um den Verifizierungs-Eintrag zu erfüllen.</li>\n<li>Mindestalter des Wiki-Accounts in Tagen um den Verifizierungs-Eintrag zu erfüllen.</li>\n<li>Ob der Discord-Benutzername zu dem Wiki-Benutzernamen geändert werden soll, wenn der Benutzer die Verifizierung erfüllt.</li>\n</ul>",

+ 11 - 2
dashboard/i18n/en.json

@@ -96,6 +96,15 @@
             "text": "Please define settings for the server first.",
             "title": "Server not set up yet!"
         },
+        "noslash": {
+            "note": "Enable slash commands.",
+            "text": "The slash commands of Wiki-Bot are not enabled on this server.",
+            "title": "Slash commands are not enabled!"
+        },
+        "noverify": {
+            "text": "The restrictions for the $1 command can't be changed without verifications being set up.",
+            "title": "Verifications are not set up!"
+        },
         "readonly": {
             "text": "You can currently only view your settings, but not change them.",
             "title": "Read-only database!"
@@ -186,15 +195,15 @@
     },
     "slash": {
         "desc": "These are the slash commands for $1:",
-        "explanation": "<h2>Slash Commands</h2>\n<p>The usage of specific slash commands can be restricted per role or user. You can do that for the slash commands of Wiki-Bot here.</p>",
+        "explanation": "<h2>Slash Commands</h2>\n<p>The usage of specific slash commands can be restricted per role. You can do that for the slash commands of Wiki-Bot here.</p>",
         "form": {
             "add": "Add",
             "allow": "Allow",
+            "default": "Default",
             "default_allow": "By default this command is allowed to be used by everyone.",
             "default_deny": "By default this command is not allowed to be used by anyone.",
             "deny": "Deny",
             "entry": "Command $1",
-            "default": "Default",
             "role": "Role:",
             "select_role": "-- Select a Role --"
         }

+ 4 - 0
dashboard/i18n/hi.json

@@ -7,6 +7,10 @@
         " "
     ],
     "general": {
+        "botlist": {
+            "text": "बॉट सूचियों पर वोट करके Wiki-Bot को ढूँढ़ने में दूसरों की मदद करें:",
+            "title": "बॉट की सूचियाँ"
+        },
         "delete": "डिलीट करें",
         "invite": "Wiki-Bot को इनवाइट करें",
         "language": "भाषा बदलें",

+ 17 - 1
dashboard/i18n/pt-br.json

@@ -21,6 +21,7 @@
         "save": "Salvar",
         "selector": "Seletor de servidor",
         "settings": "Configurações",
+        "slash": "Comandos de slash",
         "support": "Servidor de suporte",
         "theme-dark": "Usar tema escuro",
         "theme-light": "Usar tema claro",
@@ -134,7 +135,7 @@
     },
     "rcscript": {
         "desc": "Estes são os webhooks de mudanças recentes para $1:",
-        "explanation": "<h2>Webhook de mudanças recentes</h2>\n<p>O Wiki-Bot é capaz de executar um webhook de mudanças recentes baseado no <a href=\"https://gitlab.com/piotrex43/RcGcDw\" target=\"_blank\">RcGcDw</a>. As mudanças recentes podem ser exibidas em mensagens de texto compactas com links embutidos ou mensagens incorporadas com etiquetas de edição e mudanças de categoria.</p>\n<p>Requisitos para adicionar um webhook de mudanças recentes:</p>\n<ul>\n<li>A wiki precisa estar no <a href=\"https://www.mediawiki.org/wiki/MediaWiki_1.30\" target=\"_blank\">MediaWiki 1.30</a> ou superior.</li>\n<li>A mensagem de sistema <code>MediaWiki:Custom-RcGcDw</code> precisa ser definida com o ID do servidor do Discord <code class=\"user-select\" id=\"server-id\"></code>.</li>\n</ul>",
+        "explanation": "<h2>Webhook de mudanças recentes</h2>\n<p>O Wiki-Bot é capaz de executar um webhook de mudanças recentes baseado no <a href=\"https://gitlab.com/piotrex43/RcGcDw\" target=\"_blank\">RcGcDw</a>. As mudanças recentes podem ser exibidas em mensagens de texto compactas com links embutidos ou mensagens incorporadas com etiquetas de edição e mudanças de categoria.</p>\n<p>Requisitos para adicionar um webhook de mudanças recentes:</p>\n<ul>\n<li>A wiki precisa estar no <a href=\"https://www.mediawiki.org/wiki/MediaWiki_1.30\" target=\"_blank\">MediaWiki 1.30</a> ou superior.</li>\n<li>A mensagem de sistema <code class=\"user-select\">MediaWiki:Custom-RcGcDw</code> precisa ser definida com o ID do servidor do Discord <code class=\"user-select\" id=\"server-id\"></code>.</li>\n</ul>",
         "form": {
             "channel": "Canal:",
             "confirm": "Tem certeza de que deseja excluir o webhook de mudanças recentes?",
@@ -183,6 +184,21 @@
         },
         "new": "Nova sobreposição de canal"
     },
+    "slash": {
+        "desc": "Estes são os comandos de slash para $1:",
+        "explanation": "<h2>Comandos slash</h2>\n<p>O uso de comandos de slash específicos pode ser restrito por função ou usuário. Você pode fazer isso para os comandos de slash do Wiki-Bot aqui.</p>",
+        "form": {
+            "add": "Adicionar",
+            "allow": "Permitir",
+            "default": "Padrão",
+            "default_allow": "Por padrão, este comando pode ser usado por todos.",
+            "default_deny": "Por padrão, este comando não pode ser usado por ninguém.",
+            "deny": "Negar",
+            "entry": "Comando $1",
+            "role": "Cargo:",
+            "select_role": "-- Selecionar cargo --"
+        }
+    },
     "verification": {
         "desc": "Estas são as verificações para $1:",
         "explanation": "<h2>Verificação de usuários</h2>\n<p>Usando o comando <code class=\"prefix\">verify &lt;wiki username&gt;</code>, os usuários podem verificar a si mesmos como um usuário específico do wiki usando o campo do Discord em seu perfil da wiki. Se o usuário corresponder e as verificações do usuário forem configuradas no servidor, o Wiki-Bot dará a ele as funções para todas as entradas de verificação que corresponderem.</p>\n<p>Cada entrada de verificação permite várias restrições sobre quando um usuário deve corresponder à verificação:</p>\n<ul>\n<li>Canal para usar o comando <code class=\"prefix\">verify</code>.</li>\n<li>Cargo obtido caso a entrada de verificação corresponda.</li>\n<li>Contagem de edições necessária na wiki para corresponder à entrada de verificação.</li>\n<li>Grupo de usuários obrigatório para ser um membro na wiki para corresponder à entrada de verificação.</li>\n<li>Idade necessária da conta em dias para corresponder à entrada de verificação.</li>\n<li>Se o apelido do usuário do Discord deve ser definido como o nome de usuário da wiki quando corresponder à entrada de verificação.</li>\n</ul>",

+ 17 - 1
dashboard/i18n/ru.json

@@ -21,6 +21,7 @@
         "save": "Сохранить",
         "selector": "Выбор Сервера",
         "settings": "Настройки",
+        "slash": "Слэш-Команды",
         "support": "Сервер Поддержки",
         "theme-dark": "Переключиться на тёмную тему",
         "theme-light": "Переключиться на светлую тему",
@@ -134,7 +135,7 @@
     },
     "rcscript": {
         "desc": "Вебхуки свежих правок на $1:",
-        "explanation": "<h2>Вебхук Свежих Правок</h2>\n<p>Вики-Бот может создавать вебхук свежих правок, основанный на <a href=\"https://gitlab.com/piotrex43/RcGcDw\" target=\"_blank\">RcGcDw</a>. Свежие правки могут отображаться как компактные текстовые сообщения со встроенными ссылками или встроенные сообщения с метками правок и изменениями категорий.</p>\n<p>Требования для создания нового вебхука свежих правок:</p>\n<ul>\n<li>Вики должна работать на <a href=\"https://www.mediawiki.org/wiki/MediaWiki_1.30\" target=\"_blank\">MediaWiki 1.30</a> или выше.</li>\n<li>Системное сообщение <code>MediaWiki:Custom-RcGcDw</code> должно содержать ID сервера: <code class=\"user-select\" id=\"server-id\"></code>.</li>\n</ul>",
+        "explanation": "<h2>Вебхук Свежих Правок</h2>\n<p>Вики-Бот может создавать вебхук свежих правок, основанный на <a href=\"https://gitlab.com/piotrex43/RcGcDw\" target=\"_blank\">RcGcDw</a>. Свежие правки могут отображаться как компактные текстовые сообщения со встроенными ссылками или встроенные сообщения с метками правок и изменениями категорий.</p>\n<p>Требования для создания нового вебхука свежих правок:</p>\n<ul>\n<li>Вики должна работать на <a href=\"https://www.mediawiki.org/wiki/MediaWiki_1.30\" target=\"_blank\">MediaWiki 1.30</a> или выше.</li>\n<li>Системное сообщение <code class=\"user-select\">MediaWiki:Custom-RcGcDw</code> должно содержать ID сервера: <code class=\"user-select\" id=\"server-id\"></code>.</li>\n</ul>",
         "form": {
             "channel": "Канал:",
             "confirm": "Вы действительно хотите удалить вебхук свежих правок?",
@@ -183,6 +184,21 @@
         },
         "new": "Новая перезапись настроек канала"
     },
+    "slash": {
+        "desc": "Слэш-Команды на $1:",
+        "explanation": "<h2>Слэш-Команды</h2>\n<p>Использование конкретных слэш-команд может быть ограничено по ролям. Здесь вы можете это сделать для слэш-команд Вики-Бота.</p>",
+        "form": {
+            "add": "Добавить",
+            "allow": "Разрешить",
+            "default": "По умолчанию",
+            "default_allow": "По умолчанию все могут пользоваться этой командой.",
+            "default_deny": "По умолчанию никто не может пользоваться этой командой.",
+            "deny": "Запретить",
+            "entry": "Команда $1",
+            "role": "Роль:",
+            "select_role": "-- Выберите Роль --"
+        }
+    },
     "verification": {
         "desc": "Верификации для $1:",
         "explanation": "<h2>Верификация Пользователей</h2>\n<p>Используя команду <code class=\"prefix\">verify &lt;имя пользователя на вики&gt;</code>, пользователи могут подтвердить, что их аккаунт Discord и их учётная запись на вики принадлежат им, используя поле \"Discord\" в вики-профиле. Если пользователи совпадают и верификации настроены на сервере, Вики-Бот назначит им роли за все верификации, под которые они подходят.</p>\n<p>Для каждой верификации можно настроить ограничения, которым должен следовать пользователь, чтобы подойти под верификацию:</p>\n<ul>\n<li>Канал, в котором можно использовать команду <code class=\"prefix\">verify</code>.</li>\n<li>Роль, которую получит пользователь при успешной верификации.</li>\n<li>Необходимое количество правок на вики для успешной верификации.</li>\n<li>Группа пользователей на вики, в которой необходимо состоять для успешной верификации.</li>\n<li>Необходимое время с момента создания аккаунта в днях для успешной верификации.</li>\n<li>Изменять ли никнейм пользователя Discord на имя участника на вики при успешной верификации.</li>\n</ul>",

+ 17 - 1
dashboard/i18n/zh-hans.json

@@ -21,6 +21,7 @@
         "save": "保存",
         "selector": "选择服务器",
         "settings": "设置",
+        "slash": "斜杠命令",
         "support": "支持服务器",
         "theme-dark": "使用酷黑主题",
         "theme-light": "使用明亮主题",
@@ -134,7 +135,7 @@
     },
     "rcscript": {
         "desc": "这些是 $1 的最近更改 webhook:",
-        "explanation": "<h2>最近更改 webhook</h2>\n<p>Wiki-Bot可以运行基于<a href=\"https://gitlab.com/piotrex43/RcGcDw\" target=\"_blank\">RcGcDw</a>的最近更改 webhook。最近更改可以以多种显示模式显示:有行内链接的紧凑型文字信息或有编辑标签和分类更改的嵌入式消息。</p>\n<p>添加最近更改 webhook 的基本要求:</p>\n<ul>\n<li>需要以<a href=\"https://www.mediawiki.org/wiki/MediaWiki_1.30\" target=\"_blank\">MediaWiki 1.30</a>或更高版本运行的 wiki。</li>\n<li>系统消息<code>MediaWiki:Custom-RcGcDw</code>需要设置为 Discord 服务器的服务器 ID <code class=\"user-select\" id=\"server-id\"></code>。</li>\n</ul>",
+        "explanation": "<h2>最近更改 webhook</h2>\n<p>Wiki-Bot可以运行基于<a href=\"https://gitlab.com/piotrex43/RcGcDw\" target=\"_blank\">RcGcDw</a>的最近更改 webhook。最近更改可以以多种显示模式显示:有行内链接的紧凑型文字信息或有编辑标签和分类更改的嵌入式消息。</p>\n<p>添加最近更改 webhook 的基本要求:</p>\n<ul>\n<li>需要以<a href=\"https://www.mediawiki.org/wiki/MediaWiki_1.30\" target=\"_blank\">MediaWiki 1.30</a>或更高版本运行的 wiki。</li>\n<li>系统消息<code class=\"user-select\">MediaWiki:Custom-RcGcDw</code>需要设置为 Discord 服务器的服务器 ID <code class=\"user-select\" id=\"server-id\"></code>。</li>\n</ul>",
         "form": {
             "channel": "频道:",
             "confirm": "你真的想删除最近更改 webhook 吗?",
@@ -183,6 +184,21 @@
         },
         "new": "新的频道覆写设置"
     },
+    "slash": {
+        "desc": "以下是$1的斜杠命令:",
+        "explanation": "<h2>斜杠命令</h2>\n<p>可以为每个身份组设置特定斜杠命令的使用限制。在此你可以设置 Wiki-Bot 斜杠命令的使用限制。</p>",
+        "form": {
+            "add": "添加",
+            "allow": "允许",
+            "default": "默认",
+            "default_allow": "默认情况下,此命令可被任何人使用。",
+            "default_deny": "默认情况下,此命令不允许任何人使用。",
+            "deny": "拒绝",
+            "entry": "命令 $1",
+            "role": "身份组:",
+            "select_role": "-- 选择身份组 --"
+        }
+    },
     "verification": {
         "desc": "这些是 $1 的验证方式:",
         "explanation": "<h2>用户验证</h2>\n<p>使用<code class=\"prefix\">verify &lt;wiki用户名&gt;</code>命令,用户可以将他们验证为特定的 wiki 用户,只需要他们在 wiki 个人资料的 Discord 栏位中填入自己的 Discord 即可。若验证结果匹配并且服务器设置了用户验证,那么 Wiki-Bot 就会对应所有与他们相匹配的验证项,给予相应的用户组。</p>\n<p>每条验证项都允许填入多条匹配条件:</p>\n<ul>\n<li>允许使用 <code class=\"prefix\">verify</code> 命令的频道。</li>\n<li>匹配该验证项时授予的身份组。</li>\n<li>匹配该验证项所需的编辑次数。</li>\n<li>匹配该验证项所需的 wiki 用户组。</li>\n<li>匹配该验证项所需的账号注册时长(单位为天)。</li>\n<li>匹配该验证项时是否将 Discord 用户的昵称设置为他们的 wiki 用户名。</li>\n</ul>",

+ 17 - 1
dashboard/i18n/zh-hant.json

@@ -21,6 +21,7 @@
         "save": "儲存",
         "selector": "選擇伺服器",
         "settings": "設定",
+        "slash": "斜槓指令",
         "support": "支援伺服器",
         "theme-dark": "使用灰暗主題",
         "theme-light": "使用明亮主題",
@@ -134,7 +135,7 @@
     },
     "rcscript": {
         "desc": "以下為 $1 的近期變更webhook:",
-        "explanation": "<h2>近期變更webhook</h2>\n<p>Wiki-Bot能運行基於<a href=\"https://gitlab.com/piotrex43/RcGcDw\" target=\"_blank\">RcGcDw</a>的近期變更webhook。近期變更可以以多種顯示模式顯示:包含行內連結的精簡文字訊息或包含圖片預覽及編輯差異的嵌入式訊息。</p>\n<p>加入近期變更webhook的基本需求:</p>\n<ul>\n<li>需要以<a href=\"https://www.mediawiki.org/wiki/MediaWiki_1.30\" target=\"_blank\">MediaWiki 1.30</a>或更高版本運行的wiki。</li>\n<li>系統訊息<code>MediaWiki:Custom-RcGcDw</code>需要設為Discord伺服器的伺服器id <code class=\"user-select\" id=\"server-id\"></code>。</li>\n</ul>",
+        "explanation": "<h2>近期變更webhook</h2>\n<p>Wiki-Bot能運行基於<a href=\"https://gitlab.com/piotrex43/RcGcDw\" target=\"_blank\">RcGcDw</a>的近期變更webhook。近期變更可以以多種顯示模式顯示:包含行內連結的精簡文字訊息或包含圖片預覽及編輯差異的嵌入式訊息。</p>\n<p>加入近期變更webhook的基本需求:</p>\n<ul>\n<li>需要以<a href=\"https://www.mediawiki.org/wiki/MediaWiki_1.30\" target=\"_blank\">MediaWiki 1.30</a>或更高版本運行的wiki。</li>\n<li>系統訊息<code class=\"user-select\">MediaWiki:Custom-RcGcDw</code>需要設為Discord伺服器的伺服器id <code class=\"user-select\" id=\"server-id\"></code>。</li>\n</ul>",
         "form": {
             "channel": "頻道:",
             "confirm": "您確定要刪除近期變更webhook嗎?",
@@ -183,6 +184,21 @@
         },
         "new": "新的頻道覆寫設定"
     },
+    "slash": {
+        "desc": "以下是$1的斜槓指令:",
+        "explanation": "<h2>斜槓指令</h2>\n<p>可以為每個身分組設定特定斜槓指令的使用限制。在此你可以設定Wiki-Bot斜槓指令的使用限制。</p>",
+        "form": {
+            "add": "新增",
+            "allow": "允許",
+            "default": "預設",
+            "default_allow": "預設情況下,此指令可被任何人使用。",
+            "default_deny": "預設情況下,此指令不允許被任何人使用。",
+            "deny": "拒絕",
+            "entry": "指令$1",
+            "role": "身分組:",
+            "select_role": "-- 選擇身分組 --"
+        }
+    },
     "verification": {
         "desc": "以下為 $1 的驗證方式:",
         "explanation": "<h2>使用者驗證功能</h2>\n<p>使用 <code class=\"prefix\">verify &lt;wiki使用者名稱&gt;</code> 指令時,使用者可以透過填寫wiki個人檔案的Discord欄位將自己的帳號驗證為特定的wiki使用者。若該伺服器有設定驗證功能且驗證條件相符,則Wiki-Bot會根據符合的驗證規則授與相對應的身分組。</p>\n<p>每項驗證規則都允許填入多個條件:</p>\n<ul>\n<li>允許使用 <code class=\"prefix\">verify</code> 指令的頻道。</li>\n<li>符合該驗證規則時需授予的身分組。</li>\n<li>符合該驗證規則所需的編輯次數。</li>\n<li>符合該驗證規則所需的wiki使用者群組。</li>\n<li>符合該驗證規則所需的帳號註冊時長(以天為單位)。</li>\n<li>符合該驗證規則時是否要將Discord使用者的暱稱變更為其wiki使用者名稱。</li>\n</ul>",

+ 1 - 0
dashboard/index.js

@@ -218,6 +218,7 @@ const server = http.createServer( (req, res) => {
 	let action = '';
 	if ( reqURL.searchParams.get('refresh') === 'success' ) action = 'refresh';
 	if ( reqURL.searchParams.get('refresh') === 'failed' ) action = 'refreshfail';
+	if ( reqURL.searchParams.get('slash') === 'noverify' ) action = 'noverify';
 	return dashboard(res, dashboardLang, themeCookie, sessionData.get(state), reqURL, action);
 } );
 

+ 2 - 9
dashboard/oauth.js

@@ -3,14 +3,7 @@ const cheerio = require('cheerio');
 const {defaultPermissions} = require('../util/default.json');
 const Wiki = require('../util/wiki.js');
 const allLangs = require('./i18n.js').allLangs().names;
-const {got, sessionData, settingsData, sendMsg, addWidgets, createNotice, hasPerm} = require('./util.js');
-
-const DiscordOauth2 = require('discord-oauth2');
-const oauth = new DiscordOauth2( {
-	clientId: process.env.bot,
-	clientSecret: process.env.secret,
-	redirectUri: process.env.dashboard
-} );
+const {got, oauth, sessionData, settingsData, sendMsg, addWidgets, createNotice, hasPerm} = require('./util.js');
 
 const file = require('fs').readFileSync('./dashboard/login.html');
 
@@ -151,7 +144,7 @@ function dashboard_oauth(res, state, searchParams, lastGuild) {
 					else settings.guilds.notMember.set(guilds[i].id, guilds[i]);
 				} );
 				settingsData.set(user.id, settings);
-				if ( searchParams.has('guild_id') ) {
+				if ( searchParams.has('guild_id') && !lastGuild.startsWith( searchParams.get('guild_id') + '/' ) ) {
 					lastGuild = searchParams.get('guild_id') + '/settings';
 				}
 				res.writeHead(302, {

+ 35 - 10
dashboard/slash.js

@@ -1,5 +1,5 @@
 const Lang = require('../util/i18n.js');
-const {got, db, slashCommands, sendMsg, createNotice, escapeText, hasPerm} = require('./util.js');
+const {got, db, slashCommands, sendMsg, createNotice, hasPerm} = require('./util.js');
 
 const fieldset = {
 	role: '<label for="wb-settings-addrole">Role:</label>'
@@ -120,17 +120,33 @@ function dashboard_slash(res, $, guild, args, dashboardLang) {
 			var permissions = [];
 			if ( response.statusCode !== 200 || !response.body ) {
 				if ( response.statusCode !== 404 || response.body?.message !== 'Unknown application command permissions' ) {
-					console.log( '- Dashboard: ' + response.statusCode + ': Error while getting the slash command permissions: ' + response.body?.message );
-					createNotice($, 'error', dashboardLang);
+					if ( response.statusCode === 403 && response.body?.message === 'Missing Access' ) {
+						createNotice($, 'noslash', dashboardLang, [guild.id]);
+					}
+					else {
+						console.log( '- Dashboard: ' + response.statusCode + ': Error while getting the slash command permissions: ' + response.body?.message );
+						createNotice($, 'error', dashboardLang);
+					}
 					$('#text .description').html(dashboardLang.get('slash.explanation'));
 					$('.channel#slash').addClass('selected');
 					return;
 				}
-				else if ( slashCommand.name === 'verify' ) {
-					res.writeHead(302, {Location: `/guild/${guild.id}/verification/new${suffix}`});
+				else if ( slashCommand.name === 'verify' ) return db.query( 'SELECT 1 FROM verification WHERE guild = $1 LIMIT 1', [guild.id] ).then( ({rows}) => {
+					if ( rows.length ) {
+						$('<p>').html(dashboardLang.get('slash.desc', true, $('<code>').text(guild.name))).appendTo('#text .description');
+						$(`.channel#channel-${slashCommand.id}`).addClass('selected');
+						createForm($, slashCommand, dashboardLang, permissions, guild.id, guild.roles).attr('action', `/guild/${guild.id}/slash/${slashCommand.id}`).appendTo('#text');
+						return;
+					}
+					res.writeHead(302, {Location: `/guild/${guild.id}/verification/new${suffix}` + ( suffix ? '&' : '?' ) + 'slash=noverify'});
 					res.end();
 					return true;
-				}
+				}, dberror => {
+					console.log( '- Dashboard: Error while checking for verifications: ' + dberror );
+					res.writeHead(302, {Location: `/guild/${guild.id}/verification/new${suffix}` + ( suffix ? '&' : '?' ) + 'slash=noverify'});
+					res.end();
+					return true;
+				} );
 			}
 			else permissions = response.body.permissions;
 			$('<p>').html(dashboardLang.get('slash.desc', true, $('<code>').text(guild.name))).appendTo('#text .description');
@@ -201,12 +217,22 @@ function update_slash(res, userSettings, guild, type, settings) {
 			timeout: 10000
 		} ).then( response=> {
 			if ( response.statusCode !== 200 || !response.body ) {
-				if ( response.statusCode !== 404 || response.body?.message !== 'Unknown application command permissions' ) {
+				if ( response.statusCode === 403 && response.body?.message === 'Missing Access' ) {
+					res(`/guild/${guild}/slash/${type}`, 'noslash', guild);
+					return Promise.reject();
+				}
+				else if ( response.statusCode !== 404 || response.body?.message !== 'Unknown application command permissions' ) {
 					console.log( '- Dashboard: ' + response.statusCode + ': Error while getting the old slash command permissions: ' + response.body?.message );
 				}
-				else if ( commandName === 'verify' ) {
+				else if ( commandName === 'verify' ) return db.query( 'SELECT 1 FROM verification WHERE guild = $1 LIMIT 1', [guild] ).then( ({rows}) => {
+					if ( rows.length ) return [];
+					res(`/guild/${guild}/verification/new`, 'noverify');
 					return Promise.reject();
-				}
+				}, dberror => {
+					console.log( '- Dashboard: Error while checking for verifications: ' + dberror );
+					res(`/guild/${guild}/verification/new`, 'noverify');
+					return Promise.reject();
+				} );
 				return [];
 			}
 			return response.body.permissions;
@@ -258,7 +284,6 @@ function update_slash(res, userSettings, guild, type, settings) {
 				console.log( '- Dashboard: Error while getting the old slash command permissions: ' + error );
 				return res(`/guild/${guild}/slash/${type}`, 'savefail');
 			}
-			return res(`/guild/${guild}/verification/new`, 'savefail');
 		} );
 	}, error => {
 		console.log( '- Dashboard: Error while getting the member: ' + error );

+ 1 - 4
dashboard/src/lang.js

@@ -25,9 +25,6 @@ else {
 	document.documentElement.classList.remove('theme-light');
 }
 
-var currentLang = ( document.cookie.split('; ').find( cookie => {
-	return cookie.split('=')[0] === 'language' && /^"[a-z\-]+"$/.test(( cookie.split('=')[1] || '' ));
-} ) || 'en' ).replace( /^language="([a-z\-]+)"$/, '$1' );
 var channellist = document.getElementById('channellist');
 var langSelector = document.createElement('div');
 langSelector.id = 'lang-selector';
@@ -41,7 +38,7 @@ langDropdown.setAttribute('style', `max-height: ${window.innerHeight - 80}px;`);
 var langOptions = Object.keys(allLangs).map( function(lang) {
 	var langOption = document.createElement('div');
 	langOption.textContent = allLangs[lang];
-	if ( currentLang === lang ) langOption.className = 'current';
+	if ( document.documentElement.lang === lang ) langOption.className = 'current';
 	langOption.onclick = function() {
 		document.cookie = `language="${lang}"; Path=/; Max-Age=31536000`;
 		location.reload();

+ 18 - 1
dashboard/util.js

@@ -11,6 +11,12 @@ const db = new Pool();
 db.on( 'error', dberror => {
 	console.log( '- Dashboard: Error while connecting to the database: ' + dberror );
 } );
+const DiscordOauth2 = require('discord-oauth2');
+const oauth = new DiscordOauth2( {
+	clientId: process.env.bot,
+	clientSecret: process.env.secret,
+	redirectUri: process.env.dashboard
+} );
 
 const slashCommands = require('../interactions/commands.json');
 
@@ -269,6 +275,17 @@ function createNotice($, notice, dashboardLang, args = []) {
 			title.text(dashboardLang.get('notice.invalidusergroup.title'));
 			text.text(dashboardLang.get('notice.invalidusergroup.text'));
 			break;
+		case 'noverify':
+			type = 'info';
+			title.text(dashboardLang.get('notice.noverify.title'));
+			text.html(dashboardLang.get('notice.noverify.text', true, $('<code>').text('/verify')));
+			break;
+		case 'noslash':
+			type = 'error';
+			title.text(dashboardLang.get('notice.noslash.title'));
+			text.text(dashboardLang.get('notice.noslash.text'));
+			note = $('<a target="_blank">').text(dashboardLang.get('notice.noslash.note')).attr('href', `https://discord.com/api/oauth2/authorize?client_id=${process.env.bot}&scope=applications.commands&guild_id=${args[0]}`);
+			break;
 		case 'wikiblocked':
 			type = 'error';
 			title.text(dashboardLang.get('notice.wikiblocked.title'));
@@ -358,4 +375,4 @@ function hasPerm(all = 0, ...permission) {
 	} ).every( perm => perm );
 }
 
-module.exports = {got, db, slashCommands, sessionData, settingsData, sendMsg, addWidgets, createNotice, escapeText, hasPerm};
+module.exports = {got, db, oauth, slashCommands, sessionData, settingsData, sendMsg, addWidgets, createNotice, escapeText, hasPerm};

+ 10 - 9
functions/verify.js

@@ -21,7 +21,7 @@ function verify(lang, channel, member, username, wiki, rows, old_username = '')
 		content: '', embed,
 		reaction: ''
 	};
-	return got.get( wiki + 'api.php?action=query&meta=siteinfo&siprop=general&list=users&usprop=blockinfo|groups|editcount|registration&ususers=' + encodeURIComponent( username ) + '&format=json' ).then( response => {
+	return got.get( wiki + 'api.php?action=query&meta=siteinfo&siprop=general&list=users&usprop=blockinfo|groups|editcount|registration|gender&ususers=' + encodeURIComponent( username ) + '&format=json' ).then( response => {
 		var body = response.body;
 		if ( body && body.warnings ) log_warn(body.warnings);
 		if ( response.statusCode !== 200 || body?.batchcomplete === undefined || !body?.query?.users ) {
@@ -55,7 +55,7 @@ function verify(lang, channel, member, username, wiki, rows, old_username = '')
 					result.content = lang.get('verify.user_missing_reply', escapeFormatting(username));
 					return;
 				}
-				return verify(lang, channel, member, wsbody.users[0].name.split(' '), wiki, rows, username);
+				return wsbody.users[0].name;
 			}, error => {
 				console.log( '- Error while searching the user: ' + error );
 				result.content = lang.get('verify.user_missing_reply', escapeFormatting(username));
@@ -181,7 +181,7 @@ function verify(lang, channel, member, username, wiki, rows, old_username = '')
 							comment.push(lang.get('verify.failed_rename', queryuser.gender));
 						} ));
 					}
-					return Promise.all(verify_promise).finally( () => {
+					return Promise.all(verify_promise).then( () => {
 						if ( channel.permissionsFor(channel.guild.me).has('EMBED_LINKS') ) {
 							if ( roles.length ) embed.addField( lang.get('verify.qualified'), roles.map( role => '<@&' + role + '>' ).join('\n') );
 							if ( missing.length ) embed.setColor('#008800').addField( lang.get('verify.qualified_error'), missing.map( role => '<@&' + role + '>' ).join('\n') );
@@ -193,7 +193,7 @@ function verify(lang, channel, member, username, wiki, rows, old_username = '')
 							if ( comment.length ) text += '\n\n' + comment.join('\n');
 						}
 						result.content = text;
-					} );
+					}, log_error );
 				}
 				
 				embed.setColor('#FFFF00').setDescription( lang.get('verify.user_matches', member.toString(), '[' + escapeFormatting(username) + '](' + pagelink + ')', queryuser.gender) );
@@ -280,7 +280,7 @@ function verify(lang, channel, member, username, wiki, rows, old_username = '')
 						comment.push(lang.get('verify.failed_rename', queryuser.gender));
 					} ));
 				}
-				return Promise.all(verify_promise).finally( () => {
+				return Promise.all(verify_promise).then( () => {
 					if ( channel.permissionsFor(channel.guild.me).has('EMBED_LINKS') ) {
 						if ( roles.length ) embed.addField( lang.get('verify.qualified'), roles.map( role => '<@&' + role + '>' ).join('\n') );
 						if ( missing.length ) embed.setColor('#008800').addField( lang.get('verify.qualified_error'), missing.map( role => '<@&' + role + '>' ).join('\n') );
@@ -292,7 +292,7 @@ function verify(lang, channel, member, username, wiki, rows, old_username = '')
 						if ( comment.length ) text += '\n\n' + comment.join('\n');
 					}
 					result.content = text;
-				} );
+				}, log_error );
 			}
 			
 			embed.setColor('#FFFF00').setDescription( lang.get('verify.user_matches', member.toString(), '[' + escapeFormatting(username) + '](' + pagelink + ')', queryuser.gender) );
@@ -306,9 +306,10 @@ function verify(lang, channel, member, username, wiki, rows, old_username = '')
 		console.log( '- Error while getting the user: ' + error );
 		embed.setColor('#000000').setDescription( lang.get('verify.error') );
 		result.content = lang.get('verify.error_reply');
-	} ).then( () => {
-		return result;
+	} ).then( new_username => {
+		if ( !new_username ) return result;
+		return verify(lang, channel, member, new_username, wiki, rows, username);
 	} );
 }
 
-module.exports = verify;
+module.exports = verify;

+ 6 - 0
i18n/de.json

@@ -393,6 +393,12 @@
         "pause": "**Ich bin auf diesem Server derzeit pausiert!**\nNur diese Befehle können ausgeführt werden:"
     },
     "interaction": {
+        "dashboard": {
+            "perm_allow": "Erlaubt",
+            "perm_default": "Standard",
+            "perm_deny": "Verboten",
+            "updated": "$1 hat die Berechtigungen für `$2` bearbeitet."
+        },
         "inline": "Bitte gebe einen Text mit [[Wikitext]]-Links an um diesen Befehl zu nutzen.",
         "nowiki": "Das genutzte Wiki existiert nicht!",
         "verify": "Bitte gebe deinen Wiki-Benutzernamen an um diesen Befehl dazu zu nutzen, deinen Discord-Account mit deinem Wiki-Account zu verifizieren und Rollen passend zu deinem Wiki-Account zu erhalten."

+ 1 - 1
i18n/en.json

@@ -395,8 +395,8 @@
     "interaction": {
         "dashboard": {
             "perm_allow": "Allow",
-            "perm_deny": "Deny",
             "perm_default": "Default",
+            "perm_deny": "Deny",
             "updated": "$1 updated the slash command permission overwrites for `$2`."
         },
         "inline": "Please provide some text with [[wikitext]] links to use this command.",

+ 4 - 1
i18n/hi.json

@@ -695,7 +695,10 @@
                 "years": "$1 साल"
             },
             "header": "$1 इस समय ब्लॉक्ड है!",
-            "indef_noreason": "$4 द्वारा $1 को बेमियादी ब्लॉक किया गया।"
+            "indef_noreason": "$4 द्वारा $1 को बेमियादी ब्लॉक किया गया।",
+            "indef_text": "$1 द्वारा $4 को कारण \"$5\" के साथ ब्लॉक किया गया।",
+            "noreason": "$4 द्वारा $1 को $3 तक $2 के लिए ब्लॉक किया गया।",
+            "text": "$4 द्वारा $1 को $3 तक कारण \"$5\" से $2 के लिए ब्लॉक किया गया।"
         },
         "gblock": {
             "disabled": "यह अकाउंट ग्लोबल रूप से ब्लॉक हो चुका है!",

+ 6 - 0
i18n/pt-br.json

@@ -393,6 +393,12 @@
         "pause": "**Estou atualmente em pausa neste servidor!**\nSom estes comandos podem ser executados:"
     },
     "interaction": {
+        "dashboard": {
+            "perm_allow": "Permitir",
+            "perm_default": "Padrão",
+            "perm_deny": "Negar",
+            "updated": "$1 atualizou as substituições de permissão do comando slash para `$2`."
+        },
         "inline": "Forneça algum texto com links de [[wikitexto]] para usar este comando.",
         "nowiki": "A wiki utilizada não existe!",
         "verify": "Por favor, forneça o seu nome de usuário na wiki para usar este comando e verificar a sua conta do Discord com a sua conta da wiki e obter cargos correspondentes à sua conta da wiki."

+ 8 - 1
i18n/ru.json

@@ -114,7 +114,7 @@
     "dateformat": "ru-RU",
     "diff": {
         "badrev": "отсутствует хотя бы одна из версий!",
-        "hidden": "*скрыто*",
+        "hidden": "*скрытая*",
         "info": {
             "added": "Добавлено:",
             "bytes": "$1 {{PLURAL:$2|байт|байта|байтов}} $3",
@@ -393,7 +393,14 @@
         "pause": "**Я в сейчас приостановлен на этом сервере!**\nМогут быть выполнены только эти команды:"
     },
     "interaction": {
+        "dashboard": {
+            "perm_allow": "Разрешить",
+            "perm_default": "По умолчанию",
+            "perm_deny": "Запретить",
+            "updated": "$1 обновил перезаписи разрешений на использование слэш-команды `$2`."
+        },
         "inline": "Чтобы использовать эту команду, предоставьте текст со ссылками в [[викитекст-разметке]].",
+        "nowiki": "Используемая вики не существует!",
         "verify": "Укажите ваше имя пользователя на вики через эту команду, чтобы подтвердить, что ваш аккаунт Discord и ваша учётная запись на вики принадлежат вам, и получить роли соответствующие вашей учётной записи на вики."
     },
     "invite": {

BIN
i18n/widgets/bn.png


BIN
i18n/widgets/de.png


BIN
i18n/widgets/en.png


BIN
i18n/widgets/es.png


BIN
i18n/widgets/fr.png


BIN
i18n/widgets/hi.png


BIN
i18n/widgets/it.png


BIN
i18n/widgets/ja.png


BIN
i18n/widgets/ko.png


BIN
i18n/widgets/nl.png


BIN
i18n/widgets/pl.png


BIN
i18n/widgets/pt-br.png


BIN
i18n/widgets/ru.png


BIN
i18n/widgets/th.png


BIN
i18n/widgets/tr.png


BIN
i18n/widgets/uk.png


BIN
i18n/widgets/vi.png


BIN
i18n/widgets/zh-hans.png


BIN
i18n/widgets/zh-hant.png


+ 7 - 1
i18n/zh-hans.json

@@ -393,6 +393,12 @@
         "pause": "**我目前处于暂停状态!**\n仅能使用以下命令:"
     },
     "interaction": {
+        "dashboard": {
+            "perm_allow": "允许",
+            "perm_default": "默认",
+            "perm_deny": "拒绝",
+            "updated": "$1更新了`$2`的斜杠命令权限覆写。"
+        },
         "inline": "请提供一些有 [[wiki 文本]] 的文字来使用此命令。",
         "nowiki": "所使用的 wiki 不存在!",
         "verify": "为了验证您的 Discord 与您的 wiki 账户相匹配并授予与您 wiki 账户相符合的身份组,请提供您的 wiki 用户名。"
@@ -786,7 +792,7 @@
         "help_fandom": "https://community.fandom.com/zh/wiki/Special:VerifyUser",
         "help_gamepedia": "https://help.fandom.com/zh/wiki/Gamepedia帮助Wiki:Discord验证",
         "help_guide": "请根据[此指导]($1)来添加您的 Discord 用户名至您的 wiki 资料页:",
-        "help_subpage": "请将您的 Discord 用户名($1)添加至您在 wiki 上的 `/Discord` 子页面:",
+        "help_subpage": "请将您的 Discord 用户名($1)添加至您在 wiki 上的 Discord 子页面:",
         "missing": "本频道无可用的验证方式。",
         "notice": "注意:",
         "qualified": "符合:",

+ 6 - 0
i18n/zh-hant.json

@@ -393,6 +393,12 @@
         "pause": "**我目前處於暫停狀態!**\n僅能使用以下指令:"
     },
     "interaction": {
+        "dashboard": {
+            "perm_allow": "允許",
+            "perm_default": "預設",
+            "perm_deny": "拒絕",
+            "updated": "$1更新了`$2`的斜槓指令權限覆寫。"
+        },
         "inline": "請提供一些有 [[wikitext]] 的文字來使用此指令。",
         "nowiki": "所使用的wiki不存在!",
         "verify": "為了能透過您的wiki帳號驗證您的Discord帳號與並授予與您wiki帳號相符的身分組,請提供您的wiki使用者名稱以使用此指令。"

+ 2 - 1
interactions/verify.js

@@ -25,6 +25,7 @@ function slash_verify(interaction, lang, wiki, channel) {
 			}
 		}
 	} ).catch(log_error);
+	console.log( interaction.guild_id + ': Slash: /' + interaction.data.name + ' ' + interaction.data.options?.[0]?.value );
 	if ( !channel.guild.me.permissions.has('MANAGE_ROLES') ) {
 		console.log( channel.guild.id + ': Missing permissions - MANAGE_ROLES' );
 		return interaction.client.api.interactions(interaction.id, interaction.token).callback.post( {
@@ -93,7 +94,7 @@ function slash_verify(interaction, lang, wiki, channel) {
 						else message.content = reply + lang.get('verify.error_reply');
 						message.embeds = [];
 					}
-					return sendMessage(interaction, message, channel);
+					return sendMessage(interaction, message);
 				}, error => {
 					console.log( '- Error during the verifications: ' + error );
 					return sendMessage(interaction, {

+ 1 - 1
util/functions.js

@@ -438,7 +438,7 @@ function allowDelete(msg, author) {
  * @param {Object} interaction - The interaction.
  * @param {Object} message - The message.
  * @param {String} message.content - The message content.
- * @param {{parse: String[], roles?: String[]}} message.allowed_mentions - The allowed mentions.
+ * @param {{parse: String[], roles?: String[], users?: String[]}} message.allowed_mentions - The allowed mentions.
  * @param {import('discord.js').TextChannel} [channel] - The channel for the interaction.
  */
 function sendMessage(interaction, message, channel) {