Profile picture

[Python] 텔레그램 메시지 전송 - Telegram API

JaehyoJJAng2023년 08월 20일

◾️ 개요

Telegram API를 활용하여 파이썬 코드로 메시지를 보내보자.


◾️ 텔레그램 봇 생성

텔레그램 봇을 생성하는 과정에 대해서는 아래 블로그를 참고 해보도록 하자. 아주 자세하게 설명이 되어있다.
https://blog.naver.com/monkeychoi/223185247922


◾️ chat_id 추출

매번 번거롭게 URL을 특정 양식에 맞게 브라우저에 입력하지말고
코드로 간단하게 알아내보자.

import requests as rq
import json
import sys

def get_chat_id(token: str) -> int:
    _request_url: str = f'https://api.telegram.org/bot{token}/getUpdates'
    res: rq.Response = rq.get(url=_request_url)

    if res.status_code == 200: 
        if len(res.json()['result']) == 0:
            print('봇 채팅방에 아무 텍스트를 전송한 후 다시 실행하세요.')
            sys.exit()
        room_infos: dict[str,int|dict] = json.loads(res.text)['result'][0]

        # chaid 추출
        chat_id: int = int(room_infos['channel_post']['chat']['id'])
        return chat_id

token: str = 'XXXX'
print(get_chat_id(token=token))

코드 실행 시 chat id를 확인할 수 있다.

$ python3 getChatId.py
-12345678

◾️ 메시지 보내기

from getChatId.py import get_chat_id 
import requests as rq

class Telegram():
    def __init__(self,chat_id: int, token: str) -> None:
        self._TOKEN = token
        self._CHATID = chat_id
    
    def send_text(self,text: str) -> None:
        request_url: str = f"https://api.telegram.org/bot{self._TOKEN}/sendMessage"
        params: dict[str,int|str] = {'chat_id': self._CHATID, 'text': text}
        resp: rq.Response = rq.get(url=request_url,params=params)
        
        if resp.status_code == 200:
            print(resp.json())


token: str = 'XXXX'
chat_id: int = get_chat_id(token=token)
telegram = Telegram(chat_id=chat_id,token=token)

# 메시지 보내기
telegram.send_text(text='안녕하세요')

코드 실행 시 다음과 같은 결과를 볼 수 있을 것이다.

$ python3 sendMesg.py
{'ok': True, 'result': {'message_id': 1036, 'sender_chat': {'id': -1002025858581, 'title': '서버 알림', 'type': 'channel'}, 'chat': {'id': -1002025858581, 'title': '서버 알림', 'type': 'channel'}, 'date': 1709538406, 'text': '안녕하세요'}}

image


▸ 이미지 보내기

이미지를 보내려면 아래와 같이 코드를 작성하면 된다.

import requests as rq
from io import BytesIO

class Telegram():
    def __init__(self,chat_id: int, token: str) -> None:
        self._TOKEN = token
        self._CHATID = chat_id

    def send_image(self,image_path: str) -> None:
        request_url: str = f"https://api.telegram.org/bot{token}/sendPhoto"
        # 이미지 파일 열기
        with open(image_path,'rb') as photo:
            files = {'photo': photo}
            data =  {'chat_id': self._CHATID}

            # POST 요청으로 이미지 보내기
            resp: rq.Response = rq.post(url=request_url,files=files,data=data)
            if resp.status_code == 200:
                print(resp.json())

token: str = 'XXXX'
chat_id: int = get_chat_id(token=token)
telegram = Telegram(chat_id=chat_id,token=token)

# 메시지 보내기
telegram.send_image(image_path='test.png')

코드 실행 시 다음과 같은 결과를 볼 수 있을 것이다.

$ python3 sendMesgImage.py
{'ok': True, 'result': {'message_id': 1037, 'sender_chat': {'id': -1002025858581, 'title': '서버 알림', 'type': 'channel'}, 'chat': {'id': -1002025858581, 'title': '서버 알림', 'type': 'channel'}, 'date': 1709538485, 'photo': [{'file_id': 'AgACAgUAAx0EeMAmFQACBA1l5Xy1oXL07nhDB2vJkpNZBVrqjAAC-boxG9n5MVdZqtENpAfAfAEAAwIAA3MAAzQE', 'file_unique_id': 'AQAD-boxG9n5MVd4', 'file_size': 1289, 'width': 90, 'height': 90}, {'file_id': 'AgACAgUAAx0EeMAmFQACBA1l5Xy1oXL07nhDB2vJkpNZBVrqjAAC-boxG9n5MVdZqtENpAfAfAEAAwIAA20AAzQE', 'file_unique_id': 'AQAD-boxG9n5MVdy', 'file_size': 7378, 'width': 320, 'height': 320}, {'file_id': 'AgACAgUAAx0EeMAmFQACBA1l5Xy1oXL07nhDB2vJkpNZBVrqjAAC-boxG9n5MVdZqtENpAfAfAEAAwIAA3gAAzQE', 'file_unique_id': 'AQAD-boxG9n5MVd9', 'file_size': 19456, 'width': 800, 'height': 800}, {'file_id': 'AgACAgUAAx0EeMAmFQACBA1l5Xy1oXL07nhDB2vJkpNZBVrqjAAC-boxG9n5MVdZqtENpAfAfAEAAwIAA3kAAzQE', 'file_unique_id': 'AQAD-boxG9n5MVd-', 'file_size': 34125, 'width': 1280, 'height': 1280}, {'file_id': 'AgACAgUAAx0EeMAmFQACBA1l5Xy1oXL07nhDB2vJkpNZBVrqjAAC-boxG9n5MVdZqtENpAfAfAEAAwIAA3cAAzQE', 'file_unique_id': 'AQAD-boxG9n5MVd8', 'file_size': 80299, 'width': 2480, 'height': 2480}]}}

image


Loading script...