앞서 작성한 코드를 클래스로 정리해 보겠습니다.


# -*- 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"}'

  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 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)

agent = TelegramAgent()
agent.setDumpData(True)
agent.setToken("<텔레그램 봇 토큰>")
agent.sendMessage("@<채널 ID>", "test string [한글]")


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


,