다음은 몇가지 부가적인 기능이 추가된 예제입니다.

  • getMe : 텔레그램 봇 자신에 대한 정보를 가져온다.
  • getUpdates : 텔레그램 봇의 상태 정보를 가져온다.
  • sendPhoto : 텔레그램 봇 채널에 이미지를 전송한다.
# -*- coding: utf-8 -*-

import http.client, urllib
import json
import datetime

class TelegramAgent:

  API_URL = "api.telegram.org"
  CONTENT_TYPE = "Content-type"
  APPLICATION_JSON = "application/json"

  BOT_PATH = "/bot%s"
  SEND_MESSAGE_PATH = "/sendMessage"
  SEND_MESSAGE_DATA = '{"chat_id": %s, "text": "%s"}'
  GET_ME_PATH = "/getMe"
  GET_UPDATES_PATH = "/getUpdates"
  GET_UPDATES_DATA = '{"offset": "%d"}'
  SEND_PHOTO_PATH = "/sendPhoto"
  SEND_PHOTO_DATA = '{"chat_id": %s, "photo": "%s"}'

  def __init__(self):
    self.bContinue = True
    self.response = None
    self.callback = None
    self.bDumpData = False

  def setToken(self, token):
    self.token = token

  def setCallback(self, callback):
    self.callback = callback

  def setContinue(self, bContinue):
    self.bContinue = bContinue

  def setDumpData(self, bDumpData):
    self.bDumpData = bDumpData

  def convertDate(self, date, format):
    return datetime.datetime.fromtimestamp(date).strftime(format)

  def packChatId(self, chatId):
    if len(chatId) > 0 and chatId[:1] == "@":
      return "\"%s\"" % chatId
    return chatId

  def postRequest(self, url, path, headers, paramsRaw):
    params = paramsRaw
    conn = http.client.HTTPSConnection(url)
    conn.request("POST", path, params.encode("UTF-8"), headers)
    self.response = conn.getresponse()
    self.data = self.response.read().decode("UTF-8")
    if self.bDumpData:
      print(self.data)
    conn.close()

  def sendCommon(self, actionPath, data):
    path = self.BOT_PATH % self.token + actionPath
    self.postRequest(self.API_URL, path, 
        {self.CONTENT_TYPE : self.APPLICATION_JSON}, data);

  def sendNoData(self, actionPath):
    self.sendCommon(actionPath, "")

  def sendMessage(self, chatId, message):
    chatId = self.packChatId(chatId)
    data = self.SEND_MESSAGE_DATA % (chatId, message)
    self.sendCommon(self.SEND_MESSAGE_PATH, data)

  def sendPhoto(self, chatId, photoUrl):
    chatId = self.packChatId(chatId)
    data = self.SEND_PHOTO_DATA % (chatId, photoUrl)
    self.sendCommon(self.SEND_PHOTO_PATH, data)

  def getMe(self):
    self.sendNoData(self.GET_ME_PATH)

  def getUpdates(self, offset):
    data = self.GET_UPDATES_DATA % offset
    self.sendCommon(self.GET_UPDATES_PATH, data)

agent = TelegramAgent()
agent.setDumpData(True)
agent.setToken("<텔레그램 봇 토큰>")
agent.getMe()
agent.getUpdates(0)
agent.sendPhoto("@<채널 ID>", "http://t1.daumcdn.net/thumb/R0x640/?fname=http%3A%2F%2Fcfile168.uf.daum.net%2Fimage%2F235D1A445731A2332F780E")

<테스트 환경>
- OS : Windows 7
- Python 버전 : 3.6


,