Advertisement
Alexofp

Untitled

Oct 7th, 2016
445
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 67.76 KB | None | 0 0
  1. import vk
  2. import sys
  3. import time
  4. import random
  5. import requests
  6. from html.parser import HTMLParser
  7. import json
  8. import requests
  9. import math
  10. #from srquest import QuestPlayer
  11.  
  12. #https://api.citilink.ru/v1/discussions/377803/
  13. #https://www.citilink.ru/search/fast/?text=gtx%20970
  14. #https://api.citilink.ru/v1/product/spb_cl:spmvnovg/971257/
  15. #https://api.citilink.ru/v1/products/spb_cl:spmvnovg/computers_and_notebooks/computers/?filters=&page=1&sorting=price_asc
  16. #http://stackoverflow.com/questions/18337407/saving-utf-8-texts-in-json-dumps-as-utf8-not-as-u-escape-sequence
  17.  
  18. #from casualstone import stoneProcessMessage
  19.  
  20. import re
  21.  
  22. from os import listdir
  23. from os.path import isfile, join
  24. from PIL import Image, ImageDraw, ImageFont
  25.  
  26. import feedparser
  27. import html2text
  28. import os
  29. import time
  30. import threading
  31.  
  32. myChatId = 9
  33.  
  34. myAppId = ""
  35. myUsername = ""
  36. myPassword = ""
  37. myToken = ""
  38.  
  39. def RepresentsInt(s):
  40. try:
  41. int(s)
  42. return True
  43. except ValueError:
  44. return False
  45.  
  46. def RepresentsFloat(s):
  47. try:
  48. float(s)
  49. return True
  50. except ValueError:
  51. return False
  52.  
  53. citilinkItems = {}
  54. shopMessages = []
  55.  
  56. def citilinkGetInfo(id):
  57. #if(not RepresentsInt(id) or int(id)<0):
  58. # return {}
  59. req = requests.get("https://api.citilink.ru/v1/product/spb_cl:spmvnovg/"+str(id)+"/")
  60. if(req.text.startswith('<!DOCTYPE html>')):
  61. return {}
  62. jsonData = req.json()
  63. if(jsonData["code"]!=0):
  64. return {}
  65. returnData = {}
  66. returnData["id"] = str(id)
  67. returnData["shortname"] = jsonData["data"]["card"]["shortName"]
  68. returnData["name"] = jsonData["data"]["card"]["name"]
  69. returnData["price"] = float(jsonData["data"]["card"]["priceColumnOne"])
  70. returnData["link"] = "http://www.citilink.ru/catalog/"+jsonData["data"]["card"]["categoryPath"]+"/"+str(id)
  71. returnData["isavailable"] = jsonData["data"]["card"]["isAvailable"]
  72. returnData["category"] = jsonData["data"]["card"]["categoryName"]
  73. return returnData
  74.  
  75. def loadShops():
  76. #citilink
  77. print("Loading shops")
  78. threads = []
  79. files = [f for f in listdir("shop/citilink/") if isfile(join("shop/citilink/", f)) and 1]
  80. for file in files:
  81. with open("shop/citilink/"+file, encoding='utf-8-sig') as data_file:
  82. data = json.load(data_file)
  83. if("id" in data):
  84. citilinkItems[data["id"]] = data
  85. #updateCitilinkInfo(data["id"])
  86. t = threading.Thread(target=updateCitilinkInfo,args=[data["id"]])
  87. t.start()
  88. threads.append(t)
  89. for t in threads:
  90. t.join()
  91.  
  92.  
  93. def saveShops():
  94. #citilink
  95. print("Saving")
  96. for citilinkProductId in citilinkItems:
  97. citilinkProduct = citilinkItems[citilinkProductId]
  98. with open("shop/citilink/"+citilinkProduct["id"]+".txt", 'w', encoding='utf-8-sig') as json_file:
  99. json.dump(citilinkProduct, json_file, ensure_ascii=False,indent=4,sort_keys=True, separators=(',', ': '))
  100.  
  101. priceLock = threading.Lock()
  102. def citilinkUpdatePrice(id):
  103. citilinkData = citilinkGetInfo(id)
  104. if(len(citilinkData)==0):
  105. return
  106.  
  107. with(priceLock):
  108. priceEntry = {}
  109. priceEntry["price"] = citilinkData["price"]
  110. priceEntry["date"] = time.time()
  111. priceEntry["nicedate"] = str(time.ctime())
  112. priceEntry["isavailable"] = citilinkData["isavailable"]
  113.  
  114. historyLen = len(citilinkItems[id]["priceHistory"])
  115. if(historyLen==0):
  116. citilinkItems[id]["priceHistory"].append(priceEntry)
  117. else:
  118. wasAvailable = True
  119. if("isavailable" in citilinkItems[id]["priceHistory"][historyLen-1]):
  120. wasAvailable = citilinkItems[id]["priceHistory"][historyLen-1]["isavailable"]
  121. if(citilinkItems[id]["priceHistory"][historyLen-1]["price"]!=priceEntry["price"]):
  122. citilinkItems[id]["priceHistory"].append(priceEntry)
  123. shopMessage = {}
  124. shopMessage["type"] = "priceChange"
  125. shopMessage["productid"] = id
  126. shopMessage["productname"] = citilinkItems[id]["shortname"]
  127. shopMessage["oldprice"] = citilinkItems[id]["priceHistory"][historyLen-1]["price"]
  128. shopMessage["newprice"] = priceEntry["price"]
  129. shopMessages.append(shopMessage)
  130. elif(wasAvailable!=priceEntry["isavailable"]):
  131. citilinkItems[id]["priceHistory"].append(priceEntry)
  132.  
  133. def updateShops():
  134. #citilink
  135. print("Updating shops")
  136. threads = []
  137. for citilinkProductId in citilinkItems:
  138. citilinkProduct = citilinkItems[citilinkProductId]
  139. t = threading.Thread(target=citilinkUpdatePrice,args=[citilinkProduct["id"]])
  140. t.start()
  141. threads.append(t)
  142. for t in threads:
  143. t.join()
  144. #threading.Thread(target=citilinkUpdatePrice,args=(citilinkProduct["id"])).start()#citilinkUpdatePrice(citilinkProduct["id"])
  145.  
  146. updateLock = threading.Lock()
  147. def updateCitilinkInfo(id):
  148. if(id not in citilinkItems):
  149. return
  150. citilinkData = citilinkGetInfo(id)
  151. if(len(citilinkData)==0):
  152. return
  153. with(updateLock):
  154. citilinkItems[id]["shortname"] = citilinkData["shortname"]
  155. citilinkItems[id]["name"] = citilinkData["name"]
  156. citilinkItems[id]["id"] = str(citilinkData["id"])
  157. citilinkItems[id]["link"] = citilinkData["link"]
  158. citilinkItems[id]["category"] = citilinkData["category"]
  159.  
  160. def addCitilinkId(id):
  161. id = str(id)
  162. if(id in citilinkItems):
  163. shopMessage = {}
  164. shopMessage["type"] = "hasItem"
  165. shopMessage["productid"] = id
  166. shopMessages.append(shopMessage)
  167. return
  168. citilinkData = citilinkGetInfo(id)
  169. if(len(citilinkData)==0):
  170. return
  171.  
  172. citilinkItems[id] = {}
  173. citilinkItems[id]["shortname"] = citilinkData["shortname"]
  174. citilinkItems[id]["name"] = citilinkData["name"]
  175. citilinkItems[id]["id"] = str(citilinkData["id"])
  176. citilinkItems[id]["link"] = citilinkData["link"]
  177. citilinkItems[id]["category"] = citilinkData["category"]
  178. citilinkItems[id]["priceHistory"] = []
  179. citilinkUpdatePrice(id)
  180.  
  181. shopMessage = {}
  182. shopMessage["type"] = "newItem"
  183. shopMessage["productid"] = id
  184. shopMessage["productname"] = citilinkItems[id]["shortname"]
  185. shopMessages.append(shopMessage)
  186.  
  187. def citilinkGetLastPrice(id):
  188. id = str(id)
  189. if(id not in citilinkItems):
  190. return 0
  191. if(len(citilinkItems[id]["priceHistory"])==0):
  192. return 0
  193. return citilinkItems[id]["priceHistory"][len(citilinkItems[id]["priceHistory"])-1]["price"]
  194.  
  195. def shopSortFunc(item):
  196. return item[1]
  197.  
  198. def superIn(value, listV, fullName):
  199. for li in listV:
  200. if(value is None):
  201. return False
  202. if((li.lower().strip() in value.lower().strip()) or (li.lower().strip() in fullName.lower().strip())):
  203. return True
  204. return False
  205.  
  206. def shopGenerateCategories():
  207. returnStringAr = []
  208. for citilinkProductId in citilinkItems:
  209. citilinkProduct = citilinkItems[citilinkProductId]
  210. if("category" in citilinkProduct and citilinkProduct["category"] is not None and citilinkProduct["category"] not in returnStringAr):
  211. returnStringAr.append(citilinkProduct["category"])
  212. return returnStringAr
  213.  
  214. def shopGenerateDiff(oldprice,newprice):
  215. oldprice = int(oldprice)
  216. newprice = int(newprice)
  217. if(newprice==oldprice):
  218. return ""
  219. returnStr = " ("
  220. if(newprice>=oldprice):
  221. returnStr+="+"
  222. returnStr+=str((newprice)-(oldprice))
  223. returnStr+="руб., "
  224. if(oldprice!=0):
  225. if(newprice>=oldprice):
  226. returnStr+="+"
  227. returnStr+="{0:.1f}".format((float(newprice-oldprice))*100/float(oldprice))
  228. returnStr+="%)"
  229. else:
  230. returnStr+="+100%)"
  231. return returnStr
  232.  
  233. def shopGenerateString(categoryFilter):
  234. anyCat = 0
  235. if(len(categoryFilter)==0):
  236. anyCat = 1
  237. returnStringArray = []
  238. for citilinkProductId in citilinkItems:
  239. citilinkProduct = citilinkItems[citilinkProductId]
  240. if(not anyCat and not superIn(citilinkProduct["category"],categoryFilter, citilinkProduct["name"])):
  241. continue
  242. returnString = ""
  243. returnString += citilinkProduct["id"]
  244. returnString += " "
  245. returnString += citilinkProduct["shortname"]
  246. if(len(citilinkProduct["priceHistory"])>0):
  247. returnString += " "
  248. returnString += str(int(citilinkProduct["priceHistory"][len(citilinkProduct["priceHistory"])-1]["price"]))
  249. returnString += "руб."
  250. if(len(citilinkProduct["priceHistory"])>1):
  251. returnString += shopGenerateDiff(citilinkProduct["priceHistory"][len(citilinkProduct["priceHistory"])-2]["price"],citilinkProduct["priceHistory"][len(citilinkProduct["priceHistory"])-1]["price"])
  252. isAvailable = True
  253. if("isavailable" in citilinkProduct["priceHistory"][len(citilinkProduct["priceHistory"])-1]):
  254. isAvailable = citilinkProduct["priceHistory"][len(citilinkProduct["priceHistory"])-1]["isavailable"]
  255. if(not isAvailable):
  256. returnString += " (Нет в наличии)"
  257. returnStringArray.append([returnString,citilinkProduct["priceHistory"][len(citilinkProduct["priceHistory"])-1]["price"]])
  258. #returnString+="\n"
  259. sortedStrA = sorted(returnStringArray,key=shopSortFunc)
  260. rs = []
  261. for rsa in sortedStrA:
  262. rs.append(rsa[0])
  263. return "\n--------------------\n".join(rs)
  264.  
  265. def shopGenerateHistory(id):
  266. id = str(id)
  267. returnString = ""
  268. if(id not in citilinkItems):
  269. return "Нету такого"
  270. citilinkProduct = citilinkItems[id]
  271. returnString += citilinkProduct["id"]
  272. returnString += " "
  273. returnString += citilinkProduct["name"]
  274. returnString += "\n"
  275. returnString += citilinkProduct["link"]
  276. returnString += "\nИстория:\n"
  277. oldPriceEntry = {}
  278. for priceEntry in citilinkProduct["priceHistory"]:
  279. returnString += str(datetime.datetime.fromtimestamp(priceEntry["date"]).strftime("%d.%m.%Y %H:%M:%S"))
  280. returnString += " - "
  281. returnString += str(int(priceEntry["price"]))
  282. returnString += "руб."
  283. if(len(oldPriceEntry)>0):
  284. returnString += shopGenerateDiff(oldPriceEntry["price"],priceEntry["price"])
  285. isAvailable = True
  286. if("isavailable" in priceEntry):
  287. isAvailable = priceEntry["isavailable"]
  288. if(not isAvailable):
  289. returnString += " (Нет в наличии)"
  290. returnString += "\n"
  291. oldPriceEntry = priceEntry
  292. return returnString
  293.  
  294. loadShops()
  295. updateShops()
  296. saveShops()
  297. print("Done ("+str(len(shopMessages))+" new messages)")
  298.  
  299. import plotly.plotly as py
  300. #import plotly.offline as py
  301. import plotly.graph_objs as go
  302. py.sign_in('Alexofp', 'v3bh877qw2')
  303.  
  304. def generateChart(id, customName="lastplot.png"):
  305. data = []
  306. id = str(id)
  307. if(id not in citilinkItems):
  308. return False
  309. if(len(citilinkItems[id]["priceHistory"])<=1):
  310. return False
  311. addDataX = []
  312. addDataY = []
  313. addDates = []
  314. zeroDVal = int(citilinkItems[id]["priceHistory"][0]["date"])
  315. for pe in citilinkItems[id]["priceHistory"]:
  316. addDataX.append(pe["date"]-zeroDVal)
  317. addDataY.append(int(pe["price"]))
  318. addDates.append(str(datetime.datetime.fromtimestamp(pe["date"]).strftime("%d.%m.%Y")))
  319.  
  320. trace = go.Scatter(
  321. x=addDataX,
  322. y=addDataY,
  323. name = "",
  324. line=dict(
  325. shape='hv'
  326. )
  327. )
  328. data.append(trace)
  329.  
  330. selDid = random.randint(1, len(addDataX)-1)
  331. if(selDid>=(len(addDataX)-1)):
  332. selDid = 1
  333.  
  334. layout = go.Layout(
  335. showlegend=False,
  336. annotations=[
  337. dict(
  338. x=addDataX[selDid],
  339. y=addDataY[selDid],
  340. xref='x',
  341. yref='y',
  342. text=citilinkItems[id]["shortname"],
  343. showarrow=True,
  344. arrowhead=7,
  345. ax=0,
  346. ay=-40
  347. )
  348. ],
  349. paper_bgcolor='rgb(255,255,255)',
  350. plot_bgcolor='rgb(229,229,229)',
  351. xaxis=dict(
  352. ticktext = addDates,
  353. tickvals = addDataX,
  354. showgrid=True,
  355. showline=False,
  356. showticklabels=True
  357. ),
  358. yaxis=dict(
  359. showgrid=True,
  360. showline=False,
  361. showticklabels=True
  362. ),
  363. )
  364.  
  365. '''trace1 = go.Scatter(
  366. x=[1, 2, 3, 4, 5,
  367. 6, 7, 8, 9, 10,
  368. 11, 12, 13, 14, 15],
  369. y=[10, 20, None, 15, 10,
  370. 5, 15, None, 20, 10,
  371. 10, 15, 25, 20, 10],
  372. name = '<b>No</b> Gaps', # Style name/legend entry with html tags
  373. connectgaps=True
  374. )
  375. trace2 = go.Scatter(
  376. x=[1, 2, 3, 4, 5,
  377. 6, 7, 8, 9, 10,
  378. 11, 12, 13, 14, 15],
  379. y=[5, 15, None, 10, 5,
  380. 0, 10, None, 15, 5,
  381. 5, 10, 20, 15, 5],
  382. name = 'Gaps',
  383. )'''
  384.  
  385. #data = [trace1, trace2]
  386.  
  387. fig = dict(data=data, layout=layout)
  388. py.image.save_as(fig, filename=customName)
  389. return True
  390. #py.offline.plot(fig, filename='simple-connectgaps')
  391.  
  392. #generateChart(353576)
  393. from openpyxl import Workbook
  394. from openpyxl.drawing.image import Image as oImage
  395. from openpyxl.styles import Font
  396.  
  397. def shopSortFunc2(item):
  398. return item[1]
  399.  
  400. def generateReport(filters):
  401. wb = Workbook()
  402. ws = wb.active
  403. ws['A1'] = 'Отчёт по ценам'
  404. startY = 3
  405. ws.column_dimensions['A'].width = 20
  406. ws.column_dimensions['C'].width = 20
  407. lastimageid = 0
  408.  
  409. nameFont = Font(size=14)
  410. categoryFont = Font(size=16, bold=True)
  411.  
  412. categoryMap = {}
  413.  
  414. for citilinkProductId in citilinkItems:
  415. citilinkProduct = citilinkItems[citilinkProductId]
  416.  
  417. category = citilinkProduct["category"]
  418. if(category is None):
  419. category = "Прочее"
  420. if(len(filters)>0 and not superIn(category,filters,"")):
  421. continue
  422. if(category not in categoryMap):
  423. categoryMap[category] = []
  424.  
  425. categoryMap[category].append([citilinkProductId,citilinkGetLastPrice(citilinkProductId)])
  426.  
  427. for category in categoryMap:
  428. ws['A'+str(startY)] = category
  429. ws['A'+str(startY)].font = categoryFont
  430. startY = startY+2
  431.  
  432. categoryMap[category].sort(key=shopSortFunc2)
  433. for shopItem in categoryMap[category]:
  434.  
  435. citilinkProductId = shopItem[0]
  436. citilinkProduct = citilinkItems[citilinkProductId]
  437. lastprice = shopItem[1]
  438.  
  439. ws['A'+str(startY)] = citilinkProduct["name"]
  440. ws['A'+str(startY)].font = nameFont
  441. startY = startY + 1
  442. ws['A'+str(startY)] = "Индекс:"
  443. ws['B'+str(startY)] = citilinkProductId
  444. startY = startY + 1
  445. ws['A'+str(startY)] = "Цена:"
  446. ws['B'+str(startY)] = int(lastprice)
  447. ws['B'+str(startY)].number_format = "0 руб"
  448. startY = startY + 1
  449. ws['A'+str(startY)] = "Ссылка:"
  450. ws['B'+str(startY)] = '=HYPERLINK("'+citilinkProduct["link"]+'","'+citilinkProduct["link"]+'")'
  451. startY = startY + 1
  452. startY = startY + 1
  453. ws['A'+str(startY)] = "История цен:"
  454. startY = startY + 1
  455. oldPriceEntry = {}
  456. for priceEntry in citilinkProduct["priceHistory"]:
  457. ws['A'+str(startY)] = str(datetime.datetime.fromtimestamp(priceEntry["date"]).strftime("%d.%m.%Y %H:%M:%S"))
  458. ws['B'+str(startY)] = int(priceEntry["price"])
  459. ws['B'+str(startY)].number_format = "0 руб"
  460. isAvailable = True
  461. if("isavailable" in priceEntry):
  462. isAvailable = priceEntry["isavailable"]
  463. if(not isAvailable):
  464. ws['D'+str(startY)] = " (Нет в наличии)"
  465. if(len(oldPriceEntry)>0):
  466. ws['C'+str(startY)] = shopGenerateDiff(oldPriceEntry["price"],priceEntry["price"])
  467. startY = startY + 1
  468. oldPriceEntry = priceEntry
  469. if(generateChart(citilinkProductId, "plotimages/plot"+str(lastimageid)+".png")):
  470. img = oImage("plotimages/plot"+str(lastimageid)+".png")
  471. ws.add_image(img, 'A'+str(startY))
  472. #ws.row_dimensions[startY].height = img.drawing.height*0.75
  473. lastimageid = lastimageid + 1
  474. startY = startY + 1
  475. startY = startY + int(math.ceil(img.drawing.height*0.75/15))
  476.  
  477.  
  478. startY = startY + 2
  479.  
  480.  
  481. startY = startY+1
  482.  
  483. #img = oImage('sukasuka.png')
  484.  
  485. #ws.add_image(img, 'A2')
  486. #ws.row_dimensions[2].height = img.drawing.height*0.75
  487. #print(img.drawing.height)
  488. wb.save('report.xlsx')
  489.  
  490. #generateReport(["Видеокарт"])
  491. #print("woof")
  492.  
  493.  
  494.  
  495.  
  496.  
  497.  
  498.  
  499.  
  500.  
  501. #def generateQuestNames():
  502. # pass
  503. '''questMode = False
  504. lastQuest = 0
  505. def questStart():
  506. files = [f for f in listdir("quests/") if isfile(join("quests/", f)) and 1]
  507. if(len(files)==0):
  508. return
  509.  
  510. global questMode
  511. questMode = True
  512. randQuest = random.choice(files)
  513. randQuestF = "quests/"+randQuest
  514. global lastQuest
  515. lastQuest = QuestPlayer(randQuestF)
  516. #for file in files:
  517.  
  518. #with open("shop/citilink/"+file, encoding='utf-8-sig') as data_file:
  519. # data = json.load(data_file)
  520.  
  521. def questStop():
  522. global questMode
  523. questMode = False
  524.  
  525. def questAnswer(id):
  526. if(questMode and RepresentsInt(id) and int(id)<len(lastQuest.getActionsNice())):
  527. lastQuest.doAction(int(id))
  528. return True
  529. return False
  530.  
  531. def questGenerateString():
  532. acts = lastQuest.getActionsNice()
  533. actsText = ""
  534. i = 0
  535. for a in acts:
  536. actsText = actsText + str(i)+") "+a+"\n"
  537. i = i + 1
  538. return lastQuest.getText()+"\n\n"+("\n".join(lastQuest.getVars()))+"\n"+actsText
  539. '''
  540.  
  541.  
  542.  
  543.  
  544.  
  545. def loadScores():
  546. file = open('scores.txt', 'r')
  547. return json.loads(file.read())
  548. def saveScores(sc):
  549. file = open('scores.txt', 'w')
  550. print(json.dumps(sc))
  551. file.write(json.dumps(sc))
  552. file.close()
  553.  
  554. scores = loadScores()
  555. def addWin(id):
  556. strid = str(id)
  557. if(strid not in scores):
  558. scores[strid] = [0,0]
  559.  
  560. scores[strid][0]+=1
  561. saveScores(scores)
  562.  
  563. def addLose(id):
  564. strid = str(id)
  565. if(strid not in scores):
  566. scores[strid] = [0,0]
  567.  
  568. scores[strid][1]+=1
  569. saveScores(scores)
  570.  
  571. def displayStats():
  572. usersToCheck = []
  573. for user_id in scores:
  574. usersToCheck.append(user_id)
  575. names = getNamesById(usersToCheck)
  576. i = 0
  577. stuff = []
  578. for user_id in scores:
  579. name = names[i]
  580. data = scores[user_id]
  581. if(data[1]<0.1):
  582. stuff.append([name + " | "+str(data[0]) + " | "+str(data[1]) + " | " + "0" ,data[0],data[1]])
  583. else:
  584. stuff.append([name + " | "+str(data[0]) + " | "+str(data[1]) + " | " + str(round(data[0]/data[1],2)) ,data[0],data[1]])
  585. #text = text + name + " "+str(data[0]) + " "+str(data[1])+"\n"
  586. i+=1
  587. stuff.sort(key=lambda x: (-x[1],x[2]))
  588. text = ""
  589. for t in stuff:
  590. text = text + t[0] + "\n"
  591. sendMessage(text)
  592.  
  593. global minionEffects
  594. global spellEffects
  595. minionEffects = [""]
  596. spellEffects = [""]
  597.  
  598. def getAllCards():
  599. headers = {
  600. 'X-Mashape-Key': '0GnNRrq481mshClxu4BKRULI2qZUp1IDue7jsnEgpGrHln1rss'
  601. }
  602.  
  603. req = requests.get("https://omgvamp-hearthstone-v1.p.mashape.com/cards?collectible=1&locale=ruRU",headers=headers)
  604. jsonData = req.json()
  605. #print((jsonData["Classic"][0]))#.decode('unicode_escape').encode('ascii','ignore')
  606. return sum(list(jsonData.values()),[])
  607.  
  608. soundsLocation = "Sounds (Sorted)/Minion Voices Sounds/"
  609. soundsLocation2 = "Minion Sounds/"
  610.  
  611. hsCards = getAllCards()
  612. for card in hsCards:
  613. if(card["type"]!="Minion" and card["type"]!="Spell"):
  614. continue
  615. #sounds = [f for f in listdir(soundsLocation) if isfile(join(soundsLocation, f)) and card["cardId"] in f]
  616. #os.makedirs(soundsLocation2+card["cardId"])
  617. #for sound in sounds:
  618. # shutil.copyfile(soundsLocation+sound,soundsLocation2+card["cardId"]+"/"+sound)
  619. #print(card["cardId"]+" "+str(sounds))
  620.  
  621. card["sounds"] = []
  622.  
  623. '''if(os.path.isdir(soundsLocation2+card["cardId"])):
  624. sounds = [f for f in listdir(soundsLocation2+card["cardId"]) if isfile(join(soundsLocation2+card["cardId"], f))]
  625. for sound in sounds:
  626. card["sounds"].append(soundsLocation2+card["cardId"]+"/"+sound)'''
  627.  
  628.  
  629. cardText = ""
  630. if("text" in card):
  631. cardText = html2text.html2text(card["text"]).strip(' \t\n\r')
  632. if(card["type"]=="Minion" and ("text" in card) and (cardText not in minionEffects)):
  633. minionEffects.append(cardText)
  634. if(card["type"]=="Spell" and ("text" in card) and (cardText not in spellEffects)):
  635. spellEffects.append(cardText)
  636.  
  637.  
  638. def getRandomHSCard():
  639. #print(random.choice(hsCards))
  640. result = random.choice(hsCards)
  641. while((result["type"]!="Minion" and result["type"]!="Spell") or ("img" not in result) or ("imgGold" not in result)):
  642. result = random.choice(hsCards)
  643. #print(result)
  644. return result
  645.  
  646. def generateChallenge():
  647. randCard = getRandomHSCard()
  648. if(randCard["type"]=="Minion"):
  649. choices = ["mana","attack","health","effects","flavor"]
  650.  
  651. if(randCard["rarity"]!="Legendary"):
  652. choices.append("rarity")
  653.  
  654. if(len(randCard["sounds"])>0):
  655. choices.append("sounds")
  656. choices.append("sounds")
  657.  
  658. choice = random.choice(choices)
  659. if(choice=="mana"):
  660. return ["mana","Сколько маны стоит данное существо?",randCard["cost"],randCard["cardId"],randCard["img"],"minion"]
  661. if(choice=="attack"):
  662. return ["attack","Какая атака у данного существа?",randCard["attack"],randCard["cardId"],randCard["img"],"minion"]
  663. if(choice=="health"):
  664. return ["health","Сколько здоровья у данного существа?",randCard["health"],randCard["cardId"],randCard["img"],"minion"]
  665. if(choice=="rarity"):
  666. ans = -1
  667. if(randCard["rarity"]=="Free"):
  668. ans = 0
  669. if(randCard["rarity"]=="Common"):
  670. ans = 1
  671. if(randCard["rarity"]=="Rare"):
  672. ans = 2
  673. if(randCard["rarity"]=="Epic"):
  674. ans = 3
  675. return ["rarity","Какова редкость данного существа (0 - Free, 1 - Common, 2 - Rare, 3 - Epic)?",ans,randCard["cardId"],randCard["img"],"minion"]
  676. if(choice=="effects"):
  677. ammount = 5
  678. curCardText = ""
  679. if("text" in randCard):
  680. curCardText = html2text.html2text(randCard["text"]).strip(' \t\n\r')
  681. curSellected = [curCardText]
  682. while(len(curSellected)!=ammount):
  683. randText = random.choice(minionEffects)
  684. if(randText not in curSellected):
  685. curSellected.append(randText)
  686.  
  687. random.shuffle(curSellected)
  688. text = "Какие эффекты имеет данное существо?\n"
  689. indx = 0
  690. answer = -1
  691. for effect in curSellected:
  692. text = text + str(indx)+": "+effect+"\n"
  693. if(effect==curCardText):
  694. answer=indx
  695. indx+=1
  696.  
  697. return ["effects",text,answer,randCard["cardId"],randCard["img"],"minion"]
  698. if(choice=="sounds"):
  699. ammount = 5
  700. curSellected = [randCard["name"]]
  701. while(len(curSellected)!=ammount):
  702. randCard2 = getRandomHSCard()
  703. if(randCard2["type"]!="Minion"):
  704. continue
  705. randText = randCard2["name"]
  706. if(randText not in curSellected):
  707. curSellected.append(randText)
  708. random.shuffle(curSellected)
  709. text = "Какое существо издаёт данный звук?\n"
  710. indx = 0
  711. answer = -1
  712. for cardName in curSellected:
  713. text = text + str(indx)+": "+cardName+"\n"
  714. if(cardName==randCard["name"]):
  715. answer=indx
  716. indx+=1
  717. return ["sounds",text,answer,randCard["cardId"],randCard["img"],"minion",random.choice(randCard["sounds"])]
  718. if(choice=="flavor"):
  719. ammount = 5
  720. curSellected = [randCard["name"]]
  721. while(len(curSellected)!=ammount):
  722. randCard2 = getRandomHSCard()
  723. randText = randCard2["name"]
  724. if(randText not in curSellected):
  725. curSellected.append(randText)
  726. random.shuffle(curSellected)
  727. text = "У какой карты данное описание: "+randCard["flavor"]+"\n"
  728. indx = 0
  729. answer = -1
  730. for cardName in curSellected:
  731. text = text + str(indx)+": "+cardName+"\n"
  732. if(cardName==randCard["name"]):
  733. answer=indx
  734. indx+=1
  735. return ["flavor",text,answer,randCard["cardId"],randCard["img"],"minion"]
  736. else:
  737. choices = ["mana","rarity","effects","flavor"]
  738. choice = random.choice(choices)
  739. if(choice=="mana"):
  740. return ["mana","Сколько маны стоит данное заклинание?",randCard["cost"],randCard["cardId"],randCard["img"],"spell"]
  741. if(choice=="rarity"):
  742. ans = -1
  743. if(randCard["rarity"]=="Free"):
  744. ans = 0
  745. if(randCard["rarity"]=="Common"):
  746. ans = 1
  747. if(randCard["rarity"]=="Rare"):
  748. ans = 2
  749. if(randCard["rarity"]=="Epic"):
  750. ans = 3
  751. return ["rarity","Какова редкость данного заклинания (0 - Free, 1 - Common, 2 - Rare, 3 - Epic)?",ans,randCard["cardId"],randCard["img"],"spell"]
  752. if(choice=="effects"):
  753. ammount = 5
  754. curCardText = ""
  755. if("text" in randCard):
  756. curCardText = html2text.html2text(randCard["text"]).strip(' \t\n\r')
  757. curSellected = [curCardText]
  758. while(len(curSellected)!=ammount):
  759. randText = random.choice(spellEffects)
  760. if(randText not in curSellected):
  761. curSellected.append(randText)
  762.  
  763. random.shuffle(curSellected)
  764. text = "Что делает данное заклинание?\n"
  765. indx = 0
  766. answer = -1
  767. for effect in curSellected:
  768. text = text + str(indx)+": "+effect+"\n"
  769. if(effect==curCardText):
  770. answer=indx
  771. indx+=1
  772.  
  773. return ["effects",text,answer,randCard["cardId"],randCard["img"],"spell"]
  774. if(choice=="flavor"):
  775. ammount = 5
  776. curSellected = [randCard["name"]]
  777. while(len(curSellected)!=ammount):
  778. randCard2 = getRandomHSCard()
  779. randText = randCard2["name"]
  780. if(randText not in curSellected):
  781. curSellected.append(randText)
  782. random.shuffle(curSellected)
  783. text = "У какой карты данное описание: "+randCard["flavor"]+"\n"
  784. indx = 0
  785. answer = -1
  786. for cardName in curSellected:
  787. text = text + str(indx)+": "+cardName+"\n"
  788. if(cardName==randCard["name"]):
  789. answer=indx
  790. indx+=1
  791. return ["flavor",text,answer,randCard["cardId"],randCard["img"],"spell"]
  792.  
  793.  
  794. def generateChallengePic(data):
  795. if(data[5]=="minion"):
  796. response = requests.get(data[4])
  797. if response.status_code == 200:
  798. f = open("challenge1.png", 'wb')
  799. f.write(response.content)
  800. f.close()
  801.  
  802. im1 = Image.open("challenge1.png")
  803. im2 = Image.open("minion hider.png")
  804. im3 = Image.open("minion desc hide.png")
  805. if(data[0]=="effects"):
  806. im1.paste(im3,(0,0),im3)
  807. im1.paste(im2,(0,0),im2)
  808. im1.save("challenge2.png", "PNG")
  809. return True
  810. return False
  811. else:
  812. response = requests.get(data[4])
  813. if response.status_code == 200:
  814. f = open("challenge1.png", 'wb')
  815. f.write(response.content)
  816. f.close()
  817.  
  818. im1 = Image.open("challenge1.png")
  819. im2 = Image.open("spell hider.png")
  820. im3 = Image.open("spell desc hide.png")
  821. if(data[0]=="effects"):
  822. im1.paste(im3,(0,0),im3)
  823. im1.paste(im2,(0,0),im2)
  824. im1.save("challenge2.png", "PNG")
  825. return True
  826. return False
  827.  
  828. global currentChallange
  829. global currentLives
  830. currentChallange = generateChallenge()
  831. #print(currentChallange)
  832. currentLives = 2
  833. generateChallengePic(currentChallange)
  834.  
  835. ridProgStr = """<tr>
  836. <td width="800" height="13" colspan="4" bgcolor="#F7F7F7">
  837. <ul>
  838. <ul>
  839. <ul>
  840. <p><span style="font-size:14pt;">(.*)</span></p>
  841. </ul>
  842. </ul>
  843. </ul>
  844. </td>
  845. </tr>"""
  846. ridProgStr = """<p><span style="font-size:14pt;">(.*)</span></p>"""
  847. riddleProg = re.compile(ridProgStr)
  848.  
  849. ridPro2gStr = """<p align="center"><b><font color="#1F497D">(.*)</font></b></p>"""
  850. riddleProg2 = re.compile(ridPro2gStr)
  851.  
  852. global globalRiddles
  853. globalRiddles = []
  854.  
  855. def loadRiddles():
  856. global globalRiddles
  857. with open('riddles.txt', 'r') as file_:
  858. riddleStr = file_.read()
  859. globalRiddles = json.loads(riddleStr)
  860. #print(stuff[1][0])
  861. loadRiddles()
  862.  
  863. def generateRiddle():
  864. #randomRiddleId = random.randint(1,4000)
  865. #req = requests.get("http://1zz.ru/"+str(randomRiddleId)+".html")
  866.  
  867. selectedRi = random.choice(globalRiddles)
  868. riddle = selectedRi[0]#riddleProg.findall(req.text)
  869. answer = selectedRi[1]#riddleProg2.findall(req.text)
  870.  
  871. #if(len(riddle)!=1 or len(answer)!=1):
  872. # return ["Не получилось",""]
  873. return [html2text.html2text(riddle).strip(),html2text.html2text(answer).strip()]
  874. global lastRiddle
  875. lastRiddle = generateRiddle()
  876.  
  877. def saveRiddles():
  878. riddles = []
  879.  
  880. for riddleId in range(1,4001):
  881. randomRiddleId = riddleId
  882. req = requests.get("http://1zz.ru/"+str(randomRiddleId)+".html")
  883.  
  884.  
  885. riddle = riddleProg.findall(req.text)
  886. answer = riddleProg2.findall(req.text)
  887.  
  888. if(len(riddle)!=1 or len(answer)!=1):
  889. pass
  890. else:
  891. riddles.append([html2text.html2text(riddle[0]).strip(),html2text.html2text(answer[0]).strip()])
  892. riddleStr = json.dumps(riddles)
  893. with open('riddles.txt', 'w') as file_:
  894. file_.write(riddleStr)
  895. print("done saving")
  896.  
  897. #saveRiddles()
  898.  
  899. def whatIsOnPicture(url):
  900. r = requests.post("https://www.imageidentify.com/objects/user-26a7681f-4b48-4f71-8f9f-93030898d70d/prd/urlapi",{"image":url})
  901. jr = r.json()
  902. #print(r.text)
  903. result = [jr["identify"]["title"],jr["identify"]["definition"]]
  904. if(jr["identify"]["definition"] is None):
  905. result = [jr["identify"]["title"],""]
  906. #print(result)
  907. return result
  908.  
  909. #whatIsOnPicture("http://fotodes.ru/upload/img1340056404.jpg")
  910.  
  911. def checkPonyNews():
  912. f = open('ponylastid.txt', 'r')
  913. lastId = f.read()
  914. f.close()
  915.  
  916. d = feedparser.parse('http://forum.legendsofequestria.com/index.php?action=.xml;type=rss2;sa=news;boards=2,3,53,54,56')
  917. #print(d["entries"][0])
  918.  
  919. textToSay=""
  920. isFirstPost=True
  921.  
  922.  
  923. for entry in reversed(d["entries"]):
  924. #print( str(time.mktime(entry["published_parsed"]))+">"+str(time.mktime(time.strptime(lastId))) )
  925. if( lastId=="" or time.mktime(entry["published_parsed"])>time.mktime(time.strptime(lastId))):
  926. lastId=time.asctime(entry["published_parsed"])
  927. #print(entry["title_detail"]["value"])
  928. #print(html2text.html2text(entry["summary_detail"]["value"]).replace("![]",""))
  929.  
  930. if(not isFirstPost):
  931. textToSay+="========================"+"\n"
  932. isFirstPost = False
  933. textToSay+=entry["title_detail"]["value"]+" "+entry["link"]+"\n"
  934. textToSay+=lastId+"\n"
  935. textToSay+=html2text.html2text(entry["summary_detail"]["value"]).replace("![]","")+"\n"
  936.  
  937. #print(textToSay)
  938.  
  939. if(textToSay!=""):
  940. sendMessage(textToSay)
  941.  
  942. f = open('ponylastid.txt', 'w')
  943. f.write(lastId)
  944. f.close()
  945.  
  946. def checkRss():
  947. #print("checkRss()")
  948. #checkPonyNews()
  949. updateShops()
  950. saveShops()
  951.  
  952. #https://www.google.ru/search?tbm=isch&q=doge
  953. #https://www.google.ru/search?q=doge&oe=utf-8&rls={moz:distributionID}:{moz:locale}:{moz:official}&client=firefox-a&um=1&ie=UTF-8&tbm=isch&source=og&hl=en&tab=wi&sa=N&start=0&ndsp=20&gws_rd=cr,ssl&ei=8CBoVoqYFoG8sQGly4K4Bw
  954.  
  955. #print(requests.get("http://rule34.paheal.net/post/list?search=mlp&q=/post/list").text)
  956. #print(requests.post("http://www.acapela-group.com/demo-tts/DemoHTML5Form_V2.php",data="Content-Type: application/x-www-form-urlencoded\nContent-Length: 381\n\nMyLanguages=sonid10&0=Leila&1=Laia&2=Eliska&3=Mette&4=Zoe&5=Jasmijn&6=Tyler&7=Deepa&8=Rhona&9=Rachel&MySelectedVoice=Sharon&11=Hanna&12=Sanna&13=Justine&14=Louise&15=Manon&16=Claudia&17=Dimitris&18=Fabiana&19=Sakura&20=Minji&21=Lulu&22=Bente&23=Monika&24=Marcia&25=Celia&26=Alyona&27=Biera&28=Ines&29=Rodrigo&30=Elin&31=Samuel&32=Kal&33=Mia&34=Ipek&MyTextForTTS=567&t=1&SendToVaaS=").text)
  957. #print(requests.post("vaas.acapela-group.com:80/Services/DemoWeb/textToMP3.php").text)
  958.  
  959. frontalImagesPaths = [f for f in listdir("dogefaces/") if isfile(join("dogefaces/", f)) and f.startswith("frontal") ]
  960. frontalImages = []
  961. for p in frontalImagesPaths:
  962. im = Image.open("dogefaces/"+p)
  963. frontalImages.append(im)
  964.  
  965. sideImagesPaths = [f for f in listdir("dogefaces/") if isfile(join("dogefaces/", f)) and f.startswith("side") ]
  966. sideImages = []
  967. for p in sideImagesPaths:
  968. im = Image.open("dogefaces/"+p)
  969. sideImages.append(im)
  970.  
  971. '''def dogify(url):
  972. headers = {
  973. 'X-Mashape-Key': '0GnNRrq481mshClxu4BKRULI2qZUp1IDue7jsnEgpGrHln1rss',
  974. "Accept": "application/json"
  975. }
  976.  
  977. req = requests.get("https://apicloud-facerect.p.mashape.com/process-url.json?url="+url,headers=headers)
  978. jsonData = req.json()
  979. print(req.text)
  980.  
  981. response = requests.get(url)
  982. if response.status_code == 200:
  983. f = open("dogify.png", 'wb')
  984. f.write(response.content)
  985. f.close()
  986.  
  987. im = Image.open("dogify.png")
  988.  
  989. for face in jsonData["faces"]:
  990. orientation = face["orientation"]
  991. w = face["width"]
  992. h = face["height"]
  993. if(orientation=="frontal" or orientation=="profile-right" or orientation=="profile-left"):
  994. im2 = 0
  995. sizeMult = 1.3
  996. addxmult = 0
  997. if(orientation=="frontal"):
  998. im2 = random.choice(frontalImages)
  999. if(orientation=="profile-right" or orientation=="profile-left"):
  1000. im2 = random.choice(sideImages)
  1001. sizeMult = 1.5
  1002. addxmult = 0.4
  1003. if(orientation=="profile-left"):
  1004. addxmult=-addxmult
  1005.  
  1006. dogeWidth = im2.width
  1007. dogeHeight = im2.height
  1008. mult = w/dogeWidth
  1009. if(orientation=="profile-right" or orientation=="profile-left"):
  1010. mult = h/dogeHeight
  1011. dogeIm = im2.resize((int(dogeWidth*mult*sizeMult),int(dogeHeight*mult*sizeMult)))
  1012. if(orientation=="profile-right"):
  1013. dogeIm = dogeIm.transpose(Image.FLIP_LEFT_RIGHT)
  1014.  
  1015. im.paste(dogeIm,(int(face["x"]-dogeWidth*mult*((sizeMult-1)/2+addxmult)),int(face["y"]-dogeHeight*mult*(sizeMult-1)/2)),dogeIm)
  1016.  
  1017. im.save("dogifed.png", "PNG")'''
  1018.  
  1019. translateWords = {}
  1020. translateWords["White"] = "Белый/ая"
  1021. translateWords["Black"] = "Чернокожий/ая"
  1022. translateWords["Asian"] = "Азиатский/ая"
  1023. translateWords["Female"] = "девушка"
  1024. translateWords["Male"] = "мужчина"
  1025. def translateIfCan(word):
  1026. if(word in translateWords):
  1027. return translateWords[word]
  1028. return word
  1029.  
  1030. def dogify(url):
  1031. headers = {
  1032. 'X-Mashape-Key': '0GnNRrq481mshClxu4BKRULI2qZUp1IDue7jsnEgpGrHln1rss',
  1033. "Accept": "application/json"
  1034. }
  1035.  
  1036. req = requests.get("https://faceplusplus-faceplusplus.p.mashape.com/detection/detect?attribute=glass%2Cpose%2Cgender%2Cage%2Crace%2Csmiling&url="+url,headers=headers)
  1037. jsonData = req.json()
  1038. print(req.text)
  1039. print("test")
  1040.  
  1041. response = requests.get(url)
  1042. if response.status_code == 200:
  1043. f = open("dogify.png", 'wb')
  1044. f.write(response.content)
  1045. f.close()
  1046.  
  1047. im = Image.open("dogify.png")
  1048. picW = jsonData["img_width"]
  1049. picH = jsonData["img_height"]
  1050.  
  1051. text = ""
  1052.  
  1053. jsonData["face"].sort(key=lambda x: x["position"]["center"]["x"])
  1054. for face in jsonData["face"]:
  1055. text+=translateIfCan(face["attribute"]["race"]["value"])+" "
  1056. text+=translateIfCan(face["attribute"]["gender"]["value"])+" "
  1057. text+="возраст "+str(face["attribute"]["age"]["value"])+"+-"+str(face["attribute"]["age"]["range"])+" "
  1058. if("glass" in face["attribute"]):
  1059. if(face["attribute"]["glass"]["value"]!="None"):
  1060. text+="с очками "
  1061. if("smiling" in face["attribute"]):
  1062. if(face["attribute"]["smiling"]["value"]>50):
  1063. text+="улыбается "
  1064.  
  1065. cx = face["position"]["center"]["x"]
  1066. cy = face["position"]["center"]["y"]
  1067. if(cx<33):
  1068. text+="слева "
  1069. if(cx>66):
  1070. text+="справа "
  1071. if(cx>=33 and cx<=66):
  1072. text+="по центру "
  1073. if(cy<25):
  1074. text+="сверху "
  1075. if(cy>75):
  1076. text+="снизу "
  1077.  
  1078. text+="\n"
  1079.  
  1080.  
  1081. #orientation = face["orientation"]
  1082. yaw = face["attribute"]["pose"]["yaw_angle"]["value"]
  1083. roll = face["attribute"]["pose"]["roll_angle"]["value"]
  1084. w = face["position"]["width"]*picW/100
  1085. h = face["position"]["height"]*picH/100
  1086. centerX = face["position"]["center"]["x"]*picW/100
  1087. centerY = face["position"]["center"]["y"]*picH/100-h*0.2
  1088.  
  1089. im2 = random.choice(frontalImages)
  1090. dogeWidth, dogeHeight = im2.size
  1091.  
  1092. mult = w/dogeWidth*1.6
  1093. newDogeWidth = int(dogeWidth*mult)
  1094. newDogeHeight = int(dogeHeight*mult)
  1095.  
  1096. dogeIm = im2.resize((newDogeWidth,newDogeHeight))
  1097.  
  1098. if(yaw>0):
  1099. dogeIm = dogeIm.transpose(Image.FLIP_LEFT_RIGHT)
  1100.  
  1101. dogeIm = dogeIm.rotate(-roll)
  1102.  
  1103. im.paste(dogeIm,(int(centerX-newDogeWidth/2),int(centerY-newDogeHeight/2)),dogeIm)
  1104.  
  1105. im.save("dogifed.png", "PNG")
  1106. return [len(jsonData["face"]),text]
  1107. return [0,""]
  1108. #dogify("http://apicloud.me/assets/facerect/image3.jpg")
  1109.  
  1110.  
  1111. VAAS_APPLICATION = "DEV"
  1112. VAAS_URL = "http://vaas.acapela-group.com/Services/Synthesizer"
  1113. VAAS_LOGIN = "~VAAS_KIOSK"
  1114. VAAS_PASSWORD = "8dbmslg8fpkl9fs"
  1115.  
  1116. def text_to_speech(text,voice="alyona"):
  1117. hash = {"prot_vers" : "2", "cl_env" : "APACHE_2.2.9_PHP_5.5", "cl_vers" : "1-00", "cl_login" : VAAS_LOGIN,
  1118. "cl_app" : VAAS_APPLICATION, "cl_pwd" : VAAS_PASSWORD, "req_voice" : voice+"22k",
  1119. "req_text" : text}#sharon
  1120.  
  1121. req = requests.post(VAAS_URL,data=hash)
  1122. print(req.text)
  1123.  
  1124. for s in req.text.split("&"):
  1125. if( s.split("=")[0] == "snd_url" ):
  1126. return s.split("=")[1]
  1127. return ""
  1128.  
  1129.  
  1130.  
  1131. imageFindProg = '"ou":"([^"%&]*)"'
  1132. proga = re.compile(imageFindProg)#'imgurl=([^"%&]*)')
  1133.  
  1134. def image_search_fast(name):
  1135. headers = {
  1136. 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0'#'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'#'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31'
  1137. }
  1138. gogl = requests.get("https://www.google.ru/search?tbm=isch&q="+name,headers=headers)
  1139. print("found")
  1140. links = proga.findall(gogl.text) #str(gogl.text.encode('ascii', 'ignore'))
  1141. print("parsed")
  1142. #print(str(links).encode('ascii', 'ignore'))
  1143. return links
  1144.  
  1145. #image_search_fast("Doge")
  1146. #print(image_search_fast("аниме девушка со странностями"))
  1147.  
  1148. def image_search(query, amount=1, st=1):
  1149. #returns 'amount' number of query results in a list.
  1150. results = []
  1151. #BASE_URL = 'https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=' + query + '&start=%d'
  1152.  
  1153. #BASE_URL = 'https://www.googleapis.com/customsearch/v1?key=AIzaSyApBnEqA7htHlZbRueKyXewnceYlV-rItA&&cref=AIzaSyAreDhTh3IqaGPqC44t08sQF_qbSGzzA7Q&cx=010855067127206535986%3Aqdh_vhglb4u&fileType=png&searchType=image&num=1&start='+str(st)+'&q='+query
  1154.  
  1155. BASE_URL = 'https://www.googleapis.com/customsearch/v1?key=AIzaSyApBnEqA7htHlZbRueKyXewnceYlV-rItA&&cx=004952762214067257436:6bahqpow8ms&fileType=png&searchType=image&num='+str(amount)+'&start='+str(st)+'&q='+query
  1156. r = requests.get(BASE_URL, timeout=6.0)
  1157. #print(r.text)
  1158. for image_info in json.loads(r.text)['items']:
  1159. url = image_info['link']
  1160. results.append([url,image_info["title"],image_info["image"]["contextLink"]])
  1161.  
  1162. return results
  1163.  
  1164.  
  1165. def embeddable_image(query, amount=1):
  1166. #returns 'amount' number of
  1167. results = []
  1168. for image in image_search(query,amount):
  1169. results.append('<img src = "{0}>'.format(image))
  1170.  
  1171. return results
  1172.  
  1173. class MLStripper(HTMLParser):
  1174. def __init__(self):
  1175. self.reset()
  1176. self.strict = False
  1177. self.convert_charrefs= True
  1178. self.fed = []
  1179. def handle_data(self, d):
  1180. self.fed.append(d)
  1181. def get_data(self):
  1182. return ''.join(self.fed)
  1183.  
  1184. def strip_tags(html):
  1185. s = MLStripper()
  1186. s.feed(html)
  1187. return s.get_data()
  1188. import json
  1189.  
  1190. emptyChar = "-"
  1191. shootedChar = "•"
  1192. ourMap = {}
  1193. enemyMap = {}
  1194. ourShips = []
  1195. enemyShips = []
  1196. for x in range(0,10):
  1197. ourMap[x] = {}
  1198. enemyMap[x] = {}
  1199. for y in range(0,10):
  1200. ourMap[x][y] = emptyChar
  1201. enemyMap[x][y] = emptyChar
  1202.  
  1203. def blockEmpty(map, x, y):
  1204. for xa in range(0,3):
  1205. for ya in range(0,3):
  1206. lx = x+xa-1
  1207. ly = y+ya-1
  1208. if(lx>=0 and ly>=0 and lx<10 and ly<10 and map[lx][ly]!=emptyChar):
  1209. return 0
  1210. return 1
  1211.  
  1212. def shootAround(map, x, y):
  1213. for xa in range(0,3):
  1214. for ya in range(0,3):
  1215. lx = x+xa-1
  1216. ly = y+ya-1
  1217. if(lx>=0 and ly>=0 and lx<10 and ly<10 and map[lx][ly]!="X"):
  1218. map[lx][ly] = shootedChar
  1219.  
  1220. def canPlace(map, x, y, size, orient):
  1221. for i in range(0,size):
  1222. if(orient==0):
  1223. if( x+i>9 or not blockEmpty(map,x+i,y) ):
  1224. return 0
  1225. if( orient==1):
  1226. if( x-i<0 or not blockEmpty(map,x-i,y) ):
  1227. return 0
  1228. if( orient==2):
  1229. if( y+i>9 or not blockEmpty(map,x,y+i) ):
  1230. return 0
  1231. if( orient==3):
  1232. if( y-i<0 or not blockEmpty(map,x,y-i) ):
  1233. return 0
  1234. return 1
  1235.  
  1236.  
  1237. def populateMap(map,Wships):
  1238. ships = [4,3,3,2,2,2,1,1,1,1]
  1239. while(len(ships)>0):
  1240. curship = ships.pop(0)
  1241. found = False
  1242. while not found:
  1243. randx = random.randint(0,9)
  1244. randy = random.randint(0,9)
  1245. randor = random.randint(0,3)
  1246. if(canPlace(map,randx,randy,curship,randor)):
  1247. found = True
  1248. Wships.append([curship,[]])
  1249. #print("LEN "+Wships)
  1250. for i in range(0,curship):
  1251. if( randor==0):
  1252. map[randx+i][randy] = "S"
  1253. Wships[len(Wships)-1][1].append([randx+i,randy])
  1254. if( randor==1):
  1255. map[randx-i][randy] = "S"
  1256. Wships[len(Wships)-1][1].append([randx-i,randy])
  1257. if( randor==2):
  1258. map[randx][randy+i] = "S"
  1259. Wships[len(Wships)-1][1].append([randx,randy+i])
  1260. if( randor==3):
  1261. map[randx][randy-i] = "S"
  1262. Wships[len(Wships)-1][1].append([randx,randy-i])
  1263.  
  1264. def canConvert(stra):
  1265. str = stra.upper()
  1266. words = ["А","Б","В","Г","Д","Е","Ж","З","И","К"]
  1267. numbers = ["0","1","2","3","4","5","6","7","8","9"]
  1268. if(len(str) != 2 and len(str) != 3):
  1269. return 0
  1270. if(not (str[0] in words) ):
  1271. return 0
  1272. if(not (str[1] in numbers)):
  1273. return 0
  1274. if(len(str)==3 and (not (str[2] in numbers))):
  1275. return 0
  1276. return 1
  1277.  
  1278. def convert(stra):
  1279. str = stra.upper()
  1280. words = ["А","Б","В","Г","Д","Е","Ж","З","И","К"]
  1281. numbers = ["1","2","3","4","5","6","7","8","9"]
  1282. n1 = words.index(str[0])
  1283. n2 = -1
  1284. if(len(str)==2):
  1285. n2 = numbers.index(str[1])
  1286. else:
  1287. n2 = 9
  1288. return [n2,n1]
  1289.  
  1290. def shipIndexByPos(ships,pos):
  1291. for i in range(0,len(ships)):
  1292. for p in ships[i][1]:
  1293. if(p[0]==pos[0] and p[1]==pos[1]):
  1294. return i
  1295. return -1
  1296.  
  1297. def tryAttack(strattack):
  1298. global isAiTurn
  1299. if(not isAiTurn and canConvert(strattack)):
  1300. apos = convert(strattack)
  1301. if(enemyMap[apos[0]][apos[1]]=="S"):
  1302.  
  1303. hasKilled = 0
  1304. shipId = shipIndexByPos(enemyShips,apos)
  1305. enemyShips[shipId][0]-=1
  1306. if(enemyShips[shipId][0])==0:
  1307. hasKilled = 1
  1308.  
  1309. for p in enemyShips[shipId][1]:
  1310. shootAround(enemyMap,p[0],p[1])
  1311.  
  1312. enemyMap[apos[0]][apos[1]] = "X"
  1313. printMapToFile()
  1314. postSeaBattle()
  1315. time.sleep(0.5)
  1316.  
  1317. if(hasKilled):
  1318. sendMessage("Ты убил")
  1319. else:
  1320. sendMessage("Ты попал")
  1321. else:
  1322. if(enemyMap[apos[0]][apos[1]]!="X"):
  1323. enemyMap[apos[0]][apos[1]] = shootedChar
  1324. sendMessage("Ты не попал")
  1325. isAiTurn = 1
  1326.  
  1327.  
  1328. isAiTurn = 0
  1329. def processAi():
  1330. global isAiTurn
  1331. if isAiTurn:
  1332. found = False
  1333. while not found:
  1334. xr = random.randint(0,9)
  1335. yr = random.randint(0,9)
  1336. if(ourMap[xr][yr]!="X" and ourMap[xr][yr]!=shootedChar):
  1337. found = True
  1338. if(ourMap[xr][yr]=="S"):
  1339. ourMap[xr][yr] = "X"
  1340.  
  1341. hasKilled = 0
  1342. shipId = shipIndexByPos(ourShips,[xr,yr])
  1343. ourShips[shipId][0]-=1
  1344. if(ourShips[shipId][0])==0:
  1345. hasKilled = 1
  1346.  
  1347. if hasKilled:
  1348. sendMessage("Бот убил")
  1349.  
  1350. for p in ourShips[shipId][1]:
  1351. shootAround(ourMap,p[0],p[1])
  1352. else:
  1353. sendMessage("Бот попал")
  1354. else:
  1355. isAiTurn = 0
  1356. ourMap[xr][yr] = shootedChar
  1357. printMapToFile()
  1358. postSeaBattle()
  1359. time.sleep(0.5)
  1360. sendMessage("Бот не попал")
  1361.  
  1362. def fogOfWar(ch):
  1363. if(ch=="S"):
  1364. return emptyChar
  1365. return ch
  1366.  
  1367.  
  1368. def printMapToFile():
  1369. im = Image.new("RGB", (500, 360), "white")
  1370.  
  1371. fnt = ImageFont.truetype('consola.ttf', 30)
  1372. d = ImageDraw.Draw(im)
  1373. d.text((0,10), " АБВГДЕЖЗИК АБВГДЕЖЗИК", font=fnt, fill=(0,0,0,255))
  1374. d.text((0,20), " __________ __________", font=fnt, fill=(0,0,0,255))
  1375. for x in range(0,10):
  1376. numstr = str(x+1)
  1377. if(len(numstr)==1):
  1378. numstr = " "+numstr
  1379. line = numstr + "|"
  1380. for y in range(0,10):
  1381. line = line + str(ourMap[x][y])
  1382. line = line + " " + numstr + "|"
  1383. for y in range(0,10):
  1384. line = line + fogOfWar( str(enemyMap[x][y]) )
  1385. #print(line)
  1386. d.text((0,50+30*x), line, font=fnt, fill=(0,0,0,255))
  1387.  
  1388. im.save("test.png", "PNG")
  1389.  
  1390. def printMap():
  1391. print(" АБВГДЕЖЗИК АБВГДЕЖЗИК")
  1392. print(" __________ __________")
  1393. for x in range(0,10):
  1394. numstr = str(x+1)
  1395. if(len(numstr)==1):
  1396. numstr = " "+numstr
  1397. line = numstr + "|"
  1398. for y in range(0,10):
  1399. line = line + str(ourMap[x][y])
  1400. line = line + " " + numstr + " |"
  1401. for y in range(0,10):
  1402. line = line + str(enemyMap[x][y])
  1403. print(line)
  1404.  
  1405. #printMap()
  1406. populateMap(ourMap,ourShips)
  1407. populateMap(enemyMap,enemyShips)
  1408. #printMap()
  1409. printMapToFile()
  1410.  
  1411.  
  1412. session = vk.AuthSession(app_id=myAppId,user_login=myUsername,user_password=myPassword)
  1413. session.access_token = myToken
  1414. vkapi = vk.API(session)
  1415.  
  1416.  
  1417.  
  1418. import datetime
  1419.  
  1420. def weather(town):
  1421. info = requests.get("http://api.openweathermap.org/data/2.5/weather?lang=ru&q="+town+"&appid=2de143494c0b295cca9337e1e96b00e0")
  1422. js = info.json()
  1423. if(js["cod"]==200):
  1424.  
  1425. response = requests.get("http://openweathermap.org/img/w/"+(js["weather"][0]["icon"])+".png")
  1426. if response.status_code == 200:
  1427. f = open("weather.png", 'wb')
  1428. f.write(response.content)
  1429. f.close()
  1430. sendText = ""
  1431. sendText = sendText + js["name"] + ", "+js["sys"]["country"] + "\n"
  1432. sendText = sendText + "Температура: " + str(round(10*(js["main"]["temp"]-273))/10) + "\n"
  1433. sendText = sendText + "Влажность: " + str(js["main"]["humidity"]) + "%\n"
  1434. sendText = sendText + "Восход: " + str(datetime.datetime.fromtimestamp(js["sys"]["sunrise"]).time()) + "\n"
  1435. sendText = sendText + "Закат: " + str(datetime.datetime.fromtimestamp(js["sys"]["sunset"]).time()) + "\n"
  1436. sendText = sendText + js["weather"][0]["main"] + ": " + js["weather"][0]["description"]
  1437. sendPictureText("weather.png",sendText)
  1438. else:
  1439. sendMessage("Город не найден")
  1440.  
  1441. quoteGroup = "wisdomofgreat"
  1442. quoteCountResp = vkapi.wall.get(domain=quoteGroup,count=1,filter="all")
  1443. quoteCount = quoteCountResp[0]
  1444.  
  1445. def postRandomQuote():
  1446. quoteNum = random.randint(1,quoteCount-1)
  1447. quoteCountResp = vkapi.wall.get(domain=quoteGroup,count=1,filter="all",offset=quoteNum)
  1448. quoteText = quoteCountResp[1]["text"] + "\n" + "лайки: " + str(quoteCountResp[1]["likes"]["count"])
  1449. quoteText = quoteText + " " + "репосты: " + str(quoteCountResp[1]["reposts"]["count"])
  1450. sendMessage(quoteText)
  1451.  
  1452. def findSong(name):
  1453. audio = vkapi.audio.search(q=name,count=3)
  1454. print(audio)
  1455.  
  1456. #findSong("дейс")
  1457.  
  1458. def findAndPost(name):
  1459. try:
  1460. randI = 0#random.randint(0,2)
  1461. #if(random.randint(0,100)<10):
  1462. # randI = random.randint(0,3)
  1463. #if(random.randint(0,100)<30):
  1464. # randI = random.randint(0,10)
  1465.  
  1466. #stuff = image_search(name,10,randI)
  1467. stuff = image_search_fast(name)
  1468.  
  1469. if(len(stuff)==0):
  1470. return
  1471.  
  1472. selIm = random.randint(0,int((len(stuff)-1)*0.2))
  1473. imageLink = '["'+stuff[selIm]+'"]'
  1474. imageLink = json.loads(imageLink)[0]
  1475. print(imageLink)
  1476. #response = requests.get(stuff[selIm][0])
  1477. response = requests.get(imageLink)
  1478. if response.status_code == 200:
  1479. f = open("doge.png", 'wb')
  1480. f.write(response.content)
  1481. f.close()
  1482.  
  1483. img = {'photo': ('doge.png', open(r'doge.png', 'rb'))}
  1484.  
  1485. saaa = requests.post(uploadServer, files=img)
  1486. js = saaa.json()
  1487. print(js["photo"])
  1488. asdz = vkapi.photos.saveMessagesPhoto(server=js["server"], photo=js["photo"],hash = js["hash"])
  1489. print(asdz[0]["id"])
  1490. vkapi.messages.send(chat_id=myChatId,attachment=asdz[0]["id"])
  1491. #vkapi.messages.send(chat_id=myChatId,attachment=asdz[0]["id"],message=stuff[selIm][1]+"\n"+stuff[selIm][2])
  1492. except:
  1493. print("Error while finding picture")
  1494.  
  1495. #from pydub import AudioSegment
  1496. #AudioSegment.converter = "ffmpeg/bin/ffmpeg.exe"
  1497.  
  1498. '''def text_to_speech_post(text,voice="alyona"):
  1499. try:
  1500. voice = text_to_speech(fixStuff2(text),voice)
  1501. if(voice==""):
  1502. print("Error while getting voice url")
  1503. return
  1504.  
  1505. response = requests.get(voice)
  1506. if response.status_code == 200:
  1507. f = open("voice.mp3", 'wb')
  1508. f.write(response.content)
  1509. f.close()
  1510.  
  1511. song = AudioSegment.from_file("voice.mp3", format="mp3")
  1512. second_of_silence = AudioSegment.silent(duration=2000)
  1513. song = song + second_of_silence
  1514. file_handle = song.export("voice2.mp3", format="mp3")
  1515. file_handle.close()
  1516.  
  1517.  
  1518. img = {'file': ('voice.mp3', open(r'voice2.mp3', 'rb'))}
  1519.  
  1520. saaa = requests.post(voiceUploadServer, files=img)
  1521. js = saaa.json()
  1522. print(saaa.json())
  1523. asdz = vkapi.audio.save(server=js["server"], audio=js["audio"],hash = js["hash"])
  1524. print(asdz)
  1525. vkapi.audio.moveToAlbum(album_id="67775716",audio_ids=str(asdz["aid"]))
  1526. print(("audio"+str(asdz["owner_id"])+"_"+str(asdz["aid"])))
  1527. vkapi.messages.send(chat_id=myChatId,attachment=("audio"+str(asdz["owner_id"])+"_"+str(asdz["aid"])))
  1528. except vk.exceptions.VkAPIError:
  1529. print("Too short")
  1530.  
  1531. #print(text_to_speech("do me trade?"))'''
  1532.  
  1533.  
  1534.  
  1535. def fixStuff(message):
  1536. return message.replace("&quot;","\"").replace("<br />","").replace("<p>","").replace("</p>","\n").replace("&nbsp;"," ").replace("&laquo;","«").replace("&raquo;","»")
  1537.  
  1538. def fixStuff2(message):
  1539. return message.replace("&quot;"," ").replace("<br />"," ").replace("<br/>"," ").replace("<br>"," ").replace("<br >"," ").replace("<p>"," ").replace("</p>"," ").replace("&nbsp;"," ").replace("&laquo;"," ").replace("&raquo;"," ")
  1540.  
  1541. def postSeaBattle():
  1542. img = {'photo': ('test.png', open(r'test.png', 'rb'))}
  1543.  
  1544. saaa = requests.post(uploadServer, files=img)
  1545. js = saaa.json()
  1546. asdz = vkapi.photos.saveMessagesPhoto(server=js["server"], photo=js["photo"],hash = js["hash"])
  1547. vkapi.messages.send(chat_id=myChatId,attachment=asdz[0]["id"])
  1548.  
  1549.  
  1550.  
  1551. global lastmessageid
  1552. lastmessageid = vkapi.messages.getHistory(chat_id=myChatId, count = 1)[1]['mid']
  1553.  
  1554. def sayChallenge():
  1555. global lastmessageid
  1556. if(currentChallange[0]=="flavor"):
  1557. lastmessageid = sendMessage(currentChallange[1])
  1558. return
  1559. '''if(currentChallange[0]=="sounds"):
  1560. song = AudioSegment.from_file(currentChallange[6], format="ogg")
  1561. second_of_silence = AudioSegment.silent(duration=2000)
  1562. song = song + second_of_silence
  1563. file_handle = song.export("voiceChallenge.mp3", format="mp3")
  1564. file_handle.close()
  1565.  
  1566. img = {'file': ('voiceChallenge.mp3', open(r'voiceChallenge.mp3', 'rb'))}
  1567.  
  1568. saaa = requests.post(voiceUploadServer, files=img)
  1569. js = saaa.json()
  1570. asdz = vkapi.audio.save(server=js["server"], audio=js["audio"],hash = js["hash"])
  1571. vkapi.audio.moveToAlbum(album_id="67775716",audio_ids=str(asdz["aid"]))
  1572. lastmessageid = vkapi.messages.send(chat_id=myChatId,message=currentChallange[1],attachment=("audio"+str(asdz["owner_id"])+"_"+str(asdz["aid"])))
  1573. else:'''
  1574. lastmessageid = sendPictureText("challenge2.png",currentChallange[1])
  1575.  
  1576. def checkAnswer(user_id,message):
  1577. global currentChallange
  1578. global currentLives
  1579. if(RepresentsInt(message)):
  1580. if(int(message)==currentChallange[2]):
  1581. sendMessage("Правильно!")
  1582. addWin(user_id)
  1583. currentLives = 2
  1584. currentChallange = generateChallenge()
  1585. generateChallengePic(currentChallange)
  1586. time.sleep(3)
  1587. sayChallenge()
  1588. else:
  1589. currentLives-=1
  1590. addLose(user_id)
  1591. if(currentLives<=0):
  1592. sendPictureText("challenge1.png","Вы проиграли, правильный ответ: "+str(currentChallange[2]))
  1593. currentLives = 2
  1594. currentChallange = generateChallenge()
  1595. generateChallengePic(currentChallange)
  1596. time.sleep(3)
  1597. sayChallenge()
  1598. else:
  1599. #currentLives-=1
  1600. sendMessage("Не правильно, осталось жизней: "+str(currentLives))
  1601.  
  1602. def encryptRiddle(str):
  1603. newstr = ""
  1604. shouldShow = 1
  1605. for c in str:
  1606. if(c.isalpha()):
  1607. if(shouldShow==1):
  1608. newstr = newstr + c
  1609. shouldShow = 0
  1610. else:
  1611. newstr = newstr + "*"
  1612. else:
  1613. newstr = newstr + c
  1614. shouldShow = 1
  1615. return newstr
  1616.  
  1617.  
  1618. def processMessage(message,photo,user_id):
  1619.  
  1620. normalmessage = message
  1621. message = message.lower()
  1622. if message == "шутка":
  1623. r = requests.get("http://www.umori.li/api/random?num=40")
  1624. js = r.json()
  1625. smallest = js[0]["elementPureHtml"]
  1626. smallestL = len(smallest) + random.randint(0,len(smallest))*0.4
  1627. for i in range(1,5):
  1628. c = js[random.randint(0,39)]["elementPureHtml"]
  1629. cl = len(c) + random.randint(0,len(c))*0.4
  1630.  
  1631. if(cl<smallestL):
  1632. smallestL = cl
  1633. smallest = c
  1634. sendMessage(fixStuff( smallest))
  1635. if message == "doge":
  1636. findAndPost("doge")
  1637. '''if message == "морской бой":
  1638. postSeaBattle()
  1639. tryAttack(message)'''
  1640. if(message == "список"):
  1641. sendMessage(shopGenerateString([]))
  1642. if(message == "категории"):
  1643. sendMessage("\n".join(shopGenerateCategories()))
  1644. #if(message == "квест"):
  1645. # questStart()
  1646. # sendMessage(questGenerateString())
  1647. #if(message == "стопквест"):
  1648. # questStop()
  1649. global lastRiddle
  1650. if(message == "hs quiz"):
  1651. sayChallenge()
  1652.  
  1653. #if(questMode):
  1654. # if(questAnswer(message)):
  1655. # sendMessage(questGenerateString())
  1656. #else:
  1657. checkAnswer(user_id,message)
  1658. if message == "совет":
  1659. postRandomQuote()
  1660. if message == "стата":
  1661. displayStats()
  1662. if message == "загадка":
  1663. sendMessage(lastRiddle[0])
  1664. if (message == "сдаюсь" or message == "хз"):
  1665. sendMessage("Ответ: "+lastRiddle[1])
  1666. time.sleep(1)
  1667. lastRiddle = generateRiddle()
  1668. sendMessage(lastRiddle[0])
  1669. if (message == "подсказка" or message == "хелп"):
  1670. sendMessage(encryptRiddle(lastRiddle[1]))
  1671. if message.strip() == lastRiddle[1].lower().strip():
  1672. sendMessage("Правильно!")
  1673. time.sleep(1)
  1674. lastRiddle = generateRiddle()
  1675. sendMessage(lastRiddle[0])
  1676. if(photo!=""):
  1677. #data = whatIsOnPicture(photo)
  1678. #if(data[1]==""):
  1679. # sendMessage("На картинке "+data[0])
  1680. #else:
  1681. # sendMessage("На картинке "+data[0]+" - "+data[1])
  1682.  
  1683. dogifyData = dogify(photo)
  1684. count = dogifyData[0]
  1685. if(count>0):
  1686. global lastmessageid
  1687. lastmessageid = sendPictureText("dogifed.png",dogifyData[1])
  1688. #if (photo!="" and (message == "dogify" or message == "dogefy" or message == "догефай")):
  1689. # dogify(photo)
  1690. # sendPicture("dogifed.png")
  1691.  
  1692. ar = message.split(" ")
  1693. normalAr = normalmessage.split(" ")
  1694. if(len(ar)>1):
  1695. if(ar[0]=="найди"):
  1696. ar.pop(0)
  1697. findAndPost(" ".join(ar))
  1698. return 0
  1699. if(ar[0]=="погода"):
  1700. ar.pop(0)
  1701. weather(" ".join(ar))
  1702. return 0
  1703. if(ar[0]=="скажи"):
  1704. ar.pop(0)
  1705. #text_to_speech_post(" ".join(ar))
  1706. return 0
  1707. if(ar[0]=="orc"):
  1708. ar.pop(0)
  1709. #text_to_speech_post(" ".join(ar),"willlittlecreature")
  1710. return 0
  1711. if(ar[0]=="добавь" or ar[0]=="добавить"):
  1712. normalAr.pop(0)
  1713. #addCitilinkId(" ".join(ar))
  1714. for e in normalAr:
  1715. addCitilinkId(e)
  1716. saveShops()
  1717. return 0
  1718. if(ar[0]=="история"):
  1719. normalAr.pop(0)
  1720.  
  1721. if(generateChart(" ".join(normalAr))):
  1722. lastmessageid = sendPictureText("lastplot.png",shopGenerateHistory(" ".join(normalAr)))
  1723. else:
  1724. sendMessage(shopGenerateHistory(" ".join(normalAr)))
  1725. return 0
  1726. if(ar[0]=="список"):
  1727. ar.pop(0)
  1728. sendMessage(shopGenerateString(ar))
  1729. return 0
  1730.  
  1731. #stoneProcessMessage(message)
  1732. #vkapi.messages.send(chat_id=myChatId,message="123",attachment=stuff[0])
  1733. #print(stuff[0])
  1734. return 0
  1735.  
  1736. def getNameById(id):
  1737. d = vkapi.users.get(user_ids=id)
  1738. return d[0]["first_name"]+" "+d[0]["last_name"]
  1739.  
  1740. def getNamesById(ids):
  1741. d = vkapi.users.get(user_ids=",".join(ids))
  1742. res = []
  1743. i = 0
  1744. for id in ids:
  1745. res.append(d[i]["first_name"]+" "+d[i]["last_name"])
  1746. i+=1
  1747. return res
  1748.  
  1749.  
  1750. '''def processMessage(message):
  1751. #print(message)
  1752. if(RepresentsInt(message)):
  1753. if(int(message)==lastans):
  1754. sendMessage("Правильно")
  1755. time.sleep(0.5)
  1756. generateExpr()
  1757. sendMessage(lastexpr+"?")
  1758. return 1
  1759. else:
  1760. sendMessage("Не правильно")
  1761. return 0'''
  1762.  
  1763. def sendPicture(path):
  1764. if 1:
  1765.  
  1766. img = {'photo': ('pic.png', open(path, 'rb'))}
  1767.  
  1768. saaa = requests.post(uploadServer, files=img)
  1769. js = saaa.json()
  1770. asdz = vkapi.photos.saveMessagesPhoto(server=js["server"], photo=js["photo"],hash = js["hash"])
  1771. return vkapi.messages.send(chat_id=myChatId,attachment=asdz[0]["id"])
  1772.  
  1773.  
  1774. def sendPictureText(path,text):
  1775. if 1:
  1776.  
  1777. img = {'photo': ('pic.png', open(path, 'rb'))}
  1778.  
  1779. saaa = requests.post(uploadServer, files=img)
  1780. js = saaa.json()
  1781. asdz = vkapi.photos.saveMessagesPhoto(server=js["server"], photo=js["photo"],hash = js["hash"])
  1782. return vkapi.messages.send(chat_id=myChatId,attachment=asdz[0]["id"],message=text)
  1783.  
  1784. def sendMessage(message):
  1785. if(len(message.strip())==0):
  1786. print("Empty message was sent")
  1787. return vkapi.messages.send(chat_id=myChatId,message=message)
  1788.  
  1789. lastexpr = ""
  1790. lastans = 0
  1791.  
  1792. def generateExpr():
  1793. global lastexpr
  1794. global lastans
  1795. lastexpr = ""
  1796. bracketchancestart = 20
  1797. bracketchance = 20
  1798. bracketsdepth = 0
  1799.  
  1800. if(random.randint(0,100)<bracketchancestart):
  1801. lastexpr = "("
  1802. bracketsdepth+=1
  1803. lastexpr+=str(random.randint(1,20))
  1804. count = random.randint(2,5)
  1805. for i in range(0,count):
  1806. op = random.randint(1,4)
  1807. randn = 0
  1808. if(bracketsdepth>0 and random.randint(0,100)<bracketchance):
  1809. lastexpr+=')'
  1810. bracketsdepth-=1
  1811.  
  1812. if(op==1):
  1813. randn = random.randint(1,20)
  1814. lastexpr+='+'
  1815. if(op==2):
  1816. randn = random.randint(1,20)
  1817. lastexpr+='-'
  1818. if(op==3):
  1819. randn = random.randint(2,3)
  1820. lastexpr+='*'
  1821. if(op==4):
  1822. randn = random.randint(2,2)
  1823. lastexpr+='/'
  1824.  
  1825. if(i!=(count-1) and random.randint(0,100)<bracketchance):
  1826. lastexpr+='('
  1827. bracketsdepth+=1
  1828. #lastans+=randn
  1829. lastexpr+=str(randn)
  1830. while(bracketsdepth>0):
  1831. bracketsdepth-=1
  1832. lastexpr+=')'
  1833. lastans = int(eval(lastexpr))
  1834.  
  1835. generateExpr()
  1836. #print(lastexpr)
  1837. #print(lastans)
  1838. #print(eval('10+10()'))
  1839.  
  1840. st = vkapi.photos.getMessagesUploadServer()
  1841. uploadServer = st["upload_url"]
  1842. st = vkapi.audio.getUploadServer()
  1843. voiceUploadServer = st["upload_url"]
  1844. #sendMessage(lastexpr+"?")
  1845.  
  1846. #text_to_speech_post("do me trade?")
  1847. #print(text_to_speech("trade?","willlittlecreature"))
  1848. checkRssTime = 60*30
  1849. curRssTime=60*2
  1850.  
  1851. import traceback
  1852.  
  1853. def test():
  1854. pass
  1855. print("init")
  1856. while(1):
  1857. curRssTime-=3
  1858. if(curRssTime<=0):
  1859. curRssTime = checkRssTime
  1860. checkRss()
  1861.  
  1862. try:
  1863. messages = vkapi.messages.getHistory(chat_id=myChatId)
  1864. for i in reversed(range(1,len(messages))):
  1865. message = messages[i]
  1866. mid = message['mid']
  1867. if(mid>lastmessageid):
  1868. lastmessageid = mid
  1869. photo = ""
  1870. if(("attachment" in message) and (message["attachment"]["type"]=="photo")):
  1871. photo = message["attachment"]["photo"]["src_big"]
  1872.  
  1873. if processMessage(message['body'],photo,message["uid"]): break
  1874.  
  1875. processAi()
  1876. rssMessageArray = []
  1877. for mes in shopMessages:
  1878. rssMessage = ""
  1879. if(mes["type"]=="newItem"):
  1880. rssMessage+="Товар "
  1881. rssMessage+=str(mes["productname"])
  1882. rssMessage+=" добавлен"
  1883. if(mes["type"]=="hasItem"):
  1884. rssMessage+="Товар "
  1885. rssMessage+=str(mes["productid"])
  1886. rssMessage+=" уже был добавлен"
  1887. if(mes["type"]=="priceChange"):
  1888. if(mes["newprice"]<mes["oldprice"]):
  1889. rssMessage+="У "
  1890. rssMessage+=str(mes["productid"])
  1891. rssMessage+=" "
  1892. rssMessage+=str(mes["productname"])
  1893. rssMessage+=" уменьшилась цена с "
  1894. rssMessage+=str(int(mes["oldprice"]))
  1895. rssMessage+="руб. до "
  1896. rssMessage+=str(int(mes["newprice"]))
  1897. rssMessage+="руб."
  1898. rssMessage+=shopGenerateDiff(mes["oldprice"],mes["newprice"])
  1899. elif(mes["newprice"]>mes["oldprice"]):
  1900. rssMessage+="У "
  1901. rssMessage+=str(mes["productid"])
  1902. rssMessage+=" "
  1903. rssMessage+=str(mes["productname"])
  1904. rssMessage+=" увеличилась цена с "
  1905. rssMessage+=str(int(mes["oldprice"]))
  1906. rssMessage+="руб. до "
  1907. rssMessage+=str(int(mes["newprice"]))
  1908. rssMessage+="руб."
  1909. rssMessage+=shopGenerateDiff(mes["oldprice"],mes["newprice"])
  1910. rssMessage+=", пидары"
  1911. if(rssMessage!=""):
  1912. rssMessageArray.append(rssMessage)
  1913. shopMessages = []
  1914. if(len(rssMessageArray)>0):
  1915. sendMessage("\n--------------------\n".join(rssMessageArray))
  1916.  
  1917. except requests.exceptions.ReadTimeout:
  1918. print("Time out")
  1919. except Exception as e:
  1920. print(traceback.format_exc())
  1921. print(str(e))
  1922. time.sleep(3)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement