在Cloud9 上运行 Telegram Bot

旧文新发 写于 2016-03-22 15:38:36

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, 选好 nameusername 之后, 老爹会返回一串 Token:

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


from flask import Flask
app = 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


#coding=utf-8

import os
import logging
import telegram
import urlparse
from flask import Flask, render_template, request

HOST = "<Host>"
app = Flask(__name__)
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

global bot
bot = 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

os.getenv('IP')
os.getenv('PORT')

# 修改Flask
app.run(host=os.getenv('IP'), port=int(os.getenv('PORT')))

享用 Robot

访问 <cloud9-url>/set_webhook, 初始化bot, 添加机器人为好友, 发送 /echo /help /photo 试试哦.


参考:

TeleMe 是一款功能强大又方便好用的 Telegram 社群管理 Bot 机器人。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 22年12月更新:个人网站关停,如果仍旧对旧教程有兴趣参考 Github 的markdown内容[https://...
    tangyefei阅读 35,223评论 22 257
  • [TOC]一直想做源码阅读这件事,总感觉难度太高时间太少,可望不可见。最近正好时间充裕,决定试试做一下,并记录一下...
    何柯君阅读 7,219评论 3 98
  • 学习 Flask,写完一个 Flask 应用需要部署的时候,就想着折腾自己的服务器。根据搜索的教程照做,对于原理一...
    Cocoa_Coder阅读 17,216评论 4 56
  • 离别真是一种神奇的东西 它会让人在突然谂知一切的时候 空留一团虚无的空气 而让你用所有的情感去弥补 面对无法改变的...
    方晓薏阅读 421评论 2 4
  • 还记得那年夏天我们一起在喊楼,接着写完最后一篇英语作文,迷茫地选择学校,最后就是启程上大学。 陌生的地区,陌生的人...
    Z鸽阅读 386评论 1 2