본문 바로가기
ETC/Python

[Python] Telegram 메시지 봇(bot) 만들기

by Guardy 2020. 11. 25.
728x90

Python Telegram message api
파이썬 텔레그램 메시지
파이썬 텔레그램 API
텔레그램 자동 메시지
텔레그램 봇 만들기


이번 글에서는 python을 이용하여 텔레그렘 메신저에 메시지를 자동으로 보내는 프로그램 및 소스코드를 소개해드리려고 합니다.

카톡의 경우 api를 대부분 공개하지 않아, 메신저를 자동으로 보내기 힘들어 메신저 봇을 만들때는 텔레그렘을 주로 이용한다고 합니다.

우선 텔레그렘에 메시지를 보내면 띄워줄 봇을 만들어야합니다. 

봇을 만드는 방법은 간단합니다. 우선 BotFather라는 계정을 친구 추가합니다.

그런 다음 이 친구에게 다음과 같이 메시지를 보냅니다.

I can help you create and manage Telegram bots. If you're new to the Bot API, please see the manual (https://core.telegram.org/bots).

You can control me by sending these commands:

/newbot - create a new bot
/mybots - edit your bots [beta]

Edit Bots
/setname - change a bot's name
/setdescription - change bot description
/setabouttext - change bot about info
/setuserpic - change bot profile photo
/setcommands - change the list of commands
/deletebot - delete a bot

Bot Settings
/token - generate authorization token
/revoke - revoke bot access token
/setinline - toggle inline mode (https://core.telegram.org/bots/inline)
/setinlinegeo - toggle inline location requests (https://core.telegram.org/bots/inline#location-based-results)
/setinlinefeedback - change inline feedback (https://core.telegram.org/bots/inline#collecting-feedback) settings
/setjoingroups - can your bot be added to groups?
/setprivacy - toggle privacy mode (https://core.telegram.org/bots#privacy-mode) in groups

Games
/mygames - edit your games (https://core.telegram.org/bots/games) [beta]
/newgame - create a new game (https://core.telegram.org/bots/games)
/listgames - get a list of your games
/editgame - edit a game
/deletegame - delete an existing game

그러면 다음과 같이 뭐라고 나올텐데 /newbot을 입력합니다. 새로운 봇을 만들겠다는 명령어입니다.

Alright, a new bot. How are we going to call it? Please choose a name for your bot.

그렇다면 이름을 정하라고 나옵니다. 이름은 이미 있는 봇들과 중복되도 상관없어서 필자는 test라고 지었습니다.

Good. Now let's choose a username for your bot. It must end in `bot`. Like this, for example: TetrisBot or tetris_bot.

그러면 다음과 같이 username을 정하라고 나옵니다 이때 username은 다른 봇들과 중복되지 않아야하고 반드시 bot으로 끝나야 합니다. 필자는 guardy2_bot이라고 지었습니다.

그렇다면 다음과 같이 token값이 나옵니다.

Done! Congratulations on your new bot. You will find it at t.me/guardy2_bot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. By the way, when you've finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully operational before you do this.

Use this token to access the HTTP API:
0000000:AAAAAAAAA
Keep your token secure and store it safely, it can be used by anyone to control your bot.

For a description of the Bot API, see this page: https://core.telegram.org/bots/api

이 토큰 값을 이용하여 메시지를 보낼 수 있습니다.

이제 만들었던 username을 검색하여 친구추가를 합니다.

친구추가를 하고 start를 누릅니다.

우리는 메시지를 보내기 위해 토큰 이외에  chat_id 값을 알아야 합니다.

chat_id를 알아내는 방법은 매우 간단합니다. 우선 메시지를 아무거나 보냅니다. 필자는 test로 보냅습니다.

그다음 다음의 python code를 이용해 update된 정보를 알아냅니다.

import telegram

telegram_token = '토큰을 넣어주세요'

bot = telegram.Bot(token = telegram_token)

updates = bot.getUpdates()

for update in updates:
    print(update)

 이 코드의 신기한 점은 처음에는 다음과 같은 에러가 무조건 뜹니다. 

Traceback (most recent call last):
  File "test.py", line 7, in <module>
    updates = bot.getUpdates()
  File "<decorator-gen-31>", line 2, in get_updates
  File "C:\Users\devgu\AppData\Local\Programs\Python\Python37\lib\site-packages\telegram\bot.py", line 78, in decorator
    result = func(*args, **kwargs)
  File "C:\Users\devgu\AppData\Local\Programs\Python\Python37\lib\site-packages\telegram\bot.py", line 2263, in get_updates
    api_kwargs=api_kwargs)
  File "C:\Users\devgu\AppData\Local\Programs\Python\Python37\lib\site-packages\telegram\bot.py", line 185, in _post
    timeout=timeout)
  File "C:\Users\devgu\AppData\Local\Programs\Python\Python37\lib\site-packages\telegram\utils\request.py", line 328, in post
    **urlopen_kwargs)
  File "C:\Users\devgu\AppData\Local\Programs\Python\Python37\lib\site-packages\telegram\utils\request.py", line 232, in _request_wrapper
    raise TimedOut()
telegram.error.TimedOut: Timed out

이럴 땐 당황하지 말고, 메신저에 계속 메시지를 날려주면서 코드를 계속 실행시키다보면 다음과 같이 결과가 뜹니다.

{'update_id': 0000000, 'message': {'message_id': 3, 'date': 1606311669, 'chat': {'id': 000000000, 'type': 'private', 'first_name': 'X', 'last_name': 'XX'}, 'text': 'test',
'entities': [], 'caption_entities': [], 'photo': [], 'new_chat_members': [], 'new_chat_photo': [], 'delete_chat_photo': False, 'group_chat_created': False, 'supergroup_chat_created': False, 'channel_chat_created': False, 'from': 
{'id': 00000000, 'first_name': 'X', 'is_bot': False, 'last_name': 'XX', 'language_code': 'ko'}}}

이때 id에 있는 숫자가 바로 chat_id 값입니다. update_id 아닙니다 chat안에 있는 id입니다.

이제 다 만들었습니다. 다음 코드로 메시지를 텔레그렘에 보낼 수 있습니다.

import telegram

telegram_token = 'token을 넣어주세요'
bot = telegram.Bot(token = telegram_token)
send_message = "보낼 메시지를 넣어주세요"
bot.sendMessage(chat_id = 'chat_id를 넣어주세요', text=send_message)

필자는 test로 send_message를 했는데 bot이 메시지를 출력하는 것을 확인할 수 있었습니다.

이제 이 코드를 이용하여 여러 프로그램들을 만들 수 있습니다. 도움이 되셨다면 댓글과 공감 부탁드립니다!!

728x90