본문 바로가기

앱/telegram

[python - requests]gTTS를 이용한 문장 오디오 파일 변환

이 문서는 2024년 4월 25일에 작성되었습니다

목표

파이썬 라이브러리 gTTS를 이용하여 텔레그램 사용자의 채팅 문장을 mp3 파일로 변환하고, 변환된 파일을 텔레그램 API를 통해 봇 채팅방에서 사용자에게 오디오로 전송합니다.

버전 정보

  • 언어: 파이썬 3.10
  • 라이브러리:
    • gTTS: 2.5.1
    • requests: 2.31.0

목차

1. 파이썬 라이브러리 gTTS 설치

pip install gTTS

 

2. 텔레그램에서 채팅 문장 추출하기

import requests

api_host = 'https://api.telegram.org'
token = "0000000000:testboyjCs"
url = f"{api_host}/bot{token}/" + "getUpdates"
print(f"조회하는 url 정보 : {url}")
response = requests.post(url)
json = response.json()

# 사용자 메세지 변수
user_msg = None
if json['ok'] is True:
    result = json['result']
    # 사용자가 가장 최근에 보낸 메세지
    update_obj = result[-1]
    user_msg = update_obj['message']['text']
    print(f"사용자가 보낸 텍스트 : {user_msg}")

결과

⚠️참고사항 : 현재 봇의 토큰정보는 임의로 변경하여서 표시하였습니다

텔레그램 사용자의 최근 메세지 정보

3. 채팅 문장을 mp3 파일로 변환하기

from gtts import gTTS

if user_msg is not None:
    tts = gTTS("안녕하세요", lang="ko")
    savefile = 'hello_ko.mp3' # 저장 파일명
    tts.save(savefile)

 

4.변환된 mp3 파일을 텔레그램 API를 통해 봇 채팅방에서 사용자에게 전송하기

- chat_id는 자신의 아이디로 변경해주어야 함

url = f"{api_host}/bot{token}/" + "sendAudio"
with open(savefile, "rb") as audio_file:
    data = {"chat_id": 1231234123 }
    response = requests.post(url, data=data, files={"audio": audio_file})
    json = response.json()
    if json['ok'] is True:
        print("전송 완료")
    else:
        print("전송 실패")

gTTS로 변환된 mp3 파일

결론

파이썬 라이브러리 gTTS를 사용하여 텔레그램 사용자의 채팅 문장을 mp3 파일로 변환하고, 변환된 파일을 텔레그램 API를 통해 봇 채팅방에서 사용자에게 오디오로 전송하는 방법을 배울 수 있었습니다. 이를 통해 사용자 경험을 향상시키고, 더욱 다양한 방식으로 서비스를 제공할 수 있게 되었습니다.

전체 소스

필수 변경 목록

  •  token : 텔레그램 봇 key
  • chat_id : 보낼 대상의 id
import requests

api_host = 'https://api.telegram.org'
token = "0000000000:testboyjCs"
url = f"{api_host}/bot{token}/" + "getUpdates"
print(f"조회하는 url 정보 : {url}")
response = requests.post(url)
json = response.json()

# 사용자 메세지 변수
user_msg = None
if json['ok'] is True:
    result = json['result']
    # 사용자가 가장 최근에 보낸 메세지
    update_obj = result[-1]
    user_msg = update_obj['message']['text']
    print(f"사용자가 보낸 텍스트 : {user_msg}")

from gtts import gTTS

if user_msg is not None:
    tts = gTTS("안녕하세요", lang="ko")
    savefile = 'hello_ko.mp3' # 저장 파일명
    tts.save(savefile)
    
    url = f"{api_host}/bot{token}/" + "sendAudio"
    with open(savefile, "rb") as audio_file:
        data = {"chat_id": 1231234123 }
        response = requests.post(url, data=data, files={"audio": audio_file})
        json = response.json()
        if json['ok'] is True:
            print("전송 완료")
        else:
            print("전송 실패")