조회 수 651 추천 수 1 댓글 7
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부
Extra Form
라이선스 기타(따로 작성)

안녕하세요?

 

한 주 동안 다들 고생 많으셨네요~!

 

마스터 님의 허락을 받고 Studyforus 텔레그램 알림봇을 만들었어요 :)

 

필요로 하시는 분이 얼마나 계실지 모르겠지만요 ㄷㄷ

 

 

 

1. 스포어 알림 봇

 

내 알림 목록을 파싱하여 텔레그램으로 전송하는 스크립트입니다.

 

이 스크립트를 리눅스 크론이나 윈도우 작업스케줄러에 넣고 주기적으로 돌리면 되구요.

 

 

다음과 같은 특징이 있네요~!

 

1. 긴 댓글의 경우 내 알림 목록에서 짤리기 때문에 댓글 원문을 퍼옵니다.

 

2. 스티커의 경우 스티커를 다운받아서 텔레그램으로 전송하구요.

(다만 텔레그램에서 움짤을 지원하지 않아서 마치 JPG처럼 보입니다 ㅠㅠ)

 

3. 댓글 원문을 퍼오거나, 스티커를 다운받더라도 알림을 읽지 않은 상태를 유지합니다 ^^

 

 

from requests_html import HTMLSession
from bs4 import BeautifulSoup
import telegram, time


## 스포어에 로그인을 합니다. ##
def login(): 
    s = HTMLSession()
    s.get('https://studyforus.com')
    headers = {
        'origin': 'https://studyforus.com',
        'referer': 'https://studyforus.com'
    }
    formdata = {
        'error_return_url': '/',
        'mid': 'main',
        'vid': '',
        'ruleset': '@login',
        'act': 'procMemberLogin',
        'success_return_url': '/',
        'user_id': '***ID를 입력하세요***',
        'password': '***PW를 입력하세요***',
    }
    s.post('https://studyforus.com', headers = headers, data = formdata)
    return s


## 내 알림 목록을 크롤링합니다. ##
def parse(s):
    count = 0
    for i in range(1, 11):
        html = s.get('https://studyforus.com/index.php?mid=main&act=dispNcenterliteNotifyList&page=' + str(i)).text
        soup = BeautifulSoup(html, 'html5lib')
        trees = soup.find('table', {'class':'cl table table-striped table-hover'}).find('tbody').select('tr')
        result = []
        for t in trees:
            if t.select('td')[3].text.strip() == '읽음':
                count = 1
                break
            href = t.select('td')[2].find('a')['href']
            url = 'https://studyforus.com' + href
            msg = t.select('td')[2].text
            filename = ''

            if msg.endswith('..."라고 댓글을 남겼습니다.'): # 댓글의 경우 댓글 원문을 크롤링합니다.
                s2 = HTMLSession()
                html = s2.get(url).text
                soup = BeautifulSoup(html, 'html5lib')
                temp = soup.find('article', {'id': href.split('#')[-1]}).find('div', {'class':'cmt_body'}).find('div').text
                alarm = msg.split('"')[0] + '"' + temp + '"' + msg.split('"')[-1]
                time.sleep(0.5)
            elif '"{@sticker:' in msg: # 스티커의 경우 이미지를 다운받습니다.
                alarm = t.select('td')[2].text
                s2 = HTMLSession()
                html = s2.get(url).text
                soup = BeautifulSoup(html, 'html5lib')
                url = soup.find('article', {'id': href.split('#')[-1]}).find('div', {'class':'cmt_body'}).find('a')['style'].split('(')[1].split(')')[0][1:]
                rsp = s2.get('https://studyforus.com/' + url)
                filename = url.split('/')[-1]
                if rsp.status_code == 200:
                    with open(filename, 'wb') as f:
                        f.write(rsp.content)
            else: # 이외의 경우에는 알림 자체를 파싱합니다.
                alarm = t.select('td')[2].text

            if filename == '':
                result.append([alarm, url, 'no_image'])
            else:
                result.append([alarm, url, filename])
        if count == 1:
            break
        time.sleep(0.5)
    return result


## 텔레그램으로 전송합니다. ##
def telegram_bot(result):
    token = '***토큰을 입력하세요***'
    bot = telegram.Bot(token)
    try:
        chat_id = bot.getUpdates()[-1].message.chat.id
    except:
        chat_id = '***chat_id를 입력하세요***'
    try: # 로그 파일을 확인하여 한 번 알림이 오면 다시 알림이 오지 않도록 처리합니다.
        lines = [line.rstrip('\n') for line in open('sfu_tlgr.log', 'rt', encoding='utf8')]
    except: # 파일이 존재하지 않는 경우를 예외처리합니다.
        lines = ['노데이터']
    for r in result:
        if r[0] in lines:
            continue
        msg = '<a href="' + r[1] + '">' + r[0] + '</a>'
        bot.sendMessage(chat_id=chat_id, text=msg, parse_mode=telegram.ParseMode.HTML)
        if r[2] != 'no_image':
            bot.send_photo(chat_id, open(r[2], 'rb'))
    temp = [x[0] for x in result]
    with open('sfu_tlgr.log', 'wt', encoding='utf8') as f:
        f.write('\n'.join(temp))
    return


if __name__ == '__main__':
    session = login()
    alarms = parse(session)
    telegram_bot(alarms)

 

 

 

2. 봇 핸들러

 

만약 크론탭에서 지정한 시간이 되기 전에 다시 알림을 불러오고 싶다면 아래 스크립트를 이용하시면 됩니다 :)

 

텔레그램에서 '/get'이라고 입력하면 다시 크롤링을 합니다!

 

from telegram.ext import Updater, CommandHandler, CallbackQueryHandler
import telegram
import sfu_tlgr as sfu


def get_command(bot, update):
    session = sfu.login()
    alarms = sfu.parse(session)
    sfu.telegram_bot(alarms)
    return


def server():
    token = '***토큰을 입력합니다***'
    updater = Updater(token, use_context=True)
    get_handler = CommandHandler('get', get_command)
    updater.dispatcher.add_handler(get_handler)
    updater.start_polling(timeout=1, clean=True)
    updater.idle()
    return


if __name__ == '__main__':
    server()

 

 

 

3. 테스트 결과

 

현재까지 제가 테스트한 바로는 잘 작동하네요~!

 

네모 님에 대한 오마주로서 봇 이름은 샤로라고 했네요 ㄷㄷ

 

 

1. 스티커도 잘 파싱되네요 :)

 

Screenshot_20200515-195417_Telegram.jpg

 

 

 

2. 댓글의 경우 원문 전체를 퍼옵니다!

 

Screenshot_20200515-195437_Telegram.jpg

 

 

 

3. 메시지를 클릭하면 브라우저에서 해당 페이지로 바로 연결됩니다 ^^

 

Screenshot_20200515-195626_Telegram.jpg

 

 

 

추가할 만한 기능이 있으면 댓글로 말씀해주세요 :)

 

마스터 님께 그동안 여러모로 신세를 져서 항상 빚을 지고 있다는 생각이 들었는데...

 

비록 허접한 스크립트이지만 이걸로 조금이나마 마음의 빚을 갚는 기분이네요!

(물론 이 스크립트를 실제로 사용하실 분은 안 계시겠지만요 ㅜㅜ)

 

그럼 다들 좋은 주말 되세요 ^-^

 

  • profile
    Nginx 2020.05.15 21:43
    서버가 없으면 언제나 알림은 불가능..

    +) 샤로도 샤로만의 장점이 있지만 샤로 보단 치노...
  • profile
    이니스프리 2020.05.15 22:41
    허접한 스크립트인데 추천해주셔서 감사합니다 :)

    +) 저도 샤로가 1픽은 아니에요 ^^
  • profile
    이니스프리 2020.05.15 22:41
  • profile
    title: 황금 서버 (30일)humit 2020.05.15 23:21
    https://python-telegram-bot.readthedocs.io/en/stable/telegram.bot.html#telegram.Bot.send_photo

    이미지를 다운받지 않더라도 http 링크로 전달해줄 수 있습니다.

    이렇게 하면 이미지 다운로드 트래픽과 업로드 트래픽을 줄이실 수 있어요 :)
  • profile
    이니스프리 2020.05.15 23:27
    헐퀴~ 이런 기능이 있는지 처음 알았네요!
    덕분에 또 많이 배우고 가네요~
    항상 감사드립니다 ^-^
    그럼 humit 님께서도 굿밤 되세요 :)
  • profile
    title: 황금 서버 (30일)humit 2020.05.15 23:32
  • profile
    이니스프리 2020.05.15 23:28

    존재하지 않는 스티커입니다.


  1. [Python/Telegram] Studyforus 알림봇 (댓글, 스티커 파싱)

    Date2020.05.15 Category코드 By이니스프리 Views651
    Read More
  2. [Python-Gnuboard] 파이썬으로 구현한 그누보드 자동 글쓰기 함수

    Date2021.04.08 Category코드 By이니스프리 Views1231
    Read More
  3. [PyQt] sir.kr에서 스크랩한 게시글을 보여주는 윈도우앱 (검색 및 정렬 가능)

    Date2019.08.09 Category코드 By이니스프리 Views1001
    Read More
  4. [PHP] 이미지를 원하는 크기(원본비율 유지)로 리사이즈 하여 출력 (원본 이미지는 수정하지 않습니다)

    Date2018.12.20 Category코드 By이니스프리 Views7715
    Read More
  5. [PHP] 기상청 중기예보를 캐러셀로 보여주는 위젯 (매우 허접합니다 ㅠㅠ)

    Date2018.09.28 Category코드 By이니스프리 Views647
    Read More
  6. [PHP] 기상청 RSS 시간별 예보 위젯 - cache 적용(?)

    Date2018.10.28 Category코드 By이니스프리 Views850
    Read More
  7. [PHP] 그누보드 자동 게시글 작성 - 일본기상협회의 우리나라 날씨를 크롤링한 후 파파고로 번역하여 글 작성

    Date2018.11.15 Category코드 By이니스프리 Views657
    Read More
  8. [PHP] 간단한 캐싱 클래스

    Date2018.12.06 Category코드 Bytitle: 황금 서버 (30일)humit Views605
    Read More
  9. [PHP/Javascript] 아미나에 자동으로 게시글을 생성하고 Ajax로 전송하여 결과를 표시하기

    Date2019.07.09 Category코드 By이니스프리 Views780
    Read More
  10. [JS]클라이언트에서 Ip를 얻어보자

    Date2019.01.21 Category코드 ByHanam09 Views625
    Read More
  11. [JS] 클라이언트단 GET Parameter

    Date2019.11.16 Category코드 ByHanam09 Views468
    Read More
  12. [JS] http를 https로 리디렉션!

    Date2018.12.30 Category코드 ByHanam09 Views674
    Read More
  13. Koa에서 자동으로 라우팅 채워주기

    Date2020.01.22 Category코드 BySeia Views439
    Read More
  14. JavaScript에서 파이썬 문자열 처리 함수 중 하나 (바인딩)를 구현

    Date2020.01.20 Category코드 BySeia Views465
    Read More
  15. html 초보가 만든 자소서

    Date2018.04.21 Category코드 Bytitle: 대한민국 국기gimmepoint Views661
    Read More
  16. HEX를 RGB로, RGB를 HEX로 바꾸는 PHP 코드

    Date2018.05.05 Category코드 By네모 Views507
    Read More
  17. Hello, World!를 출력해보자

    Date2018.04.21 Category코드 By네모 Views568
    Read More
  18. Git 저장소에서 자동으로 받아 업데이트하는 쉘 스크립트

    Date2017.09.16 Category코드 ByNoYeah Views651
    Read More
  19. C언어 삼중자를 이용한 코드

    Date2018.07.22 Category코드 Bytitle: 황금 서버 (30일)humit Views410
    Read More
  20. CMD로 로컬 연결 고정 IP 설정하기

    Date2018.02.06 Category코드 Bytitle: 황금 서버 (30일)humit Views1038
    Read More
Board Pagination Prev 1 2 3 4 Next
/ 4