newbot.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. import copy
  2. import fastapi
  3. import fastapi.staticfiles as fastapiStaticfiles
  4. import linebot
  5. import linebot.models as linebotModels
  6. import suggests
  7. from GoogleNews import GoogleNews
  8. import dataset
  9. import datetime
  10. from fastapi.responses import HTMLResponse
  11. import matplotlib.dates as mdates
  12. import matplotlib.pyplot as plt
  13. from starlette.responses import StreamingResponse
  14. from fastapi.responses import FileResponse
  15. import numpy as np
  16. from pylab import plt
  17. from scipy.interpolate import make_interp_spline
  18. from matplotlib import dates
  19. import dataset
  20. import matplotlib.dates as mdates
  21. import random
  22. #
  23. from linebot.models import (
  24. MessageEvent, TextMessage, TextSendMessage,
  25. SourceUser, SourceGroup, SourceRoom,
  26. TemplateSendMessage, ConfirmTemplate, MessageAction,
  27. ButtonsTemplate, ImageCarouselTemplate, ImageCarouselColumn, URIAction,
  28. PostbackAction, DatetimePickerAction,
  29. CameraAction, CameraRollAction, LocationAction,
  30. CarouselTemplate, CarouselColumn, PostbackEvent,
  31. StickerMessage, StickerSendMessage, LocationMessage, LocationSendMessage,
  32. ImageMessage, VideoMessage, AudioMessage, FileMessage,
  33. UnfollowEvent, FollowEvent, JoinEvent, LeaveEvent, BeaconEvent,
  34. MemberJoinedEvent, MemberLeftEvent,
  35. FlexSendMessage, BubbleContainer, ImageComponent, BoxComponent,
  36. TextComponent, IconComponent, ButtonComponent,
  37. SeparatorComponent, QuickReply, QuickReplyButton,
  38. ImageSendMessage)
  39. #uvicorn newbot:app --host 0.0.0.0 --port 5443 --ssl-keyfile=/etc/letsencrypt/live/api.ptt.cx/privkey.pem --ssl-certfile=/etc/letsencrypt/live/api.ptt.cx/fullchain.pem
  40. #uvicorn main:app --host 0.0.0.0 --port 443 --ssl-keyfile=/etc/letsencrypt/live/ptt.cx/privkey.pem --ssl-certfile=/etc/letsencrypt/live/ptt.cx/chain.pem
  41. #uvicorn main:app --host 0.0.0.0 --port 443 --key-file=/etc/letsencrypt/live/ptt.cx/privkey.pem --certfile=/etc/letsencrypt/live/ptt.cx/cert.pem
  42. # --keyfile=./key.pem --certfile=./cert.pem
  43. # --ssl-cert-reqs 1
  44. #
  45. # --ssl-ca-certs=/etc/letsencrypt/live/ptt.cx/fullchain.crt
  46. app = fastapi.FastAPI()
  47. #app.mount(
  48. # '/static', fastapiStaticfiles.StaticFiles(directory='static'), name='static')
  49. from linebot import (
  50. LineBotApi, WebhookHandler
  51. )
  52. from linebot.exceptions import (
  53. InvalidSignatureError
  54. )
  55. from linebot.models import (
  56. MessageEvent, TextMessage,ImageSendMessage, TextSendMessage,FlexSendMessage, TemplateSendMessage,CarouselTemplate,ConfirmTemplate,PostbackAction,MessageAction,CarouselColumn,URIAction
  57. )
  58. import json
  59. import codecs
  60. seo=False
  61. s_news=False
  62. line_bot_api = LineBotApi('Gub58t+8u9z7nTBrZLLvXnCbwDR1Gmyrew3nGFlKRxsmvH/oIMGjjup2DygA4XhV1NenM6dFTO8yvpbtCDezCqP2BAV4eVn2Y63/EYqeTCw1S+oJ+BiLLzC8DdVrWu9jSfp7wXqrVNUxcYdk54eoWAdB04t89/1O/w1cDnyilFU=')
  63. handler = WebhookHandler('f761bc6038c94a3baa815124e33dea50')
  64. #line_bot_api = LineBotApi('YOUR_CHANNEL_ACCESS_TOKEN')
  65. #handler = WebhookHandler('YOUR_CHANNEL_SECRET')
  66. def get_aws():
  67. result=''
  68. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/hhh?charset=utf8mb4')
  69. cursor=db.query('SELECT from_unixtime(eventtime) as dt,area FROM hhh.aws_monitor order by eventtime desc limit 4;')
  70. for c in cursor:
  71. result+=str(c['dt'])+"\n"+c['area']+"\n"
  72. return result
  73. def get_idea():
  74. result=''
  75. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/hhh?charset=utf8mb4')
  76. cursor=db.query('SELECT query FROM hhh.gsc_weekly where clicks > 500 order by rand() limit 10;')
  77. for c in cursor:
  78. result+=str(c['query'])+"\n"
  79. return result
  80. def get_kw_ls(past=False):
  81. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/yodb?charset=utf8mb4')
  82. now = ''
  83. sql_get_newest_data_date = 'SELECT * FROM trending_searches ORDER BY ts_date DESC'
  84. for row in db.query(sql_get_newest_data_date):
  85. now = row['ts_date']
  86. break
  87. if past:
  88. now =now-datetime.timedelta(days=1)
  89. now_start = now.strftime("%Y-%m-%d 00:00:00")
  90. now_end = now.strftime("%Y-%m-%d 23:59:59")
  91. sqls = 'SELECT * FROM trending_searches WHERE "'+now_end+'">= ts_date and "'+now_start+'"<=ts_date ORDER BY ts_date DESC'
  92. ls = []
  93. for row in db.query(sqls):
  94. ls.append(row['ts_word'])
  95. ls = list(dict.fromkeys(ls))
  96. return ls
  97. def get_kw(past=False):
  98. keys = get_kw_ls(past)
  99. title = '熱門搜尋關鍵字' if past == False else '歷史關鍵字走勢'
  100. carousel_dict = {"type": "carousel","contents": []}
  101. carousel_idx = -1
  102. num = 1
  103. for k in keys:
  104. if (num-1)%12 ==0:
  105. carousel_dict['contents'] = carousel_dict['contents']+[make_bubble(title,k)]
  106. carousel_idx+=1
  107. carousel_dict['contents'][carousel_idx]['body']['contents'] += [make_box(num,k)]
  108. num+=1
  109. return carousel_dict
  110. @app.get("/aws")
  111. async def aws():
  112. result='<html><head><link href="https://getbootstrap.com/docs/4.1/dist/css/bootstrap.min.css" rel="stylesheet"></head><body>'
  113. result+='製表時間: '+str(datetime.datetime.now())+'</br></br>\n\n'
  114. result+='<table class="table table-striped">'
  115. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/hhh?charset=utf8mb4')
  116. cursor=db.query('SELECT from_unixtime(eventtime) as dt,area FROM hhh.aws_monitor order by eventtime desc limit 30;')
  117. for c in cursor:
  118. result+="<tr><td>"+str(c['dt'])+"</td><td>"+c['area']+"</td></tr>\n"
  119. result+='</table></body></html>'
  120. return HTMLResponse(content=result, status_code=200)
  121. @app.get("/msg/{item_id}")
  122. async def coffee_msg(item_id):
  123. True
  124. line_bot_api.push_message(item_id, TextSendMessage(text='開啟下方完整券樣(密碼9888)至櫃台掃碼兌換。https://txp.rs/v/EvX69b4Xq9'))
  125. return {"code":"ok" }
  126. @app.post('/callback')
  127. async def callback(request: fastapi.Request):
  128. signature = request.headers['X-Line-Signature']
  129. body = await request.body()
  130. handler.handle(body.decode('utf-8'), signature)
  131. return 'OK'
  132. @app.get('/get_trend_image')
  133. async def get_trend_image(kw_id):
  134. #def get_trend_image(kw):
  135. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/yodb?charset=utf8mb4')
  136. kw = ''
  137. sql_get_newest_data_date = 'SELECT iot_kword FROM interest_over_time WHERE iotid="'+kw_id+'"'
  138. for row in db.query(sql_get_newest_data_date):
  139. kw=row['iot_kword']
  140. sql_get_newest_data_date = 'SELECT * FROM interest_over_time WHERE iot_kword="'+kw+'" ORDER BY iot_date'
  141. x_axis = []
  142. y_axis = []
  143. for row in db.query(sql_get_newest_data_date):
  144. x_axis += [row['iot_date']]
  145. y_axis += [row['iot_value']]
  146. x = np.array(x_axis)
  147. y = np.array(y_axis)
  148. # create an array of numbers for the dates
  149. x_dates = np.array([dates.date2num(i) for i in x])
  150. # create more uniform intervals in x axis and use spline to interpolate data
  151. x_smooth = np.linspace(x_dates.min(), x_dates.max(), 200)
  152. #y_smooth = spline(x_dates, y, x_smooth)
  153. y_smooth = make_interp_spline(x_dates, y)(x_smooth)
  154. # creating a new date array from the new date number array
  155. x_new = np.array([dates.num2date(i) for i in x_smooth])
  156. plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y/%m'))
  157. plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=100)) #座標軸刻度1天
  158. #plt.figure()
  159. plt.plot(x_new, y_smooth)
  160. target_path = 'trend_image/'+kw+'.png'
  161. plt.savefig(target_path)
  162. plt.clf()
  163. return FileResponse(target_path)
  164. def get_news_by_kw(keyword):
  165. googlenews = GoogleNews(lang='zh-TW')
  166. kw=keyword
  167. googlenews.set_lang('zh-TW')
  168. googlenews.search(kw)
  169. resultstr="新聞:"
  170. idx=0
  171. rs=googlenews.results()
  172. for r in rs:
  173. if idx>0:
  174. resultstr+=','
  175. else:
  176. idx+=1
  177. resultstr+=r['title']
  178. return resultstr
  179. # print(r['desc'])
  180. # print(r['link'])
  181. # print(r['datetime'])
  182. def flex_test():
  183. js=json.load(open('test.json','r',encoding='utf-8'))
  184. for i in range(3):
  185. row_dict = {}
  186. row_dict['type'] = 'box'
  187. row_dict['layout'] = 'baseline'
  188. row_dict['contents']= [
  189. {"type": "text","text": "第"+str(i)+"名","size": "sm","color": "#aaaaaa","flex": 2},
  190. {"type": "text","text": "hello, world"+str(1),"flex": 5,"weight": "regular"}
  191. ]
  192. js['body']['contents'] = js['body']['contents'] + [row_dict]
  193. return js
  194. def make_bubble(title,kw):
  195. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/yodb?charset=utf8mb4')
  196. sql_get_newest_data_date = 'SELECT iotid FROM interest_over_time WHERE iot_kword="'+kw+'"'
  197. id=''
  198. for row in db.query(sql_get_newest_data_date):
  199. id=row['iotid']
  200. id = random.randint(1,1050)
  201. box_dict = {
  202. "type": "bubble",
  203. "hero": {
  204. "type": "image",
  205. "url": "https://api.ptt.cx:6443/get_trend_image?kw_id="+str(id),
  206. "size": "full",
  207. "gravity": "top",
  208. "margin": "none",
  209. "aspectRatio": "20:13"
  210. },
  211. "body": {
  212. "type": "box",
  213. "layout": "vertical",
  214. "contents": [
  215. {
  216. "type": "text",
  217. "text": title+"-"+kw,
  218. "size": "xl",
  219. "weight": "bold",
  220. "align": "center"
  221. }
  222. ]
  223. }
  224. }
  225. return box_dict
  226. def make_box(num, content):
  227. row_dict = {}
  228. row_dict['type'] = 'box'
  229. row_dict['layout'] = 'baseline'
  230. #row_dict["action"]= {
  231. # "type": "uri",
  232. # "label": "action",
  233. # "uri": "https://store.line.me"
  234. #}
  235. row_dict['contents']= [
  236. {
  237. "type": "text",
  238. "text": "第"+str(num)+"名",
  239. "size": "sm",
  240. "color": "#aaaaaa",
  241. "flex": 2
  242. },
  243. {
  244. "type": "text",
  245. "text": content,
  246. "flex": 5,
  247. "weight": "regular"
  248. }
  249. ]
  250. return row_dict
  251. def make_carousel():
  252. carousel_dict = {"type": "carousel","contents": []}
  253. carousel_idx = -1
  254. for i in range(26):
  255. if i%12 ==0:
  256. carousel_dict['contents'] = carousel_dict['contents']+[make_bubble()]
  257. carousel_idx+=1
  258. carousel_dict['contents'][carousel_idx]['body']['contents'] += [make_box(i,'data'+str(i))]
  259. return carousel_dict
  260. @handler.add(FollowEvent)
  261. def handle_follow(event):
  262. print(event.source.user_id)
  263. # do something
  264. @handler.add(linebotModels.MessageEvent, message=linebotModels.TextMessage)
  265. def message_text(event):
  266. global seo
  267. global s_news
  268. ## if event.message.text == 'push':
  269. # line_bot_api.push_message(
  270. # event.source.user_id, [
  271. # # TextSendMessage(text='PUSH!'),
  272. # ]
  273. # )
  274. if event.message.text == 's_news':
  275. s_news=True
  276. line_bot_api.reply_message(
  277. event.reply_token,
  278. TextSendMessage(text='請輸入要搜尋新聞的關鍵字:'))
  279. return
  280. if event.message.text == 'q_aws':
  281. line_bot_api.reply_message(
  282. event.reply_token,[TextSendMessage(text=get_aws()),TextSendMessage(text='完整報告: https://api.ptt.cx:5443/aws')])
  283. return
  284. if event.message.text == 'q_idea':
  285. s_news=True
  286. line_bot_api.reply_message(
  287. event.reply_token,
  288. TextSendMessage(text=get_idea()))
  289. return
  290. ############################
  291. if event.message.text == 'hotkeys':
  292. js = get_kw(False)
  293. line_bot_api.reply_message(event.reply_token, FlexSendMessage('ChoozMo',js))
  294. return
  295. if event.message.text == 'past_hotkeys':
  296. js = get_kw(True)
  297. line_bot_api.reply_message(event.reply_token, FlexSendMessage('ChoozMo',js))
  298. return
  299. if event.message.text == '合作提案':
  300. line_bot_api.reply_message(
  301. event.reply_token,
  302. TextSendMessage(text='合作提案請寄信至 : jared@choozmo.com 信箱'))
  303. return
  304. if event.message.text == '更多功能':
  305. line_bot_api.reply_message(
  306. event.reply_token,
  307. TextSendMessage(
  308. text='更多功能',
  309. quick_reply=QuickReply(
  310. items=[
  311. QuickReplyButton(
  312. action=MessageAction(label="合作提案", text="合作提案")
  313. ),
  314. ])))
  315. return
  316. '''
  317. if event.message.text == 'seo':
  318. seo=True
  319. line_bot_api.reply_message(
  320. event.reply_token,
  321. TextSendMessage(text='請輸入要找的關鍵字:'))
  322. return
  323. '''
  324. if event.message.text=='js test':
  325. FlexMessage = flex_test()
  326. line_bot_api.reply_message(event.reply_token, FlexSendMessage('ChoozMo',FlexMessage))
  327. return
  328. if event.message.text=='熱門關鍵字':
  329. js = get_kw(False)
  330. line_bot_api.reply_message(event.reply_token, FlexSendMessage('ChoozMo',js))
  331. return
  332. if event.message.text=='關鍵字歷史走勢':
  333. js = get_kw(True)
  334. line_bot_api.reply_message(event.reply_token, FlexSendMessage('ChoozMo',js))
  335. return
  336. if event.message.text == '叫':
  337. line_bot_api.reply_message(
  338. event.reply_token, linebotModels.AudioSendMessage(
  339. original_content_url=f'{baseUrl}/static/audio/noot_noot.mp3', duration=1000))
  340. if event.message.text=='ok':
  341. line_bot_api.reply_message(
  342. event.reply_token,
  343. TextSendMessage(text='最欣賞ChoozMo團隊說OK的人!!'))
  344. '''
  345. if event.message.text=='c' or event.message.text=='C' :
  346. line_bot_api.reply_message(
  347. event.reply_token,
  348. TextSendMessage(
  349. text='快速鍵',
  350. quick_reply=QuickReply(
  351. items=[
  352. QuickReplyButton(
  353. action=MessageAction(label="熱門關鍵字", text="hotkeys")
  354. ),
  355. QuickReplyButton(
  356. action=MessageAction(label="關鍵字歷史走勢", text="past_hotkeys")
  357. ),
  358. QuickReplyButton(
  359. action=MessageAction(label="更多功能", text="更多功能")
  360. ),
  361. #QuickReplyButton(
  362. # action=MessageAction(label="幸福空間靈感", text="q_idea")
  363. #),
  364. #QuickReplyButton(
  365. # action=MessageAction(label="查AWS", text="q_aws")
  366. #),
  367. #QuickReplyButton(
  368. # action=MessageAction(label="關聯字", text="seo")
  369. #),
  370. ])))
  371. else:
  372. if s_news:
  373. result=get_news_by_kw(event.message.text)
  374. line_bot_api.reply_message(
  375. event.reply_token,
  376. TextSendMessage(text=result))
  377. s_news=False
  378. return
  379. if seo:
  380. res='相關字:'
  381. s = suggests.suggests.get_suggests(event.message.text, source='google')
  382. idx=0
  383. for sg in s['suggests']:
  384. if idx>0:
  385. res+=','
  386. else:
  387. idx+=1
  388. res+=sg
  389. line_bot_api.reply_message(
  390. event.reply_token,
  391. TextSendMessage(text=res))
  392. seo=False
  393. # print('test')
  394. '''
  395. #if __name__ == "__main__":
  396. # app.run(host='0.0.0.0', port=443,ssl_context=('/etc/letsencrypt/live/ptt.cx/fullchain.pem', '/etc/letsencrypt/live/ptt.cx/privkey.pem'))
  397. # app.run(host='0.0.0.0', port=14404,ssl_context=('/tmp/cert.pem','/tmp/chain.pem' ))