簡體   English   中英

Discord Bot - 從網站下載 JSON 文件並提取其中的某些元素

[英]Discord Bot - Downloading JSON file from a website and extract certain elements of it

我正在處理一個命令,該命令將每天自動從鏈接中獲取一個文件並提取其中的兩個元素並將其作為消息發送到頻道中。

我的問題是我在實際下載文件時遇到了問題。 我一直在嘗試幾種不同的函數來獲取文件,但到目前為止沒有任何效果。 我附上了我在下面嘗試過的功能之一。

async function getQuote () {
        const url = "https://quotes.rest/qod?category=inspire";
        const path = Path.resolve(__dirname, 'temp', 'qod.json')
        const writer = fs.CreateWriteStream(path)

        const response = await axios({
            url,
            method: 'GET',
            responseType: 'stream'
        })

        response.data.pipe(writer)

        getQuote();

        return new Promise((resolve, reject) => {
            writer.on('finish', resolve)
            writer.on('error', reject)
        })
        }


            fs.readFile('./temp/qod.json', 'utf8', function (err, data) {
                if (err) throw err;
                var obj = JSON.parse(data);
                msg.channel.send(data);
    })

我在這里嘗試使用的文件如下所示:

{
    "success": {
        "total": 1
    },
    "contents": {
        "quotes": [
            {
                "quote": "What you do speaks so loudly that I cannot hear what you say.",
                "length": "61",
                "author": "Ralph Waldo Emerson",
                "tags": [
                    "action",
                    "inspire",
                    "leadership",
                    "management",
                    "tod"
                ],
                "category": "inspire",
                "language": "en",
                "date": "2020-08-23",
                "permalink": "https://theysaidso.com/quote/ralph-waldo-emerson-what-you-do-speaks-so-loudly-that-i-cannot-hear-what-you-say",
                "id": "eZ0NtMPtGp8c5eQJOBfJmweF",
                "background": "https://theysaidso.com/img/qod/qod-inspire.jpg",
                "title": "Inspiring Quote of the day"
            }
        ]
    },
    "baseurl": "https://theysaidso.com",
    "copyright": {
        "year": 2022,
        "url": "https://theysaidso.com"
    }
}

它想下載為json文件,但訪問鏈接時,它被列為xml文件。

我將如何下載並從中提取兩行? 如果您想知道,這兩行是引用行和作者行。

謝謝!

我建議簡單地讀取對象的引用,然后使用插值創建一個字符串並將其發送到不和諧頻道:

async function getQuote () {
    const url = "https://quotes.rest/qod?category=inspire";

    console.log("getQuote: Reading quote...");

    // Get the response as an object
    const response = await axios({
        url,
        method: 'GET'
    })

    // Use destructuring to get the quote and author
    let { quote, author } = response.data.contents.quotes[0];
    
    // Format our quote
    let data = `${quote} - ${author}`;
    
    // Add a console.log for debugging purposes..
    console.log("getQuote: Sending quote:", data);

    // Send the quote on the channel
    msg.channel.send(data);
}

今天的報價將如下所示:

Limitations are like mirages created by your own mind. When you realise that limitation do not exist, those around you will also feel it and allow you inside their space.  - Stephen Richards

我復制你的代碼並運行我的本地機器,一切都很好。

限制就像是你自己的頭腦創造的海市蜃樓。 當你意識到限制不存在時,你周圍的人也會感覺到它並允許你進入他們的空間。 ——斯蒂芬·理查茲

看起來您正在嘗試將結果寫入文件,然后從效率不高的文件中讀取。 這是一個更簡單的方法。

 async function getQuote() { const url = "https://quotes.rest/qod?category=inspire"; const response = await axios(url); const result = response.data; /* result = { "success": { "total": 1 }, "contents": { "quotes": [ { "quote": "Limitations are like mirages created by your own mind. When you realise that limitation do not exist, those around you will also feel it and allow you inside their space. ", "length": "171", "author": "Stephen Richards", "tags": [ "inspire", "motivational", "positive-thinking", "self-empowerment", "self-help", "self-improvement", "wealth", "wealth-creation" ], "category": "inspire", "language": "en", "date": "2020-08-24", "permalink": "https://theysaidso.com/quote/stephen-richards-limitations-are-like-mirages-created-by-your-own-mind-when-you", "id": "OLSVpLiSwrWplvCcFgPPiweF", "background": "https://theysaidso.com/img/qod/qod-inspire.jpg", "title": "Inspiring Quote of the day" } ] }, "baseurl": "https://theysaidso.com", "copyright": { "year": 2022, "url": "https://theysaidso.com" } } */ //this is an array of quote objects const quotes = result.contents.quotes; //extracting first quote object from the array const quoteObject = quotes[0]; //extracting quote text and author from quote object const quote = quoteObject.quote; const author = quoteObject.author; //the >>> will make it look like a quote in discord. console.log(`>>> ${quote}\\n- ${author}`); //send the formatted quote to the channel msg.channel.send(`>>> ${quote}\\n- ${author}`); //if for some reason you want to save the result to a file fs.writeFile(filePath, result, function(err) { if (err) throw err; console.log('Saved!'); }); } getQuote();
 <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM