Full Code of fengnz/fengdoorbot for AI

master d51e4ca37033 cached
44 files
112.1 KB
29.9k tokens
104 symbols
1 requests
Download .txt
Repository: fengnz/fengdoorbot
Branch: master
Commit: d51e4ca37033
Files: 44
Total size: 112.1 KB

Directory structure:
gitextract_0p3i69f1/

├── .clasp.json
├── .claspignore
├── .eslintrc.json
├── .gitignore
├── Array.js
├── Automated.js
├── Code.js
├── Common.js
├── Const.js
├── Context.js
├── Database.js
├── Get.js
├── Group.js
├── HandleAdminCommand.js
├── HandleBanCommand.js
├── HandleCallback.js
├── HandleDelMsgCommand.js
├── HandleHelpCommand.js
├── HandleMessage.js
├── HandleMessageText.js
├── HandleNoCommandAndAlias.js
├── HandleNotRobotCommand.js
├── HandlePinMessageCommand.js
├── HandleStartCommand.js
├── Index.html
├── InlineKeyboard.js
├── LICENSE
├── Mlab.js
├── Mongo.js
├── NewMember.js
├── Permission.js
├── PreparePayload.js
├── README.md
├── TelegramAPI.js
├── TelegramChat.js
├── Test.js
├── appsscript.json
├── handleInitDBCommad.js
├── jsconfig.json
├── live.sh
├── package.json
├── run.sh
├── testData.js
└── tsconfig.json

================================================
FILE CONTENTS
================================================

================================================
FILE: .clasp.json
================================================
{"scriptId":"1AnlIDvTvtwN2hkfaUJyNgSObogAF7PyPao6gwDqq8nupnQUHPqO6SLlS"}


================================================
FILE: .claspignore
================================================
jsconfig.json
tsconfig.json
.gitignore
node_modules/**

================================================
FILE: .eslintrc.json
================================================
{
    "env": {
        "browser": true
    },
    "extends": "eslint:recommended",
    "parserOptions": {
        "ecmaVersion": 3
    },
    "rules": {
        "accessor-pairs": "error",
        "array-bracket-newline": "off",
        "array-bracket-spacing": [
            "error",
            "never"
        ],
        "array-callback-return": "off",
        "array-element-newline": "off",
        "arrow-body-style": "error",
        "arrow-parens": "error",
        "arrow-spacing": "error",
        "block-scoped-var": "off",
        "block-spacing": "error",
        "brace-style": "off",
        "callback-return": "error",
        "capitalized-comments": "off",
        "class-methods-use-this": "error",
        "comma-dangle": "off",
        "comma-spacing": "off",
        "comma-style": [
            "error",
            "last"
        ],
        "complexity": "off",
        "computed-property-spacing": [
            "error",
            "never"
        ],
        "consistent-return": "off",
        "consistent-this": "error",
        "curly": "off",
        "default-case": "off",
        "dot-location": "error",
        "dot-notation": [
            "error",
            {
                "allowKeywords": false
            }
        ],
        "eol-last": "off",
        "eqeqeq": "off",
        "func-call-spacing": "error",
        "func-name-matching": "error",
        "func-names": "off",
        "func-style": [
            "error",
            "declaration"
        ],
        "function-paren-newline": "off",
        "generator-star-spacing": "error",
        "global-require": "error",
        "guard-for-in": "off",
        "handle-callback-err": "error",
        "id-blacklist": "error",
        "id-length": "off",
        "id-match": "error",
        "implicit-arrow-linebreak": "error",
        "indent": "off",
        "indent-legacy": "off",
        "init-declarations": "off",
        "jsx-quotes": "error",
        "key-spacing": "error",
        "keyword-spacing": "off",
        "line-comment-position": "off",
        "linebreak-style": "off",
        "lines-around-comment": "off",
        "lines-around-directive": "error",
        "lines-between-class-members": "error",
        "max-classes-per-file": "error",
        "max-depth": "off",
        "max-len": "off",
        "max-lines": "off",
        "max-lines-per-function": "off",
        "max-nested-callbacks": "error",
        "max-params": "error",
        "max-statements": "off",
        "max-statements-per-line": "error",
        "multiline-comment-style": [
            "error",
            "separate-lines"
        ],
        "multiline-ternary": "error",
        "new-parens": "error",
        "newline-after-var": "off",
        "newline-before-return": "off",
        "newline-per-chained-call": "error",
        "no-alert": "error",
        "no-array-constructor": "error",
        "no-async-promise-executor": "error",
        "no-await-in-loop": "error",
        "no-bitwise": "error",
        "no-buffer-constructor": "error",
        "no-caller": "error",
        "no-catch-shadow": "error",
        "no-confusing-arrow": "error",
        "no-continue": "off",
        "no-div-regex": "error",
        "no-duplicate-imports": "error",
        "no-else-return": "off",
        "no-empty-function": "error",
        "no-eq-null": "off",
        "no-eval": "error",
        "no-extend-native": "off",
        "no-extra-bind": "error",
        "no-extra-label": "error",
        "no-extra-parens": "off",
        "no-floating-decimal": "error",
        "no-implicit-globals": "off",
        "no-implied-eval": "error",
        "no-inline-comments": "off",
        "no-inner-declarations": [
            "error",
            "functions"
        ],
        "no-invalid-this": "error",
        "no-iterator": "error",
        "no-label-var": "error",
        "no-labels": "error",
        "no-lone-blocks": "error",
        "no-lonely-if": "off",
        "no-loop-func": "error",
        "no-magic-numbers": "off",
        "no-misleading-character-class": "error",
        "no-mixed-operators": "off",
        "no-mixed-requires": "error",
        "no-multi-assign": "off",
        "no-multi-spaces": "off",
        "no-multi-str": "error",
        "no-multiple-empty-lines": "off",
        "no-native-reassign": "error",
        "no-negated-condition": "off",
        "no-negated-in-lhs": "error",
        "no-nested-ternary": "error",
        "no-new": "error",
        "no-new-func": "error",
        "no-new-object": "error",
        "no-new-require": "error",
        "no-new-wrappers": "error",
        "no-octal-escape": "error",
        "no-param-reassign": "off",
        "no-path-concat": "error",
        "no-plusplus": "off",
        "no-process-env": "error",
        "no-process-exit": "error",
        "no-proto": "error",
        "no-prototype-builtins": "off",
        "no-restricted-globals": "error",
        "no-restricted-imports": "error",
        "no-restricted-modules": "error",
        "no-restricted-properties": "error",
        "no-restricted-syntax": "error",
        "no-return-assign": "error",
        "no-return-await": "error",
        "no-script-url": "error",
        "no-self-compare": "error",
        "no-sequences": "error",
        "no-shadow": "off",
        "no-shadow-restricted-names": "error",
        "no-spaced-func": "error",
        "no-sync": "error",
        "no-tabs": "off",
        "no-template-curly-in-string": "error",
        "no-ternary": "error",
        "no-throw-literal": "error",
        "no-trailing-spaces": "off",
        "no-undef-init": "error",
        "no-undefined": "error",
        "no-underscore-dangle": "off",
        "no-unmodified-loop-condition": "error",
        "no-unneeded-ternary": "error",
        "no-unused-expressions": "error",
        "no-use-before-define": "off",
        "no-useless-call": "error",
        "no-useless-computed-key": "error",
        "no-useless-concat": "off",
        "no-useless-constructor": "error",
        "no-useless-rename": "error",
        "no-useless-return": "error",
        "no-var": "off",
        "no-void": "error",
        "no-warning-comments": "error",
        "no-whitespace-before-property": "error",
        "no-with": "error",
        "object-curly-newline": "error",
        "object-curly-spacing": "off",
        "object-shorthand": "off",
        "one-var": "off",
        "one-var-declaration-per-line": "error",
        "operator-assignment": "off",
        "operator-linebreak": [
            "error",
            "before"
        ],
        "padded-blocks": "off",
        "padding-line-between-statements": "error",
        "prefer-arrow-callback": "off",
        "prefer-const": "error",
        "prefer-destructuring": "off",
        "prefer-numeric-literals": "error",
        "prefer-object-spread": "error",
        "prefer-promise-reject-errors": "error",
        "prefer-reflect": "off",
        "prefer-rest-params": "error",
        "prefer-spread": "error",
        "prefer-template": "off",
        "quote-props": "off",
        "quotes": "off",
        "radix": [
            "error",
            "as-needed"
        ],
        "require-atomic-updates": "error",
        "require-await": "error",
        "require-jsdoc": "off",
        "require-unicode-regexp": "off",
        "rest-spread-spacing": "error",
        "semi": "off",
        "semi-spacing": [
            "error",
            {
                "after": true,
                "before": false
            }
        ],
        "semi-style": "off",
        "sort-imports": "error",
        "sort-keys": "off",
        "sort-vars": "error",
        "space-before-blocks": "off",
        "space-before-function-paren": "off",
        "space-in-parens": [
            "error",
            "never"
        ],
        "space-infix-ops": "off",
        "space-unary-ops": "error",
        "spaced-comment": "off",
        "strict": [
            "error",
            "never"
        ],
        "switch-colon-spacing": "error",
        "symbol-description": "error",
        "template-curly-spacing": "error",
        "template-tag-spacing": "error",
        "unicode-bom": [
            "error",
            "never"
        ],
        "valid-jsdoc": "error",
        "vars-on-top": "off",
        "wrap-iife": "error",
        "wrap-regex": "off",
        "yield-star-spacing": "error",
        "yoda": [
            "error",
            "never"
        ]
    }
}

================================================
FILE: .gitignore
================================================
node_modules/


================================================
FILE: Array.js
================================================
Array.prototype.unique = function() {
  return this.filter(function (value, index, self) { 
    return self.indexOf(value) === index;
  });
}

function debugArray(){
  debug();
}

// https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, 'includes', {
    value: function(searchElement, fromIndex) {

      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      // 1. Let O be ? ToObject(this value).
      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If len is 0, return false.
      if (len === 0) {
        return false;
      }

      // 4. Let n be ? ToInteger(fromIndex).
      //    (If fromIndex is undefined, this step produces the value 0.)
      var n = fromIndex | 0;

      // 5. If n ≥ 0, then
      //  a. Let k be n.
      // 6. Else n < 0,
      //  a. Let k be len + n.
      //  b. If k < 0, let k be 0.
      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

      function sameValueZero(x, y) {
        return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
      }

      // 7. Repeat, while k < len
      while (k < len) {
        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
        // b. If SameValueZero(searchElement, elementK) is true, return true.
        if (sameValueZero(o[k], searchElement)) {
          return true;
        }
        // c. Increase k by 1. 
        k++;
      }

      // 8. Return false
      return false;
    }
  });
}

================================================
FILE: Automated.js
================================================
// 可以使用谷歌代码触发器每隔一段时间调用这个函数清除没有验证的过期用户
function removePendingUsers() {
    var find = {
        "status": "pending",
    };

    var findString = JSON.stringify(find);
    var members = mongo.get(Const.memberColl, "filter=" + findString);
    for (var i = 0; i < members.length; i++) {
        var member = members[i];

        //based on the gap between now and member join date, we decided whether need to add the kick payload
        var pending_time = Date.now() / 1000 - member.date;
        if (pending_time > member.timeout && member.timeout != 0) {
            // The user will be kicked and ban for 1 minute
            var kickPayload = {
                "method": "kickChatMember",
                "chat_id": member.chat.id,
                "user_id": member.user.id,
                "until_date": Date.now() / 1000 + 60,
            };

            var res = postTelegram(kickPayload);
            if (res.ok) {
                var data = { status: "kicked" };
                var setData = { "$set": data };
                mongo.setOne(Const.memberColl + "/" + member._id.$oid, setData);

                if (member.message) {
                    var deleteAskVerifyPayload = {
                        "method": "deleteMessage",
                        "message_id": member.message.message_id,
                        "chat_id": member.chat.id,
                    };
                    postTelegram(deleteAskVerifyPayload);
                }

            } else {
              var data = { status: "error" };
              
              if (res.description) {
                data.error_description = res.description;
              }
              
                var setData = { "$set": data };
                mongo.setOne(Const.memberColl + "/" + member._id.$oid, setData);                
            }
          
          
        }
    }
}

================================================
FILE: Code.js
================================================
function debugCode() {
  debug();
}
function doPost(e) {
  if (!e) {
    e = {};
    e.postData = {};
    e.postData.contents = testAdd;
  }
  var dataFromTelegram = {
    "method": "post",
    "payload": e.postData.contents
  };

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

  if (body.message && body.message.chat) {
    body.message.chat.id = body.message.chat.id + '';
  }

  var payload = preparePayload(body);
  var payloads;

  if (Array.isArray(payload)) {
    payloads = payload;
  } else {
    payloads = [payload];
  }

  for (var i = 0; i < payloads.length; i++) {
    payload = payloads[i];
    if (payload) {
      var handleResponseCallBack = null;
      var delay = 0;
      if (payload.callback) {
        handleResponseCallBack = payload.callback;
        delete payload.callback;
      }
      if (payload.delay) {
        delay = payload.delay;
        delete payload.delay;
      }


      //Be careful, as GAS can only make sync all. Only use the delay for the last payloads and adjust the delay time wisely.
      if (delay > 0) {
        Utilities.sleep(delay * 1000);
      }

      var res = postTelegram(payload);

      if (handleResponseCallBack) {
        handleResponseCallBack(res);
      }
    }
  }

}


================================================
FILE: Common.js
================================================
function debugCommons(){
  var date = getChineseDateString(new Date());
  console.log(date);

}


// Use this method to sort a array randomly
function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

function checkIsMyMessage(body){
  var text = body.message.text;
  if (text) {
    var paras = text.split(" ");
    if (paras[0] && paras[0].indexOf("@") >= 0){
      if  (paras[0].toLowerCase().indexOf(Const.myName) >= 0){
        return true;
      }
      return false;
    }
  }
  return true;
}

function isAdminOrCreator(userId, chatId) {
  payload = {
    "method": "getChatMember",
    "chat_id": chatId,
    "user_id": userId
  };

  // allow feng
  if (userId == 539065210) {
    return true;
  }

  var chatMember = postTelegram(payload);

  if (chatMember && chatMember.ok === true) {
    if (chatMember.result.status == "creator") {
      return true;
    }

    if (chatMember.result.status == "administrator") {
      return true;
    }
  }
  return false;
}

function isValidChannelId(id){
  return /^[\dA-z_-]{24}$/.test(id);
}
function isValidTelegramChatId(id){
  var isValidId = false;
  if (isNaN(id)) {
    if (id.indexOf("@") != 0) {
    } else {
      isValidId = true;
    }
  } else {
    // Number is valid Id
    if (/[\d-]{8,}/.test(id + "")) {
      isValidId = true;
    } else {
    }
  }
  return isValidId;
}

function getShareObject(body) {
  var payload;
  var from;
  var chat;
  var messageId;
  var callback_query_id;
  var origText;
 var share = {};
  // use editMessage method instead if it's a callback 
  if (body.callback_query) {
    chat = body.callback_query.message.chat;
    chat.id = chat.id + "";
    messageId = body.callback_query.message.message_id;
    from = body.callback_query.from;
    callback_query_id = body.callback_query.id;
    origText = body.callback_query.message.text;
    payload = {
      "method": "editMessageText",
      "chat_id": chat.id,
      "message_id": messageId,
      "text": "",
      "parse_mode": "markdown",
      "disable_web_page_preview": true,
    };
  } else {
    from = body.message.from;
    chat = body.message.chat;
    chat.id = chat.id + "";
    messageId = body.message.message_id;
    origText = body.message.text;
    payload = {
      "method": "sendMessage",
      "chat_id": chat.id,
      "text": "",
      "parse_mode": "markdown",
      "disable_web_page_preview": true,
    };
    
      if (body.message.new_chat_member) {
    share.new_chat_member = body.message.new_chat_member;
  }

  }


 
  share.payload = payload;
  share.from = from;
  share.chat = chat;
  share.messageId = messageId;
  share.callback_query_id = callback_query_id;
  share.origText = origText;

  return share;
}

function extractVideoIds(text) {
  var VideoIds = text.replace(/https:\/\/youtu.be\//gi, "");
  return VideoIds;
}
function escapeMarkDown(toEscapeMsg) {
  var escapedMsg = toEscapeMsg
  .replace(/_/g, "\\_")
  .replace(/\*/g, "\\*")
  .replace(/\[/g, "\\[")
  .replace(/\]/g, "\\]")
  .replace(/`/g, "\\`");
    return escapedMsg;

}

function addDeleteMeButton(payload) {
  var buttons = [];
  var button1 = {
    text: "点此删除本消息",
    callback_data: "delme" 
  };

  buttons.push(button1);

  var inlineKeyboardMarkup = generateInlineKeyboardMarkup(buttons, 3);

  payload.reply_markup = inlineKeyboardMarkup;
}

function extractChannelId(text) {
  var channelId = text.replace(/https:\/\/www.youtube.com\/channel\//i, "");
  return channelId;
}

function getGroupName(chat){
  if(chat.username) {
    return getMarkDownGroupUrl(chat.title, chat.username);
  }
  return escapeMarkDown(chat.title);
}
function getMentionName(user) {
  var mentionName = "";

  var name = getName(user);
  if (!name) {
    name = "神秘人";
  }
  mentionName = getMarkDownUserUrl(name, user.id);
  return mentionName;
}

function getMarkDownGroupUrl(title, chatUserName) {
  return getMarkDownUrl(title, "https://t.me/" + chatUserName);
}
function getMarkDownUserUrl(userName, userId) {
  return getMarkDownUrl(userName, "tg://user?id=" + userId);
}

function getMarkDownUrl(text, url) {
  return "[" + escapeMarkDown(text) + "](" + url + ")";
}

function getChannelUrlById(id) {
  return "https://www.youtube.com/channel/" + id;
}

function getChineseDateString(nzTime){

  var utcTime = new Date(nzTime.getTime() + nzTime.getTimezoneOffset() * 60000);
  var chinaTime = new Date(utcTime.getTime() + 8 * 60 * 60 * 1000);

  var year = chinaTime.getFullYear()+'年';
  var month = chinaTime.getMonth()+1+'月';
  var date = chinaTime.getDate()+'日';
  var hours = chinaTime.getHours() + '时';
  var minutes = chinaTime.getMinutes() + '分';
  return [year,month,date, hours,minutes].join('');
}

function getName(user) {
  var name = user.first_name;
  if (user.last_name) {
    name += " " + user.last_name;
  }

  return name;
}

function escapeRegex(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}



function pad(pad, str, padLeft) {
  if (typeof str === 'undefined') 
    return pad;
  if (padLeft) {
    return (pad + str).slice(-pad.length);
  } else {
    return (str + pad).substring(0, pad.length);
  }
}



function isPrivate(body) {
  var share =  getShareObject(body);
  var chat = share.chat;
  if (chat.type === "private") {
    return true;
  }
  return false;
}

================================================
FILE: Const.js
================================================
var Const = {};
// 如果你用的是 mlab 数据库, 改成 true
Const.useMlab = false;
//改成你自己的机器人 Token
//Live
// Const.botToken = "机器人ID";
//Debug
Const.botToken = "机器人ID";
Const.myId = parseInt(Const.botToken.split(":")[0]);
Const.myName = "机器人的username";
Const.myName = Const.myName.toLowerCase();

//以下是峰哥的数据库服务器,可以工作,可以用,没有数据库的可以保留
Const.restheartUrl = "https://r1.dengnz.com/user2/";
Const.restheartUser = "user2";
Const.restheartPass = "jrCtNft6TbMYZxWe";


Const.memberColl = "members";
Const.contextColl = "context";
Const.logColl = "logs";
Const.groupSettingsColl = "group-settings";
Const.toTelegram = "to-telegram";
Const.fromTelegram = "from-telegram";

Const.channelId = "@fengshare";
Const.myAtName = "@" + Const.myName;

================================================
FILE: Context.js
================================================
function setContextCommand (userId, command) {
    var query = {userId: userId};
    mongo.set(Const.contextColl, "filter=" + JSON.stringify(query), {command: command});
}

function setContextDrawId (userId, drawId) {

}

function getContext(userId) {
    var query = {userId: userId};
    var result = mongo.get(Const.contextColl, "filter=" + JSON.stringify(query));
    if (result && result.length > 0){
        return result[0];
    }
    return null;
}

function setContext(context) {
    var query = {userId: context.userId};
    // Remove old context
    mongo.remove(Const.contextColl, "filter=" + JSON.stringify(query));
    // insert new contxt
    mongo.insert(Const.contextColl, context);
}

================================================
FILE: Database.js
================================================
function debugDatabase(){
  var collectionName = Const.updateTimeColl;
  var data = {"x": 1}
  //insertToDB(collectionName, data);
  //
  
  var result = getLatestItemFromColl(collectionName);
  Logger.log(result);  
}


function getLatestItemFromColl(coll){
 var latestItems =  mongo.get(coll, 'sort={$natural:-1}&pagesize=1');
 if (latestItems.length > 0){
   return latestItems[0];
 }
 return null;
}

function clearCollection(collectionName){
  mongo.replace(collectionName, null, []);
}
// This function inserts a javascript object directly to a mongo db collection
function insertToDB(collectionName, data) {
  if (collectionName && data){  
    mongo.insert(collectionName, data)
  }
}

function getAllCollectionFromDB(collectionName){

  var option = getGetOption();
  var query = null;
  return mongo.get(collectionName, query);


}



================================================
FILE: Get.js
================================================
function doGet(e){
  //return HtmlService.createHtmlOutput("Hello World!! No, this link should be hidden!!!");
  
   return HtmlService.createHtmlOutputFromFile('Index');
}


================================================
FILE: Group.js
================================================
var groupSettings;
function debugGroup() {
  debug();
}

var defaultWelcome = {
  status: "on",
  desc: "on",
  pinned: "on",
  killme: "on",
  custom: "off",
  customtext: "您还没有设置自定义欢迎词"
};

var defaultNotRobot = {
  status: "off",
  timeout: 0
};


//Field is a string (can use dot notation), value is a json object 
function gpSetFieldValue(group, field, value) {
  try {
    // will return a default group settings in memory if not found
    var groupSettings = getGroupSettings(group);
    var data = {};
    data[field] = value;
    if (!groupSettings._id) {
      mongo.insert(Const.groupSettingsColl, groupSettings);
    }
    
    var setData = {"$set": data};
    
    var res = mongo.setOne(Const.groupSettingsColl + "/" + groupSettings._id.$oid, setData);
    if (res.getResponseCode() != 200) {
      console.log(res.getContentText());
    }
    return true;
  } catch (e) {
    return false;
  }
}

function getGroupSettings(group)
{
  var query = {
    "group.id": group.id + "",
  };

  var q = JSON.stringify(query);
  var groupSettingss = mongo.get(Const.groupSettingsColl, "filter=" + q);
  if (groupSettingss.length > 0) {
    groupSettings =  groupSettingss[0];
  }

  if (!groupSettings) {
    groupSettings = {};
    groupSettings.group= group;
    groupSettings.welcome = defaultWelcome;
    groupSettings.notRobot = defaultNotRobot;
    mongo.insert(Const.groupSettingsColl, groupSettings);
  }

  return groupSettings;
}

================================================
FILE: HandleAdminCommand.js
================================================
function debugAdminCommand() {
  debug()
}

function handleAdminCommand(body, paras, origParas) {

  var share =  getShareObject(body);
  var payload = share.payload;
  var chat = share.chat;
  var callback_query_id = share.callback_query_id;

  delete payload.parse_mode;

  if (chat.type.indexOf("group") < 0) {
    payload.text += "请将本机器人加入您的群中再使用此命令";
    return payload; 
  }

  if (!isAdminOrCreator(share.from.id, share.chat.id)) {
    if (body.callback_query) {
      var answerCallBackQueryPayload = {
        "method": "answerCallbackQuery",
        "callback_query_id": callback_query_id,
        "text": "只有本群管理才可以使用此命令",
      };
      return answerCallBackQueryPayload;
    } else {
      payload.text += "只有本群管理才可以使用此命令";
      addDeleteMeButton(payload);
      return payload;
    }
  }

  var groupSettings = getGroupSettings(chat);

  if (paras[1]) {
    switch (paras[1]) {
      case 'notrobot':
        //设置进群验证
        if (paras[2]) {
          if (paras[2] == "status") {
            if (paras[3]) {
              if (paras[3] == "on") {
                if (gpSetFieldValue(chat, "notRobot.status", "on")) {
                  payload.text = "进群验证按钮启用成功";
                  groupSettings.notRobot.status = "on";
                } else {
                  payload.text = "进群验证按钮启用失败";
                }
              } else {
                if (gpSetFieldValue(chat, "notRobot.status", "off")) {
                  payload.text = "进群验证按钮禁用成功";
                  groupSettings.notRobot.status = "off";
                } else {
                  payload.text = "进群验证按钮禁用失败";
                }
              }
              payload.text += "\n";
            }

            if (groupSettings.notRobot.status && groupSettings.notRobot.status == "on") {
              groupSettings.notRobot.status = "on";
              payload.text += "进群验证按钮已打开, 点击以下按钮关闭";
            } else {
              groupSettings.notRobot.status = "off";
              payload.text += "进群验证按钮已关闭, 点击以下按钮打开";
            }

          }

          if (paras[2] == "timeout") {
            if (paras[3]) {
              if (/[0-9]+/.test(paras[3] + "")) {
                var timeout = parseInt(paras[3]);
                if (gpSetFieldValue(chat, "notRobot.timeout", timeout)) {
                  payload.text += "进群验证倒计时已经设置为: ";
                  payload.text += timeout;
                  groupSettings.notRobot.timeout = timeout;
                  payload.text += "\n";
                  payload.text += "注意,倒计时踢人需要在谷歌GAS设置触发器调用 removePendingUsers() 函数, 如果无法自动踢人请联系机器人服务器架设者";
                  if (timeout == 0) {
                    payload.text += "倒计时设置为0时,将不会自动踢除未验证的用户";
                  }
                } else {
                  payload.text = "进群验证倒计时设置失败";
                  payload.text += "\n";
                }
              } else {
                payload.text += "倒计时只能是数字,单位为妙钟";
                payload.text += "\n";
              }
            }
          }
        } else {
          payload.text += "使用以下命令设置进群验证";
          payload.text += "\n";
          payload.text += "\n";
          payload.text += "/admin notRobot status - 开关进群验证,值可以是 on 或 off";
          payload.text += "\n";
          payload.text += "/admin notRobot timeout - 设置验证倒计时,可以是任何正数(秒)";
          payload.text += "\n";
          payload.text += "超过这个时间还没验证的用户会被踢出群. 设置成0则不踢";
          payload.text += "\n";
          payload.text += "注意! 需要在谷歌脚本使用触发器定期踢出未验证的用户";
          payload.text += "\n";
        }

        setButtonsForAdminNotRobot(payload, groupSettings);
      break;
      case 'welcome':
        if (paras[3]) {
          var value = "off";
          if (paras[3] === "on") {
            value = "on";
          }
          switch (paras[2]) {
            case "customtext":
              // custom text uses different value rather than on or off
              value = origParas.splice(3).join(" ");
            case "status":
            case "desc":
            case "pinned":
            case "killme":
            case "custom":
              var success = gpSetFieldValue(chat, "welcome." + paras[2], value);
              if (success) {
                payload.text += "设置成功 - ";
                payload.text += paras[2] + ": " + value;
                payload.text += "\n";
                groupSettings.welcome[paras[2]] = value;
              } else {
                payload.text += "设置失败";
                payload.text += "\n";
              }   
           
            break;
            default:
              payload.text += "不支持的参数\n";
            break;
          }
        }  

        var status = {};
        status["on"] = "【开】";
        status["off"] = "【关】";

        var toggle = {};
        toggle["on"] = "off";
        toggle["off"] = "on";

        if (!paras[3] && paras[2] === "customtext") {
          payload.text += '明白,要设置自定义欢迎词,请回复本消息把欢迎词发给我,你可以在欢迎词中使用以下变量:\n';
          payload.text += '$(desc) - 代表群描述\n';
          payload.text += '$(pinnedMessage) - 代表置顶消息\n';
          payload.text += '$(pinnedId) - 代表置顶消息的ID\n';
          payload.text += '$(pinnedUrl) - 代表置顶消息的链接(只有公开群有)\n';
          payload.text += '$(newMemberName) - 代表新成员的名字\n';
        } else {
          payload.text += '在这里可以打开欢迎词,欢迎词可选包含群描述和置顶消息,如果30秒自毁开启,欢迎词将在30秒后被删除\n';
          payload.text += '请问还有什么我可以帮你的吗?';
        }

        var buttons = [
          {
            text: "切换欢迎词" + status[groupSettings.welcome.status],
            callback_data: "admin:welcome:status:" + toggle[groupSettings.welcome.status]
          },
        ];


        if (groupSettings.welcome.status === "on") {
          if (groupSettings.welcome.custom === "on") {
            buttons.push(
              {
                text: "自定义消息" + status[groupSettings.welcome.custom],
                callback_data: "admin:welcome:custom:" + toggle[groupSettings.welcome.custom]
              }
            );

            buttons.push(
              {
                text: "编辑自定义消息",
                callback_data: "admin:welcome:customtext"
              }
            );

          } else {
            buttons.push(
              {
                text: "群描述" + status[groupSettings.welcome.desc],
                callback_data: "admin:welcome:desc:" + toggle[groupSettings.welcome.desc]
              }
            );

            buttons.push(
              {
                text: "置顶消息" + status[groupSettings.welcome.pinned],
                callback_data: "admin:welcome:pinned:" + toggle[groupSettings.welcome.pinned]
              }
            );

            buttons.push(
              {
                text: "自定义消息" + status[groupSettings.welcome.custom],
                callback_data: "admin:welcome:custom:" + toggle[groupSettings.welcome.custom]
              }
            );

          }

          buttons.push(
            {
              text: "30秒自毁" + status[groupSettings.welcome.killme],
              callback_data: "admin:welcome:killme:" + toggle[groupSettings.welcome.killme]
            }
          );


        }

        buttons.push(
          {
            text: "返回主菜单",
            callback_data: "admin"
          }
        );

        var inlineKeyboardMarkup = generateInlineKeyboardMarkup(buttons, 2);

        payload.reply_markup = inlineKeyboardMarkup;

        break;
      default:
        payload.text = "欢迎使用Admin命令\n"
          + "\n"
          + "输入 admin welcome 设置欢迎词"
          + "\n"
          + "输入 admin notRobot 设置进群验证"
          ;
        break;
    }

  } else {
    payload.text += "欢迎来到机器人设置\n";
    payload.text += "有什么我可以帮您的吗?\n";
    var buttons = [
      {
        text: "欢迎词设置",
        callback_data: "admin:welcome"
      },
      {
        text: "进群验证",
        callback_data: "admin:notrobot"
      }
    ];

    var inlineKeyboardMarkup = generateInlineKeyboardMarkup(buttons, 2);

    payload.reply_markup = inlineKeyboardMarkup;

  }
  return payload;

}



function setButtonsForAdminNotRobot(payload, groupSettings) {

  var status = {};
  status["on"] = "【开】";
  status["off"] = "【关】";

  var toggle = {};
  toggle["on"] = "off";
  toggle["off"] = "on";

  var buttons = [
  ];

  buttons.push(
    {
      text: "进群验证按钮" + status[groupSettings.notRobot.status],
      callback_data: "admin:notrobot:status:" + toggle[groupSettings.notRobot.status]
    }
  );


  if (groupSettings.notRobot.status == "on") {
    buttons.push(
      {
        text: "踢出倒计时【" + groupSettings.notRobot.timeout + "秒】" + "✅",
        callback_data: "admin:notrobot:timeout:" + groupSettings.notRobot.timeout,
      }
    );

    if (groupSettings.notRobot.timeout !== 0) {
      buttons.push(
        {
          text: "踢出倒计时【" + 0 + "秒】",
          callback_data: "admin:notrobot:timeout:" + 0,
        }
      );
    }
    if (groupSettings.notRobot.timeout !== 120) {
      buttons.push(
        {
          text: "踢出倒计时【" + 120 + "秒】",
          callback_data: "admin:notrobot:timeout:" + 120,
        }
      );
    }

    if (groupSettings.notRobot.timeout !== 3600) {
      buttons.push(
        {
          text: "踢出倒计时【" + 1 + "小时】",
          callback_data: "admin:notrobot:timeout:" + 3600,
        }
      );
    }
    if (groupSettings.notRobot.timeout !== 3600 * 24) {
      buttons.push(
        {
          text: "踢出倒计时【" + 1 + "天】",
          callback_data: "admin:notrobot:timeout:" + 3600 * 24,
        }
      );
    }

  }



  buttons.push(
    {
      text: "返回主菜单",
      callback_data: "admin"
    }
  );

  var inlineKeyboardMarkup = generateInlineKeyboardMarkup(buttons, 2);
  payload.reply_markup = inlineKeyboardMarkup;
}

================================================
FILE: HandleBanCommand.js
================================================
function debugBanCommand() {
  debug()
}

function handleBanCommand(body, paras, origParas) {

  var share =  getShareObject(body);
  var payload = share.payload;
  var chat = share.chat;
  var callback_query_id = share.callback_query_id;

  var payloads = [];

  if (chat.type.indexOf("group") < 0) {
    payload.text += "请将本机器人加入您的群中再使用此命令";
    return payload; 
  }

  var targetUser;

  var theUser;

  if (origParas.length > 1) {
    targetUser = origParas[1];
  } else {
    if (body.message && body.message.reply_to_message) {
      targetUser = body.message.reply_to_message.from.id;
      theUser = body.message.reply_to_message.from;
    }
  }

  if (targetUser) {
    var isAdmin = isAdminOrCreator(share.from.id, share.chat.id);
    if (isAdmin) {
      var payload4 = {
        "method": "kickChatMember",
        "chat_id": share.chat.id,
        "user_id": targetUser,
      };
      payloads.push(payload4);

      if (theUser) {
        payload.text += getMentionName(share.from);
        payload.text += "踢了";
        payload.text += getMentionName(theUser);
        payloads.push(payload);
      }
    } else {
      if (body.callback_query) {
        var answerCallBackQueryPayload = {
          "method": "answerCallbackQuery",
          "callback_query_id": callback_query_id,
          "text": "只有本群管理才可以使用此命令",
        };
        return answerCallBackQueryPayload;
      } else {
        payload.text += "只有本群管理才可以使用此命令";
        return payload;
      }
    }
  }

  return payloads;
}

================================================
FILE: HandleCallback.js
================================================
function debugCallback(){
  debug();
}

function handleCallback(body) {
 
  var chatId = body.callback_query.message.chat.id + "";
  var chat = body.callback_query.message.chat;
  var from = body.callback_query.from;
  var messageId = body.callback_query.message.message_id;
  var payload = {
    "method": "editMessageText",
    "chat_id": chatId,
    "message_id": messageId,
    "text": "Callback received: " + body.callback_query.data,
    "parse_mode": "markdown",
    "disable_web_page_preview": false,
  };

  // remove carried info
  body.callback_query.data = body.callback_query.data.split('|||')[0];

  var lowerData = body.callback_query.data.toLowerCase();
  var paras = lowerData.split(":");
  var origParas = body.callback_query.data.split(":");

  var queryType = paras[0];

  switch(queryType){
    case "delme": 
      paras[0] = "delmsg";
      paras.push(messageId + "");
      return handleDelMsgCommand(body, paras, origParas);
    break;
    case "admin":
      return handleAdminCommand(body, paras, origParas);
    break;
    case "notrobot":
      return handleNotRobotCommand(body, paras, origParas);
    break;
  }

  return payload;
}
  



================================================
FILE: HandleDelMsgCommand.js
================================================
function debugDelMsgCommand() {
  debug();
}

function handleDelMsgCommand(body, paras, origParas) {

  var share =  getShareObject(body);
  var payload = share.payload;
  var chat = share.chat;
  var callback_query_id = share.callback_query_id;

  var payloads = [];

  if (chat.type.indexOf("group") < 0 && chat.type.indexOf("channel") < 0) {
    payload.text += "请将本机器人加入您的群中再使用此命令";
    return payload; 
  }


  if (!allowed(body, paras, origParas)) {
    payload += "对不起,只有管理可以使用此命令!";
    addDeleteMeButton(payload);
    return payload;
  }

  if (paras[1]) {
    var messageId = paras[1];
    messageId = messageId.replace(/https:\/\/t.me\/[^/]*\//i, "");
    payload = {
      "method": "deleteMessage",
      "message_id": messageId,
      "chat_id": chat.id
    };

    return payload;
  }

  return null;


}

================================================
FILE: HandleHelpCommand.js
================================================
function debugHelp() {
  debug();
}
function handleHelpCommand(body, paras, origParas) {
  var payload = {
    "method": "sendMessage",
    "chat_id": body.message.chat.id,
    "text": "",
    "parse_mode": "markdown",
    "disable_web_page_preview": true,	
  };
      payload.text += "欢迎使用群管机器人!!\n\n";
      payload.text += "以下是本BOT的独家命令:"
        + "\n\n"
        + "/help - 输出帮助" + "\n"
        + "/admin - 机器人设置" + "\n"
        + "/ban - 用此命令回复消息踢发消息的人" + "\n"
        + "\n"
        ;

        

      payload.text += "本机器人由YuFeng Deng峰哥开发" + "\n"
        + "点击[此处](https://www.youtube.com/channel/UCG6xoef2xU86hnrCsS5m5Cw?sub_confirmation=1)订阅我的Youtube频道" + "\n"
        + "点击[此处](https://t.me/fengsharegroup)加入我的电报群" + "\n"
        ;
      return payload;

}


================================================
FILE: HandleMessage.js
================================================
function debugMessage(){
  debug();
}

function handleMessage(body){
  var payload;
  var chatId = body.message.chat.id;
  payload = {
    "method": "sendMessage",
    "chat_id": chatId,
    "text": "",
    "disable_web_page_preview": true,
  };

  if (body.message.new_chat_member) {
    // mongo.insert(Const.fromTelegram, body);
    payload = handleNewMember(body);
    return payload;
  }

  if (body.message.text) {
    var isMyMessage = checkIsMyMessage(body);
    if (!isMyMessage) {
      return null;
    }
    return handleMessageText(body);
  }

  return payload
}

================================================
FILE: HandleMessageText.js
================================================
function debugMessageText(){
  debug();
}


function handleMessageText(body) {

  var payload = {
    "method": "sendMessage",
    "chat_id": body.message.chat.id,
    "text": "",
    "parse_mode": "markdown",
    "disable_web_page_preview": true,	
  };


  var regex = new RegExp("(^/[^ ]+)@" + Const.myName + "", "i");
  var origMessageText = body.message.text.replace(regex, '$1');

    // Covert a not command to command
    origMessageText = handleNoCommandAndAlias(body, origMessageText);

    if (origMessageText.indexOf("/") !== 0) {
      //Check context and convert it to a command
      if (isPrivate(body)) {
        if (body.message && body.message.from) {
          var context = getContext(body.message.from.id);
          if (context && context.command) {
            var command = context.command;
            origMessageText = '/' + command.split(':').join(' ') + ' ' + origMessageText;
          } else {
            return null;
          }
        } else {
          return null;
        }

      } else {
        // Not a command 
        return null;
      }
    }

    body.message.text = origMessageText;
    var messageText = origMessageText.toLowerCase();

    var commands = [
      "/draw",
      "/admin",
      "/allowme",
      "/help",
      "/start",
      "/initdb",
      "/delmsg",
      "/ban",
    ];

    var paras = messageText.trim().split(" ");
    // remove empty strings
    paras = paras.filter(function(para){
      if (para){
        return true;
      }
    });

    var command = paras[0];
    if (!command) {
      return;
    }

    // remove ! from command, a commamnd start with /! is from feng
    command = command.replace("!", "");
    if (!commands.includes(command)) {
      // not a command 
      return null;
    }

    // mongo.insert(Const.fromTelegram, body);

    
    var origParas = origMessageText.trim().split(" ");
    // remove empty strings
    origParas = origParas.filter(function(para){
      if (para){
        return true;
      }
    });

      if (!allowed(body, paras, origParas)) {
        payload.text = "对不起,您无权执行此操作,";
        payload.text += "喜欢";
        payload.text += "[本bot](https://telegram.me/" + Const.myName + ")";
        payload.text += "的话";
        payload.text += "[加我到您群中](https://telegram.me/" + Const.myName + "?startgroup=true)!";
        addDeleteMeButton(payload);
        return payload;
      }

    
    if (command.indexOf("/jump") == 0) {
      var foundMessageId = paras[1];
      if (isNaN(foundMessageId)) {
        payload.text = "消息ID必需是数";
        return payload;
      }

      payload.reply_to_message_id = foundMessageId;
      payload.text = "点击以上引用可跳转到原消";

      return payload;
    }

    if (command.indexOf("/admin") == 0) {
      return handleAdminCommand(body, paras, origParas);
    }

    if (command.indexOf("/initdb") == 0) {
      return handleInitDBCommand(body, paras, origParas);
    }



    if (command.indexOf("/notrobot") == 0) {
      return handleNotRobotCommand(body, paras, origParas);
    }

    if (command.indexOf("/ban") == 0) {
      return handleBanCommand(body, paras, origParas);
    }

    if (command.indexOf("/pinmessage") == 0) {
      return handlePinMessageCommand(body, paras, origParas);
    }

    if (command.indexOf("/gpset") == 0) {

      if (body.message.from.id !== 539065210) {
        payload += "此命令极其危险,暂时只有峰哥可以使用";
        return payload;
      }

      if (paras[2]) {
        var field = origParas[1];
        var value = origParas.splice(2).join(" ");
        
        if (gpSetFieldValue(body.message.chat, field, value)) {
          payload.text = "设置成功";
        } else {
          payload.text = "设置失败";
          payload.text += "\n";
        }
        return payload;
      }

      return null;
      
    }
    if (command.indexOf("/delmsg") == 0) {

     return handleDelMsgCommand(body, paras, origParas);
      
    }
    if (command.indexOf("/help") == 0) {
      return handleHelpCommand(body, paras, origParas);
    }
    if (command.indexOf("/start") == 0) {
      return handleStartCommand(body, paras, origParas);
    }

    return null;
}


================================================
FILE: HandleNoCommandAndAlias.js
================================================
function debugNoCommandAndAlias() {
  debug();
}
function handleNoCommandAndAlias(body, origMessageText) {
  //Handle Alias
  if (body.message.reply_to_message) {
    if (body.message.reply_to_message.from.id == Const.myId) {
      // This message is replied to me, but it's not a command
      if (origMessageText.indexOf('/') != 0) {
        var reply_to_message_text = body.message.reply_to_message.text;
        if (reply_to_message_text.indexOf('明白,要设置自定义欢迎词') == '0') {
          origMessageText = '/admin welcome customtext ' + origMessageText;
        }
      }
    }
  }
  origMessageText = origMessageText.replace(/^\/allowme( |$)/i, "/notrobot allowme");
  origMessageText = origMessageText.replace(/^\/帮助( |$)/i, "/help ");
  return origMessageText;
}

================================================
FILE: HandleNotRobotCommand.js
================================================
function debugNotRobotCommand() {
  debug()
}

function generateSelfUnlockButtonMarkup() {
  var buttons = [];
  var button1 = {
    text: "点击这里解禁",
    callback_data: "notRobot:self"
  };

  buttons.push(button1);
  var inlineKeyboardMarkup = generateInlineKeyboardMarkup(buttons, 3);
  return inlineKeyboardMarkup;
}

function handleNotRobotCommand(body, paras, origParas) {

  var share =  getShareObject(body);
  var payload = share.payload;
  var chat = share.chat;
  var callback_query_id = share.callback_query_id;

  var payloads = [];

  if (chat.type.indexOf("group") < 0) {
    payload.text += "请将本机器人加入您的群中再使用此命令";
    return payload; 
  }

  var targetUser = origParas[1];

  if (paras[1] == "allowme") {
    payload.text = "如果你被禁言了,请点击以下按钮自助解禁";
    payload.reply_markup = generateSelfUnlockButtonMarkup();
    return payload;
  }

  if (targetUser == "self"){
    targetUser = share.from.id;
  }

  if (!/-?[0-9]+/.test(targetUser + "")) {
    return null;
  }

  targetUser = parseInt(targetUser);

  var isAdmin = isAdminOrCreator(share.from.id, share.chat.id);
  var isNotRobotCallback = (share.from.id + "") === origParas[1] && body.callback_query;

  if (isAdmin || isNotRobotCallback || origParas[1] =="self") {
    // update the member stats in db
    var find = {
      "user.id": targetUser,
    };

    var findString = JSON.stringify(find);
    var res = mongo.setMany(Const.memberColl, "filter=" + findString, { status: "normal" });
    var payload2 = {
      "method": "restrictChatMember",
      "chat_id": chat.id,
      "user_id": targetUser,
      "can_send_messages": true,
      "can_send_media_messages": true,
      "can_send_other_messages": true,
      "can_add_web_page_previews": true,
    };

    payload2.callback = function(res) {
      if (res.ok) {
        var chatMember = getChatMember(share.chat.id, targetUser);
        var username = getName(chatMember.user);
        var payload7 = {
          "method": "answerCallbackQuery",
          "callback_query_id": callback_query_id,
          "text": "解禁成功," + username + "可以发言了",
        };
        payloads.push(payload7);

        // Send welcome message if needed
        var groupSettings = getGroupSettings(share.chat);
        share.new_chat_member = chatMember.user;
        // will send a seperate welcome message rather than edit message
        setWelcomePayload(share, groupSettings, payloads);

      }
    };

    payloads.push(payload2);

  } else {
    if (body.callback_query) {
      var answerCallBackQueryPayload = {
        "method": "answerCallbackQuery",
        "callback_query_id": callback_query_id,
        "text": "只有本群管理才可以使用此命令",
      };
      return answerCallBackQueryPayload;
    } else {
      payload.text += "只有本群管理才可以使用此命令";
      return payload;
    }
  }



  if (origParas[1] !="self") {
    // Delete this message when callback received
    var payload4 = {
      "method": "deleteMessage",
      "message_id": share.messageId,
      "chat_id": chat.id
    };

    payloads.push(payload4);
  } else {
    if (share.origText) {
      payload.text += share.origText;
      payload.text += "\n";
    }
    payload.text += getName(share.from) + "点了本按钮";
    payload.reply_markup = generateSelfUnlockButtonMarkup();
    payloads.push(payload);
  }


  return payloads;
}

================================================
FILE: HandlePinMessageCommand.js
================================================
function debugPinMessageCommand() {
  debug()
}

function handlePinMessageCommand(body, paras, origParas) {

  var share =  getShareObject(body);
  var payload = share.payload;
  var chat = share.chat;
  var callback_query_id = share.callback_query_id;

  var payloads = [];

  if (chat.type.indexOf("group") < 0) {
    payload.text += "请将本机器人加入您的群中再使用此命令";
    return payload; 
  }

  var targetMessage = origParas[1];

  var isAdmin = isAdminOrCreator(share.from.id, share.chat.id);

  if (isAdmin) {
    var payload2 = {
      "method": "pinChatMessage",
      "chat_id": share.chat.id,
      "message_id": parseInt(targetMessage)
    };

    return payload2;

  } else {
    if (body.callback_query) {
      var answerCallBackQueryPayload = {
        "method": "answerCallbackQuery",
        "callback_query_id": callback_query_id,
        "text": "只有本群管理才可以使用此命令",
      };
      return answerCallBackQueryPayload;
    } else {
      payload.text += "只有本群管理才可以使用此命令";
      return payload;
    }
  }

}

================================================
FILE: HandleStartCommand.js
================================================
function debugStart() {
  debug();
}
function handleStartCommand(body, paras, origParas) {
  var payload = {
    "method": "sendMessage",
    "chat_id": body.message.chat.id,
    "text": "",
    "parse_mode": "markdown",
    "disable_web_page_preview": true,
  };

  if (isPrivate(body)) {
    if (paras[1]) {
      return handleStartToken(body, paras, origParas);
    }

    payload.text += "本机器人要加入群中才能工作";
    payload.text += "\n";
    var buttons = [];
    var button1 = {
      text: "添加本机器人到群中",
      url: "https://telegram.me/" + Const.myName + "?startgroup=true"
    };

    buttons.push(button1);

    var inlineKeyboardMarkup = generateInlineKeyboardMarkup(buttons, 3);

    payload.reply_markup = inlineKeyboardMarkup;

    return payload;
  } else {
    paras[0] = "/help";
    return handleHelpCommand(body, paras, origParas);

  }
}


function handleStartToken(body, paras, origParas) {
  var share =  getShareObject(body);
  var payload = share.payload;
  var chat = share.chat;

  var token=paras[1];



  origParas = token.split('_-_');
  paras = token.toLowerCase().split('_-_');



  payload.text += token;
  return payload;
}

================================================
FILE: Index.html
================================================
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <meta charset="UTF-8">

    <script src="Channel.js"></script>
    <script src="Code.js"></script>
    <script src="Common.js"></script>
    <script src="Data.js"></script>
    <script src="DataChannels.js"></script>
    <script src="Get.js"></script>
    <script src="Test.js"></script>
  </head>
  <body>
    <script>
      var payload = preparePayload(JSON.parse(testPersonName));
      console.log(payload);
      console.log(JSON.stringify(payload));

      </script>
    Hello world from html
  </body>
</html>




================================================
FILE: InlineKeyboard.js
================================================
function debugInlineKeyboard(){
  debug();
}

function generateInlineKeyboardMarkup(buttons, numberOfButtonsPerRow) {
  var inlineKeyboardMarkup = {};
  inlineKeyboardMarkup.inline_keyboard = [];
  var count = 0;
  for (var i = 0; i < buttons.length / numberOfButtonsPerRow; i++) {
    var keyboardRow = [];
    for (var j = 0; j < numberOfButtonsPerRow; j++) {
      var button = buttons[i * numberOfButtonsPerRow + j];
      var keyboardButton = button;
      count++;
      keyboardRow.push(keyboardButton);
      if (count >= buttons.length) {
        break;
      }
    }
    inlineKeyboardMarkup.inline_keyboard.push(keyboardRow);
  }
  return inlineKeyboardMarkup;
}

================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.


================================================
FILE: Mlab.js
================================================
// 如果你要使用Mlab 而不是 Restheart 的话, 请把以下的KEY改成你自己的KEY
var mlabKey = "WULdZqaqxqikzrGePcLC5uWBeyvGZqBp";

var baseUrl = "https://api.mlab.com/api/1/";
var dbUrl = baseUrl + "databases/mongo/";
var collectionUrl = dbUrl + "collections/";

var mlab = {};

if (Const.useMlab) {
    mongo = mlab;
  
}

function debugMLab(){
  debug();
}

function convertRestHeartParasToMlabParas(query) {
  if (!query){
    return query;
  }
    query = query.replace("filter=", "q=");
    query = query.replace("sort=", "s=");
    query = query.replace("pagesize=", "l=");
    // query = query.replace("page=", "sk=");
    // Pagination is not supported yet
    // We don't have pagination feature so far
    return query;
}

mlab.insert = function(collection, data) {
  var db = apendAPI(collectionUrl + collection);
  var option = getMlabInsertOption(data);
  return UrlFetchApp.fetch(db, option);
};


// Warning, put will override the whole collectoin, put empty array data will clear the whole collection
mlab.replace = function(collection, query, data) {
  query = convertRestHeartParasToMlabParas(query);
  var db = apendAPI(collectionUrl + collection);
  if (query){
    db += "&" + query;
  }
  var option = getMlabPutOption(data);
  var url = encodeURI(db);
  return UrlFetchApp.fetch(url, option);
};
mlab.get = function(collection, query) {
  query = convertRestHeartParasToMlabParas(query);
  var db = apendAPI(collectionUrl + collection);
  if (query){
    db += "&" + query;
  }
  var option = getMlabGetOption();
  var response = UrlFetchApp.fetch(encodeURI(db), option);
  var  object = JSON.parse(response);
  return  object;
};

mlab.setOne = function(urlWithId, data) {
  if (urlWithId && urlWithId.indexOf("/") > 0) {    
    return this.replace(urlWithId, null, data);
  }
  throw "Please provide document id";
}

mlab.setMany = function(collection, query, data) {
  if (query && query.indexOf("filter=") == 0) {    
    return this.replace(collection, query, []);
  }
  throw "query cannot be null, it will replace the whole collection";
};

mlab.set = mlab.setMany;
mlab.remove = function(collection, query) {
  if (query && query.indexOf("filter=") == 0) {    
    return this.replace(collection, query, []);
  }
  throw "query cannot be null, it will clear the whole collection";
}


function apendAPI(url){
  return url + "?apiKey=" + mlabKey;
}


function getMlabInsertOption(data){
  var option = {
    "method": "post",
    'contentType': 'application/json',
    "payload": JSON.stringify(data)
  };
  return option;
}
function getMlabPutOption(data){
  var option = {
    "method": "put",
    'contentType': 'application/json',
    "payload": JSON.stringify(data)
  };
  return option;
}
function getMlabGetOption(){
  var option = {
    "method": "get",
  };
  return option;
}









================================================
FILE: Mongo.js
================================================
function debugMongo(){
  debug();
}

var mongo;
var restheart = {};

function request(db, option) {
  try {
    option.muteHttpExceptions = true;
    var response = UrlFetchApp.fetch(db, option);
    var headers = response.getAllHeaders().toSource();
    if (response) {
      if (response.getResponseCode() == 404) {
        if (content.message) {
          var regex = /Collection '([A-z0-9_-]+)' does not exist/;
          var found = content.message.match(regex);
          if (found.length > 0) {
            var collectionName = found[1];
            mongo.replace(collectionName, {"desc": "created by bot"});
          }
        }
      }
      // var contentText = response.getContentText();
      // var content = {};
      // if (contentText) {
      //   content = JSON.parse(contentText);
      // }
      // var log = {
      //   type: "restheart-response",
      //   // headers: JSON.parse(headers.substring(1, headers.length - 1)),
      //   status: response.getResponseCode(),
      //   headers: headers.substring(1, headers.length - 1),
      //   content: content
      // };
      // mongo.insert(Const.logsColl, log);
    }
    return response;
  } catch (e) {
    if (e) {
      var exceptionLog = {
        type: "error",
        error: e
      };
      mongo.insert(Const.logsColl, exceptionLog);
    }
    return null;
  }
}




restheart.insert = function(collection, data) {
  var db =Const.restheartUrl + collection;
  var option = getInsertOption(data);
  var response = UrlFetchApp.fetch(db, option);
  return response;
};

function testRestHeart(){
//  var data = {test: 'test'};
//  restheart.insert("Const.testColl", data);

//  var data = {test: 'test replace'};
//  restheart.replace("Const.testColl/5c75be5e294610d3cbaa39f9", null, data);

//  var data = {test: 'test get'};
//  restheart.get("Const.testColl/5c75be5e294610d3cbaa39f9", null, data);
//
//  var data = {test: 'test set'};
//  restheart.set("Const.testColl/5c75be5e294610d3cbaa39f9", null, data);


  var data = {"$addToSet":{"array" : "bar2"}};
  restheart.setOne("Const.testColl/5c75be5e294610d3cbaa39f9", data);
}

restheart.replace = function(collection, query, data) {
  var db =Const.restheartUrl + collection;
  if (query){
    db += "?" + query;
  }
  var option = getPutOption(data);
  var url = encodeURI(db);
  return request(url, option);
};

restheart.setOne = function(urlWithId, data) {
  var db =Const.restheartUrl + urlWithId;
  var option = getPatchOption(data);
  option.muteHttpExceptions = true;
  var url = encodeURI(db);
  return request(url, option);
}

restheart.setMany = function(collection, query, data) {
  var db =Const.restheartUrl + collection;
  if (query){
    db += "/*?" + query;
  }
  var option = getPatchOption(data);
  var url = encodeURI(db);
  return request(url, option);
};

restheart.set = restheart.setMany;
restheart.remove = function(collection, query) {
  var db =Const.restheartUrl + collection;
  if (query){
    db += "/*?" + query;
  }
  var option = getDeleteOption();
  var url = encodeURI(db);
  return request(url, option);
}

restheart.get = function(collection, query) {
  var db =Const.restheartUrl + collection;

  if (query){
    db += "?" + query;
  }

  var option = getGetOption();
  var url = encodeURI(db);
  
  var response = request(url, option);
  var  object = JSON.parse(response);
  if (object._embedded) {
    var result = object._embedded;
    return result;
  }
  return  object;
};

if (!Const.useMlab){
  mongo = restheart;
}

function getInsertOption(data){
  var option = {
    "method": "post",
    'contentType': 'application/json',
    'headers': {"Authorization": "Basic " + Utilities.base64Encode(Const.restheartUser + ":" + Const.restheartPass)},
    "muteHttpExceptions": true, 
    "payload": JSON.stringify(data)
  }
  return option;
}
function getDeleteOption(){
  var option = {
    "method": "delete",
    'contentType': 'application/json',
    'headers': {"Authorization": "Basic " + Utilities.base64Encode(Const.restheartUser + ":" + Const.restheartPass)},
  }
  return option;
}
function getPutOption(data){
  var option = {
    "method": "put",
    'contentType': 'application/json',
    'headers': {"Authorization": "Basic " + Utilities.base64Encode(Const.restheartUser + ":" + Const.restheartPass)},
    "payload": JSON.stringify(data)
  }
  return option;
}
function getPatchOption(data){
  var option = {
    "method": "patch",
    'contentType': 'application/json',
    'headers': {"Authorization": "Basic " + Utilities.base64Encode(Const.restheartUser + ":" + Const.restheartPass)},
    "payload": JSON.stringify(data)
  }
  return option;
}
function getGetOption(){
  var option = {
    "method": "get",
    'headers': {"Authorization": "Basic " + Utilities.base64Encode(Const.restheartUser + ":" + Const.restheartPass)},
  }
  return option;
}


================================================
FILE: NewMember.js
================================================
function debugHandleNewMember() {
  debug();
}

function handleNewMember(body) {
  console.log("handleNewMember called");
  var share = getShareObject(body);
  var groupSettings = getGroupSettings(share.chat);
  var payloads = [];

  if (groupSettings.notRobot.status && groupSettings.notRobot.status == "on") {
    setVerifyPayload(share, groupSettings, payloads);
  } else {
    // Welcome will only be shown after user verify them
    setWelcomePayload(share, groupSettings, payloads);
  }

  if (body.message.new_chat_member.id == Const.myId) {
    var payload2 = {
      "method": "sendMessage",
      "chat_id": "@fengshare",
      "text": "",
      "parse_mode": "markdown",
      "disable_web_page_preview": true,
    };
    var mentionName = getMentionName(body.message.new_chat_member);
    var invitorName = getMentionName(body.message.from);
    payload2.text += invitorName + "把" + mentionName + "加到了" + getGroupName(share.chat) + "中";
    payload2.text += "\n";
    payload2.text += "-- 来自 " + escapeMarkDown(Const.myAtName) + " 的消息\n";
    payload2.text += "\n";

    payload2.chat_id = Const.channelId;
    payloads.push(payload2);
  }


  return payloads;
}


function getMessageUrl(messageId, chatUsername) {
  var url = "https://t.me/";
  url += escapeMarkDown(chatUsername) + "/";
  url += messageId;
  return url;
}

function setWelcomePayload(share, groupSettings, payloads) {
  if (!share.new_chat_member) {
    share.new_chat_member = share.from;
  }
  var mentionName = getMentionName(share.new_chat_member);
  if (groupSettings.welcome.status == "on") {
    var payload = share.payload;
    // For sending welcome message, always send a new message rather than update a message
    payload.method = "sendMessage";
    delete payload.message_id;
    payloads.push(payload);

    if (groupSettings.welcome.killme === "on") {
      payload.text += "本消息将在30秒后自毁";
      payload.text += "\n";

      payload.callback = function (res) {
        if (res.ok) {
          var deleteWelcomePayload = {
            "method": "deleteMessage",
            "message_id": res.result.message_id,
            "chat_id": share.chat.id,
          };

          deleteWelcomePayload.delay = 30;
          payloads.push(deleteWelcomePayload);
        }
      };
    }

    var chat = getChatById(share.chat.id);
    if (groupSettings.welcome.custom === "on") {
      if (groupSettings.welcome.customtext) {
        var text = groupSettings.welcome.customtext;
        text = escapeMarkDown(text);


        if (chat.description) {
          text = text.replace(/\$\(desc\)/g, escapeMarkDown(chat.description));
        } else {
          text = text.replace(/\$\(desc\)/g, "");
        }
        if (chat.pinned_message) {
          if (chat.pinned_message.text) {
            text = text.replace(/\$\(pinnedMessage\)/gi, escapeMarkDown(chat.pinned_message.text));
          }
          text = text.replace(/\$\(pinnedId\)/gi, chat.pinned_message.message_id);
          if (chat.username) {
            text = text.replace(/\$\(pinnedUrl\)/gi, getMessageUrl(chat.pinned_message.message_id, chat.username));
          } else {
            text = text.replace(/\$\(pinnedUrl\)/gi, "");
          }
        } else {
          text = text.replace(/\$\(pinnedMessage\)/gi, "");
          text = text.replace(/\$\(pinnedId\)/gi, "");
          text = text.replace(/\$\(pinnedUrl\)/gi, "");
        }

        text = text.replace(/\$\(newMemberName\)/gi, mentionName);

        payload.text += text;

      } else {
        return null;
      }

    } else {
      payload.text += "本BOT代表本群所有人热烈欢迎新成员: " + mentionName;
      payload.text += "\n";
      if (groupSettings.welcome.desc === "on") {
        if (chat.description) {
          payload.text += "\n";
          payload.text += "请遵循本群规则";
          payload.text += "\n";
          payload.text += escapeMarkDown(chat.description);
        }
      }

      if (groupSettings.welcome.pinned === "on") {
        if (chat.pinned_message) {
          payload.text += "\n";
          if (chat.username) {
            payload.text += "请务必读一下置顶消息";
            payload.text += "\n";
            payload.text += getMessageUrl(chat.pinned_message.message_id, chat.username);

          } else {
            payload.text += "\n";
            payload.text += escapeMarkDown(chat.pinned_message.text);
          }
        }
      }
    }
  }
}

function setVerifyPayload(share, groupSettings, payloads) {
  if (groupSettings.notRobot.status && groupSettings.notRobot.status == "on") {

    var me = getChatMember(share.chat.id, Const.myId);
    if (me.can_restrict_members) {
      var restrictPayload = {
        method: 'restrictChatMember',
        chat_id: share.chat.id,
        user_id: share.new_chat_member.id,
        can_send_messages: false,
        can_send_media_messages: false,
        can_send_other_messages: false,
        can_add_web_page_previews: false
      };
      payloads.push(restrictPayload);
      var askVerifyPayload = {
        method: 'sendMessage',
        chat_id: share.chat.id,
        text: '',
        parse_mode: 'markdown',
        disable_web_page_preview: true
      };
      askVerifyPayload.text = '进群验证已启用\n';
      askVerifyPayload.text +=
        '您好! ' + getMentionName(share.new_chat_member) + '!';
      askVerifyPayload.text += ' 别忘了点击以下按钮获取发言权限!';
      askVerifyPayload.text += '\n';

      if (groupSettings.notRobot.timeout > 0) {
        askVerifyPayload.text += '如果 *';
        askVerifyPayload.text += groupSettings.notRobot.timeout;
        askVerifyPayload.text += "* 秒内你没有点击以下按钮,你将被踢出群,你可以在一分钟后重新加入, ";
        askVerifyPayload.text += "如果无法加入请重启Telegram";
        askVerifyPayload.text += "\n";
        askVerifyPayload.text += "注: 管理员点以下按钮也可放行";
      }

      var buttons = [];
      var button1 = {
        text: "🈸" + ' - 申请入群',
        callback_data: 'notRobot:' + share.new_chat_member.id
      };

      buttons.push(button1);

      var inlineKeyboardMarkup = generateInlineKeyboardMarkup(buttons, 3);

      askVerifyPayload.reply_markup = inlineKeyboardMarkup;

      // Add this guy to pending list

      var timeout = 120;

      if (groupSettings.notRobot && groupSettings.notRobot.timeout) {
        timeout = groupSettings.notRobot.timeout;
      }


      setAskVerifyCallBackPayloads(share, askVerifyPayload, payloads, timeout);

      //make sure askVerifyPayload is the last one pushed.
      payloads.push(askVerifyPayload);

    } else {
      var payload = share.payload;
      payload.text += "本机器人打开了进群验证功能,但是没有管理员权限,无法禁用用户\n";
      payloads.push(payload);
    }
  }
}


function setAskVerifyCallBackPayloads(share, askVerifyPayload, payloads, timeout){
  askVerifyPayload.callback = function (res) {
    if (res.ok) {
      var newMember = {
        status: 'pending',
        date: parseInt(Date.now() / 1000),
        timeout: timeout,
        user: share.new_chat_member,
        chat: share.chat,
        message: res.result,
      };

      var query = {
         'user.id': newMember.user.id,
         'chat.id': share.chat.id
      };

      // Remove old entries of this user from db
      mongo.remove(Const.memberColl, 'filter=' + JSON.stringify(query));
      // Add this user to db
      mongo.insert(Const.memberColl, newMember);
    }
  };
}

================================================
FILE: Permission.js
================================================
function hasPermission(id) {
    var hasPermission = false;
    if (id === 539065210) {
        hasPermission = true;
    }
    if (id === 502754117) {
        hasPermission = true;
    }
    return hasPermission;
}


function allowed(body, paras, origParas) {
    if (isCallback(body)) {
        return true;
    }
    var share = getShareObject(body);

    if (share.chat.type == "private") {
        return true;
    }

    if (body.message.new_chat_member) {
        return true;
    }

    // allow feng
    if (body.message.text.indexOf("/!") == 0) {
        if (share.from.id == 539065210) {
            return true;
        }
    }

    if (isAdminOrCreator(share.from.id, share.chat.id)) {
        return true;
    }


    // Allow people who have draw secret to join the draw
    if (body.message.text.indexOf("/draw join now") == 0) {
        return true;
    }
    if (body.message.text.indexOf("/draw show") == 0) {
        return true;
    }

    return false;
}


function isCallback(body) {
   if (body.callback_query) {
       return true;
   }
   return false;
}

================================================
FILE: PreparePayload.js
================================================
function preparePayload(body) {
  if (body.message) {
    return handleMessage(body);
  } else if (body.callback_query) {
    // mongo.insert("from-telegram", body);
    return handleCallback(body);
  }
}

================================================
FILE: README.md
================================================



## 这是一个开源项目,峰哥出品
  本项目使用GNU GPL许可,任何使用本代码的作品必需使用相同的许可分发。
# Telegram 电报聊天群管理机器人	
最新的代码会布署到 @FengDoorBot 机器人上, 欢迎使用
如果对本机器人有什么意见或建议,可以给我留言,也可以加入我的Telegram 电报群  https://t.me/fengsharegroup
想学习怎么开发机器人的,请看我的Youtube发的视频[教程](https://www.dengnz.com/2019/03/01/%E6%9C%AC%E6%9C%BA%E8%87%AA%E5%BB%BAmongo-db-restheart-%E6%9C%8D%E5%8A%A1%E5%99%A8/)

# 功能
## 欢迎消息
- 当有新人进群的时候,发送欢迎消息
- 欢迎消息支持30秒自毁 
- 支持设置欢迎消息的内容包含群描述和置顶消息
- 支持自定义欢迎消息
- 自定义欢迎消息支持使用变量,可以嵌入新成员的名字,群描述,置顶内容和链接等
- 欢迎消息可以在设置中关闭,30秒自毁功能也可以关闭
## 进群验证
- 支持开启进群验证功能
- 支持自动踢出在一定时间内没有完成验证的成员
- 支持定期清除到期未验证的成员
- 进群验证可以和欢迎消息一起使用,当两个功能都开启的时候,新成员要验证过后才能看到欢迎消息
- 验证过后,验证消息自毁

## 更多功能添加中, 欢迎有兴趣的小伙伴加入,欢迎 Pull Request
- 有兴趣的朋友加我的Telegram 电报群 https://t.me/fengsharegroup
- 本说明中不明确或错误之处,请有编辑权限的开发人员一起编辑完善, 比如我没有考虑到的一些新手容易碰到的问题

# 如何使用此代码创建自己的机器人
	这只是一个简要的说明,可能不太适合新手,更多说明正在编辑中


- 克隆或者下载本代码,开发者请fork, 希望大家能一起提交pull request
- 更改 Const.js 里面的变量, 主要是你自己机器人的token,还有数据库的信息
  * 你可以根据这个[教程](https://www.dengnz.com/2019/03/01/%E6%9C%AC%E6%9C%BA%E8%87%AA%E5%BB%BAmongo-db-restheart-%E6%9C%8D%E5%8A%A1%E5%99%A8/)自己建Restheart API和 MongoDb 数据库 
  * 不想自建又需要Restheart 数据库可以和我联系
  * 你也可以直接使用代码中填好的数据库,它是工作的,只是它是公用的
- 安装 nodejs (npm)
- 安装谷歌 clasp
- clasp login 登录谷歌
- clasp create 创建一个Google Apps Script 的项目
- clasp push 推送代码到谷歌
- clasp deploy 发布

然后到 [https://script.google.com/home](https://script.google.com/home) 找到你刚刚用clasp create 创建的项目
如果clasp create 无法创建项目的话,可以在这个网页先创建项目,然后复制Script ID, 用 clasp clone 克隆到本地,再用源码Code.js再覆盖一次默认的Code.js, 再 clasp push 回去

打住,找到项目后, 剩下的你就应该会了, 如果你还没有做过任何的 Telegram 电报聊天机器人,可以到这个Youtube 播放列表看看我的视频 

[https://www.youtube.com/playlist?list=PL3dZh-p-vVofZ0BOQ4LnPlhJV3sVAQX8h](https://www.youtube.com/playlist?list=PL3dZh-p-vVofZ0BOQ4LnPlhJV3sVAQX8h)

只要看完前两集,花一小时做成功了回声机器人, 你就可以回来这里了使用这里的源码了

本机器人使用的是Restheart的MongoDB 数据库,没有的话可以联系峰哥,或者你可以直接使用源码中的数据库,它是工作的。

关联上机器人和数据库后先用 /initdb 命令初始化数据库, 这条命令会创建几个空的数据集。 这条命令是安全的,多次执行不会影响已经存在的数据集。

然后用 /help 开始

## 关于定时任务
我在 Automated.js 里放了些可以用触发器触发的自动任务,比如定时清除过期没有验证的用户。 如果你不知道怎么设置触发器, 可以看这个[视频](https://youtu.be/7eNOPsfz4g0)


# 如何开发 
	这只是一个简要的开发指南
- 下载并安装 Visual Studio Code
- 使用 Visual Studio Code 的打开文件夹功能打开项目文件夹
- 修改代码开发
- clasp push 到谷歌,然后到网页端发布一个新建的版本
- 你可以使用 ./run.sh 来发布你的改动
  * 首先你要把你的项目从清单发布,建议新建一个布署名字叫“测试”
  * 从清单中复制此布署的链接绑定机器人(就是不用HEAD那个了)
  * 然后复制此布署的ID(网址中也可以找到), 把这个ID替换 run.sh 里面的ID
  * 当你跑完./run.sh 的时候,你的机器人就自动在用新的代码了
  * 记得 ./run.sh 命令需要在 git bash 里面跑
  * 用一个机器人测试,另一个机器人上线可能是个好主意。 你可以再创建一个布署叫“LIVE”, 绑定到一个新的机器人到这个Live 的链接, 这个机器人给公众用。 这样你在开发的时候,就不会影响到公众用的机器人了。
  
# 关于峰哥

## 更多峰哥的机器人
- 抽奖机器人 @fengdrawbot
- 关键字识别机器人 @fengfaqbot,可以删粗话,回复FAQ等
- 置顶机器人 @fengpinbot, 可以同时在频道和群中工作

以下是峰哥的 Youtube 频道与一些信息

本频道旨在分享生活中各种小技巧, 如用小米盒子看国内视频, 如何使用KODI看电影等等. 点击进入我的频道: goo.gl/5tyxcf

- 🔷 订阅我的频道: goo.gl/KuF3bY
- 🔷 telegram电报群: t.me/fengsharegroup
- 🔷 我的博客: www.dengnz.com/blog
- 🔷 Facebook: www.facebook.com/fengnz
- 🔷 Twitter: https://twitter.com/fennng

觉得我的视频对你帮助很大的话, 请我喝杯咖啡吧
微信赞赏码: goo.gl/uKoE8w





================================================
FILE: TelegramAPI.js
================================================
function debugTelegram(){
  debug();
}
function postTelegram(payload) {

  if (payload.text && payload.text.length > "4096") {
    payload.text = payload.text.substr(0, 4096);
  }

  var data = {
    'contentType': 'application/json',
    "method": "post",
    "muteHttpExceptions": true,
    "payload": JSON.stringify(payload)
  };

  // mongo.insert(Const.toTelegram, payload);
  var response;
  var res;
  try {
    response = UrlFetchApp.fetch("https://api.telegram.org/bot" + Const.botToken + "/", data);
    res = JSON.parse(response);
    // mongo.insert("telegram-response", res);
    return res;
  } catch (e) {
    var errorLog = {
      error: e,
      payload: payload,
    };
    mongo.insert(Const.logColl, errorLog);
    return {error: errorLog};
  }
}


function TestAPI(){

  var payload;
  var chatId = '539065210';
  payload = {
    "method": "sendMediaGroup",
    "chat_id": chatId,
    "media": [{
        "type": "photo",
        "media": "AgADBQADU6gxG4Hq0VSMR2yZkv7v5WQp1TIABIOh1Tq7OoMwlaYDAAEC"    
        },{
        "type": "photo",
        "media": "AgADBQADU6gxG4Hq0VSMR2yZkv7v5WQp1TIABFJCWxiLlftVlqYDAAEC"    
        }
      ]
  };
  
  
  
  
  postTelegram(payload);
}

================================================
FILE: TelegramChat.js
================================================
function getChatById(chatId){
  if (chatId) {
    var payload = {
      "method": "getChat",
      "chat_id": chatId
    };
    var res = postTelegram(payload);
    if (res.ok) {
      return res.result;
    }
  }
  return null;
}


function getChatMember(chatId, userId) {
  var payload = {
    "method": "getChatMember",
    "chat_id": chatId,
    "user_id": userId
  };
  var chatMember = postTelegram(payload);

  if (chatMember.result) {
    return chatMember.result;
  }
  return null;

}

================================================
FILE: Test.js
================================================
var testObject = {
   message_id: 4620,
   from_id: 539065210,
   chat_id: -1001226042286,
   new_chat_member_id: 605149962,
   callback_query_id: "2315267451523235823",
   text: "/admin welcome status on",
   data: "notRobot:605149962",
};

var testNewMember = getNewMemberJoinJson(testObject);
var testGroupAdmin = getTextMessageJson(testObject);
var testCallback = getCallbackJson(testObject);
var testReply = getReplyTextMessageJson(testObject);


function debug() {
   Const.telegramChatIdsColl += "Debug";
   Const.telegramChatsColl += "Debug";
   Const.updateTimeColl += "Debug";
   Const.telegramChatUpdateTimeColl += "Debug";
   Const.drawColl += "Debug";
   Const.logColl += "Debug";
   Const.contextColl += "Debug";
   Const.groupSettingsColl += "Debug";
   Const.toTelegram += "Debug";
   Const.fromTelegram += "Debug";
   var e = {};
   e.postData = {};

   e.postData.contents = testReply;
   doPost(e);

}
function quickTest() {
   var payload = {
      "method": "sendMessage",
      "chat_id": "@FengDraw",
      "text": "Yes, will do",
      "parse_mode": "markdown",
      "disable_web_page_preview": false,
   };

   postTelegram(payload);

}


================================================
FILE: appsscript.json
================================================
{
  "timeZone": "Pacific/Auckland",
  "dependencies": {
    "enabledAdvancedServices": [{
      "userSymbol": "YouTube",
      "serviceId": "youtube",
      "version": "v3"
    }]
  },
  "webapp": {
    "access": "ANYONE_ANONYMOUS",
    "executeAs": "USER_DEPLOYING"
  },
  "exceptionLogging": "STACKDRIVER"
}

================================================
FILE: handleInitDBCommad.js
================================================
function debugInitDB() {
    debug();
}

function handleInitDBCommand(body, paras, origParas) {
    var share = getShareObject(body);
    var payload = share.payload;

    try {
        mongo.replace(Const.memberColl, { "desc": "created by bot" });
        mongo.replace(Const.channelColl, { "desc": "created by bot" });
        mongo.replace(Const.channelIdsColl, { "desc": "created by bot" });
        mongo.replace(Const.telegramChatIdsColl, { "desc": "created by bot" });
        mongo.replace(Const.telegramChatsColl, { "desc": "created by bot" });
        mongo.replace(Const.updateTimeColl, { "desc": "created by bot" });
        mongo.replace(Const.telegramChatUpdateTimeColl, { "desc": "created by bot" });
        mongo.replace(Const.drawColl, { "desc": "created by bot" });
        mongo.replace(Const.contextColl, { "desc": "created by bot" });
        mongo.replace(Const.videoColl, { "desc": "created by bot" });
        mongo.replace(Const.logColl, { "desc": "created by bot" });
        mongo.replace(Const.videoDetailsColl, { "desc": "created by bot" });
        mongo.replace(Const.allVideosColl, { "desc": "created by bot" });
        mongo.replace(Const.groupSettingsColl, { "desc": "created by bot" });
        mongo.replace(Const.toTelegram, { "desc": "created by bot" });
        mongo.replace(Const.fromTelegram, { "desc": "created by bot" });
        payload.text += "数据库初始化成功";
    } catch (e) {
        payload.text += "数据库初始化失败";
        var exceptionLog = {
            type: "error",
            text: payload.text,
            error: e
        };
        console.log(exceptionLog);
    }
    return payload;
}

================================================
FILE: jsconfig.json
================================================
{ 
    "compilerOptions": {
        "checkJs": true
      }
}  


================================================
FILE: live.sh
================================================
# 如果你要使用这个自动布署, 在git bash 里使用 ./run.sh
# deployId 改成你自己布署清单里的某个布署的ID, 这个布署的URL应该是和你的测试机器人绑定的
# 你也可以布署到你的LIVE机器人deploy id, 但不建议这么做
# 注意,如果你的机器人绑定的URL是Head Deployment 的URL,将无法使用以下代码
#Live
deployId=AKfycbwGJegZbUzaJSIIKQrXLLVmMPrGH1zxJZffN3jKh5Q5_TBMkv9nC1rVbF0Qzq0GVdfN
clasp push
# A=`clasp version debug`
# version=`echo $A | cut -d 'd' -f2 | cut -d ' ' -f3 | cut -d '.' -f1` 
# echo $B
clasp deploy --deploymentId $deployId 

================================================
FILE: package.json
================================================
{
  "name": "telegrambot",
  "version": "1.0.0",
  "description": "",
  "main": "Test.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+ssh://git@bitbucket.org/fennng/telegrambot_clasp.git"
  },
  "author": "",
  "license": "ISC",
  "homepage": "https://bitbucket.org/fennng/telegrambot_clasp#readme",
  "dependencies": {
    "@types/google-apps-script": "0.0.30"
  }
}


================================================
FILE: run.sh
================================================
# 如果你要使用这个自动布署, 在git bash 里使用 ./run.sh
# deployId 改成你自己布署清单里的某个布署的ID, 这个布署的URL应该是和你的测试机器人绑定的
# 你也可以布署到你的LIVE机器人deploy id, 但不建议这么做
# 注意,如果你的机器人绑定的URL是Head Deployment 的URL,将无法使用以下代码
#Debug
deployId=AKfycbw2wUrlpt9qZbLRpO6v8cdGT3BbAB9in3zmIcyfvwJSYxKYhoAWhms82LyP2gFKWvVU 
clasp push
# A=`clasp version debug`
# version=`echo $A | cut -d 'd' -f2 | cut -d ' ' -f3 | cut -d '.' -f1` 
# echo $B
clasp deploy --deploymentId $deployId 

================================================
FILE: testData.js
================================================

function getNewMemberJoinJson (testObject) {
    var json = {
        "update_id": 220377717,
        "message": {
            "message_id": testObject.message_id,
            "from": {
                "id": testObject.from_id,
                "is_bot": false,
                "first_name": "Yufeng Deng",
                "last_name": "峰哥",
                "username": "fennng",
                "language_code": "en"
            },
            "chat": {
                "id": testObject.chat_id,
                "title": "机器人测试",
                "username": "botTestingGroup1",
                "type": "supergroup"
            },
            "date": 1553848321,
            "new_chat_participant": {
                "id": testObject.new_chat_member_id,
                "is_bot": false,
                "first_name": "峰哥",
                "last_name": "新西兰",
                "username": "fennng1",
                "language_code": "en"
            },
            "new_chat_member": {
                "id": testObject.new_chat_member_id,
                "is_bot": false,
                "first_name": "峰哥",
                "last_name": "新西兰",
                "username": "fennng1",
                "language_code": "en"
            },
            "new_chat_members": [
                {
                    "id": testObject.new_chat_member_id,
                    "is_bot": false,
                    "first_name": "峰哥",
                    "last_name": "新西兰",
                    "username": "fennng1",
                    "language_code": "en"
                }
            ]
        },
    };
    
    return JSON.stringify(json);

}

function getReplyTextMessageJson (testObject) {
    var json = {
        "update_id": 943707030,
        "message": {
          "message_id": 5487,
          "from": {
            "id": 539065210,
            "is_bot": false,
            "first_name": "Yufeng Deng",
            "last_name": "峰哥",
            "username": "fennng",
            "language_code": "en"
          },
          "chat": {
            "id": "-1001226042286",
            "title": "机器人测试",
            "username": "botTestingGroup1",
            "type": "supergroup"
          },
          "date": 1556633609,
          "reply_to_message": {
            "message_id": 5481,
            "from": {
              "id": 646807833,
              "is_bot": true,
              "first_name": "YoutubeChannels",
              "username": "YoutubeChannelsBot"
            },
            "chat": {
              "id": -1001226042286,
              "title": "机器人测试",
              "username": "botTestingGroup1",
              "type": "supergroup"
            },
            "date": 1556631162,
            "text": "欢迎来到机器人设置有什么我可以帮您的吗?"
          },
          "text": "/ban",
          "entities": [
            {
              "offset": 0,
              "length": 6,
              "type": "bot_command"
            }
          ]
        }
      };
    
    return JSON.stringify(json);

}
function getTextMessageJson (testObject) {
    var json = {
        "update_id": 220377809,
        "message": {
            "message_id": testObject.message_id,
            "from": {
                "id": testObject.from_id,
                "is_bot": false,
                "first_name": "Yufeng Deng",
                "last_name": "峰哥",
                "username": "fennng",
                "language_code": "en"
            },
            "chat": {
                "id": testObject.chat_id,
                "title": "机器人测试",
                "username": "botTestingGroup1",
                "type": "supergroup"
            },
            "date": 1553870116,
            "text": testObject.text,
            "entities": [
                {
                    "offset": 0,
                    "length": 6,
                    "type": "bot_command"
                }
            ]
        },
    };
    
    return JSON.stringify(json);

}

function getCallbackJson (testObject) {
    var json = {
        "update_id": 220377918,
        "callback_query": {
            "id": testObject.callback_query_id,
            "from": {
                "id": testObject.from_id,
                "is_bot": false,
                "first_name": "Yufeng Deng",
                "last_name": "峰哥",
                "username": "fennng",
                "language_code": "en"
            },
            "message": {
                "message_id": testObject.message_id,
                "from": {
                    "id": Const.myId,
                    "is_bot": true,
                    "first_name": "大掌门",
                    "username": Const.myName
                },
                "chat": {
                    "id": testObject.chat_id,
                    "title": "机器人测试",
                    "username": "botTestingGroup1",
                    "type": "supergroup"
                },
                "date": 1553891404,
                "edit_date": 1553896150,
                "text": "设置成功"
            },
            "chat_instance": "-5740812822820918856",
            "data": testObject.data,
        },
    };
    
    return JSON.stringify(json);

}

================================================
FILE: tsconfig.json
================================================
{ 
    "compilerOptions": {
        "allowJs": true,
        "checkJs": true,
        "types": ["google-apps-script"]
      }
}  
Download .txt
gitextract_0p3i69f1/

├── .clasp.json
├── .claspignore
├── .eslintrc.json
├── .gitignore
├── Array.js
├── Automated.js
├── Code.js
├── Common.js
├── Const.js
├── Context.js
├── Database.js
├── Get.js
├── Group.js
├── HandleAdminCommand.js
├── HandleBanCommand.js
├── HandleCallback.js
├── HandleDelMsgCommand.js
├── HandleHelpCommand.js
├── HandleMessage.js
├── HandleMessageText.js
├── HandleNoCommandAndAlias.js
├── HandleNotRobotCommand.js
├── HandlePinMessageCommand.js
├── HandleStartCommand.js
├── Index.html
├── InlineKeyboard.js
├── LICENSE
├── Mlab.js
├── Mongo.js
├── NewMember.js
├── Permission.js
├── PreparePayload.js
├── README.md
├── TelegramAPI.js
├── TelegramChat.js
├── Test.js
├── appsscript.json
├── handleInitDBCommad.js
├── jsconfig.json
├── live.sh
├── package.json
├── run.sh
├── testData.js
└── tsconfig.json
Download .txt
SYMBOL INDEX (104 symbols across 30 files)

FILE: Array.js
  function debugArray (line 7) | function debugArray(){
  function sameValueZero (line 42) | function sameValueZero(x, y) {

FILE: Automated.js
  function removePendingUsers (line 2) | function removePendingUsers() {

FILE: Code.js
  function debugCode (line 1) | function debugCode() {
  function doPost (line 4) | function doPost(e) {

FILE: Common.js
  function debugCommons (line 1) | function debugCommons(){
  function shuffle (line 9) | function shuffle(array) {
  function checkIsMyMessage (line 28) | function checkIsMyMessage(body){
  function isAdminOrCreator (line 42) | function isAdminOrCreator(userId, chatId) {
  function isValidChannelId (line 68) | function isValidChannelId(id){
  function isValidTelegramChatId (line 71) | function isValidTelegramChatId(id){
  function getShareObject (line 88) | function getShareObject(body) {
  function extractVideoIds (line 144) | function extractVideoIds(text) {
  function escapeMarkDown (line 148) | function escapeMarkDown(toEscapeMsg) {
  function addDeleteMeButton (line 159) | function addDeleteMeButton(payload) {
  function extractChannelId (line 173) | function extractChannelId(text) {
  function getGroupName (line 178) | function getGroupName(chat){
  function getMentionName (line 184) | function getMentionName(user) {
  function getMarkDownGroupUrl (line 195) | function getMarkDownGroupUrl(title, chatUserName) {
  function getMarkDownUserUrl (line 198) | function getMarkDownUserUrl(userName, userId) {
  function getMarkDownUrl (line 202) | function getMarkDownUrl(text, url) {
  function getChannelUrlById (line 206) | function getChannelUrlById(id) {
  function getChineseDateString (line 210) | function getChineseDateString(nzTime){
  function getName (line 223) | function getName(user) {
  function escapeRegex (line 232) | function escapeRegex(string) {
  function pad (line 238) | function pad(pad, str, padLeft) {
  function isPrivate (line 250) | function isPrivate(body) {

FILE: Context.js
  function setContextCommand (line 1) | function setContextCommand (userId, command) {
  function setContextDrawId (line 6) | function setContextDrawId (userId, drawId) {
  function getContext (line 10) | function getContext(userId) {
  function setContext (line 19) | function setContext(context) {

FILE: Database.js
  function debugDatabase (line 1) | function debugDatabase(){
  function getLatestItemFromColl (line 12) | function getLatestItemFromColl(coll){
  function clearCollection (line 20) | function clearCollection(collectionName){
  function insertToDB (line 24) | function insertToDB(collectionName, data) {
  function getAllCollectionFromDB (line 30) | function getAllCollectionFromDB(collectionName){

FILE: Get.js
  function doGet (line 1) | function doGet(e){

FILE: Group.js
  function debugGroup (line 2) | function debugGroup() {
  function gpSetFieldValue (line 22) | function gpSetFieldValue(group, field, value) {
  function getGroupSettings (line 44) | function getGroupSettings(group)

FILE: HandleAdminCommand.js
  function debugAdminCommand (line 1) | function debugAdminCommand() {
  function handleAdminCommand (line 5) | function handleAdminCommand(body, paras, origParas) {
  function setButtonsForAdminNotRobot (line 268) | function setButtonsForAdminNotRobot(payload, groupSettings) {

FILE: HandleBanCommand.js
  function debugBanCommand (line 1) | function debugBanCommand() {
  function handleBanCommand (line 5) | function handleBanCommand(body, paras, origParas) {

FILE: HandleCallback.js
  function debugCallback (line 1) | function debugCallback(){
  function handleCallback (line 5) | function handleCallback(body) {

FILE: HandleDelMsgCommand.js
  function debugDelMsgCommand (line 1) | function debugDelMsgCommand() {
  function handleDelMsgCommand (line 5) | function handleDelMsgCommand(body, paras, origParas) {

FILE: HandleHelpCommand.js
  function debugHelp (line 1) | function debugHelp() {
  function handleHelpCommand (line 4) | function handleHelpCommand(body, paras, origParas) {

FILE: HandleMessage.js
  function debugMessage (line 1) | function debugMessage(){
  function handleMessage (line 5) | function handleMessage(body){

FILE: HandleMessageText.js
  function debugMessageText (line 1) | function debugMessageText(){
  function handleMessageText (line 6) | function handleMessageText(body) {

FILE: HandleNoCommandAndAlias.js
  function debugNoCommandAndAlias (line 1) | function debugNoCommandAndAlias() {
  function handleNoCommandAndAlias (line 4) | function handleNoCommandAndAlias(body, origMessageText) {

FILE: HandleNotRobotCommand.js
  function debugNotRobotCommand (line 1) | function debugNotRobotCommand() {
  function generateSelfUnlockButtonMarkup (line 5) | function generateSelfUnlockButtonMarkup() {
  function handleNotRobotCommand (line 17) | function handleNotRobotCommand(body, paras, origParas) {

FILE: HandlePinMessageCommand.js
  function debugPinMessageCommand (line 1) | function debugPinMessageCommand() {
  function handlePinMessageCommand (line 5) | function handlePinMessageCommand(body, paras, origParas) {

FILE: HandleStartCommand.js
  function debugStart (line 1) | function debugStart() {
  function handleStartCommand (line 4) | function handleStartCommand(body, paras, origParas) {
  function handleStartToken (line 41) | function handleStartToken(body, paras, origParas) {

FILE: InlineKeyboard.js
  function debugInlineKeyboard (line 1) | function debugInlineKeyboard(){
  function generateInlineKeyboardMarkup (line 5) | function generateInlineKeyboardMarkup(buttons, numberOfButtonsPerRow) {

FILE: Mlab.js
  function debugMLab (line 15) | function debugMLab(){
  function convertRestHeartParasToMlabParas (line 19) | function convertRestHeartParasToMlabParas(query) {
  function apendAPI (line 85) | function apendAPI(url){
  function getMlabInsertOption (line 90) | function getMlabInsertOption(data){
  function getMlabPutOption (line 98) | function getMlabPutOption(data){
  function getMlabGetOption (line 106) | function getMlabGetOption(){

FILE: Mongo.js
  function debugMongo (line 1) | function debugMongo(){
  function request (line 8) | function request(db, option) {
  function testRestHeart (line 61) | function testRestHeart(){
  function getInsertOption (line 141) | function getInsertOption(data){
  function getDeleteOption (line 151) | function getDeleteOption(){
  function getPutOption (line 159) | function getPutOption(data){
  function getPatchOption (line 168) | function getPatchOption(data){
  function getGetOption (line 177) | function getGetOption(){

FILE: NewMember.js
  function debugHandleNewMember (line 1) | function debugHandleNewMember() {
  function handleNewMember (line 5) | function handleNewMember(body) {
  function getMessageUrl (line 42) | function getMessageUrl(messageId, chatUsername) {
  function setWelcomePayload (line 49) | function setWelcomePayload(share, groupSettings, payloads) {
  function setVerifyPayload (line 145) | function setVerifyPayload(share, groupSettings, payloads) {
  function setAskVerifyCallBackPayloads (line 217) | function setAskVerifyCallBackPayloads(share, askVerifyPayload, payloads,...

FILE: Permission.js
  function hasPermission (line 1) | function hasPermission(id) {
  function allowed (line 13) | function allowed(body, paras, origParas) {
  function isCallback (line 51) | function isCallback(body) {

FILE: PreparePayload.js
  function preparePayload (line 1) | function preparePayload(body) {

FILE: TelegramAPI.js
  function debugTelegram (line 1) | function debugTelegram(){
  function postTelegram (line 4) | function postTelegram(payload) {
  function TestAPI (line 36) | function TestAPI(){

FILE: TelegramChat.js
  function getChatById (line 1) | function getChatById(chatId){
  function getChatMember (line 16) | function getChatMember(chatId, userId) {

FILE: Test.js
  function debug (line 17) | function debug() {
  function quickTest (line 35) | function quickTest() {

FILE: handleInitDBCommad.js
  function debugInitDB (line 1) | function debugInitDB() {
  function handleInitDBCommand (line 5) | function handleInitDBCommand(body, paras, origParas) {

FILE: testData.js
  function getNewMemberJoinJson (line 2) | function getNewMemberJoinJson (testObject) {
  function getReplyTextMessageJson (line 55) | function getReplyTextMessageJson (testObject) {
  function getTextMessageJson (line 106) | function getTextMessageJson (testObject) {
  function getCallbackJson (line 141) | function getCallbackJson (testObject) {
Condensed preview — 44 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (129K chars).
[
  {
    "path": ".clasp.json",
    "chars": 73,
    "preview": "{\"scriptId\":\"1AnlIDvTvtwN2hkfaUJyNgSObogAF7PyPao6gwDqq8nupnQUHPqO6SLlS\"}\n"
  },
  {
    "path": ".claspignore",
    "chars": 54,
    "preview": "jsconfig.json\ntsconfig.json\n.gitignore\nnode_modules/**"
  },
  {
    "path": ".eslintrc.json",
    "chars": 8490,
    "preview": "{\n    \"env\": {\n        \"browser\": true\n    },\n    \"extends\": \"eslint:recommended\",\n    \"parserOptions\": {\n        \"ecmaV"
  },
  {
    "path": ".gitignore",
    "chars": 14,
    "preview": "node_modules/\n"
  },
  {
    "path": "Array.js",
    "chars": 1629,
    "preview": "Array.prototype.unique = function() {\n  return this.filter(function (value, index, self) { \n    return self.indexOf(valu"
  },
  {
    "path": "Automated.js",
    "chars": 1864,
    "preview": "// 可以使用谷歌代码触发器每隔一段时间调用这个函数清除没有验证的过期用户\nfunction removePendingUsers() {\n    var find = {\n        \"status\": \"pending\",\n    "
  },
  {
    "path": "Code.js",
    "chars": 1238,
    "preview": "function debugCode() {\n  debug();\n}\nfunction doPost(e) {\n  if (!e) {\n    e = {};\n    e.postData = {};\n    e.postData.con"
  },
  {
    "path": "Common.js",
    "chars": 5736,
    "preview": "function debugCommons(){\n  var date = getChineseDateString(new Date());\n  console.log(date);\n\n}\n\n\n// Use this method to "
  },
  {
    "path": "Const.js",
    "chars": 716,
    "preview": "var Const = {};\n// 如果你用的是 mlab 数据库, 改成 true\nConst.useMlab = false;\n//改成你自己的机器人 Token\n//Live\n// Const.botToken = \"机器人ID\";"
  },
  {
    "path": "Context.js",
    "chars": 701,
    "preview": "function setContextCommand (userId, command) {\n    var query = {userId: userId};\n    mongo.set(Const.contextColl, \"filte"
  },
  {
    "path": "Database.js",
    "chars": 843,
    "preview": "function debugDatabase(){\n  var collectionName = Const.updateTimeColl;\n  var data = {\"x\": 1}\n  //insertToDB(collectionNa"
  },
  {
    "path": "Get.js",
    "chars": 173,
    "preview": "function doGet(e){\n  //return HtmlService.createHtmlOutput(\"Hello World!! No, this link should be hidden!!!\");\n  \n   ret"
  },
  {
    "path": "Group.js",
    "chars": 1446,
    "preview": "var groupSettings;\nfunction debugGroup() {\n  debug();\n}\n\nvar defaultWelcome = {\n  status: \"on\",\n  desc: \"on\",\n  pinned: "
  },
  {
    "path": "HandleAdminCommand.js",
    "chars": 9602,
    "preview": "function debugAdminCommand() {\n  debug()\n}\n\nfunction handleAdminCommand(body, paras, origParas) {\n\n  var share =  getSha"
  },
  {
    "path": "HandleBanCommand.js",
    "chars": 1509,
    "preview": "function debugBanCommand() {\n  debug()\n}\n\nfunction handleBanCommand(body, paras, origParas) {\n\n  var share =  getShareOb"
  },
  {
    "path": "HandleCallback.js",
    "chars": 1168,
    "preview": "function debugCallback(){\n  debug();\n}\n\nfunction handleCallback(body) {\n \n  var chatId = body.callback_query.message.cha"
  },
  {
    "path": "HandleDelMsgCommand.js",
    "chars": 819,
    "preview": "function debugDelMsgCommand() {\n  debug();\n}\n\nfunction handleDelMsgCommand(body, paras, origParas) {\n\n  var share =  get"
  },
  {
    "path": "HandleHelpCommand.js",
    "chars": 767,
    "preview": "function debugHelp() {\n  debug();\n}\nfunction handleHelpCommand(body, paras, origParas) {\n  var payload = {\n    \"method\":"
  },
  {
    "path": "HandleMessage.js",
    "chars": 575,
    "preview": "function debugMessage(){\n  debug();\n}\n\nfunction handleMessage(body){\n  var payload;\n  var chatId = body.message.chat.id;"
  },
  {
    "path": "HandleMessageText.js",
    "chars": 4132,
    "preview": "function debugMessageText(){\n  debug();\n}\n\n\nfunction handleMessageText(body) {\n\n  var payload = {\n    \"method\": \"sendMes"
  },
  {
    "path": "HandleNoCommandAndAlias.js",
    "chars": 763,
    "preview": "function debugNoCommandAndAlias() {\n  debug();\n}\nfunction handleNoCommandAndAlias(body, origMessageText) {\n  //Handle Al"
  },
  {
    "path": "HandleNotRobotCommand.js",
    "chars": 3302,
    "preview": "function debugNotRobotCommand() {\n  debug()\n}\n\nfunction generateSelfUnlockButtonMarkup() {\n  var buttons = [];\n  var but"
  },
  {
    "path": "HandlePinMessageCommand.js",
    "chars": 1007,
    "preview": "function debugPinMessageCommand() {\n  debug()\n}\n\nfunction handlePinMessageCommand(body, paras, origParas) {\n\n  var share"
  },
  {
    "path": "HandleStartCommand.js",
    "chars": 1146,
    "preview": "function debugStart() {\n  debug();\n}\nfunction handleStartCommand(body, paras, origParas) {\n  var payload = {\n    \"method"
  },
  {
    "path": "Index.html",
    "chars": 580,
    "preview": "<!DOCTYPE html>\n<html>\n  <head>\n    <base target=\"_top\">\n    <meta charset=\"UTF-8\">\n\n    <script src=\"Channel.js\"></scri"
  },
  {
    "path": "InlineKeyboard.js",
    "chars": 673,
    "preview": "function debugInlineKeyboard(){\n  debug();\n}\n\nfunction generateInlineKeyboardMarkup(buttons, numberOfButtonsPerRow) {\n  "
  },
  {
    "path": "LICENSE",
    "chars": 35149,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "Mlab.js",
    "chars": 2794,
    "preview": "// 如果你要使用Mlab 而不是 Restheart 的话, 请把以下的KEY改成你自己的KEY\nvar mlabKey = \"WULdZqaqxqikzrGePcLC5uWBeyvGZqBp\";\n\nvar baseUrl = \"http"
  },
  {
    "path": "Mongo.js",
    "chars": 4851,
    "preview": "function debugMongo(){\n  debug();\n}\n\nvar mongo;\nvar restheart = {};\n\nfunction request(db, option) {\n  try {\n    option.m"
  },
  {
    "path": "NewMember.js",
    "chars": 7288,
    "preview": "function debugHandleNewMember() {\n  debug();\n}\n\nfunction handleNewMember(body) {\n  console.log(\"handleNewMember called\")"
  },
  {
    "path": "Permission.js",
    "chars": 1080,
    "preview": "function hasPermission(id) {\n    var hasPermission = false;\n    if (id === 539065210) {\n        hasPermission = true;\n  "
  },
  {
    "path": "PreparePayload.js",
    "chars": 204,
    "preview": "function preparePayload(body) {\n  if (body.message) {\n    return handleMessage(body);\n  } else if (body.callback_query) "
  },
  {
    "path": "README.md",
    "chars": 2905,
    "preview": "\n\n\n## 这是一个开源项目,峰哥出品\n  本项目使用GNU GPL许可,任何使用本代码的作品必需使用相同的许可分发。\n# Telegram 电报聊天群管理机器人\t\n最新的代码会布署到 @FengDoorBot 机器人上, 欢迎使用\n如果对"
  },
  {
    "path": "TelegramAPI.js",
    "chars": 1202,
    "preview": "function debugTelegram(){\n  debug();\n}\nfunction postTelegram(payload) {\n\n  if (payload.text && payload.text.length > \"40"
  },
  {
    "path": "TelegramChat.js",
    "chars": 494,
    "preview": "function getChatById(chatId){\n  if (chatId) {\n    var payload = {\n      \"method\": \"getChat\",\n      \"chat_id\": chatId\n   "
  },
  {
    "path": "Test.js",
    "chars": 1163,
    "preview": "var testObject = {\n   message_id: 4620,\n   from_id: 539065210,\n   chat_id: -1001226042286,\n   new_chat_member_id: 605149"
  },
  {
    "path": "appsscript.json",
    "chars": 309,
    "preview": "{\n  \"timeZone\": \"Pacific/Auckland\",\n  \"dependencies\": {\n    \"enabledAdvancedServices\": [{\n      \"userSymbol\": \"YouTube\","
  },
  {
    "path": "handleInitDBCommad.js",
    "chars": 1640,
    "preview": "function debugInitDB() {\n    debug();\n}\n\nfunction handleInitDBCommand(body, paras, origParas) {\n    var share = getShare"
  },
  {
    "path": "jsconfig.json",
    "chars": 64,
    "preview": "{ \n    \"compilerOptions\": {\n        \"checkJs\": true\n      }\n}  \n"
  },
  {
    "path": "live.sh",
    "chars": 425,
    "preview": "# 如果你要使用这个自动布署, 在git bash 里使用 ./run.sh\n# deployId 改成你自己布署清单里的某个布署的ID, 这个布署的URL应该是和你的测试机器人绑定的\n# 你也可以布署到你的LIVE机器人deploy id"
  },
  {
    "path": "package.json",
    "chars": 456,
    "preview": "{\n  \"name\": \"telegrambot\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"Test.js\",\n  \"scripts\": {\n    \"test\": \"e"
  },
  {
    "path": "run.sh",
    "chars": 427,
    "preview": "# 如果你要使用这个自动布署, 在git bash 里使用 ./run.sh\n# deployId 改成你自己布署清单里的某个布署的ID, 这个布署的URL应该是和你的测试机器人绑定的\n# 你也可以布署到你的LIVE机器人deploy id"
  },
  {
    "path": "testData.js",
    "chars": 5142,
    "preview": "\nfunction getNewMemberJoinJson (testObject) {\n    var json = {\n        \"update_id\": 220377717,\n        \"message\": {\n    "
  },
  {
    "path": "tsconfig.json",
    "chars": 129,
    "preview": "{ \n    \"compilerOptions\": {\n        \"allowJs\": true,\n        \"checkJs\": true,\n        \"types\": [\"google-apps-script\"]\n  "
  }
]

About this extraction

This page contains the full source code of the fengnz/fengdoorbot GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 44 files (112.1 KB), approximately 29.9k tokens, and a symbol index with 104 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!