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


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
# -*- 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


,