newbot.py 14 KB

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