728x90
필요한 패키지 설치
pip install telegram
pip install python-telegram-bot (telegram.ext)
(corona) PS C:\Users\Desktop\corona19_latest> pip install telegram
Processing c:\users\appdata\local\pip\cache\wheels\00\aa\b5\9eae4467e5075c888fad004d7c44c669a8b8a4e69bb9b95a6f\telegram-0.0.1-py3-none-any.whl
Installing collected packages: telegram
Successfully installed telegram-0.0.1
(corona) PS C:\Users\Desktop\corona19_latest> pip install python-telegram-bot
Collecting python-telegram-bot
Downloading python_telegram_bot-12.8-py2.py3-none-any.whl (375 kB)
|████████████████████████████████| 375 kB 819 kB/s
Collecting cryptography
Using cached cryptography-2.9.2-cp36-cp36m-win_amd64.whl (1.5 MB)
Requirement already satisfied: certifi in c:\programdata\anaconda3\envs\corona\lib\site-packages (from python-telegram-bot) (2020.6.20)
Collecting decorator>=4.4.0
Using cached decorator-4.4.2-py2.py3-none-any.whl (9.2 kB)
Collecting tornado>=5.1
Using cached tornado-6.0.4-cp36-cp36m-win_amd64.whl (417 kB)
Collecting six>=1.4.1
Using cached six-1.15.0-py2.py3-none-any.whl (10 kB)
Collecting cffi!=1.11.3,>=1.8
Using cached cffi-1.14.0-cp36-cp36m-win_amd64.whl (176 kB)
Collecting pycparser
Using cached pycparser-2.20-py2.py3-none-any.whl (112 kB)
Installing collected packages: six, pycparser, cffi, cryptography, decorator, tornado, python-telegram-bot
Successfully installed cffi-1.14.0 cryptography-2.9.2 decorator-4.4.2 pycparser-2.20 python-telegram-bot-12.8 six-1.15.0 tornado-6.0.4
(corona) PS C:\Users\Desktop\corona19_latest>
에코봇 구현하기
지난 포스팅에서 발급받은 토큰을 이용하여 간단한 봇을 구현해보겠습니다.
텔레그램 API는 기능이 많은 만큼 복잡합니다. (ㅠㅠ)
사용자가 전달한 메시지를 핸들링하는 간단한 코드를 보시겠습니다.
콜백함수인 get_message()의 매개변수 bot, update의 내용물을 살펴봅니다.
from telegram.ext import Updater, MessageHandler, Filters
def get_message(bot, update):
chat_id = bot.message.chat.id
msg = bot.message.text
update.bot.send_message(chat_id, msg)
if __name__ == '__main__':
token = 'Input Your Token'
updater = Updater(token, use_context=True)
message_handler = MessageHandler(Filters.text, get_message)
updater.dispatcher.add_handler(message_handler)
updater.start_polling()
updater.idle()
bot.message.chat.id, bot.message.text
print(bot)
{'update_id': 797425890, 'message': {'message_id': 66, 'date': 1594903008, 'chat': {'id': 407125837, 'type': 'private', 'first_name': '길동', 'last_name': '홍'}, 'text': '반갑습니다', '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': 407125837, 'first_name': '길동', 'is_bot': False, 'last_name': '홍', 'language_code': 'ko'}}}
print(dir(update))
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_bot_data', '_chat_data', '_dispatcher', '_user_data', 'args', 'bot', 'bot_data', 'chat_data', 'dispatcher', 'error', 'from_error', 'from_job', 'from_update', 'job', 'job_queue', 'match', 'matches', 'update', 'update_queue', 'user_data']
update.bot 안에 send_message 를 이용했습니다.
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_commands', '_id_attrs', '_message', '_request', '_validate_token', 'addStickerToSet', 'add_sticker_to_set', 'answerCallbackQuery', 'answerInlineQuery', 'answerPreCheckoutQuery', 'answerShippingQuery', 'answer_callback_query', 'answer_inline_query', 'answer_pre_checkout_query', 'answer_shipping_query', 'base_file_url', 'base_url', 'bot', 'can_join_groups', 'can_read_all_group_messages', 'commands', 'createNewStickerSet', 'create_new_sticker_set', 'de_json', 'defaults', 'deleteChatPhoto', 'deleteChatStickerSet', 'deleteMessage', 'deleteStickerFromSet', 'deleteWebhook', 'delete_chat_photo', 'delete_chat_sticker_set', 'delete_message', 'delete_sticker_from_set', 'delete_webhook', 'editMessageCaption', 'editMessageLiveLocation', 'editMessageMedia', 'editMessageReplyMarkup', 'editMessageText', 'edit_message_caption', 'edit_message_live_location', 'edit_message_media', 'edit_message_reply_markup', 'edit_message_text', 'exportChatInviteLink', 'export_chat_invite_link', 'first_name', 'forwardMessage', 'forward_message', 'getChat', 'getChatAdministrators', 'getChatMember', 'getChatMembersCount', 'getFile', 'getGameHighScores', 'getMe', 'getMyCommands', 'getStickerSet', 'getUpdates', 'getUserProfilePhotos', 'getWebhookInfo', 'get_chat', 'get_chat_administrators', 'get_chat_member', 'get_chat_members_count', 'get_file', 'get_game_high_scores', 'get_me', 'get_my_commands', 'get_sticker_set', 'get_updates', 'get_user_profile_photos', 'get_webhook_info', 'id', 'kickChatMember', 'kick_chat_member', 'last_name', 'leaveChat', 'leave_chat', 'link', 'logger', 'name', 'pinChatMessage', 'pin_chat_message', 'promoteChatMember', 'promote_chat_member', 'request', 'restrictChatMember', 'restrict_chat_member', 'sendAnimation', 'sendAudio', 'sendChatAction', 'sendContact', 'sendDice', 'sendDocument', 'sendGame', 'sendInvoice', 'sendLocation', 'sendMediaGroup', 'sendMessage', 'sendPhoto', 'sendPoll', 'sendSticker', 'sendVenue', 'sendVideo', 'sendVideoNote', 'sendVoice', 'send_animation', 'send_audio', 'send_chat_action', 'send_contact', 'send_dice', 'send_document', 'send_game', 'send_invoice', 'send_location', 'send_media_group', 'send_message', 'send_photo', 'send_poll', 'send_sticker', 'send_venue', 'send_video', 'send_video_note', 'send_voice', 'setChatAdministratorCustomTitle', 'setChatDescription', 'setChatPermissions', 'setChatPhoto', 'setChatStickerSet', 'setChatTitle', 'setGameScore', 'setMyCommands', 'setPassportDataErrors', 'setStickerPositionInSet', 'setStickerSetThumb', 'setWebhook', 'set_chat_administrator_custom_title', 'set_chat_description', 'set_chat_permissions', 'set_chat_photo', 'set_chat_sticker_set', 'set_chat_title', 'set_game_score', 'set_my_commands', 'set_passport_data_errors', 'set_sticker_position_in_set', 'set_sticker_set_thumb', 'set_webhook', 'stopMessageLiveLocation', 'stopPoll', 'stop_message_live_location', 'stop_poll', 'supports_inline_queries', 'to_dict', 'to_json', 'token', 'unbanChatMember', 'unban_chat_member', 'unpinChatMessage', 'unpin_chat_message', 'uploadStickerFile', 'upload_sticker_file', 'username']
결과입니다.
'Bot' 카테고리의 다른 글
텔레그램 봇 : 블로거 뇌구조 그리기 (0) | 2020.07.27 |
---|---|
텔레그램 봇 : 블로거를 위한 내 게시글 검색순위 찾기 (0) | 2020.07.23 |
파이썬 텔레그램 봇 만들기 -3 : 날씨 검색봇 (0) | 2020.07.22 |
라사(Rasa) 튜토리얼 -1 : 설치 및 구동 (0) | 2020.07.17 |
파이썬 텔레그램 봇 만들기 -1 : API 토큰 발급 절차 (0) | 2020.07.16 |