« 上一篇下一篇 »

Telegram Bot 连接Mongo DB 数据库, 超酷超好用的JSON数据库, 不需要学SQL啦[第七集]

本视频是Telegram Bot 机器人编程系列的第七集。 本集介绍如何在谷歌 Google App Scripts 中使用Mongo Db 数据库。 Mongo DB做为文档数据库, 数据的格式为JSON, 也就是和我们机器人处理的消息是同样的格式, 非常的方便, 而且大家也不用学SQL啦。


mongo express 建站代码(可选)

docker run -it --rm  ^

    --name mongo-express  ^

    -p 8082:8081  ^

    -e ME_CONFIG_MONGODB_PORT="端口"  ^

    -e ME_CONFIG_MONGODB_SERVER="服务器链接"       ^

    -e ME_CONFIG_MONGODB_AUTH_DATABASE="mongo" ^

    -e ME_CONFIG_MONGODB_AUTH_USERNAME="用户名" ^

    -e ME_CONFIG_MONGODB_AUTH_PASSWORD="密码" ^

    -e ME_CONFIG_MONGODB_ENABLE_ADMIN="false" ^

    mongo-express



代码.gs

function doGet(e){

  return HtmlService.createHtmlOutput("Hello World!! No, this link should be hidden!!!");

   

 //  return HtmlService.createHtmlOutputFromFile('Index');

}

 

 

function doPost(e){

  var body = JSON.parse(e.postData.contents);

   

  body.message.chat.id = body.message.chat.id + '';

  mongo.insert(logColl, body);

 

  var payload = preparePayload(body);

  var data = {    

    "method": "post",

    "contentType": 'application/json',

    "payload": JSON.stringify(payload),

  }

   

  mongo.insert("to-telegram", payload);

   

  UrlFetchApp.fetch("https://api.telegram.org/bot这里放机器人的token/", data);

}

 

function getName(user) {

  var name = user.first_name;

  if (user.last_name) {

    name += " " + user.last_name;

  }

 

  return name;

}

 

function escapeMarkDown(toEscapeMsg) {

  var escapedMsg = toEscapeMsg

  .replace(/_/g, "\\_")

  .replace(/\*/g, "\\*")

  .replace(/\[/g, "\\[")

  .replace(/`/g, "\\`");

    return escapedMsg;

 

}

 

 

function getMentionName(user) {

  var username = user.username;

  var mentionName = "";

 

  var name = getName(user);

  if (!name) {

    name = "神秘人";

  }

 

  // if (!username) {

    mentionName = getMarkDownUserUrl(escapeMarkDown(name), user.id);

  // } else {

  //   mentionName = "[" + escapeMarkDown(name) + "](@" + escapeMarkDown(username) + ")";

  // }

 

  return mentionName;

}

 

function getMarkDownUserUrl(userName, userId) {

  return "[" + userName + "](tg://user?id=" + userId + ")";

}

 

 

function preparePayload(body){

  var payload;

   

  if (body.message.new_chat_member) {

     payload = {

        "method": "sendMessage",

        "chat_id": body.message.chat.id,

        "text": "你好, 欢迎加入本群",

        "parse_mode": "Markdown",

        "disable_web_page_preview": true,

      } 

       

      payload.text = "你好!" + getMentionName(body.message.new_chat_member) + ", 欢迎加入本群";

      return payload;

  }

   

  if (body.message.left_chat_member) {

     payload = {

        "method": "sendMessage",

        "chat_id": body.message.chat.id,

        "text": "你好, 欢迎加入本群",

        "parse_mode": "Markdown",

        "disable_web_page_preview": true,

      } 

       

      payload.text = getMentionName(body.message.left_chat_member) + "君, 一路走好!";

      return payload;

  }

   

   if (body.message.pinned_message) {

    payload = {

        "method": "sendMessage",

        "chat_id": body.message.chat.id,

        "text": "你好, 欢迎加入本群",

        "parse_mode": "Markdown",

        "disable_web_page_preview": true,

      } 

    var whoPinned = getName(body.message.from);

    var whoOwned = getName(body.message.pinned_message.from);

 

    payload.text = whoPinned + "置顶了消息:\n\n" + body.message.pinned_message.text

      + "\n\n"

      + "本BOT代表" + whoOwned + "感谢您"

      ;

    return payload;

  }

 

 

  body.message.text = body.message.text.toLowerCase();

  body.message.text = body.message.text.replace(/@temptestbot2/g, '');

   

  var paras = body.message.text.trim().split(" ");

  // remove empty strings

  paras = paras.filter(function(para){

    if (para){

      return true;

    }

  });

   

   

   

  if (body.message.text){

   

      payload = {

        "method": "sendMessage",

        "chat_id": body.message.chat.id,

        "text": "你好, 欢迎使用本机器人, 本机器人现在只认识颜色。",

        "parse_mode": "Markdown",

        "disable_web_page_preview": true,

      } 

       

      if(body.message.text.indexOf("/help") === 0){      

         payload.text = "你好, 欢迎使用本机器人, 本机器人现在只认识颜色。";

         return payload;

      }

       

      if(body.message.text.indexOf("/colors") === 0){   

         payload.text = "红\n黄\n蓝";        

         return payload;

      }

       

      if(body.message.text.indexOf("/list") === 0){ 

         if (paras[1]){

           switch (paras[1].toLowerCase()){

             case "people":  

               if (paras[2]){

                 if ("JS神技能".toLowerCase().indexOf(paras[2]) >= 0){

                   payload.text = "JS神技能 - https://www.youtube.com/";

                 }

                 if ("悟空的日常".toLowerCase().indexOf(paras[2]) >= 0){

                   payload.text = "悟空的日常 - https://www.youtube.com/";

                 }

                 if ("YuFeng Deng".toLowerCase().indexOf(paras[2]) >= 0){

                   payload.text = "YuFeng Deng - https://www.youtube.com/";

                 }

               } else {                 

                 payload.text = "JS神技能\n"

                   + "悟空的日常\n"

                   + "YuFeng Deng\n";        

                   return payload;

                }

               break;

             default:  

               payload.text = "红\n黄\n蓝";            

             break;

           }

                 

           return payload;

         } else {         

           payload.text = "*JS神技能*\n"

             + "[悟空的日常](https://www.youtube.com)\n"

             + "[*YuFeng Deng*](https://www.youtube.com/)\n"

             + "_YuFeng Deng_\n"

             + "`01|" + "UCii04BCvYIdQvshrdNDAcww" + " | `\n"

             + "`02|" + "UCG6xoef2xU86hnrCsS5m5Cw" + " | `\n"

             + "```javascript\n"

             + 'payload = {\n'

             + '    "method": "sendMessage",\n'

             + '    "chat_id": body.message.chat.id,\n'

             + '    "text": body.message.text,\n'

             + '}'

             + "```"

             ;

                        

            var inlineKeyboardMarkup = {};

            inlineKeyboardMarkup.inline_keyboard = [];

            var keyboardRow = [];

            var keyboardButton1 = {

                text: "按钮1",

                url: "https://www.google.com"

            };

             

            var keyboardButton2 = {

                text: "按钮2",

                url: "https://www.google.com"

            };

             

            var keyboardRow2 = [];

            var keyboardButton3 = {

                text: "按钮3",

                url: "https://www.google.com"

            };

             

            var keyboardButton4 = {

                text: "按钮4",

                url: "https://www.google.com"

            };

 

            keyboardRow.push(keyboardButton1);

            keyboardRow.push(keyboardButton2);

             

            keyboardRow2.push(keyboardButton3);

            keyboardRow2.push(keyboardButton4);

            inlineKeyboardMarkup.inline_keyboard.push(keyboardRow);

            inlineKeyboardMarkup.inline_keyboard.push(keyboardRow2);

            payload.reply_markup = inlineKeyboardMarkup;

 

        

           return payload;

         }

      }

       

 

   

      payload = {

          "method": "sendMessage",

          "chat_id": body.message.chat.id,

          "text": body.message.text,

      } 

     

  }

  else if (body.message.sticker){

    payload = {

      "method": "sendSticker",

      "chat_id": body.message.chat.id,

      "sticker": body.message.sticker.file_id

    }

   }

  else if (body.message.photo){

    array = body.message.photo;

    text = array[1];

    payload = {

      "method": "sendPhoto",

      "chat_id": body.message.chat.id,

      "photo": text.file_id

    }

   }

    else {

    payload = {

      "method": "sendMessage",

      "chat_id": body.message.chat.id,

      "text": "Try other stuff"

    }

   }

  return payload

}


代码Test.gs

var testList = '{"update_id":427274836,"message":{"message_id":173,"from":{"id":539065210,"is_bot":false,"first_name":"Yufeng Deng","last_name":"峰哥","username":"fennng","language_code":"en-US"},"chat":{"id":539065210,"first_name":"Yufeng Deng","last_name":"峰哥","username":"fennng","type":"private"},"date":1538193751,"text":"/list","entities":[{"offset":0,"length":5,"type":"bot_command"}]}}';

var testList2 = '{"update_id":427275035,"message":{"message_id":211,"from":{"id":539065210,"is_bot":false,"first_name":"Yufeng Deng","last_name":"峰哥","username":"fennng","language_code":"en-US"},"chat":{"id":"539065210","first_name":"Yufeng Deng","last_name":"峰哥","username":"fennng","type":"private"},"date":1540807486,"text":"/list","entities":[{"offset":0,"length":5,"type":"bot_command"}]}}';

var isDebug = false;

 

function debug() {

  e = {};

  e.postData = {};

  e.postData.contents = testList2;

  doPost(e);

}


代码MLab.gs

var baseUrl = "https://api.mlab.com/api/1/";

var dbUrl = baseUrl + "databases/mongo/";

var collectionUrl = dbUrl + "collections/";

 

var logColl = "logs";

 

var mongo = {};

 

function debugMLab(){

  debug();

}

 

function testMLab(){

 

  var testObject = {"name": "峰哥"};

  mongo.insert(logColl, testObject);

 

}

 

function testMLab2() {

  var query = {"message.from.id": 539065210};

  var q = JSON.stringify(query);

  var a = mongo.get(logColl, "q=" + q);

  var b = a[0];

  Logger.log(a);

}

 

 

function testMLab3() {

  mongo.put(logColl, null, []);

}

 

mongo.insert = function(collection, data) {

  var db = apendAPI(collectionUrl + collection);

  var option = getInsertOption(data);

   Logger.log(data);

  var response = UrlFetchApp.fetch(db, option);

//  Logger.log(response);

   Logger.log(data);

}

 

mongo.update = function(collection, query, set) {

  var db = apendAPI(collectionUrl + collection);

  db += "&" + query + "&m=true&u=true";

  var option = getPutOption(set);

  UrlFetchApp.fetch(db, option);

}

 

// Warning, put will override the whole collectoin, put empty array data will clear the whole collection

mongo.put = function(collection, query, data) {

  var db = apendAPI(collectionUrl + collection);

  if (query){

    db += "&" + query;

  }

  var option = getPutOption(data);

  var url = encodeURI(db);

  UrlFetchApp.fetch(url, option);

}

mongo.get = function(collection, query) {

  var db = apendAPI(collectionUrl + collection);

 

  if (query){

    db += "&" + query;

  }

 

  var option = getGetOption();

  var response = UrlFetchApp.fetch(encodeURI(db), option);

 

  return JSON.parse(response);

}

 

function apendAPI(url){

  return url + "?apiKey=WULdZqaqxqikzrGePcLC5uWBeyvGZqBp";

}

 

 

function getInsertOption(data){

  var option = {

    "method": "post",

    'contentType': 'application/json',

//    "muteHttpExceptions": true, 

    "payload": JSON.stringify(data)

  }

  return option;

}

function getPutOption(data){

  var option = {

    "method": "put",

    'contentType': 'application/json',

    "payload": JSON.stringify(data)

  }

  return option;

}

function getGetOption(){

  var option = {

    "method": "get",

  }

  return option;

}