Toggle navigation
Toggle navigation
This project
Loading...
Sign in
wlstp8473
/
telegram_Messenger_Chatbot
Go to a project
Toggle navigation
Toggle navigation pinning
Projects
Groups
Snippets
Help
Project
Activity
Repository
Pipelines
Graphs
Issues
0
Merge Requests
0
Wiki
Snippets
Network
Create a new issue
Builds
Commits
Issue Boards
Authored by
wlstp8473
2021-06-10 22:31:02 +0900
Browse Files
Options
Browse Files
Download
Email Patches
Plain Diff
Commit
cdd8c008550a72b1956fa7b7d113e64edef961d7
cdd8c008
1 parent
41d2cdd6
chatbotcode_resturant location using html map
Show whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
338 additions
and
0 deletions
tele_chatbot_code.py
tele_chatbot_code.py
0 → 100644
View file @
cdd8c00
#total_chatbot_code
import
telegram
from
telegram.ext
import
Updater
from
telegram.ext
import
MessageHandler
,
Filters
import
os
import
webbrowser
import
telegram
from
telegram.ext
import
Updater
from
telegram.ext
import
MessageHandler
,
Filters
from
bs4
import
BeautifulSoup
from
selenium
import
webdriver
import
urllib.request
as
req
from
selenium.webdriver.support.ui
import
WebDriverWait
from
selenium.webdriver.support
import
expected_conditions
as
EC
from
selenium.webdriver.common.by
import
By
from
pprint
import
pprint
import
requests
html
=
requests
.
get
(
'https://search.naver.com/search.naver?query=날씨'
)
#pprint(html.text)
import
json
from
io
import
StringIO
#return_print 하기 위해
################ 음식점 검색 기능 ##############
class
KakaoLocalAPI
:
"""
Kakao Local API 컨트롤러
"""
def
__init__
(
self
,
rest_api_key
):
"""
Rest API키 초기화 및 기능 별 URL 설정
"""
# REST API 키 설정
self
.
rest_api_key
=
"1c74642c092d28c438467486c366c6cf"
self
.
headers
=
{
"Authorization"
:
"KakaoAK {}"
.
format
(
rest_api_key
)}
# 서비스 URL 설정
# 05 키워드 검색
self
.
URL_05
=
"https://dapi.kakao.com/v2/local/search/keyword.json"
def
search_keyword
(
self
,
query
,
category_group_code
=
None
,
x
=
None
,
y
=
None
,
radius
=
None
,
rect
=
None
,
page
=
None
,
size
=
None
,
sort
=
None
):
"""
05 키워드 검색
"""
#params = {'query': f"{query}",
# 'x': f"{x}",
# 'y': f"{y}"}
params
=
{
'query'
:
f
"{query}"
,
'x'
:
f
"{x}"
,
'y'
:
f
"{y}"
,}
if
radius
!=
None
:
params
[
'radius'
]
=
f
"{radius}"
if
rect
!=
None
:
params
[
'rect'
]
=
f
"{rect}"
if
page
!=
None
:
params
[
'page'
]
=
f
"{page}"
if
size
!=
None
:
params
[
'size'
]
=
f
"{params}"
if
sort
!=
None
:
params
[
'sort'
]
=
f
"{sort}"
res
=
requests
.
get
(
self
.
URL_05
,
headers
=
self
.
headers
,
params
=
params
)
document
=
json
.
loads
(
res
.
text
)
return
document
# REST API 키
rest_api_key
=
"1c74642c092d28c438467486c366c6cf"
kakao
=
KakaoLocalAPI
(
rest_api_key
)
## Set params
query
=
"인덕원 닭갈비"
#검색 키워드
x
=
126.98083352703802
#내 위치 위도와 경도
y
=
37.39403042340368
radius
=
1
#반경 km 검색
## Request
result_5
=
kakao
.
search_keyword
(
query
,
x
,
y
,
radius
)
# + json파일 확인해보기 이후 데이터를 추출해야함
#json_string = json.dumps(result_5, indent=2)
#print(json_string)
#json파일 특정 키워드 추출
#추출할 리스트 place_name, place_url, x, y (x y는 위치임), 검색키워드, 선택 지역(위치)
#from pprint import pprint
same_name_list
=
[
x_
for
x_
in
result_5
[
'meta'
][
'same_name'
]
.
values
()]
keyword
=
"검색 키워드: "
+
same_name_list
[
0
]
selected_region
=
"검색 위치: "
+
same_name_list
[
2
]
total_count
=
{
result_5
[
'meta'
][
'total_count'
]}
#set은 파싱이 불가능하기 때문에 list나 튜플로 바꿔야함, list로 바꾼 후 인덱스를 활용하여 int로 바꾼 후 문자열과 더하기 위해 str로 형변환
total_count_list
=
list
(
total_count
)
total_count
=
"총 검색 개수: "
+
str
(
total_count_list
[
0
])
#print(keyword) # 밑 코드에서 메제지들은 텔레그렘 봇으로 보내기!!
#print(selected_region)
#print(total_count)
#print("----------")
place_name_list
=
[
x_
[
'place_name'
]
for
x_
in
result_5
[
'documents'
]]
#print(place_name_list)
#print('------')
phone_list
=
[
x_
[
'phone'
]
for
x_
in
result_5
[
'documents'
]]
#print(phone_list)
#print('------')
place_url_list
=
[
x_
[
'place_url'
]
for
x_
in
result_5
[
'documents'
]]
#print(place_url_list)
#print('------')
#print(x_list) 위치 시각화 할때 사용
x_list
=
[
x_
[
'x'
]
for
x_
in
result_5
[
'documents'
]]
y_list
=
[
x_
[
'y'
]
for
x_
in
result_5
[
'documents'
]]
#print(y_list)
#print(x_list)
#print('------')
road_address_name_list
=
[
x_
[
'road_address_name'
]
for
x_
in
result_5
[
'documents'
]]
#print(road_address_name_list)
#print('------')
resturant_info_list
=
[]
total_count_num
=
str
(
total_count_list
[
0
])
total_count_num
=
int
(
total_count_num
)
resturant_info
=
""
resturant_string
=
"관련 음식점 정보: "
+
'
\n
'
resturant_location_string
=
"음식점의 x y좌표"
+
'
\n
'
#프린트 결과를 리턴받기 위한 함수
#from io import StringIO
def
return_print
(
*
message
):
io
=
StringIO
()
print
(
*
message
,
file
=
io
,
end
=
""
)
return
io
.
getvalue
()
for
i
in
range
(
0
,
10
):
#total_count_num가 너무 크면 인덱스 범위가 벗어나서 실행이 안됨, 임시로 10개까지만
resturant_info
=
[
place_name_list
[
i
]
+
" "
+
phone_list
[
i
]
+
" "
+
road_address_name_list
[
i
]
+
" "
+
place_url_list
[
i
]]
resturant_string
+=
str
(
resturant_info
)
+
"
\n
"
+
"
\n
"
for
i
in
range
(
0
,
10
):
#total_count_num가 너무 크면 인덱스 범위가 벗어나서 실행이 안됨, 임시로 10개까지만
resturant_location
=
[
x_list
[
i
]
+
", "
+
y_list
[
i
]]
resturant_location_string
+=
str
(
resturant_location
)
+
"
\n
"
########################### 날씨 크롤링 기능 ########################
def
weather_info_crawling
():
soup
=
BeautifulSoup
(
html
.
text
,
'html.parser'
)
data1
=
soup
.
find
(
'div'
,
{
'class'
:
'weather_box'
})
find_address
=
data1
.
find
(
'span'
,
{
'class'
:
'btn_select'
})
.
text
find_address_info
=
(
'현재 위치: '
+
find_address
+
"
\n
"
)
find_currenttemp
=
data1
.
find
(
'span'
,{
'class'
:
'todaytemp'
})
.
text
find_currenttemp_info
=
(
'현재 온도: '
+
find_currenttemp
+
'℃'
+
"
\n
"
)
data2
=
data1
.
findAll
(
'dd'
)
find_dust
=
data2
[
0
]
.
find
(
'span'
,
{
'class'
:
'num'
})
.
text
find_dust_info
=
(
'현재 미세먼지: '
+
find_dust
+
"
\n
"
)
result
=
find_address_info
+
' '
+
find_currenttemp_info
+
' '
+
find_dust_info
return
result
def
find_currenttemp_num
():
soup
=
BeautifulSoup
(
html
.
text
,
'html.parser'
)
data1
=
soup
.
find
(
'div'
,
{
'class'
:
'weather_box'
})
find_currenttemp
=
data1
.
find
(
'span'
,{
'class'
:
'todaytemp'
})
.
text
find_currenttemp_num
=
int
(
find_currenttemp
)
result
=
find_currenttemp_num
return
result
######################## 코로나 확진자 수 관련 뉴스 크롤링 기능 ###########
def
covid_num_crawling
():
code
=
req
.
urlopen
(
"https://search.naver.com/search.naver?where=nexearch&sm=top_hty&fbm=0&ie=utf8&query=
%
ED
%99%95%
EC
%
A7
%84%
EC
%9
E
%90
"
)
soup
=
BeautifulSoup
(
code
,
"html.parser"
)
info_num
=
soup
.
select
(
"div.status_today em"
)
result
=
int
(
info_num
[
0
]
.
string
)
+
int
(
info_num
[
1
]
.
string
)
return
result
def
covid_news_crawling
():
code
=
req
.
urlopen
(
"https://search.naver.com/search.naver?where=news&sm=tab_jum&query=
%
EC
%
BD
%94%
EB
%
A1
%9
C
%
EB
%82%98
"
)
soup
=
BeautifulSoup
(
code
,
"html.parser"
)
title_list
=
soup
.
select
(
"a.news_tit"
)
output_result
=
""
for
i
in
title_list
:
title
=
i
.
text
news_url
=
i
.
attrs
[
"href"
]
output_result
+=
title
+
"
\n
"
+
news_url
+
"
\n\n
"
if
title_list
.
index
(
i
)
==
2
:
break
return
output_result
#####텔레그램 관련 코드##############################################
token
=
"1721885449:AAHDGMbjSJfhXxML6nfSCpfiU7SghpL_vOE"
id
=
"1657858421"
bot
=
telegram
.
Bot
(
token
)
updater
=
Updater
(
token
=
token
,
use_context
=
True
)
dispatcher
=
updater
.
dispatcher
updater
.
start_polling
()
url
=
"file:///C:/Users/user/Documents/project_opensw-chatbot/telegram_Messenger_Chatbot/index.html"
#가능한 응답 리스트 목록
menual_message
=
'''사용가능한 기능 #(모해?) #(맛집) #(오늘 날씨) #(코로나 정보) #(기능) '''
menual_message_info
=
"#(모해?) #(맛집) #(오늘 날씨) #(코로나 정보) #(기능)"
bot
.
sendMessage
(
chat_id
=
id
,
text
=
menual_message
)
#특정 단어 시 호출되는 메세지들
mohae_message
=
'''나 내일 입을 옷 고민 중 #(어떤 옷?)'''
react_weather
=
'''오늘 날씨 봐봐'''
news_message
=
'''관련 뉴스도 엄청 많이 보도되고 있더라,,, (#뉴스)'''
worried_message
=
'''진세도 꼭 마스크 끼고 손 씻고 주의해!! (#웅웅 너도)'''
react01_message
=
'''오키 ㅎㅎ'''
### 챗봇 답장 코드
def
handler
(
update
,
context
):
user_text
=
update
.
message
.
text
# 사용자가 보낸 메세지를 user_text 변수에 저장합니다.
# 모해?
if
(
"모해?"
in
user_text
):
bot
.
sendMessage
(
chat_id
=
id
,
text
=
mohae_message
)
elif
(
user_text
==
"어떤 옷?"
):
bot
.
send_message
(
chat_id
=
id
,
text
=
"잠깐만 옷 좀.."
)
#이미지를 디렉토리에서 한장씩 보냄
bot
.
send_photo
(
chat_id
=
id
,
photo
=
open
(
r'C:\Users\user\Documents\project_opensw-chatbot\telegram_Messenger_Chatbot\img\cloth1.jpg'
,
'rb'
))
###절대 경로니까 수정하세요!!!!!!
bot
.
send_photo
(
chat_id
=
id
,
photo
=
open
(
r'C:\Users\user\Documents\project_opensw-chatbot\telegram_Messenger_Chatbot\img\cloth2.jpg'
,
'rb'
))
bot
.
send_photo
(
chat_id
=
id
,
photo
=
open
(
r'C:\Users\user\Documents\project_opensw-chatbot\telegram_Messenger_Chatbot\img\cloth3.jpg'
,
'rb'
))
bot
.
send_message
(
chat_id
=
id
,
text
=
"1~3 번 중에서 어떤게 더 남? (#1~3번)"
)
elif
(
"1번"
in
user_text
)
or
(
"2번"
in
user_text
)
or
(
"3번"
in
user_text
):
###1~3번이 들어오면 오케이
bot
.
send_message
(
chat_id
=
id
,
text
=
"👌"
)
bot
.
send_message
(
chat_id
=
id
,
text
=
"낼 이거 입고 나가야지"
)
bot
.
send_message
(
chat_id
=
id
,
text
=
"진세 밥 먹었어?? #(응응 먹었어, 아직 안 먹었어)"
)
elif
(
user_text
==
"응응 먹었어"
):
bot
.
send_message
(
chat_id
=
id
,
text
=
"우왕 뭐 먹었어? #(닭갈비 먹었어)"
)
elif
(
user_text
==
"닭갈비 먹었어"
):
bot
.
send_message
(
chat_id
=
id
,
text
=
"오,, 대박 이 근처에 닭갈비 맛집 있다던데 가봤어? #맛집?"
)
#################네이버 지도 연결해서 위치 뜨게 하기!! 혹은 크롤링해서 정보 수집 ㄱ
# 맛집 키워드 답장
elif
(
"맛집"
in
user_text
):
bot
.
sendMessage
(
chat_id
=
id
,
text
=
resturant_string
)
#bot.sendMessage(chat_id=id, text=resturant_location_string) 음식점 xy좌표 반환할 거임
bot
.
sendMessage
(
chat_id
=
id
,
text
=
webbrowser
.
open
(
url
))
#############################webpage 내 위치 기바ㄴ
elif
(
"고마워"
in
user_text
):
bot
.
send_message
(
chat_id
=
id
,
text
=
"웅 ㅎㅎ"
)
elif
(
user_text
==
"아직 안 먹었어"
):
bot
.
send_message
(
chat_id
=
id
,
text
=
"헐헐 어쩌다?, 같이 뭐라도 먹을래? #(그래 같이 먹자)"
)
elif
(
user_text
==
"그래 같이 먹자"
):
bot
.
send_message
(
chat_id
=
id
,
text
=
"웅웅 집앞으로 나와"
)
########################################################################### 이어서 작업 ㄱㄱㄱ
# 오늘 날씨 답장
elif
(
"오늘 날씨"
in
user_text
):
weather_info
=
weather_info_crawling
()
bot
.
send_message
(
chat_id
=
id
,
text
=
weather_info
)
bot
.
sendMessage
(
chat_id
=
id
,
text
=
react_weather
)
if
(
find_currenttemp_num
()
>=
27
):
bot
.
send_message
(
chat_id
=
id
,
text
=
"와 미친,, 27도가 넘는데? 낼 무조건 시원하게 얇고 통풍 잘 되는 거 입어, 쪄 죽겠다 ㅋㅋㅋㅋ"
)
elif
(
find_currenttemp_num
()
>=
23
):
bot
.
send_message
(
chat_id
=
id
,
text
=
"날씨가 23도 이상이네,,, ㅜㅜ 반팔에 반바지 정도 입으면 충분할 듯!"
)
elif
(
find_currenttemp_num
()
>=
20
):
bot
.
send_message
(
chat_id
=
id
,
text
=
"20도 이상이면 밤엔 많이 쌀쌀할 듯 ㅠㅠ,, 진세 감기 조심해!"
)
elif
(
find_currenttemp_num
()
>=
15
):
bot
.
send_message
(
chat_id
=
id
,
text
=
"헐 15도 이상이면 가을 날씨네,,,따뜻하게 입고가!!"
)
else
:
update
.
message
.
reply_text
(
"꽁꽁 싸매고 나가"
)
# 오늘 확진자 수 답장
elif
(
"코로나 정보"
in
user_text
):
bot
.
sendMessage
(
chat_id
=
id
,
text
=
"진세 진세, 오늘 코로나 확진자 수 몇명인지 알아?? 완전 무섭다,,, "
)
covid_num
=
covid_num_crawling
()
bot
.
send_message
(
chat_id
=
id
,
text
=
"오늘 확진자 수 : {} 명이래 ㅎㄷㄷ.."
.
format
(
covid_num
))
bot
.
sendMessage
(
chat_id
=
id
,
text
=
news_message
)
covid_news
=
covid_news_crawling
()
bot
.
send_message
(
chat_id
=
id
,
text
=
covid_news
)
bot
.
sendMessage
(
chat_id
=
id
,
text
=
worried_message
)
elif
(
user_text
==
"웅웅 너도"
):
bot
.
sendMessage
(
chat_id
=
id
,
text
=
react01_message
)
elif
(
user_text
==
"기능"
):
bot
.
sendMessage
(
chat_id
=
id
,
text
=
menual_message_info
)
else
:
update
.
message
.
reply_text
(
"ㅎㅎ"
)
echo_handler
=
MessageHandler
(
Filters
.
text
,
handler
)
dispatcher
.
add_handler
(
echo_handler
)
\ No newline at end of file
Please
register
or
login
to post a comment