接外包,有相关需求的可以联系我:Telegram | Email

Telegram机器人🤖️

该文章创建(更新)于04/18/2020,请注意文章的时效性!

缘由

最近让朋友上线telegram,由于家里的电脑是在辣鸡,自己就租了一个阿里云服务器搭建了一个jupyter lab。看到有人用这个telegram的bot来管理vps,自己就尝试了一下。嗯,真香!

环境

  • 用的python,尝试过sh来配置,奈何没什么用过,就放弃了;
  • 包是telegram官方的telethon,有其它包,但感觉还是官方好一些。虽说资料都是英文,刚开始自己也有点抵触,但奈何没中文版。就尝试去看了一下,感觉没自己想象的困难,而且我碰到的问题里面都有解决方案和缘由;
  • 获取系统信息是psutil

搭建

创建机器人🤖️

  • 在telegram里面搜索BotFather按引导创建即可; > 创建成功后会给你一个token,注意后面要用。这个可以更改!

B2F4C839-FF13-4B72-A33C-7C742149A557-1

获取调用API所需的信息

信息分别是api_hash、api_id

注册

注意

  • 填手机号,如为国内的手机号,手机号前面加+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,输入电话会要求验证码,个人感觉有点麻烦!
79CB3AC5-C853-4350-ABEF-8BF9DCB65DE8

    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 EF4D0BB2-DEF5-4659-A5AB-5F908015BEC0
  • 使用command和key word获取的信息; C5ECF250-1F86-42B2-8505-BE9ED0899152
  • say hi! 751AEEF4-C6F5-45B9-8661-97A920785582

  • 如果提示什么database is locked,就把session文件删除重新运行即可;

官方有一些常见问题的解决办法和缘由!

9EA2D779-3BA5-4AFD-B1CD-76FDCE6AF499

守护进程 | 更新(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 ?

如果想了解更过,自己去看文档吧!


要不赞赏一下?

微信
支付宝
PayPal
Bitcoin

版权声明 | Copyright

除非特别说明,本博客所有作品均采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。转载请注明转自-
https://www.emperinter.info/2020/04/18/telegram-bot/


要不聊聊?

我相信你准备留下的内容是经过思考的!【勾选防爬虫,未勾选无法留言】

*

*



微信公众号

优惠码

阿里云国际版20美元
Vultr10美元
搬瓦工 | Bandwagon应该有折扣吧?
域名 | namesiloemperinter(1美元)