wlstp8473

chatbot_code(weather_info,covid_info,resturant_info,simple react)

1 +#total_chatbot_code
2 +import telegram
3 +from telegram.ext import Updater
4 +from telegram.ext import MessageHandler, Filters
5 +import os
6 +
7 +import telegram
8 +from telegram.ext import Updater
9 +from telegram.ext import MessageHandler, Filters
10 +from bs4 import BeautifulSoup
11 +from selenium import webdriver
12 +import urllib.request as req
13 +from selenium.webdriver.support.ui import WebDriverWait
14 +from selenium.webdriver.support import expected_conditions as EC
15 +from selenium.webdriver.common.by import By
16 +
17 +from pprint import pprint
18 +import requests
19 +
20 +html = requests.get('https://search.naver.com/search.naver?query=날씨')
21 +#pprint(html.text)
22 +
23 +import json
24 +from io import StringIO #return_print 하기 위해
25 +
26 +
27 +
28 +
29 +################ 음식점 검색 기능 ##############
30 +class KakaoLocalAPI:
31 + """
32 + Kakao Local API 컨트롤러
33 + """
34 +
35 + def __init__(self, rest_api_key):
36 + """
37 + Rest API키 초기화 및 기능 별 URL 설정
38 + """
39 +
40 +
41 + # REST API 키 설정
42 + self.rest_api_key = "1c74642c092d28c438467486c366c6cf"
43 + self.headers = {"Authorization": "KakaoAK {}".format(rest_api_key)}
44 +
45 + # 서비스 URL 설정
46 +
47 +
48 + # 05 키워드 검색
49 + self.URL_05 = "https://dapi.kakao.com/v2/local/search/keyword.json"
50 +
51 +
52 + def search_keyword(self,query,category_group_code=None,x=None,y=None,radius=None,rect=None,page=None,size=None,sort=None):
53 + """
54 + 05 키워드 검색
55 + """
56 + #params = {'query': f"{query}",
57 + # 'x': f"{x}",
58 + # 'y': f"{y}"}
59 +
60 + params = {'query': f"{query}",
61 + 'x': f"{x}",
62 + 'y': f"{y}",}
63 +
64 + if radius != None:
65 + params['radius'] = f"{radius}"
66 + if rect != None:
67 + params['rect'] = f"{rect}"
68 + if page != None:
69 + params['page'] = f"{page}"
70 + if size != None:
71 + params['size'] = f"{params}"
72 + if sort != None:
73 + params['sort'] = f"{sort}"
74 +
75 + res = requests.get(self.URL_05, headers=self.headers, params=params)
76 + document = json.loads(res.text)
77 + return document
78 +
79 +# REST API 키
80 +rest_api_key = "1c74642c092d28c438467486c366c6cf"
81 +kakao = KakaoLocalAPI(rest_api_key)
82 +
83 +## Set params
84 +query = "인덕원 닭갈비" #검색 키워드
85 +x = 126.98083352703802 #내 위치 위도와 경도
86 +y = 37.39403042340368
87 +radius = 1 #반경 km 검색
88 +
89 +## Request
90 +result_5 = kakao.search_keyword(query,x,y,radius)
91 +
92 +
93 +# + json파일 확인해보기 이후 데이터를 추출해야함
94 +#json_string = json.dumps(result_5, indent=2)
95 +#print(json_string)
96 +
97 +
98 +#json파일 특정 키워드 추출
99 +#추출할 리스트 place_name, place_url, x, y (x y는 위치임), 검색키워드, 선택 지역(위치)
100 +#from pprint import pprint
101 +
102 +same_name_list = [ x_ for x_ in result_5['meta']['same_name'].values()]
103 +keyword = "검색 키워드: " + same_name_list[0]
104 +selected_region= "검색 위치: " +same_name_list[2]
105 +
106 +total_count = {result_5['meta']['total_count']} #set은 파싱이 불가능하기 때문에 list나 튜플로 바꿔야함, list로 바꾼 후 인덱스를 활용하여 int로 바꾼 후 문자열과 더하기 위해 str로 형변환
107 +total_count_list=list(total_count)
108 +total_count = "총 검색 개수: " + str(total_count_list[0])
109 +#print(keyword) # 밑 코드에서 메제지들은 텔레그렘 봇으로 보내기!!
110 +#print(selected_region)
111 +#print(total_count)
112 +
113 +#print("----------")
114 +
115 +place_name_list = [ x_['place_name'] for x_ in result_5['documents']]
116 +#print(place_name_list)
117 +
118 +#print('------')
119 +
120 +phone_list = [ x_['phone'] for x_ in result_5['documents']]
121 +#print(phone_list)
122 +
123 +#print('------')
124 +
125 +place_url_list = [ x_['place_url'] for x_ in result_5['documents']]
126 +
127 +#print(place_url_list)
128 +
129 +#print('------')
130 +
131 +#print(x_list) 위치 시각화 할때 사용
132 +x_list = [ x_['x'] for x_ in result_5['documents']]
133 +y_list = [ x_['y'] for x_ in result_5['documents']]
134 +
135 +#print(y_list)
136 +#print(x_list)
137 +
138 +#print('------')
139 +
140 +road_address_name_list = [ x_['road_address_name'] for x_ in result_5['documents']]
141 +
142 +
143 +#print(road_address_name_list)
144 +
145 +#print('------')
146 +
147 +resturant_info_list = []
148 +total_count_num = str(total_count_list[0])
149 +total_count_num = int(total_count_num)
150 +resturant_info = ""
151 +resturant_string = "관련 음식점 정보: " + '\n'
152 +
153 +#프린트 결과를 리턴받기 위한 함수
154 +#from io import StringIO
155 +def return_print(*message):
156 + io = StringIO()
157 + print(*message, file=io, end="")
158 + return io.getvalue()
159 +
160 +for i in range(0,10): #total_count_num가 너무 크면 인덱스 범위가 벗어나서 실행이 안됨, 임시로 10개까지만
161 + resturant_info = [place_name_list[i] + " " +phone_list[i] + " " + road_address_name_list[i] + " " + place_url_list[i]]
162 + resturant_string += str(resturant_info) + "\n" + "\n"
163 +
164 +
165 +########################### 날씨 크롤링 기능 ########################
166 +
167 +def weather_info_crawling():
168 + soup = BeautifulSoup(html.text, 'html.parser')
169 + data1 = soup.find('div', {'class': 'weather_box'})
170 +
171 + find_address = data1.find('span', {'class':'btn_select'}).text
172 + find_address_info = ('현재 위치: '+find_address + "\n")
173 +
174 + find_currenttemp = data1.find('span',{'class': 'todaytemp'}).text
175 + find_currenttemp_info=('현재 온도: '+find_currenttemp+'℃'+ "\n")
176 +
177 + data2 = data1.findAll('dd')
178 + find_dust = data2[0].find('span', {'class':'num'}).text
179 + find_dust_info=('현재 미세먼지: '+find_dust + "\n")
180 + result = find_address_info + ' ' + find_currenttemp_info + ' ' + find_dust_info
181 + return result
182 +
183 +
184 +def find_currenttemp_num():
185 + soup = BeautifulSoup(html.text, 'html.parser')
186 + data1 = soup.find('div', {'class': 'weather_box'})
187 +
188 + find_currenttemp = data1.find('span',{'class': 'todaytemp'}).text
189 + find_currenttemp_num = int(find_currenttemp)
190 + result = find_currenttemp_num
191 + return result
192 +
193 +
194 +
195 +######################## 코로나 확진자 수 관련 뉴스 크롤링 기능 ###########
196 +
197 +def covid_num_crawling():
198 + 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%9E%90")
199 + soup = BeautifulSoup(code, "html.parser")
200 + info_num = soup.select("div.status_today em")
201 + result = int(info_num[0].string) + int(info_num[1].string)
202 + return result
203 +
204 +def covid_news_crawling():
205 + code = req.urlopen("https://search.naver.com/search.naver?where=news&sm=tab_jum&query=%EC%BD%94%EB%A1%9C%EB%82%98")
206 + soup = BeautifulSoup(code, "html.parser")
207 + title_list = soup.select("a.news_tit")
208 + output_result = ""
209 + for i in title_list:
210 + title = i.text
211 + news_url = i.attrs["href"]
212 + output_result += title + "\n" + news_url + "\n\n"
213 + if title_list.index(i) == 2:
214 + break
215 + return output_result
216 +
217 +
218 +
219 +#####텔레그램 관련 코드##############################################
220 +token = "1721885449:AAHDGMbjSJfhXxML6nfSCpfiU7SghpL_vOE"
221 +id = "1657858421"
222 +bot = telegram.Bot(token)
223 +
224 +updater = Updater(token=token, use_context=True)
225 +dispatcher = updater.dispatcher
226 +updater.start_polling()
227 +
228 +
229 +
230 +#가능한 응답 리스트 목록
231 +menual_message = '''사용가능한 기능 #(모해?) #(맛집) #(오늘 날씨) #(코로나 정보) #(기능) '''
232 +menual_message_info = "#(모해?) #(맛집) #(오늘 날씨) #(코로나 정보) #(기능)"
233 +bot.sendMessage(chat_id=id, text=menual_message)
234 +
235 +
236 +
237 +#특정 단어 시 호출되는 메세지들
238 +mohae_message = '''나 내일 입을 옷 고민 중 #(어떤 옷?)'''
239 +react_weather = '''오늘 날씨 봐봐'''
240 +news_message = '''관련 뉴스도 엄청 많이 보도되고 있더라,,, (#뉴스)'''
241 +worried_message = '''진세도 꼭 마스크 끼고 손 씻고 주의해!! (#웅웅 너도)'''
242 +react01_message = '''오키 ㅎㅎ'''
243 +
244 +
245 +### 챗봇 답장 코드
246 +def handler(update, context):
247 + user_text = update.message.text # 사용자가 보낸 메세지를 user_text 변수에 저장합니다.
248 +
249 + # 모해?
250 + if ( "모해?" in user_text):
251 + bot.sendMessage(chat_id=id, text=mohae_message)
252 +
253 + elif (user_text == "어떤 옷?"):
254 + bot.send_message(chat_id=id, text="잠깐만 옷 좀..")
255 + #이미지를 디렉토리에서 한장씩 보냄
256 + bot.send_photo(chat_id=id, photo=open(r'C:\Users\user\Documents\project_opensw-chatbot\telegram_Messenger_Chatbot\img\cloth1.jpg', 'rb')) ###절대 경로니까 수정하세요!!!!!!
257 + bot.send_photo(chat_id=id, photo=open(r'C:\Users\user\Documents\project_opensw-chatbot\telegram_Messenger_Chatbot\img\cloth2.jpg', 'rb'))
258 + bot.send_photo(chat_id=id, photo=open(r'C:\Users\user\Documents\project_opensw-chatbot\telegram_Messenger_Chatbot\img\cloth3.jpg', 'rb'))
259 + bot.send_message(chat_id=id, text="1~3 번 중에서 어떤게 더 남? (#1~3번)")
260 +
261 + elif ("1번" in user_text) or ("2번" in user_text) or ("3번" in user_text): ###1~3번이 들어오면 오케이
262 + bot.send_message(chat_id=id, text="👌")
263 + bot.send_message(chat_id=id, text="낼 이거 입고 나가야지")
264 + bot.send_message(chat_id=id, text="진세 밥 먹었어?? #(응응 먹었어, 아직 안 먹었어)")
265 +
266 + elif (user_text == "응응 먹었어"):
267 + bot.send_message(chat_id=id, text="우왕 뭐 먹었어? #(닭갈비 먹었어)")
268 + elif (user_text == "닭갈비 먹었어"):
269 + bot.send_message(chat_id=id, text="오,, 대박 이 근처에 닭갈비 맛집 있다던데 가봤어? #맛집?") #################네이버 지도 연결해서 위치 뜨게 하기!! 혹은 크롤링해서 정보 수집 ㄱ
270 +
271 + # 맛집 키워드 답장
272 + elif ("맛집" in user_text):
273 + bot.sendMessage(chat_id=id, text=resturant_string)
274 + elif ("고마워" in user_text):
275 + bot.send_message(chat_id=id, text="웅 ㅎㅎ")
276 +
277 +
278 + elif (user_text == "아직 안 먹었어"):
279 + bot.send_message(chat_id=id, text="헐헐 어쩌다?, 같이 뭐라도 먹을래? #(그래 같이 먹자)")
280 + elif (user_text == "그래 같이 먹자"):
281 + bot.send_message(chat_id=id, text="웅웅 집앞으로 나와")
282 + ########################################################################### 이어서 작업 ㄱㄱㄱ
283 +
284 + # 오늘 날씨 답장
285 + elif ("오늘 날씨" in user_text):
286 + weather_info = weather_info_crawling()
287 + bot.send_message(chat_id=id, text= weather_info)
288 + bot.sendMessage(chat_id=id, text=react_weather)
289 + #bot.send_photo(chat_id=id, photo=open(r'C:\Users\user\Documents\project_opensw-chatbot\telegram_Messenger_Chatbot\img\weather_cloth_info.jpg', 'rb')) ###절대 경로니까 수정하세요!!!!!!
290 + if (find_currenttemp_num()>=27):
291 + bot.send_message(chat_id=id, text="와 미친,, 27도가 넘는데? 낼 무조건 시원하게 얇고 통풍 잘 되는 거 입어, 쪄 죽겠다 ㅋㅋㅋㅋ")
292 + elif (find_currenttemp_num()>=23):
293 + bot.send_message(chat_id=id, text="날씨가 23도 이상이네,,, ㅜㅜ 반팔에 반바지 정도 입으면 충분할 듯!")
294 + elif (find_currenttemp_num()>=20):
295 + bot.send_message(chat_id=id, text="20도 이상이면 밤엔 많이 쌀쌀할 듯 ㅠㅠ,, 진세 감기 조심해!")
296 + elif (find_currenttemp_num()>=15):
297 + bot.send_message(chat_id=id, text="헐 15도 이상이면 가을 날씨네,,,따뜻하게 입고가!!")
298 + else:
299 + update.message.reply_text("꽁꽁 싸매고 나가")
300 +
301 +
302 + # 오늘 확진자 수 답장
303 + elif ("코로나 정보" in user_text):
304 + bot.sendMessage(chat_id=id, text= "진세 진세, 오늘 코로나 확진자 수 몇명인지 알아?? 완전 무섭다,,, ")
305 + covid_num = covid_num_crawling()
306 + bot.send_message(chat_id=id, text="오늘 확진자 수 : {} 명이래 ㅎㄷㄷ..".format(covid_num))
307 + bot.sendMessage(chat_id=id, text=news_message)
308 +
309 + covid_news = covid_news_crawling()
310 + bot.send_message(chat_id=id, text=covid_news)
311 + bot.sendMessage(chat_id=id, text=worried_message)
312 + elif (user_text == "웅웅 너도"):
313 + bot.sendMessage(chat_id=id, text=react01_message)
314 +
315 + elif (user_text == "기능"):
316 + bot.sendMessage(chat_id=id, text=menual_message_info)
317 +
318 + else:
319 + update.message.reply_text("ㅎㅎ")
320 +
321 +echo_handler = MessageHandler(Filters.text, handler)
322 +dispatcher.add_handler(echo_handler)
...\ No newline at end of file ...\ No newline at end of file