Telegram 是俄罗斯人开发的一款即时聊天工具, 详细的介绍请看 Rei 的 介绍Telegram .
Cloud9 是什么呢? Cloud9 provides a development environment in the cloud that allows developers to get started with coding immediately and collaborate with their peers.
申请 Telegram Bot 添加 机器老爹-BotFather 输入指令 /newbot, 选好 name 和 username 之后, 老爹会返回一串 Token:
1 2 3 4 Use this token to access the HTTP API: 161xxxx:xxxx_xxxx-xxxxxx For a description of the Bot API, see this page: https://core.telegram.org/bots/api
Flask 运行 server 1 安装 Flask, pip install Flask, pip 类似于 gem
2 来个 hello world
1 2 3 4 5 6 7 8 9 10 from flask import Flaskapp = Flask(__name__) @app.route("/" ) def hello (): return "Hello World!" if __name__ == "__main__" : app.run()
运行 python hello.py, 访问 http://localhost:5000/ , 修改端口 app.run(port='xxxx')
使用 telegram python sdk 用python-telegram-bot 简化开发.
代码如下, 适用于py 2.7
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 import osimport loggingimport telegramimport urlparsefrom flask import Flask, render_template, requestHOST = "<Host>" app = Flask(__name__) logging.basicConfig(level=logging.DEBUG, format ='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) global botbot = telegram.Bot(token = "<Token>" ) botName = "@MustangBot" @app.route("/" , methods=["POST" , "GET" ] ) def setWebhook (): if request.method == "GET" : logging.info("Hello, Telegram!" ) return "OK, Telegram Bot!" @app.route("/set_webhook" , methods=['GET' ] ) def setWebHook (): result = bot.setWebhook("{}/bot_talk" .format (HOST)) if result: return "{} WebHook Setup OK!" .format (botName) else : return "{} WebHook Setup Failed!" .format (botName) @app.route("/bot_talk" , methods=["POST" ] ) def bot_talk (): if request.method == "POST" : update = telegram.Update.de_json(request.get_json(force=True )) if update is None : return "Show me your TOKEN please!" logging.info("Calling {}" .format (update.message)) handdle_message(update.message) return "ok" def handdle_message (msg ): text = msg.text if "/echo" in text: bot.sendMessage(chat_id=msg.chat.id , text="Hello, I am a nerd" ) if "/photo" in text: bot.sendPhoto(chat_id=msg.chat.id , photo="<photo-url>" ) elif "/help" in text: helpInfo(msg) else : helpInfo(msg) def helpInfo (msg ): text =""" /echo - echo /photo - photo /help - Help Info -------------------------- 在cloud9上跑了个telegram_bot """ sendTxtMsg(msg, text) def sendTxtMsg (msg, text ): bot.sendMessage(chat_id=msg.chat.id , text=text) if __name__ == "__main__" : app.run(host=os.getenv('IP' ),port=int (os.getenv('PORT' )))
NOTICE 必须把应用设为 public, 获取cloud9的 IP 和 Port
1 2 3 4 5 os.getenv('IP' ) os.getenv('PORT' ) app.run(host=os.getenv('IP' ), port=int (os.getenv('PORT' )))
享用 Robot 访问 <cloud9-url>/set_webhook, 初始化bot, 添加机器人为好友, 发送 /echo /help /photo 试试哦.