[python] aiohttp를 사용하여 비동기적으로 웹 크롤러 결과를 Telegram 채널로 전송하기

이번에는 asyncio와 aiohttp를 사용하여 비동기적으로 웹 크롤러 결과를 Telegram 채널로 전송하는 방법에 대해 알아보겠습니다. Telegram은 실시간 메시지 전송을 지원하는 인기 있는 메신저입니다. aiohttp는 비동기 웹 요청을 처리하기 위해 사용되는 라이브러리로, 웹 크롤링에 매우 유용합니다.

필요한 패키지 설치

먼저, 코드를 실행하기 위해 필요한 패키지를 설치해야 합니다. 아래의 명령어로 필요한 패키지를 설치할 수 있습니다.

pip install aiohttp
pip install python-telegram-bot

Telegram Bot 생성하기

Telegram 봇을 생성해야 합니다. Telegram에서 @BotFather를 검색하고, 새로운 봇을 생성하십시오. 봇이 생성되면 BotFather는 봇의 토큰을 제공합니다. 이 토큰은 우리가 코드에서 Telegram Bot API에 액세스하는 데 사용될 것입니다.

코드 작성

이제 우리는 웹 크롤러를 위한 비동기 코드를 작성할 수 있습니다. 아래의 예제 코드를 확인해보세요.

import asyncio
import aiohttp
from bs4 import BeautifulSoup
from telegram.ext import Updater

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def get_website_content(url):
    async with aiohttp.ClientSession() as session:
        html = await fetch(session, url)
        return html

def parse_html(html):
    soup = BeautifulSoup(html, 'html.parser')
    # 데이터 파싱 작업 수행
    # 원하는 데이터를 추출하는 로직 작성

    return parsed_data

async def send_to_telegram(token, chat_id, message):
    updater = Updater(token=token, use_context=True)
    await updater.bot.send_message(chat_id=chat_id, text=message)

async def main():
    # 크롤링할 웹 사이트 URL 설정
    url = "https://example.com"

    # Telegram Bot API 토큰 및 채팅 ID 설정
    telegram_token = "YOUR_TELEGRAM_BOT_TOKEN"
    telegram_chat_id = "YOUR_TELEGRAM_CHANNEL_ID"

    html = await get_website_content(url)
    parsed_data = parse_html(html)

    # 크롤링한 데이터를 Telegram으로 전송
    await send_to_telegram(telegram_token, telegram_chat_id, parsed_data)

if __name__ == '__main__':
    asyncio.run(main())

위의 코드에서 YOUR_TELEGRAM_BOT_TOKEN을 생성한 Telegram 봇의 토큰으로, YOUR_TELEGRAM_CHANNEL_ID를 전송할 채널의 ID로 변경해주십시오.

코드 실행

코드를 실행하기 전에, Telegram으로 메시지를 전송할 수 있는 권한이 있는지 확인해야 합니다. 봇이 채널에 메시지를 보낼 수 있는지 확인하려면, 봇을 채널의 관리자로 추가해야 합니다.

위의 코드를 실행하면 비동기적으로 웹 사이트를 크롤링하고, 파싱한 데이터를 Telegram 채널로 전송하는 기능을 구현할 수 있습니다.

이제 비동기적으로 웹 크롤러 결과를 Telegram 채널로 전송하는 방법에 대해 알아보았습니다. aiohttp의 강력한 기능을 활용하여 웹 크롤링 작업을 보다 효율적으로 수행할 수 있습니다.