【发布时间】:2018-10-13 09:41:21
【问题描述】:
我想知道如何在 Telegram 上创建机器人并发送消息,并发送命令,例如 /commandPi sudo apt-get update ... 您需要使用信息配置机器人并创建令牌,但我不知道如何对其进行编程。您需要用 Python 修改“机器人档案”或其他东西吗? 泰
【问题讨论】:
标签: python raspberry-pi telegram-bot python-telegram-bot
我想知道如何在 Telegram 上创建机器人并发送消息,并发送命令,例如 /commandPi sudo apt-get update ... 您需要使用信息配置机器人并创建令牌,但我不知道如何对其进行编程。您需要用 Python 修改“机器人档案”或其他东西吗? 泰
【问题讨论】:
标签: python raspberry-pi telegram-bot python-telegram-bot
注意:允许通过 Web 界面直接访问命令行不是一个好主意。有人可能会发送恶意命令让您的机器人在您的 Raspberry Pi 上执行并控制它!
我所描述的内容可以在(以及许多其他操作手册)中找到: https://www.hackster.io/Salmanfarisvp/telegram-bot-with-raspberry-pi-f373da
通过向 BotFather 发送请求来创建新机器人:
/新机器人
并按照 BotFather 给出的说明进行操作。
如果您的 RPi 上没有 git 和 python,请安装它。
下载现有的 bot python 脚本进行修改(如我链接的文章中建议的那样):
或创建您自己的。
编辑 telegrambot.py 文件并更改行
bot = telepot.Bot('Bot Token')
包含您的令牌而不是 Bot 令牌
最后换行(或添加新行):
if command == 'on':
elif command =='off':
匹配您想要发送的任何命令。既然你想写的不仅仅是一个单词的命令,可以看看startswith:
if command.startswith('commandPi'):
并提取其余参数以传递给您的命令行
arguments = command[8:]
并调用 apt-get,例如使用https://stackoverflow.com/a/8482033/1619146 中描述的子进程
from subprocess import STDOUT, check_call
import os
check_call(['apt-get', 'update'],
stdout=open(os.devnull,'wb'), stderr=STDOUT)
【讨论】: