seo_monitor.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-
  3. import pandas as pd
  4. from datetime import datetime
  5. import pymysql
  6. pymysql.install_as_MySQLdb()
  7. import dataset
  8. import requests
  9. import gspread
  10. from gspread_pandas import Spread, Client
  11. from oauth2client.service_account import ServiceAccountCredentials
  12. import smtplib
  13. from userdata import *
  14. from email.message import EmailMessage
  15. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/seo?charset=utf8mb4')
  16. data = pd.DataFrame()
  17. scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
  18. credentials = ServiceAccountCredentials.from_json_keyfile_name("choozmointernal-2e314f3d4e12.json", scope)
  19. gc = gspread.authorize(credentials)
  20. def notify_group(msg):
  21. gid='WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD'
  22. headers = {"Authorization": "Bearer " + gid,"Content-Type": "application/x-www-form-urlencoded"}
  23. r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params={"message": msg})
  24. def send_email(message):
  25. server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
  26. server.ehlo()
  27. server.login(gmail_username, gmail_password)
  28. emails = {"Jared": "jared@choozmo.com", "Morrison": "morrison@choozmo.com", "Ginia": "ginia@choozmo.com", "Doris": "doris@choozmo.com"}
  29. for name in emails:
  30. msg = EmailMessage()
  31. msg['Subject'] = 'SEO亮點字績效通知' + str(datetime.date.today())
  32. msg['From'] = "service@choozmo.com"
  33. msg['To'] = emails[name]
  34. msg.set_content(name + "您好,\n\n" + message)
  35. print ('Sending email to ' + msg['To'])
  36. server.send_message(msg)
  37. print ('Email sent to ' + msg['To'])
  38. fname = name+'.txt'
  39. with open(fname, 'w', encoding="UTF+8") as f:
  40. f.write(name + "您好,\n\n" + message)
  41. server.close()
  42. def download(client, date, newest=True):
  43. """關鍵字清單"""
  44. lst_kw = []
  45. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/seo?charset=utf8mb4')
  46. cursor_kw = db.query(f"SELECT term FROM seo.selected_kw where client='{client}'")
  47. for c in cursor_kw:
  48. for i in c.values():
  49. lst_kw.append(i)
  50. print(len(lst_kw))
  51. """抓取general_log關鍵字"""
  52. last_check_lst = []
  53. for i in lst_kw:
  54. if newest:
  55. cursor_last_check = db.query(f"select kw,ranking from seo.general_log where kw='{i}' order by dt desc limit 1")
  56. else:
  57. cursor_last_check = db.query(f"select kw,ranking from seo.general_log where kw='{i}' order by dt limit 1")
  58. group = []
  59. n = 0
  60. for c in cursor_last_check:
  61. for j in c.values():
  62. if 'site' in str(j):
  63. n+=1
  64. if n==1 and j==1:
  65. group.append(101)
  66. else:
  67. group.append(j)
  68. n = 0
  69. last_check_lst.append(group)
  70. # df2 = pd.DataFrame(not_match_kw_lst,columns=['關鍵字組','搜尋排名'])
  71. df3 = pd.DataFrame(last_check_lst, columns=['關鍵字組', '搜尋排名'])
  72. # df_all = pd.concat([df, df3])
  73. df3.to_csv(f"./排名CSV/{client}當日排名{date}.csv", index=False, encoding='utf_8_sig')
  74. db.close()
  75. def combine_df(client, date1, date2):
  76. df = pd.read_csv(f'./排名CSV/{client}當日排名{date1}.csv')
  77. df2 = pd.read_csv(f'./排名CSV/{client}當日排名{date2}.csv')
  78. df_result = pd.merge(df, df2, on='關鍵字組', how='outer').fillna(0)
  79. date1 = arrange_date(date1)
  80. date2 = arrange_date(date2)
  81. df_result.columns = ['kw', 'starting_rank', 'current_rank']
  82. p = df_result['starting_rank'].tolist()
  83. l = df_result['current_rank'].tolist()
  84. c = [u"\u2197 "+str(abs(int(i)-int(j))) if int(i)-int(j)>0 \
  85. else u"\u2198 "+str(abs(int(i)-int(j))) if int(i)-int(j)<0 \
  86. else u"\u2192 "+str(abs(int(i)-int(j))) for (i, j) in zip(p, l)]
  87. df_result['client'] = client
  88. df_result['change'] = c
  89. df_result['kw'] = df_result['kw'].str.split('site',0).str[0]
  90. df_result.to_csv(f"./排名CSV/combine/{client}排名變化.csv", index=False, encoding='utf_8_sig')
  91. return df_result, date1, date2
  92. def arrange_date(date):
  93. if date[0] == 0 :
  94. date = date[1]+'/'+date[2:]
  95. else:
  96. date = date[:2]+'/'+date[2:]
  97. return date
  98. def checkrank(data, targetcust, targetkw):
  99. '''
  100. msg = "以下是排名下降的關鍵字:\n"
  101. msg2 = "以下是目前排名於百名外的關鍵字:\n"
  102. '''
  103. msg = "以下是亮點字的績效:\n"
  104. flag1=0
  105. flag2=0
  106. for row in data.index:
  107. #print(row)
  108. delta = int(data['starting_rank'][row])-int(data['current_rank'][row])
  109. for t in targetkw:
  110. try:
  111. w = data['kw'][row]
  112. if ((t in w) and data['client'][row] in targetcust):
  113. msg += "[" + data['client'][row] + "] " + data['kw'][row] + ": " + str(int(data['starting_rank'][row])) + " -> " + str(int(data['current_rank'][row])) + " (" + str(int(delta)) + ")\n"
  114. except:
  115. pass
  116. '''
  117. if (delta < 0):
  118. msg += "[" + data['client'][row] + "] " + data['kw'][row] + ": " + str(int(data['starting_rank'][row])) + " -> " + str(int(data['current_rank'][row])) + " (" + str(int(delta)) + ")\n"
  119. flag1=1
  120. if (int(data['current_rank'][row]) == 101): #out of range...
  121. msg2 += "[" + data['client'][row] + "] " + data['kw'][row] + "\n"
  122. flag2=1
  123. '''
  124. print(msg)
  125. #print(msg2)
  126. return msg
  127. #return msg, msg2, flag1, flag2
  128. if __name__ == "__main__":
  129. date1 = '0707'
  130. date2 = '0717'
  131. lst = ['清原', '神助物流', '班尼斯', '有夠讚', '仁本', '火柴星人', '呷茶', 'ChoozMo']
  132. sheet = gc.open('SEO 亮點字')
  133. sheet_instance = sheet.get_worksheet(0)
  134. records_data = sheet_instance.get_all_records()
  135. #print(records_data[0])
  136. targetkw = []
  137. for rd in records_data:
  138. targetkw.append(rd["亮點字"])
  139. print(targetkw)
  140. for client in lst:
  141. date1 = '0707'
  142. date2 = '0718'
  143. download(client, date1, newest=False)
  144. download(client, date2, newest=True)
  145. res, d1, d2 = combine_df(client, date1, date2)
  146. data = data.append(res, ignore_index=True)
  147. data.to_csv(f"./排名CSV/combine/__排名變化.csv", index=False, encoding='utf_8_sig')
  148. spread = Spread("kw_ranking_tracker",creds=credentials)
  149. spread.df_to_sheet(data, index=False, sheet="main", start="A1", replace=False)
  150. time_stamp = datetime.now()
  151. time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S")
  152. spread.sheet.update('G1', '最後更新:' + time_stamp)
  153. #msg, msg2, flag1, flag2=checkrank(data, lst, targetkw)
  154. msg = checkrank(data, lst, targetkw)
  155. msg += "\n完整資料請至https://cmm.ai/seo1"
  156. #msg2 += "\n完整資料請至https://cmm.ai/seo1"
  157. msg01 = [msg[i:i+1000] for i in range(0, len(msg), 1000)]
  158. for m1 in msg01:
  159. notify_group(m1)
  160. print(m1)
  161. send_email(msg)
  162. '''
  163. if flag1 == 1:
  164. msg01 = [msg[i:i+1000] for i in range(0, len(msg), 1000)]
  165. for m1 in msg01:
  166. notify_group(m1)
  167. print(m1)
  168. if flag2 == 1:
  169. msg02 = [msg2[i:i+1000] for i in range(0, len(msg2), 1000)]
  170. for m2 in msg02:
  171. notify_group(m2)
  172. print(m2)
  173. '''