前言
之前在多次比赛中都遇到了telegram的机器人,那么自己尝试搭建一个属于自己的机器人玩玩~
前期准备
本次搭建需要准备的东西有:
1.Telegram客户端
2.Python3的运行环境(python2应该也可以)
3.合理的科学上网手段
4.一丢丢的编程知识
搭建过程
Telegram下载
直接去官网下载,网址为https://telegram.org/
然后打开后注册账号,注册完成后就自动进入了tg(以下内容均用tg代称telegram)的页面
Bot的开通
注册好tg后,搜索@botfather
点击进入后,使用/newbot来创建一个bot,接下来会让你输入一些bot的信息,设置完后,会显示出你的token
请保存这个token并不要泄露给其他人,这个token将在之后的步骤中起到很重要的用途
bot测试
接下来我们测试bot是否能收到我们的信息,首先你得在tg中按照之前的步骤,添加你的bot,名字是你最后设置的那个名字
然后打开这个网址https://api.telegram.org/bot```你的token```/getupdates
把网址里的你的token替换为之前得到的那串字符串,正常情况下打开后你会看到
然后向你在tg里的bot发送一条消息,刷新页面后你应该会看到
python编写脚本
首先,用pip安装telepot
python3 -m pip install telepot
先写一个简单的脚本测试bot
import telepot
bot = telepot.Bot('你的token')
print(bot.getMe())
注意,请在科学上网的服务器或电脑上运行,否则无法得到返回信息,正常情况下,会返回
编写命令自动返回对话脚本
首先,在botfather里,有一个setcommand指令
输入后,它会要求你按一定的格式输入你需要的命令和命令的介绍
OK. Send me a list of commands for your bot. Please use this format:
command1 - Description
command2 - Another description
比如我输入
flag - Get the flag
那么当你对输入/flag,就是运行了这个命令
接来下,我们编写后台的返回值,依旧使用python
import time
import telepot
from telepot.loop import MessageLoop
def handle(msg):
content_type, chat_type, chat_id = telepot.glance(msg)
print(content_type, chat_type, chat_id)
if msg['text'] == '/flag':
bot.sendMessage(chat_id, '你想要flag吗?')
else :
bot.sendMessage(chat_id, "I don't understand your mean")
TOKEN = '你的token'
bot = telepot.Bot(TOKEN)
MessageLoop(bot, handle).run_as_thread()
print ('Listening ...')
# 设置脚本运行时间.
while 1:
time.sleep(100000000)
运行后,我们去tg里试试
那么,一个简单的机器人就搭建完成了~
hint:Bot脚本已经上传到github哟,快去找找我的github吧