這個問題在這里已經有了答案: 使用 JavaScript 檢測文本中的 URL 13 個答案 3天前關閉。
我試圖讓我的機器人檢測來自特定人的訊息。如果此訊息是鏈接/影像/檔案,我希望它自動與指定的表情符號做出反應。
一切正常,除了“如果訊息是鏈接”。這似乎根本不起作用。我已經嘗試搜索檔案,但似乎找不到解決方案。
任何幫助表示贊賞!
client.on('messageCreate', message => {
if (message.author.id === '217900978756780032') { //works
if (message.content.includes("https://")) { //does NOT work
if (message.attachments.size > 0) { //works
message.react('<:facebook:1009793997872562287>')
message.react('<a:siren:886047171768635432>')
}}}
})
uj5u.com熱心網友回復:
此解決方案使用正則運算式來檢查鏈接是否為http[s]鏈接并在以下條件下進行驗證:
- 鏈接以http開頭
- 鏈接在 :// 之后有內容
此外,為了更好的實踐,您應該使用我在下面插入您的代碼中的Guard Clauses來撰寫更清晰的代碼。
client.on('messageCreate', message => {
if (message.author.id !== '217900978756780032') return;
const isLink = new RegExp(/https?:\/\/\S /g).test(message.content);
if (!isLink) return;
if (message.attachments.size > 0) return;
message.react('<:facebook:1009793997872562287>');
message.react('<a:siren:886047171768635432>');
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/512667.html
