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

웹 크롤러를 사용하여 데이터를 수집한 후에는 종종 결과를 다른 플랫폼으로 전송해야하는 경우가 있습니다. 이 예시에서는 aiohttp를 사용하여 비동기적으로 웹 크롤러 결과를 Telegram 채널로 전송하는 방법을 알아보겠습니다.

aiohttp란?

aiohttp는 비동기 웹 프레임워크로, HTTP 클라이언트와 서버 기능을 제공합니다. Python의 asyncio 라이브러리와 함께 사용되어 비동기적으로 네트워크 요청을 처리할 수 있습니다.

Telegram 봇 생성하기

먼저 Telegram 봇을 생성해야합니다. Telegram 웹사이트에서 @BotFather 봇을 찾아 새로운 봇을 만듭니다. 봇의 API 토큰을 메모해둡니다.

aiohttp 설치하기

aiohttp를 설치하기 위해 다음 명령을 사용합니다:

pip install aiohttp

웹 크롤러 작성하기

아래는 aiohttp를 사용하여 간단한 웹 크롤러를 작성한 예시입니다. 크롤링할 웹페이지의 URL과 필요한 데이터 추출 로직에 따라 코드를 수정하세요.

import aiohttp
import asyncio

async def fetch_html(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.text()

async def scrape_website():
    url = "https://example.com"
    html = await fetch_html(url)
    
    # 데이터 추출 로직을 작성하세요
    # 예시: title 태그 내용 추출하기
    title = html.split("<title>")[1].split("</title>")[0]
    
    return title

async def main():
    result = await scrape_website()
    print(result)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

Telegram으로 결과 전송하기

이제는 Telegram 채널에 결과를 전송하는 함수를 작성해보겠습니다. Telegram Bot API를 사용하여 채널에 메시지를 보낼 수 있습니다.

import aiohttp
import asyncio

async def send_to_telegram_channel(message):
    chat_id = "YOUR_CHANNEL_ID"  # 채널의 챗 ID를 입력하세요
    bot_token = "YOUR_BOT_TOKEN"  # 봇의 API 토큰을 입력하세요
    
    url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
    params = {
        "chat_id": chat_id,
        "text": message
    }
    
    async with aiohttp.ClientSession() as session:
        async with session.get(url, params=params) as response:
            return await response.json()

async def scrape_and_send():
    result = await scrape_website()
    await send_to_telegram_channel(result)

async def main():
    await scrape_and_send()

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

위의 코드에서 YOUR_CHANNEL_IDYOUR_BOT_TOKEN을 각각 채널의 챗 ID와 봇의 API 토큰으로 대체해야합니다. 그리고 scrape_website() 메서드를 통해 데이터를 수집하고 send_to_telegram_channel() 메서드를 통해 채널에 메시지를 전송합니다.

이제 코드를 실행하면 웹 크롤러가 실행되고 Telegram 채널로 결과가 전송됩니다.

이 예시를 통해 aiohttp를 사용하여 비동기적으로 웹 크롤러 결과를 Telegram 채널로 전송하는 방법을 배웠습니다. 이를 응용하여 다양한 기능을 구현할 수 있습니다.