[英]How to use discord.js in HTML
我正在嘗試制作一個 discord.js 儀表板,但實際上我無法使用 discord.js 庫並將其與客戶端連接
這是我的 javascript 代碼(項目是 node.js 使用 express 發送一個 HTML 文件)
const express = require('express');
const bodyparser = require('body-parser')
const app = express();
const path = require('path');
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/home.html'))
});
app.use(bodyparser.text())
app.listen(3000, () => {
console.log('server started');
});
還有我的 HTML 代碼
<!DOCTYPE html>
<html>
<head>
<style>
@import url('https://fonts.googleapis.com/css2?family=Prompt:ital,wght@1,200&display=swap');
#title {
font-family: 'Prompt', sans-serif;
text-align: center;
}
</style>
</head>
<body>
<h1 id="title">Bot Dashboard</h1>
<p id="join">Join our discord!</p>
<iframe src="Removed Widget URL" width="350" height="200" allowtransparency="true" frameborder="0" sandbox="allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts"></iframe>
<button id="sendtest" onclick="">Send a test</button>
</body>
</html>
我想讓測試按鈕在頻道中發送消息(我只需要一個可以在 node.js 中執行的 function)。 “onclick”中會有什么?
如果您的 Express 服務器可以訪問您的 discord.js 客戶端 object,您可以從瀏覽器向 Express 發送 HTTP 請求,它可以將您的機器人信息發回。
在您的 HTML 文件中:
<!DOCTYPE html>
<html>
<head>
<style>
@import url('https://fonts.googleapis.com/css2?family=Prompt:ital,wght@1,200&display=swap');
#title {
font-family: 'Prompt', sans-serif;
text-align: center;
}
</style>
<script>
const buttonText = document.getElementById("buttontext");
function botTest() {
fetch("https://localhost:3000/test")
.then(() => response.json())
.then((data) => buttonText.innerText = `The bot's tag is ${data.tag}`);
}
</script>
</head>
<body>
<h1 id="title">Bot Dashboard</h1>
<p id="join">Join our discord!</p>
<iframe src="Removed Widget URL" width="350" height="200" allowtransparency="true" frameborder="0" sandbox="allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts"></iframe>
<button onclick="botTest()">Send a test</button>
<p id="buttontext">Click the button!</p>
</body>
</html>
在您的 Express 文件中:
const express = require('express');
const bodyparser = require('body-parser')
const app = express();
const path = require('path');
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/home.html'))
});
app.get('/test', (req, res) => {
// make sure your discord.js client is available somewhere in this file
res.json({
tag: client.user.tag
});
});
app.use(bodyparser.text())
app.listen(3000, () => {
console.log('server started');
});
確保您的 discord.js 客戶端在文件中的某處可用。 這可以是從您的 index.js 文件或任何具有您的 Client 實例並使用module.exports
導出它的文件的導入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.