這是我第二篇文章有關於 Telegram 機器人,此機器人的功能極其簡單!監控伺服器的使用率,最近因為在伺服器又搞了一個很麻煩的東西,要時時刻刻注意有沒有異常。所以才寫了這個小程式(如圖)。
本文直接省略@BotFather產生機器人的說明,我想那應該不是問題。第一篇文章請參考:淺談Telegram開發機器人
本程式一旦運行,就不會停止,每隔固定幾秒鐘會自動更新訊息,會一直不斷的編輯,而不是一直送出(Telegram 有支持編輯訊息的功能)。直接上程式碼。這次使用Python,因為牽扯到系統,用 PHP 就不太適合了。
# coding: utf-8
"""By Weil Jimmer"""
import os,urllib.request,shutil,sys,re,datetime,json,psutil
from time import sleep
from sys import platform as _platform
def __init__(self):
print("")
GRAY = "\033[1;30m"
RED = "\033[1;31m"
LIME = "\033[1;32m"
YELLOW = "\033[1;33m"
BLUE = "\033[1;34m"
MAGENTA = "\033[1;35m"
CYAN = "\033[1;36m"
WHITE = "\033[1;37m"
BGRAY = "\033[1;47m"
BRED = "\033[1;41m"
BLIME = "\033[1;42m"
BYELLOW = "\033[1;43m"
BBLUE = "\033[1;44m"
BMAGENTA = "\033[1;45m"
BCYAN = "\033[1;46m"
BDARK_RED = "\033[1;48m"
UNDERLINE = "\033[4m"
END = "\033[0m"
if _platform.find("linux")<0:
GRAY = ""
RED = ""
LIME = ""
YELLOW = ""
BLUE = ""
MAGENTA = ""
CYAN = ""
WHITE = ""
BGRAY = ""
BRED = ""
BLIME = ""
BYELLOW = ""
BBLUE = ""
BMAGENTA = ""
BCYAN = ""
UNDERLINE = ""
END = ""
os.system("color c")
print (RED)
print ("*" * 40)
print ("* Name:\tServer Status Telegram Bot")
print ("* Team:" + LIME + "\tWhite Birch Forum Team" + RED)
print ("* Developer:\tWeil Jimmer")
print ("* Website:\thttps://weils.net/")
print ("* Date:\t2016.07.04")
print ("*" * 40)
print (END)
chat_id = "123456789"
api_key = "123456789:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
root_dir = "/tmp/"
msg_id = ""
sleep_second = 5
def int_s(k):
try:
return int(k)
except:
return -1
def reporthook2(blocknum, blocksize, totalsize):
do_nothing=True
def url_encode(url_):
return urllib.parse.quote(url_, safe='~@#$&()*!+=:;,.?/\'')
def upload_URL(url,encode,data_X,method_X):
file_name="temp_file_pyserverstatus"
opener = urllib.request.FancyURLopener({})
opener.version = 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36'
opener.addheader("Referer", url)
opener.addheader("X-Forwarded-For", "0.0.0.0")
opener.addheader("Client-IP", "0.0.0.0")
if method_X=="POST":
local_file,response_header=opener.retrieve(url_encode(url), root_dir + file_name, reporthook2, urllib.parse.urlencode(data_X))
else:
local_file,response_header=opener.retrieve(url, root_dir + file_name, reporthook2)
return open(local_file,encoding=encode).read()
def api_make_req_json(data_X):
api_url = "https://api.telegram.org/bot" + api_key + "/"
response=(upload_URL(api_url,"utf-8",data_X,"POST"))
return json.loads(response)
def sendMessage(text,chatid):
return api_make_req_json({"method":"sendMessage","chat_id":chatid,"text":text})
def editMessageText(text,chatid,messageid):
return api_make_req_json({"method":"editMessageText","chat_id":chatid,"message_id":messageid,"text":text})
while True:
time_now_str = "當前時間:\n" + str(datetime.datetime.now())
cpu_useage_str = "CPU使用率:" + str(psutil.cpu_percent(interval=1)) + " %"
memory_useage = psutil.virtual_memory()
memory_useage_str = "記憶體使用率:" + str(memory_useage.percent) + " %\n已用:" + str(round(memory_useage.total*0.01*memory_useage.percent/1024/1024/1024,3)) + " GB" + "\n總共:" + str(round(memory_useage.total/1024/1024/1024,3)) + " GB"
str_value = time_now_str + "\n" + cpu_useage_str + "\n" + memory_useage_str
if msg_id=="":
dom=sendMessage(str_value,chat_id)
msg_id=dom['result']['message_id']
else:
editMessageText(str_value,chat_id,msg_id)
sleep(sleep_second)
input("\n\n請輸入ENTER鍵結束...")
若在 Linux 的環境下,使用 tmux 輸入指令會比較好。因為它可以在背景運作,可以直接關掉 terminal。