app.js 3.63 KB
const TelegramBot = require('node-telegram-bot-api');
const express = require('express');
const app = express();
const mongoose = require('mongoose');

const token = 'your bot token';
const db = require('./config').mongoURI;

const User = require('./models/User');
// Bot
const bot = new TelegramBot(token, { polling: true });

// connect to mongoDB
mongoose
    .connect(db, { useNewUrlParser: true })
    // { useCreateIndex: true, useUnifiedTopology: true, useNewUrlParser: true, useUnifiedTopology: true }
    .then(() => console.log("MongoDB Connected"))
    .catch(err => console.log(err));

// start
bot.onText(/\/start/, msg => {
    const chatId = msg.chat.id;
    bot.sendMessage(chatId, "Welcome");
});

// do
bot.onText(/\/todo/, msg => {
    let todo = msg.text
        .split(' ')
        .slice(1)
        .join(' ');

    if (!todo) {
        return bot.sendMessage(msg.chat.id, "please input your todo item.");
    }

    User.findOne({ user: msg.chat.username })
        .then(user => {
            if (!user) {
                //creat new
                const newUser = new User({
                    user: msg.chat.username,
                    todos: [todo]
                });

                //save newuser
                newUser.save()
                    .then(console.log('New User Saved'))
                    .catch(err => console.log(err));
            }
            else {
                ///add new item
                user.todos.push(todo);
                User.update(
                    { user: user.user },
                    { $set: { todos: user.todos } },
                    (err, raw) => {
                        if (err) return console.log(err);
                        console.log("Success Added new item");
                    }); // there user => moudule key user: findOne user.findOne user key(Schema users config)
            }
        });
    bot.sendMessage(msg.chat.id, "You success added a item");
});

// list 
bot.onText(/\/list/, msg => {
    User.findOne({ user: msg.chat.username }).then(user => {
        if (!user) {
            return bot.sendMessage(msg.chat.id, "you haven\t added a item.")
        }
        else {
            if (user.todos.length === 0) return bot.sendMessage(msg.chat.id, 'You already done all!');

            let todoList = "";
            user.todos.forEach((todo, index) => {
                todoList += `[${index}] - ` + todo + "\n";
            });
            return bot.sendMessage(msg.chat.id, `your list: \n\n ${todoList}`);
        }
    });
});

/// Check
bot.onText(/\/check/, msg => {
    User.findOne({ user: msg.chat.username }).then(user => {
        if (!user) {
            return bot.sendMessage(msg.chat.id, "you haven\t added a item.")
        }
        else {
            if (user.todos.length === 0) return bot.sendMessage(msg.chat.id, 'You already done all!');
            let num = msg.text.split(' ')[1];

            // No num passed in
            if (!num) {
                return bot.sendMessage(
                    msg.chat.id,
                    "Please input the number."
                );
            }

            // wrong num
            if (num >= user.todos.length || num < 0) {
                return bot.sendMessage(
                    msg.chat.id,
                    "There's no item with the number, please type /list and check it."
                );
            }

            //Remove todo from mongoDB
            user.todos.splice(num, 1);
            User.update({ user: user.user }, { $set: { todos: user.todos } }, (err, raw) => {
                if (err) return console.log(err);
                bot.sendMessage(msg.chat.id, "Done.");
            });
        }
    })
})