Code012

C

简单Telegram Bot,通过Telegram Bot来更新Cloudflare DDNS IP。

使用NPM/Node.JS搭建简单Telegram Bot,使用node-telegram-bot-api.

环境Ubuntu 18.04LTS。

首先是安装NPM:

sudo apt-get install npm

安装好后安装Node.JS:

curl -sL https://deb.nodesource.com/setup_13.x | sudo -E bash -
sudo apt-get install -y nodejs

安装好之后查看通过-v查看各自的版本,我使用的版本是:

新建一个文件夹,然后初始化NPM

npm init -y

新的一个package.json描述文件完成,接下来先添加一些dependency:

首先是node-telegram-bot-api

npm i node-telegram-bot-api

然后因为我的机子是在国内,所以用Socks5来连外网和Telegram通讯:

npm i socks5-https-client

有这些就差不多了,开始配置文件啦

首先在Telegram里面找到@BotFather,输入指令/newbot便可以通过指引创建bot

  1. Alright, a new bot. How are we going to call it? Please choose a name for your bot.
  2. Good. Now let’s choose a username for your bot. It must end in bot. Like this, for example: TetrisBot or tetris_bot.

回答完问题后会给出你的Bot的API Token,通过Token可以和Bot建立链接,别泄露了Toke噢。

刚刚初始化好了文件夹,创建index.js,内容可以用官方文档做例子:

const TelegramBot = require('node-telegram-bot-api');

// replace the value below with the Telegram token you receive from @BotFather
const token = 'YOUR_TELEGRAM_BOT_TOKEN';

// Create a bot that uses 'polling' to fetch new updates
const bot = new TelegramBot(token, {polling: true});

// Matches "/echo [whatever]"
bot.onText(/\/echo (.+)/, (msg, match) => {
  // 'msg' is the received Message from Telegram
  // 'match' is the result of executing the regexp above on the text content
  // of the message

  const chatId = msg.chat.id;
  const resp = match[1]; // the captured "whatever"

  // send back the matched "whatever" to the chat
  bot.sendMessage(chatId, resp);
});

// Listen for any kind of message. There are different kinds of
// messages.
bot.on('message', (msg) => {
  const chatId = msg.chat.id;

  // send a message to the chat acknowledging receipt of their message
  bot.sendMessage(chatId, 'Received your message');
});
Documen

这样找到你的Bot,输入echo -something,他就会有反应啦!

才没有呢,骗你的 (如果你的机子也在国内的话

国内机子需要走代理,加入我们刚刚下载好的dependency:然后用本地localhost的共享端口链接酸酸乳,我的代码如下:

const TelegramBot = require('node-telegram-bot-api');
const Agent = require('socks5-https-client/lib/Agent');
const shell = require('shelljs');
const fs = require("fs");
const path = require("path");
const filePath = path.join(__dirname, '/res.txt');

const token = 'TOKEN HERE';
const bot = new TelegramBot(token, {
  polling: true,
  request: { // 设置代理
    agentClass: Agent,
    agentOptions: {
            socksPort: 1083  // SOCKS5 localhost 端口
    }
  }
});

bot.onText(/\/echo (.+)/, (msg, match) => {
  // 'msg' is the received Message from Telegram
  // 'match' is the result of executing the regexp above on the text content
  // of the message

  const chatId = msg.chat.id;
  const resp = match[1]; // the captured "whatever"

  // send back the matched "whatever" to the chat
  bot.sendMessage(chatId, resp);
});
bot.onText(/\/check/, function onLoveText(msg) {
  bot.sendMessage(msg.chat.id, 'Start Checking...');
  shell.exec('./start.sh > ./res.txt');
  bot.sendMessage(msg.chat.id, 'Wait 3s');
  setTimeout(function (){
        fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
    if (err) {
        bot.sendMessage(msg.chat.id, 'Cannot Read Response File')
    } else {
       bot.sendMessage(msg.chat.id, data);  // 将执行情况推送到Bot上
    }
  });
  bot.sendMessage(msg.chat.id, 'Done!');
}, 3000);
});

接下来上线一下:Node index.js就可以使用(前面记录删掉了没有截图quq

我在这里配置来/check,不过这应该算是假的命令,在Bot那里没有自动补全,应该只是通过文本来处理的(官方的Template好像也有点这个味道)

程序里面加了个./start.sh脚本,用来刷新clouflare的DNS记录来达到DDNS对抗动态公网IP:

这里安装了cloudflare-ddns-client,安装详细过程在Repo的README自取。如何获取Token/KEY参考原来这篇文章

start.sh里面,主要是执行DDNS更新的命令,不过因为挂了梯子,所以要把梯子先关掉。(因为是好像是子程序所以应该不用后面加回来)

#!/bin/bash
echo "Start Processing IP Check"
date
echo "Unset ALL_PROXY"
unset ALL_PROXY
echo "Unset Done"
echo "Start DDNS Script"
LOG="$(cloudflare-ddns --update-now)"
echo "Program Output:"
echo "$LOG"
echo "$LOG" > ./result.txt
echo "Write to File Done"
echo "Get Proxy Back"
export ALL_PROXY=socks5://127.0.0.1:1083
echo "Done!"

将DDNS更新输入到同一个目录的result.txt里面,便于查看

整个脚本echo出来的东西都会被装到同一目录下res.txt文件中,最终被推送到Bot再到手机街面上。

(其实用crontab就可以解决所有事情为什么我要用Telegram Bot呢???

我的crontab指令好像没有响过一个,然后因为机子在国内,人在国外,每次调试要通过国内的人开远程桌面什么的(还是QQ远程桌面,有空一定要把Windows远程配置好),Telegram Bot确实方便了很多。

安装pm2来加载后台:npm i pm2,然后使用pm2 start index.js --name bot运行

使用效果图:

Add comment

There is a Google reCAPTCHA underneath. Access it with a ladder if you can't see it~

About

Ambitious Egotist's Blog
For life
For code
For physics

Handle With Passion ❤