Telegram Bot的Python接口使用

By | 2017年12月22日

原来部署的是基于php版本的接口,《Telegram Bot部署和配置》,最近部署了下Python版本的,重新申请了个bot,测试了几个Command。

Python版的接口地址:https://python-telegram-bot.org/

安装很简单,直接pip即可:

pip install python-telegram-bot

安装完成后,就可以开始使用了。

Bot的消息处理有两种方式,一种是被动的Webhook,一种是主动的Update,这里使用python接口的update方式,简单更快的上手。

首先新建一个config.json文件,保存token配置信息:

{
	"BOT_TOKEN":"463114q8xxxx"
}

然后创建getUpdate.py文件,内容如下:

import telegram
from telegram.ext import Updater,CommandHandler
import json
import logging

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',level=logging.INFO)
logger = logging.getLogger(__name__)

def start(bot, update):
	update.message.reply_text('Hello,Please input command!')
	#bot.send_message(chat_id=update.message.chat_id, text="I'm a bot, talk to me!")
	
def myid(bot,update):
	data = "Your ID = "+str(update.message.chat_id)
	update.message.reply_text(data)	

def error(bot, update, error):
    logger.warning('Update "%s" caused error "%s"', update, error)

with open("config.json") as configData:
	config = configData.read()
	data = json.loads(config)
	tokenValue = data['BOT_TOKEN']

updater = Updater(token=tokenValue)

dp = updater.dispatcher
#注册命令
dp.add_handler(CommandHandler('start', start))
dp.add_handler(CommandHandler('myid', myid))
# log all errors
dp.add_error_handler(error)

updater.start_polling()
updater.idle()

运行:

pyhon getUpdate.py

如果需要隐藏黑色cmd执行,在bat文件中写入:

@echo off 
if "%1"=="h" goto begin 
start mshta vbscript:createobject("wscript.shell").run("""%~nx0"" h",0)(window.close)&&exit 
:begin
python getUpdate.py

经过测试,在TG下回复命令(/help,/myid),秒回应,延迟很少。

欢迎关注我的Bot,@coderecord_bot