Discord-бот, использующий js - PullRequest
       8

Discord-бот, использующий js

0 голосов
/ 10 сентября 2018

Я использую Nedb для этого бота. Мне нужно закончить функцию к определенной дате, она должна загрузить и сохранить все разговоры для человека, который является моей целью. для всех сообщений мне нужно проверить, существует ли уже в базе данных с edited_date меньше, чем. если таковые не существуют, то вставьте. Кто-нибудь может мне помочь? Я действительно отчаянно пытаюсь понять это

const fetch = require('node-fetch');
const moment = require('moment');
const config = require('./config');
const querystring = require("querystring");
var Datastore = require('nedb');

var db = new Datastore({ filename: 'discord.db', autoload: true });
const TO_DAYS      = 4194304 * 1000 * 60 * 60 * 24;
const ROOT_DATE    = moment([2018, 3, 30]);
const ROOT_DATE_ID = 440557948108800000;

// this inserts scott into the database
// var scott = {
//   name: 'Scott',
//   twitter: '@ScottWRobinson'
// };
// db.insert(scott, function (err, doc) {
//   console.log('Inserted', doc.name, 'with ID', doc._id);
// });


// this finds all items in the database and prints them.  
// db.find({}).exec(function (err, docs) {
//     console.log(docs);
//     docs.forEach(function (d) {
//         console.log('Found user:', d.name);
//     });
// });


const DATE_ID = function (date) {
    return ROOT_DATE_ID + date.diff(ROOT_DATE, "days") * TO_DAYS;
}

class discordApi {
  constructor() {}
  // this function sends a request to discords servers, and pulls down JSON
  get(momentDate, authorId, offset = 0) {
    const url =
      config.endpoint +
      querystring.stringify({
        min_id: DATE_ID(momentDate),
        author_id: authorId
      });
    return fetch(url, {
      headers: {
        method: "GET",
        Authorization: config.auth
      }
    }).then(res => {
      console.log(res.url);
      return res.json();
    });
  }
  // TODO finish this function.  for a specific date, it should download and save all the conversations for a person.
  // for all messages, check if already exist in database with edited_date less than.
  // if any do not exist, then insert.
  sync(momentDate) {
    // for this date, get all the messages from targets.
    config.targets.map(author_id => {
      this.get(momentDate, author_id).then(({ total_results, messages }) => {
        console.log(messages);
        messages.map(conversation => {
          conversation.map(({ attachments, author, content, timestamp }) => {
            console.log(timestamp, author.username, content);
          });
        });
      });
    });
  }
}

module.exports = new discordApi();

1 Ответ

0 голосов
/ 13 сентября 2018

Я не знаю много о недб, но вы, похоже, в основном ответили на свой вопрос.

Запросите в БД все результаты по вашей цели.

Создайте флаг, инициализированный как false, итерируйте по всем возвращенным записям, если они соответствуют критериям даты, установите флаг в true.

Тогда, если флаг все еще ложен, создайте запись в БД.

...