안녕하세요.
프로그램은 배워본적 없는 사람입니다.
제가 보고 싶은 뉴스가 있어 특정 단어로 된 뉴스를 검색해서 텔레그램으로 쏴주는 봇을 만들고 싶습니다.
인터넷을 검색해서 botfather 를 이용해 봇까지는 만들었습니다.
파이썬도 깔고 인터넷에 공유된 파일로 py 파일도 만들어서 실행도 했습니다.
하지만 텔레그램에 뉴스가 배달되지 않습니다.
여기서 궁금한건 어떻게 해야 할까요 ?
1. 실시간으로 뉴스를 받으려면 다른 서버가 필요한가요 ?
현재는 데스크탑에서 파일을 실행했습니다.
2. py 파일이 잘 못 된게 있을까요 ? 토큰 ID는 입력해서 사용했습니다.
- 파일 내용은 이렇습니다.
# -*- coding: euc-kr -*-
# python3.5
from bs4 import BeautifulSoup
from urllib import parse
from collections import OrderedDict #중복 제거
import requests
import os
import telegram
def Site_ON():
search = parse.urlparse('https://www.boannews.com/search/news_list.asp?search=title&find=취약점')
query = parse.parse_qs(search.query) #보안뉴스 인코딩 값이 euc-kr
S_query = parse.urlencode(query, encoding='euc-kr', doseq=True) # URL 인코딩
url = "https://www.boannews.com/search/news_list.asp?{}".format(S_query)
Article_Crawll(url)
def Article_Crawll(url):
news_link = []
response = requests.get(url)
html = response.text
soup = BeautifulSoup(html, 'html.parser')
for link in soup.find_all('a', href=True):
notices_link = link['href']
if '/media/view.asp?idx=' in notices_link:
news_link.append(notices_link) #news_link에 리스트 추가
news_link = list(OrderedDict.fromkeys(news_link)) #중복제거
Compare(news_link)
def Compare(news_link):
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
temp = []
cnt = 0
with open(os.path.join(BASE_DIR, 'compare.txt'), 'r')as f_read:
before = f_read.readlines()
before = [line.rstrip() for line in before] #(\n)strip in list
f_read.close()
for i in news_link:
if i not in before:
temp.append(i)
cnt = cnt + 1
with open(os.path.join(BASE_DIR, 'compare.txt'), 'a') as f_write:
f_write.write(i+'\n')
f_write.close()
if cnt > 0: #cnt가 1이라도 증가하면 새로운 기사가 있다는 뜻
Maintext_Crawll(temp, cnt)
def Maintext_Crawll(temp, cnt):
bot = telegram.Bot(token='ID 입력 ')
chat_id = bot.getUpdates()[-1].message.chat.id
NEW = "[+] 보안뉴스 ' 취약점 '에 새로운 뉴스는 {}개 입니다.".format(cnt)
bot.sendMessage(chat_id=chat_id, text=NEW)
for n in temp:
Main_URL = "https://www.boannews.com{}" .format (n.strip())
bot.sendMessage(chat_id=chat_id, text=Main_URL)
response = requests.get(Main_URL)
html = response.text
soup = BeautifulSoup(html, 'html.parser')
title = soup.find_all("div",{"id":"news_title02"})
contents = soup.find_all("div",{"id":"news_content"})
date = soup.find_all("div",{"id":"news_util01"})
photos = soup.find_all("div",{"class":"news_image"})
for n in contents:
text = n.text.strip()
if __name__ == "__main__":
Site_ON()
----------------------------
인터넷에 공유 된 자료인데 문제점을 찾을 수가 없네요 ..
1. 서버가 아니더라도 원하는 시간에 파이썬 스크립트를 동작시킬 컴퓨터가 필요합니다. 당연히 그 시간에 컴퓨터가 켜져 있어야겠죠.
2.
가져오신 소스가 별로 맘에 들지는 않지만
작동할정도만 수정했어요.
from bs4 import BeautifulSoup
from urllib import parse
from collections import OrderedDict #중복 제거
import requests
import os
import telegram
def Site_ON():
search = parse.urlparse('https://www.boannews.com/search/news_list.asp?search=title&find=취약점')
query = parse.parse_qs(search.query) #보안뉴스 인코딩 값이 euc-kr
S_query = parse.urlencode(query, encoding='euc-kr', doseq=True) # URL 인코딩
url = "https://www.boannews.com/search/news_list.asp?{}".format(S_query)
Article_Crawll(url)
def Article_Crawll(url):
news_link = []
response = requests.get(url)
html = response.text
soup = BeautifulSoup(html, 'html.parser')
for link in soup.find_all('a', href=True):
notices_link = link['href']
if '/media/view.asp?idx=' in notices_link:
news_link.append(notices_link) #news_link에 리스트 추가
news_link = list(OrderedDict.fromkeys(news_link)) #중복제거
Compare(news_link)
def Compare(news_link):
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
temp = []
cnt = 0
with open(os.path.join(BASE_DIR, 'compare.txt'), 'w+')as f_read:
before = f_read.readlines()
before = [line.rstrip() for line in before] #(\n)strip in list
f_read.close()
for i in news_link:
if i not in before:
temp.append(i)
cnt = cnt + 1
with open(os.path.join(BASE_DIR, 'compare.txt'), 'a') as f_write:
f_write.write(i+'\n')
f_write.close()
if cnt > 0: #cnt가 1이라도 증가하면 새로운 기사가 있다는 뜻
Maintext_Crawll(temp, cnt)
def Maintext_Crawll(temp, cnt):
bot = telegram.Bot(token="토큰"')
# 어차피 혼자 쓰실 테니 기존 코드보다는 본인의 chat_id를 사용하세요. 구글링 해보세요.
chat_id = "챗 아이디"
NEW = "[+] 보안뉴스 ' 취약점 '에 새로운 뉴스는 {}개 입니다.".format(cnt)
bot.sendMessage(chat_id=chat_id, text=NEW)
for n in temp:
Main_URL = "https://www.boannews.com{}".format (n.strip())
bot.sendMessage(chat_id=chat_id, text=Main_URL)
response = requests.get(Main_URL)
html = response.text
soup = BeautifulSoup(html, 'html.parser')
title = soup.find_all("div",{"id":"news_title02"})
contents = soup.find_all("div",{"id":"news_content"})
date = soup.find_all("div",{"id":"news_util01"})
photos = soup.find_all("div",{"class":"news_image"})
for n in contents:
text = n.text.strip()
if __name__ == "__main__":
Site_ON()
프로그래밍에 대해서 아는게 없어서 ..
오류가 나진 않고 봇으로 전송이 안되어서 글을 올린거였습니다.진짜 감사드립니다.