文章目录[隐藏]
缘由
最近让朋友上线telegram,由于家里的电脑是在辣鸡,自己就租了一个阿里云服务器搭建了一个jupyter lab。看到有人用这个telegram的bot来管理vps,自己就尝试了一下。嗯,真香!
环境
- 用的python,尝试过sh来配置,奈何没什么用过,就放弃了;
- 包是telegram官方的telethon,有其它包,但感觉还是官方好一些。虽说资料都是英文,刚开始自己也有点抵触,但奈何没中文版。就尝试去看了一下,感觉没自己想象的困难,而且我碰到的问题里面都有解决方案和缘由;
- 获取系统信息是psutil
搭建
创建机器人🤖️
- 在telegram里面搜索BotFather按引导创建即可; > 创建成功后会给你一个token,注意后面要用。这个可以更改!
获取调用API所需的信息
信息分别是api_hash、api_id
注册
- 登入 https://my.telegram.org/即可;
注意
- 填手机号,如为国内的手机号,手机号前面加+86
- 如果telegram登陆在线,会直接发送到telegram上,我没收到信息;
python包
psutil
- Linux Ubuntu / Debian:
sudo apt-get install gcc python3-dev
sudo pip3 install psutil
- Linux Redhat:
sudo yum install gcc python3-devel
sudo pip3 install psutil
- Windows:
pip3 install psutil
telethon(最新版本)
pip3 install -U https://github.com/LonamiWebs/Telethon/archive/master.zip
测试
更新(2020-05-16)
token也可直接嵌入,免去验证
from telethon import TelegramClient, events
import psutil,datetime
"""
telethon: telegram api
more in:https://docs.telethon.dev/en/latest/
psutil: get system information
more in:https://psutil.readthedocs.io/en/latest/
"""
"""
get some telegram information in:https://api.telegram.org
get a new bot,search Botfather in telegram and you can get something!
"""
api_id= your_id
api_hash = 'your_hash'
bot_token = 'your_token'
#define some function to get system info!
#get MemUsed
def GetMemUsed():
return psutil.virtual_memory().used
def GetMemFree():
return psutil.virtual_memory().free/1024/1024
def GetMemTotal():
return psutil.virtual_memory().total
#get MemUsedPercent()
def GetMemUsedPercent():
return int(GetMemUsed()/float(GetMemTotal())*100)
#get bootime()
def GetBootTime():
return datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
#get diskinfo()
def GetDiskFree():
return psutil.disk_usage('/').free/1024/1024/1024
SystemInfo = str('MemFree:' + str(int(GetMemFree())) + ' M\n\nBootTime:' + str(GetBootTime()) + '\n\nFreeDisk:' + str(int(GetDiskFree())) + ' G')
client = TelegramClient('bot', api_id, api_hash).start(bot_token=bot_token)
# print('start\n\n')
@client.on(events.NewMessage)
async def my_event_handler(event):
if 'hello' in event.raw_text:
await event.reply('hi!')
print('\n\nMessage: hello')
elif 'info' in event.raw_text:
await event.reply(SystemInfo)
print('\n\nMessage: info \n\n\n' + SystemInfo)
# else:
# await event.reply('😄Try to use another key words !')
# print('\n Message: not key words !')
client.start()
client.run_until_disconnected()
# 和nohup的功能类似,不断运行!但这个是有问题就失败,但nohup则不会!
print('\n warrning ! disconnected !')
测试代码(自己写了一个小的代码)
注意替换api为自己的api,保存成文件后运行。自己在jupyter lab运行会失败!运行会让你输入电话或token,我一般选token,输入电话会要求验证码,个人感觉有点麻烦!
from telethon import TelegramClient, events
import psutil,datetime
"""
telethon: telegram api
more in:https://docs.telethon.dev/en/latest/
psutil: get system information
more in:https://psutil.readthedocs.io/en/latest/
get some telegram information in:https://api.telegram.org
get a new bot,search Botfather in telegram and you can get something!
"""
api_id= your api_id
api_hash = 'your api_hash'
#define some function to get system info!
#get MemUsed
def GetMemUsed():
return psutil.virtual_memory().used
def GetMemFree():
return psutil.virtual_memory().free/1024/1024
def GetMemTotal():
return psutil.virtual_memory().total
#get MemUsedPercent()
def GetMemUsedPercent():
return int(GetMemUsed()/float(GetMemTotal())*100)
#get bootime()
def GetBootTime():
return datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
#get diskinfo()
def GetDiskFree():
return psutil.disk_usage('/').free/1024/1024/1024
SystemInfo = str('MemFree:' + str(GetMemFree()) + 'nnBootTime:' + str(GetBootTime()) + 'nnFreeDisk:' + str(float(GetDiskFree())) + 'G')
client = TelegramClient('bot', api_id, api_hash)
@client.on(events.NewMessage)
async def my_event_handler(event):
if 'hello' in event.raw_text:
await event.reply('hi!')
elif 'info' in event.raw_text:
await event.reply(SystemInfo)
else:
await event.reply('😄Try to use another key words !')
client.start()
client.run_until_disconnected()`</pre>
该代码实现的功能
- 把info(区分大小写)回复给机器人,它会返回部分服务器信息,回复hello它会回复hi;也可把这两个在BotFather那里设置为command;
- 在BotFather设置command
- 使用command和key word获取的信息;
- say hi!
-
如果提示什么database is locked,就把session文件删除重新运行即可;
官方有一些常见问题的解决办法和缘由!
守护进程 | 更新(2020-05-16)
#! /bin/sh
#进程名字可修改
PRO_NAME="bot.py"
#打开特定工作目录
cd /home/lab/Telegram
while true
do
T=$(date)
#用ps获取$PRO_NAME进程数量
Process=`ps aux | grep "${PRO_NAME}" | grep -v grep `
# echo "$T : $Process"
NUM=`ps aux | grep "${PRO_NAME}" | grep -v grep |wc -l`
# echo "$T : ${NUM}"
#少于1,重启进程
if [ "${NUM}" -lt "1" ];then
echo "$T"
echo "${PRO_NAME} was killed,started again !"
nohup python3 -u bot.py >> bot.log 2>&1 &
sleep 10s
#大于1,杀掉所有进程,重启
elif [ "${NUM}" -gt "1" ];then
echo "$T"
echo "more than 1 ${PRO_NAME},killall ${PRO_NAME}"
echo "$Process"
ps -ef | grep $PRO_NAME | grep -v grep| grep -v "bot.sh" | cut -c 9-15 | xargs kill -9
nohup pyton3 -u bot.py >> bot.log 2>&1 &
sleep 10s
fi
sleep 60s
done
exit 0
Wanna More ?
如果想了解更过,自己去看文档吧!