Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import vk
- import sys
- import time
- import random
- import requests
- from html.parser import HTMLParser
- import json
- import requests
- import math
- #from srquest import QuestPlayer
- #https://api.citilink.ru/v1/discussions/377803/
- #https://www.citilink.ru/search/fast/?text=gtx%20970
- #https://api.citilink.ru/v1/product/spb_cl:spmvnovg/971257/
- #https://api.citilink.ru/v1/products/spb_cl:spmvnovg/computers_and_notebooks/computers/?filters=&page=1&sorting=price_asc
- #http://stackoverflow.com/questions/18337407/saving-utf-8-texts-in-json-dumps-as-utf8-not-as-u-escape-sequence
- #from casualstone import stoneProcessMessage
- import re
- from os import listdir
- from os.path import isfile, join
- from PIL import Image, ImageDraw, ImageFont
- import feedparser
- import html2text
- import os
- import time
- import threading
- myChatId = 9
- myAppId = ""
- myUsername = ""
- myPassword = ""
- myToken = ""
- def RepresentsInt(s):
- try:
- int(s)
- return True
- except ValueError:
- return False
- def RepresentsFloat(s):
- try:
- float(s)
- return True
- except ValueError:
- return False
- citilinkItems = {}
- shopMessages = []
- def citilinkGetInfo(id):
- #if(not RepresentsInt(id) or int(id)<0):
- # return {}
- req = requests.get("https://api.citilink.ru/v1/product/spb_cl:spmvnovg/"+str(id)+"/")
- if(req.text.startswith('<!DOCTYPE html>')):
- return {}
- jsonData = req.json()
- if(jsonData["code"]!=0):
- return {}
- returnData = {}
- returnData["id"] = str(id)
- returnData["shortname"] = jsonData["data"]["card"]["shortName"]
- returnData["name"] = jsonData["data"]["card"]["name"]
- returnData["price"] = float(jsonData["data"]["card"]["priceColumnOne"])
- returnData["link"] = "http://www.citilink.ru/catalog/"+jsonData["data"]["card"]["categoryPath"]+"/"+str(id)
- returnData["isavailable"] = jsonData["data"]["card"]["isAvailable"]
- returnData["category"] = jsonData["data"]["card"]["categoryName"]
- return returnData
- def loadShops():
- #citilink
- print("Loading shops")
- threads = []
- files = [f for f in listdir("shop/citilink/") if isfile(join("shop/citilink/", f)) and 1]
- for file in files:
- with open("shop/citilink/"+file, encoding='utf-8-sig') as data_file:
- data = json.load(data_file)
- if("id" in data):
- citilinkItems[data["id"]] = data
- #updateCitilinkInfo(data["id"])
- t = threading.Thread(target=updateCitilinkInfo,args=[data["id"]])
- t.start()
- threads.append(t)
- for t in threads:
- t.join()
- def saveShops():
- #citilink
- print("Saving")
- for citilinkProductId in citilinkItems:
- citilinkProduct = citilinkItems[citilinkProductId]
- with open("shop/citilink/"+citilinkProduct["id"]+".txt", 'w', encoding='utf-8-sig') as json_file:
- json.dump(citilinkProduct, json_file, ensure_ascii=False,indent=4,sort_keys=True, separators=(',', ': '))
- priceLock = threading.Lock()
- def citilinkUpdatePrice(id):
- citilinkData = citilinkGetInfo(id)
- if(len(citilinkData)==0):
- return
- with(priceLock):
- priceEntry = {}
- priceEntry["price"] = citilinkData["price"]
- priceEntry["date"] = time.time()
- priceEntry["nicedate"] = str(time.ctime())
- priceEntry["isavailable"] = citilinkData["isavailable"]
- historyLen = len(citilinkItems[id]["priceHistory"])
- if(historyLen==0):
- citilinkItems[id]["priceHistory"].append(priceEntry)
- else:
- wasAvailable = True
- if("isavailable" in citilinkItems[id]["priceHistory"][historyLen-1]):
- wasAvailable = citilinkItems[id]["priceHistory"][historyLen-1]["isavailable"]
- if(citilinkItems[id]["priceHistory"][historyLen-1]["price"]!=priceEntry["price"]):
- citilinkItems[id]["priceHistory"].append(priceEntry)
- shopMessage = {}
- shopMessage["type"] = "priceChange"
- shopMessage["productid"] = id
- shopMessage["productname"] = citilinkItems[id]["shortname"]
- shopMessage["oldprice"] = citilinkItems[id]["priceHistory"][historyLen-1]["price"]
- shopMessage["newprice"] = priceEntry["price"]
- shopMessages.append(shopMessage)
- elif(wasAvailable!=priceEntry["isavailable"]):
- citilinkItems[id]["priceHistory"].append(priceEntry)
- def updateShops():
- #citilink
- print("Updating shops")
- threads = []
- for citilinkProductId in citilinkItems:
- citilinkProduct = citilinkItems[citilinkProductId]
- t = threading.Thread(target=citilinkUpdatePrice,args=[citilinkProduct["id"]])
- t.start()
- threads.append(t)
- for t in threads:
- t.join()
- #threading.Thread(target=citilinkUpdatePrice,args=(citilinkProduct["id"])).start()#citilinkUpdatePrice(citilinkProduct["id"])
- updateLock = threading.Lock()
- def updateCitilinkInfo(id):
- if(id not in citilinkItems):
- return
- citilinkData = citilinkGetInfo(id)
- if(len(citilinkData)==0):
- return
- with(updateLock):
- citilinkItems[id]["shortname"] = citilinkData["shortname"]
- citilinkItems[id]["name"] = citilinkData["name"]
- citilinkItems[id]["id"] = str(citilinkData["id"])
- citilinkItems[id]["link"] = citilinkData["link"]
- citilinkItems[id]["category"] = citilinkData["category"]
- def addCitilinkId(id):
- id = str(id)
- if(id in citilinkItems):
- shopMessage = {}
- shopMessage["type"] = "hasItem"
- shopMessage["productid"] = id
- shopMessages.append(shopMessage)
- return
- citilinkData = citilinkGetInfo(id)
- if(len(citilinkData)==0):
- return
- citilinkItems[id] = {}
- citilinkItems[id]["shortname"] = citilinkData["shortname"]
- citilinkItems[id]["name"] = citilinkData["name"]
- citilinkItems[id]["id"] = str(citilinkData["id"])
- citilinkItems[id]["link"] = citilinkData["link"]
- citilinkItems[id]["category"] = citilinkData["category"]
- citilinkItems[id]["priceHistory"] = []
- citilinkUpdatePrice(id)
- shopMessage = {}
- shopMessage["type"] = "newItem"
- shopMessage["productid"] = id
- shopMessage["productname"] = citilinkItems[id]["shortname"]
- shopMessages.append(shopMessage)
- def citilinkGetLastPrice(id):
- id = str(id)
- if(id not in citilinkItems):
- return 0
- if(len(citilinkItems[id]["priceHistory"])==0):
- return 0
- return citilinkItems[id]["priceHistory"][len(citilinkItems[id]["priceHistory"])-1]["price"]
- def shopSortFunc(item):
- return item[1]
- def superIn(value, listV, fullName):
- for li in listV:
- if(value is None):
- return False
- if((li.lower().strip() in value.lower().strip()) or (li.lower().strip() in fullName.lower().strip())):
- return True
- return False
- def shopGenerateCategories():
- returnStringAr = []
- for citilinkProductId in citilinkItems:
- citilinkProduct = citilinkItems[citilinkProductId]
- if("category" in citilinkProduct and citilinkProduct["category"] is not None and citilinkProduct["category"] not in returnStringAr):
- returnStringAr.append(citilinkProduct["category"])
- return returnStringAr
- def shopGenerateDiff(oldprice,newprice):
- oldprice = int(oldprice)
- newprice = int(newprice)
- if(newprice==oldprice):
- return ""
- returnStr = " ("
- if(newprice>=oldprice):
- returnStr+="+"
- returnStr+=str((newprice)-(oldprice))
- returnStr+="руб., "
- if(oldprice!=0):
- if(newprice>=oldprice):
- returnStr+="+"
- returnStr+="{0:.1f}".format((float(newprice-oldprice))*100/float(oldprice))
- returnStr+="%)"
- else:
- returnStr+="+100%)"
- return returnStr
- def shopGenerateString(categoryFilter):
- anyCat = 0
- if(len(categoryFilter)==0):
- anyCat = 1
- returnStringArray = []
- for citilinkProductId in citilinkItems:
- citilinkProduct = citilinkItems[citilinkProductId]
- if(not anyCat and not superIn(citilinkProduct["category"],categoryFilter, citilinkProduct["name"])):
- continue
- returnString = ""
- returnString += citilinkProduct["id"]
- returnString += " "
- returnString += citilinkProduct["shortname"]
- if(len(citilinkProduct["priceHistory"])>0):
- returnString += " "
- returnString += str(int(citilinkProduct["priceHistory"][len(citilinkProduct["priceHistory"])-1]["price"]))
- returnString += "руб."
- if(len(citilinkProduct["priceHistory"])>1):
- returnString += shopGenerateDiff(citilinkProduct["priceHistory"][len(citilinkProduct["priceHistory"])-2]["price"],citilinkProduct["priceHistory"][len(citilinkProduct["priceHistory"])-1]["price"])
- isAvailable = True
- if("isavailable" in citilinkProduct["priceHistory"][len(citilinkProduct["priceHistory"])-1]):
- isAvailable = citilinkProduct["priceHistory"][len(citilinkProduct["priceHistory"])-1]["isavailable"]
- if(not isAvailable):
- returnString += " (Нет в наличии)"
- returnStringArray.append([returnString,citilinkProduct["priceHistory"][len(citilinkProduct["priceHistory"])-1]["price"]])
- #returnString+="\n"
- sortedStrA = sorted(returnStringArray,key=shopSortFunc)
- rs = []
- for rsa in sortedStrA:
- rs.append(rsa[0])
- return "\n--------------------\n".join(rs)
- def shopGenerateHistory(id):
- id = str(id)
- returnString = ""
- if(id not in citilinkItems):
- return "Нету такого"
- citilinkProduct = citilinkItems[id]
- returnString += citilinkProduct["id"]
- returnString += " "
- returnString += citilinkProduct["name"]
- returnString += "\n"
- returnString += citilinkProduct["link"]
- returnString += "\nИстория:\n"
- oldPriceEntry = {}
- for priceEntry in citilinkProduct["priceHistory"]:
- returnString += str(datetime.datetime.fromtimestamp(priceEntry["date"]).strftime("%d.%m.%Y %H:%M:%S"))
- returnString += " - "
- returnString += str(int(priceEntry["price"]))
- returnString += "руб."
- if(len(oldPriceEntry)>0):
- returnString += shopGenerateDiff(oldPriceEntry["price"],priceEntry["price"])
- isAvailable = True
- if("isavailable" in priceEntry):
- isAvailable = priceEntry["isavailable"]
- if(not isAvailable):
- returnString += " (Нет в наличии)"
- returnString += "\n"
- oldPriceEntry = priceEntry
- return returnString
- loadShops()
- updateShops()
- saveShops()
- print("Done ("+str(len(shopMessages))+" new messages)")
- import plotly.plotly as py
- #import plotly.offline as py
- import plotly.graph_objs as go
- py.sign_in('Alexofp', 'v3bh877qw2')
- def generateChart(id, customName="lastplot.png"):
- data = []
- id = str(id)
- if(id not in citilinkItems):
- return False
- if(len(citilinkItems[id]["priceHistory"])<=1):
- return False
- addDataX = []
- addDataY = []
- addDates = []
- zeroDVal = int(citilinkItems[id]["priceHistory"][0]["date"])
- for pe in citilinkItems[id]["priceHistory"]:
- addDataX.append(pe["date"]-zeroDVal)
- addDataY.append(int(pe["price"]))
- addDates.append(str(datetime.datetime.fromtimestamp(pe["date"]).strftime("%d.%m.%Y")))
- trace = go.Scatter(
- x=addDataX,
- y=addDataY,
- name = "",
- line=dict(
- shape='hv'
- )
- )
- data.append(trace)
- selDid = random.randint(1, len(addDataX)-1)
- if(selDid>=(len(addDataX)-1)):
- selDid = 1
- layout = go.Layout(
- showlegend=False,
- annotations=[
- dict(
- x=addDataX[selDid],
- y=addDataY[selDid],
- xref='x',
- yref='y',
- text=citilinkItems[id]["shortname"],
- showarrow=True,
- arrowhead=7,
- ax=0,
- ay=-40
- )
- ],
- paper_bgcolor='rgb(255,255,255)',
- plot_bgcolor='rgb(229,229,229)',
- xaxis=dict(
- ticktext = addDates,
- tickvals = addDataX,
- showgrid=True,
- showline=False,
- showticklabels=True
- ),
- yaxis=dict(
- showgrid=True,
- showline=False,
- showticklabels=True
- ),
- )
- '''trace1 = go.Scatter(
- x=[1, 2, 3, 4, 5,
- 6, 7, 8, 9, 10,
- 11, 12, 13, 14, 15],
- y=[10, 20, None, 15, 10,
- 5, 15, None, 20, 10,
- 10, 15, 25, 20, 10],
- name = '<b>No</b> Gaps', # Style name/legend entry with html tags
- connectgaps=True
- )
- trace2 = go.Scatter(
- x=[1, 2, 3, 4, 5,
- 6, 7, 8, 9, 10,
- 11, 12, 13, 14, 15],
- y=[5, 15, None, 10, 5,
- 0, 10, None, 15, 5,
- 5, 10, 20, 15, 5],
- name = 'Gaps',
- )'''
- #data = [trace1, trace2]
- fig = dict(data=data, layout=layout)
- py.image.save_as(fig, filename=customName)
- return True
- #py.offline.plot(fig, filename='simple-connectgaps')
- #generateChart(353576)
- from openpyxl import Workbook
- from openpyxl.drawing.image import Image as oImage
- from openpyxl.styles import Font
- def shopSortFunc2(item):
- return item[1]
- def generateReport(filters):
- wb = Workbook()
- ws = wb.active
- ws['A1'] = 'Отчёт по ценам'
- startY = 3
- ws.column_dimensions['A'].width = 20
- ws.column_dimensions['C'].width = 20
- lastimageid = 0
- nameFont = Font(size=14)
- categoryFont = Font(size=16, bold=True)
- categoryMap = {}
- for citilinkProductId in citilinkItems:
- citilinkProduct = citilinkItems[citilinkProductId]
- category = citilinkProduct["category"]
- if(category is None):
- category = "Прочее"
- if(len(filters)>0 and not superIn(category,filters,"")):
- continue
- if(category not in categoryMap):
- categoryMap[category] = []
- categoryMap[category].append([citilinkProductId,citilinkGetLastPrice(citilinkProductId)])
- for category in categoryMap:
- ws['A'+str(startY)] = category
- ws['A'+str(startY)].font = categoryFont
- startY = startY+2
- categoryMap[category].sort(key=shopSortFunc2)
- for shopItem in categoryMap[category]:
- citilinkProductId = shopItem[0]
- citilinkProduct = citilinkItems[citilinkProductId]
- lastprice = shopItem[1]
- ws['A'+str(startY)] = citilinkProduct["name"]
- ws['A'+str(startY)].font = nameFont
- startY = startY + 1
- ws['A'+str(startY)] = "Индекс:"
- ws['B'+str(startY)] = citilinkProductId
- startY = startY + 1
- ws['A'+str(startY)] = "Цена:"
- ws['B'+str(startY)] = int(lastprice)
- ws['B'+str(startY)].number_format = "0 руб"
- startY = startY + 1
- ws['A'+str(startY)] = "Ссылка:"
- ws['B'+str(startY)] = '=HYPERLINK("'+citilinkProduct["link"]+'","'+citilinkProduct["link"]+'")'
- startY = startY + 1
- startY = startY + 1
- ws['A'+str(startY)] = "История цен:"
- startY = startY + 1
- oldPriceEntry = {}
- for priceEntry in citilinkProduct["priceHistory"]:
- ws['A'+str(startY)] = str(datetime.datetime.fromtimestamp(priceEntry["date"]).strftime("%d.%m.%Y %H:%M:%S"))
- ws['B'+str(startY)] = int(priceEntry["price"])
- ws['B'+str(startY)].number_format = "0 руб"
- isAvailable = True
- if("isavailable" in priceEntry):
- isAvailable = priceEntry["isavailable"]
- if(not isAvailable):
- ws['D'+str(startY)] = " (Нет в наличии)"
- if(len(oldPriceEntry)>0):
- ws['C'+str(startY)] = shopGenerateDiff(oldPriceEntry["price"],priceEntry["price"])
- startY = startY + 1
- oldPriceEntry = priceEntry
- if(generateChart(citilinkProductId, "plotimages/plot"+str(lastimageid)+".png")):
- img = oImage("plotimages/plot"+str(lastimageid)+".png")
- ws.add_image(img, 'A'+str(startY))
- #ws.row_dimensions[startY].height = img.drawing.height*0.75
- lastimageid = lastimageid + 1
- startY = startY + 1
- startY = startY + int(math.ceil(img.drawing.height*0.75/15))
- startY = startY + 2
- startY = startY+1
- #img = oImage('sukasuka.png')
- #ws.add_image(img, 'A2')
- #ws.row_dimensions[2].height = img.drawing.height*0.75
- #print(img.drawing.height)
- wb.save('report.xlsx')
- #generateReport(["Видеокарт"])
- #print("woof")
- #def generateQuestNames():
- # pass
- '''questMode = False
- lastQuest = 0
- def questStart():
- files = [f for f in listdir("quests/") if isfile(join("quests/", f)) and 1]
- if(len(files)==0):
- return
- global questMode
- questMode = True
- randQuest = random.choice(files)
- randQuestF = "quests/"+randQuest
- global lastQuest
- lastQuest = QuestPlayer(randQuestF)
- #for file in files:
- #with open("shop/citilink/"+file, encoding='utf-8-sig') as data_file:
- # data = json.load(data_file)
- def questStop():
- global questMode
- questMode = False
- def questAnswer(id):
- if(questMode and RepresentsInt(id) and int(id)<len(lastQuest.getActionsNice())):
- lastQuest.doAction(int(id))
- return True
- return False
- def questGenerateString():
- acts = lastQuest.getActionsNice()
- actsText = ""
- i = 0
- for a in acts:
- actsText = actsText + str(i)+") "+a+"\n"
- i = i + 1
- return lastQuest.getText()+"\n\n"+("\n".join(lastQuest.getVars()))+"\n"+actsText
- '''
- def loadScores():
- file = open('scores.txt', 'r')
- return json.loads(file.read())
- def saveScores(sc):
- file = open('scores.txt', 'w')
- print(json.dumps(sc))
- file.write(json.dumps(sc))
- file.close()
- scores = loadScores()
- def addWin(id):
- strid = str(id)
- if(strid not in scores):
- scores[strid] = [0,0]
- scores[strid][0]+=1
- saveScores(scores)
- def addLose(id):
- strid = str(id)
- if(strid not in scores):
- scores[strid] = [0,0]
- scores[strid][1]+=1
- saveScores(scores)
- def displayStats():
- usersToCheck = []
- for user_id in scores:
- usersToCheck.append(user_id)
- names = getNamesById(usersToCheck)
- i = 0
- stuff = []
- for user_id in scores:
- name = names[i]
- data = scores[user_id]
- if(data[1]<0.1):
- stuff.append([name + " | "+str(data[0]) + " | "+str(data[1]) + " | " + "0" ,data[0],data[1]])
- else:
- stuff.append([name + " | "+str(data[0]) + " | "+str(data[1]) + " | " + str(round(data[0]/data[1],2)) ,data[0],data[1]])
- #text = text + name + " "+str(data[0]) + " "+str(data[1])+"\n"
- i+=1
- stuff.sort(key=lambda x: (-x[1],x[2]))
- text = ""
- for t in stuff:
- text = text + t[0] + "\n"
- sendMessage(text)
- global minionEffects
- global spellEffects
- minionEffects = [""]
- spellEffects = [""]
- def getAllCards():
- headers = {
- 'X-Mashape-Key': '0GnNRrq481mshClxu4BKRULI2qZUp1IDue7jsnEgpGrHln1rss'
- }
- req = requests.get("https://omgvamp-hearthstone-v1.p.mashape.com/cards?collectible=1&locale=ruRU",headers=headers)
- jsonData = req.json()
- #print((jsonData["Classic"][0]))#.decode('unicode_escape').encode('ascii','ignore')
- return sum(list(jsonData.values()),[])
- soundsLocation = "Sounds (Sorted)/Minion Voices Sounds/"
- soundsLocation2 = "Minion Sounds/"
- hsCards = getAllCards()
- for card in hsCards:
- if(card["type"]!="Minion" and card["type"]!="Spell"):
- continue
- #sounds = [f for f in listdir(soundsLocation) if isfile(join(soundsLocation, f)) and card["cardId"] in f]
- #os.makedirs(soundsLocation2+card["cardId"])
- #for sound in sounds:
- # shutil.copyfile(soundsLocation+sound,soundsLocation2+card["cardId"]+"/"+sound)
- #print(card["cardId"]+" "+str(sounds))
- card["sounds"] = []
- '''if(os.path.isdir(soundsLocation2+card["cardId"])):
- sounds = [f for f in listdir(soundsLocation2+card["cardId"]) if isfile(join(soundsLocation2+card["cardId"], f))]
- for sound in sounds:
- card["sounds"].append(soundsLocation2+card["cardId"]+"/"+sound)'''
- cardText = ""
- if("text" in card):
- cardText = html2text.html2text(card["text"]).strip(' \t\n\r')
- if(card["type"]=="Minion" and ("text" in card) and (cardText not in minionEffects)):
- minionEffects.append(cardText)
- if(card["type"]=="Spell" and ("text" in card) and (cardText not in spellEffects)):
- spellEffects.append(cardText)
- def getRandomHSCard():
- #print(random.choice(hsCards))
- result = random.choice(hsCards)
- while((result["type"]!="Minion" and result["type"]!="Spell") or ("img" not in result) or ("imgGold" not in result)):
- result = random.choice(hsCards)
- #print(result)
- return result
- def generateChallenge():
- randCard = getRandomHSCard()
- if(randCard["type"]=="Minion"):
- choices = ["mana","attack","health","effects","flavor"]
- if(randCard["rarity"]!="Legendary"):
- choices.append("rarity")
- if(len(randCard["sounds"])>0):
- choices.append("sounds")
- choices.append("sounds")
- choice = random.choice(choices)
- if(choice=="mana"):
- return ["mana","Сколько маны стоит данное существо?",randCard["cost"],randCard["cardId"],randCard["img"],"minion"]
- if(choice=="attack"):
- return ["attack","Какая атака у данного существа?",randCard["attack"],randCard["cardId"],randCard["img"],"minion"]
- if(choice=="health"):
- return ["health","Сколько здоровья у данного существа?",randCard["health"],randCard["cardId"],randCard["img"],"minion"]
- if(choice=="rarity"):
- ans = -1
- if(randCard["rarity"]=="Free"):
- ans = 0
- if(randCard["rarity"]=="Common"):
- ans = 1
- if(randCard["rarity"]=="Rare"):
- ans = 2
- if(randCard["rarity"]=="Epic"):
- ans = 3
- return ["rarity","Какова редкость данного существа (0 - Free, 1 - Common, 2 - Rare, 3 - Epic)?",ans,randCard["cardId"],randCard["img"],"minion"]
- if(choice=="effects"):
- ammount = 5
- curCardText = ""
- if("text" in randCard):
- curCardText = html2text.html2text(randCard["text"]).strip(' \t\n\r')
- curSellected = [curCardText]
- while(len(curSellected)!=ammount):
- randText = random.choice(minionEffects)
- if(randText not in curSellected):
- curSellected.append(randText)
- random.shuffle(curSellected)
- text = "Какие эффекты имеет данное существо?\n"
- indx = 0
- answer = -1
- for effect in curSellected:
- text = text + str(indx)+": "+effect+"\n"
- if(effect==curCardText):
- answer=indx
- indx+=1
- return ["effects",text,answer,randCard["cardId"],randCard["img"],"minion"]
- if(choice=="sounds"):
- ammount = 5
- curSellected = [randCard["name"]]
- while(len(curSellected)!=ammount):
- randCard2 = getRandomHSCard()
- if(randCard2["type"]!="Minion"):
- continue
- randText = randCard2["name"]
- if(randText not in curSellected):
- curSellected.append(randText)
- random.shuffle(curSellected)
- text = "Какое существо издаёт данный звук?\n"
- indx = 0
- answer = -1
- for cardName in curSellected:
- text = text + str(indx)+": "+cardName+"\n"
- if(cardName==randCard["name"]):
- answer=indx
- indx+=1
- return ["sounds",text,answer,randCard["cardId"],randCard["img"],"minion",random.choice(randCard["sounds"])]
- if(choice=="flavor"):
- ammount = 5
- curSellected = [randCard["name"]]
- while(len(curSellected)!=ammount):
- randCard2 = getRandomHSCard()
- randText = randCard2["name"]
- if(randText not in curSellected):
- curSellected.append(randText)
- random.shuffle(curSellected)
- text = "У какой карты данное описание: "+randCard["flavor"]+"\n"
- indx = 0
- answer = -1
- for cardName in curSellected:
- text = text + str(indx)+": "+cardName+"\n"
- if(cardName==randCard["name"]):
- answer=indx
- indx+=1
- return ["flavor",text,answer,randCard["cardId"],randCard["img"],"minion"]
- else:
- choices = ["mana","rarity","effects","flavor"]
- choice = random.choice(choices)
- if(choice=="mana"):
- return ["mana","Сколько маны стоит данное заклинание?",randCard["cost"],randCard["cardId"],randCard["img"],"spell"]
- if(choice=="rarity"):
- ans = -1
- if(randCard["rarity"]=="Free"):
- ans = 0
- if(randCard["rarity"]=="Common"):
- ans = 1
- if(randCard["rarity"]=="Rare"):
- ans = 2
- if(randCard["rarity"]=="Epic"):
- ans = 3
- return ["rarity","Какова редкость данного заклинания (0 - Free, 1 - Common, 2 - Rare, 3 - Epic)?",ans,randCard["cardId"],randCard["img"],"spell"]
- if(choice=="effects"):
- ammount = 5
- curCardText = ""
- if("text" in randCard):
- curCardText = html2text.html2text(randCard["text"]).strip(' \t\n\r')
- curSellected = [curCardText]
- while(len(curSellected)!=ammount):
- randText = random.choice(spellEffects)
- if(randText not in curSellected):
- curSellected.append(randText)
- random.shuffle(curSellected)
- text = "Что делает данное заклинание?\n"
- indx = 0
- answer = -1
- for effect in curSellected:
- text = text + str(indx)+": "+effect+"\n"
- if(effect==curCardText):
- answer=indx
- indx+=1
- return ["effects",text,answer,randCard["cardId"],randCard["img"],"spell"]
- if(choice=="flavor"):
- ammount = 5
- curSellected = [randCard["name"]]
- while(len(curSellected)!=ammount):
- randCard2 = getRandomHSCard()
- randText = randCard2["name"]
- if(randText not in curSellected):
- curSellected.append(randText)
- random.shuffle(curSellected)
- text = "У какой карты данное описание: "+randCard["flavor"]+"\n"
- indx = 0
- answer = -1
- for cardName in curSellected:
- text = text + str(indx)+": "+cardName+"\n"
- if(cardName==randCard["name"]):
- answer=indx
- indx+=1
- return ["flavor",text,answer,randCard["cardId"],randCard["img"],"spell"]
- def generateChallengePic(data):
- if(data[5]=="minion"):
- response = requests.get(data[4])
- if response.status_code == 200:
- f = open("challenge1.png", 'wb')
- f.write(response.content)
- f.close()
- im1 = Image.open("challenge1.png")
- im2 = Image.open("minion hider.png")
- im3 = Image.open("minion desc hide.png")
- if(data[0]=="effects"):
- im1.paste(im3,(0,0),im3)
- im1.paste(im2,(0,0),im2)
- im1.save("challenge2.png", "PNG")
- return True
- return False
- else:
- response = requests.get(data[4])
- if response.status_code == 200:
- f = open("challenge1.png", 'wb')
- f.write(response.content)
- f.close()
- im1 = Image.open("challenge1.png")
- im2 = Image.open("spell hider.png")
- im3 = Image.open("spell desc hide.png")
- if(data[0]=="effects"):
- im1.paste(im3,(0,0),im3)
- im1.paste(im2,(0,0),im2)
- im1.save("challenge2.png", "PNG")
- return True
- return False
- global currentChallange
- global currentLives
- currentChallange = generateChallenge()
- #print(currentChallange)
- currentLives = 2
- generateChallengePic(currentChallange)
- ridProgStr = """<tr>
- <td width="800" height="13" colspan="4" bgcolor="#F7F7F7">
- <ul>
- <ul>
- <ul>
- <p><span style="font-size:14pt;">(.*)</span></p>
- </ul>
- </ul>
- </ul>
- </td>
- </tr>"""
- ridProgStr = """<p><span style="font-size:14pt;">(.*)</span></p>"""
- riddleProg = re.compile(ridProgStr)
- ridPro2gStr = """<p align="center"><b><font color="#1F497D">(.*)</font></b></p>"""
- riddleProg2 = re.compile(ridPro2gStr)
- global globalRiddles
- globalRiddles = []
- def loadRiddles():
- global globalRiddles
- with open('riddles.txt', 'r') as file_:
- riddleStr = file_.read()
- globalRiddles = json.loads(riddleStr)
- #print(stuff[1][0])
- loadRiddles()
- def generateRiddle():
- #randomRiddleId = random.randint(1,4000)
- #req = requests.get("http://1zz.ru/"+str(randomRiddleId)+".html")
- selectedRi = random.choice(globalRiddles)
- riddle = selectedRi[0]#riddleProg.findall(req.text)
- answer = selectedRi[1]#riddleProg2.findall(req.text)
- #if(len(riddle)!=1 or len(answer)!=1):
- # return ["Не получилось",""]
- return [html2text.html2text(riddle).strip(),html2text.html2text(answer).strip()]
- global lastRiddle
- lastRiddle = generateRiddle()
- def saveRiddles():
- riddles = []
- for riddleId in range(1,4001):
- randomRiddleId = riddleId
- req = requests.get("http://1zz.ru/"+str(randomRiddleId)+".html")
- riddle = riddleProg.findall(req.text)
- answer = riddleProg2.findall(req.text)
- if(len(riddle)!=1 or len(answer)!=1):
- pass
- else:
- riddles.append([html2text.html2text(riddle[0]).strip(),html2text.html2text(answer[0]).strip()])
- riddleStr = json.dumps(riddles)
- with open('riddles.txt', 'w') as file_:
- file_.write(riddleStr)
- print("done saving")
- #saveRiddles()
- def whatIsOnPicture(url):
- r = requests.post("https://www.imageidentify.com/objects/user-26a7681f-4b48-4f71-8f9f-93030898d70d/prd/urlapi",{"image":url})
- jr = r.json()
- #print(r.text)
- result = [jr["identify"]["title"],jr["identify"]["definition"]]
- if(jr["identify"]["definition"] is None):
- result = [jr["identify"]["title"],""]
- #print(result)
- return result
- #whatIsOnPicture("http://fotodes.ru/upload/img1340056404.jpg")
- def checkPonyNews():
- f = open('ponylastid.txt', 'r')
- lastId = f.read()
- f.close()
- d = feedparser.parse('http://forum.legendsofequestria.com/index.php?action=.xml;type=rss2;sa=news;boards=2,3,53,54,56')
- #print(d["entries"][0])
- textToSay=""
- isFirstPost=True
- for entry in reversed(d["entries"]):
- #print( str(time.mktime(entry["published_parsed"]))+">"+str(time.mktime(time.strptime(lastId))) )
- if( lastId=="" or time.mktime(entry["published_parsed"])>time.mktime(time.strptime(lastId))):
- lastId=time.asctime(entry["published_parsed"])
- #print(entry["title_detail"]["value"])
- #print(html2text.html2text(entry["summary_detail"]["value"]).replace("![]",""))
- if(not isFirstPost):
- textToSay+="========================"+"\n"
- isFirstPost = False
- textToSay+=entry["title_detail"]["value"]+" "+entry["link"]+"\n"
- textToSay+=lastId+"\n"
- textToSay+=html2text.html2text(entry["summary_detail"]["value"]).replace("![]","")+"\n"
- #print(textToSay)
- if(textToSay!=""):
- sendMessage(textToSay)
- f = open('ponylastid.txt', 'w')
- f.write(lastId)
- f.close()
- def checkRss():
- #print("checkRss()")
- #checkPonyNews()
- updateShops()
- saveShops()
- #https://www.google.ru/search?tbm=isch&q=doge
- #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
- #print(requests.get("http://rule34.paheal.net/post/list?search=mlp&q=/post/list").text)
- #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)
- #print(requests.post("vaas.acapela-group.com:80/Services/DemoWeb/textToMP3.php").text)
- frontalImagesPaths = [f for f in listdir("dogefaces/") if isfile(join("dogefaces/", f)) and f.startswith("frontal") ]
- frontalImages = []
- for p in frontalImagesPaths:
- im = Image.open("dogefaces/"+p)
- frontalImages.append(im)
- sideImagesPaths = [f for f in listdir("dogefaces/") if isfile(join("dogefaces/", f)) and f.startswith("side") ]
- sideImages = []
- for p in sideImagesPaths:
- im = Image.open("dogefaces/"+p)
- sideImages.append(im)
- '''def dogify(url):
- headers = {
- 'X-Mashape-Key': '0GnNRrq481mshClxu4BKRULI2qZUp1IDue7jsnEgpGrHln1rss',
- "Accept": "application/json"
- }
- req = requests.get("https://apicloud-facerect.p.mashape.com/process-url.json?url="+url,headers=headers)
- jsonData = req.json()
- print(req.text)
- response = requests.get(url)
- if response.status_code == 200:
- f = open("dogify.png", 'wb')
- f.write(response.content)
- f.close()
- im = Image.open("dogify.png")
- for face in jsonData["faces"]:
- orientation = face["orientation"]
- w = face["width"]
- h = face["height"]
- if(orientation=="frontal" or orientation=="profile-right" or orientation=="profile-left"):
- im2 = 0
- sizeMult = 1.3
- addxmult = 0
- if(orientation=="frontal"):
- im2 = random.choice(frontalImages)
- if(orientation=="profile-right" or orientation=="profile-left"):
- im2 = random.choice(sideImages)
- sizeMult = 1.5
- addxmult = 0.4
- if(orientation=="profile-left"):
- addxmult=-addxmult
- dogeWidth = im2.width
- dogeHeight = im2.height
- mult = w/dogeWidth
- if(orientation=="profile-right" or orientation=="profile-left"):
- mult = h/dogeHeight
- dogeIm = im2.resize((int(dogeWidth*mult*sizeMult),int(dogeHeight*mult*sizeMult)))
- if(orientation=="profile-right"):
- dogeIm = dogeIm.transpose(Image.FLIP_LEFT_RIGHT)
- im.paste(dogeIm,(int(face["x"]-dogeWidth*mult*((sizeMult-1)/2+addxmult)),int(face["y"]-dogeHeight*mult*(sizeMult-1)/2)),dogeIm)
- im.save("dogifed.png", "PNG")'''
- translateWords = {}
- translateWords["White"] = "Белый/ая"
- translateWords["Black"] = "Чернокожий/ая"
- translateWords["Asian"] = "Азиатский/ая"
- translateWords["Female"] = "девушка"
- translateWords["Male"] = "мужчина"
- def translateIfCan(word):
- if(word in translateWords):
- return translateWords[word]
- return word
- def dogify(url):
- headers = {
- 'X-Mashape-Key': '0GnNRrq481mshClxu4BKRULI2qZUp1IDue7jsnEgpGrHln1rss',
- "Accept": "application/json"
- }
- req = requests.get("https://faceplusplus-faceplusplus.p.mashape.com/detection/detect?attribute=glass%2Cpose%2Cgender%2Cage%2Crace%2Csmiling&url="+url,headers=headers)
- jsonData = req.json()
- print(req.text)
- print("test")
- response = requests.get(url)
- if response.status_code == 200:
- f = open("dogify.png", 'wb')
- f.write(response.content)
- f.close()
- im = Image.open("dogify.png")
- picW = jsonData["img_width"]
- picH = jsonData["img_height"]
- text = ""
- jsonData["face"].sort(key=lambda x: x["position"]["center"]["x"])
- for face in jsonData["face"]:
- text+=translateIfCan(face["attribute"]["race"]["value"])+" "
- text+=translateIfCan(face["attribute"]["gender"]["value"])+" "
- text+="возраст "+str(face["attribute"]["age"]["value"])+"+-"+str(face["attribute"]["age"]["range"])+" "
- if("glass" in face["attribute"]):
- if(face["attribute"]["glass"]["value"]!="None"):
- text+="с очками "
- if("smiling" in face["attribute"]):
- if(face["attribute"]["smiling"]["value"]>50):
- text+="улыбается "
- cx = face["position"]["center"]["x"]
- cy = face["position"]["center"]["y"]
- if(cx<33):
- text+="слева "
- if(cx>66):
- text+="справа "
- if(cx>=33 and cx<=66):
- text+="по центру "
- if(cy<25):
- text+="сверху "
- if(cy>75):
- text+="снизу "
- text+="\n"
- #orientation = face["orientation"]
- yaw = face["attribute"]["pose"]["yaw_angle"]["value"]
- roll = face["attribute"]["pose"]["roll_angle"]["value"]
- w = face["position"]["width"]*picW/100
- h = face["position"]["height"]*picH/100
- centerX = face["position"]["center"]["x"]*picW/100
- centerY = face["position"]["center"]["y"]*picH/100-h*0.2
- im2 = random.choice(frontalImages)
- dogeWidth, dogeHeight = im2.size
- mult = w/dogeWidth*1.6
- newDogeWidth = int(dogeWidth*mult)
- newDogeHeight = int(dogeHeight*mult)
- dogeIm = im2.resize((newDogeWidth,newDogeHeight))
- if(yaw>0):
- dogeIm = dogeIm.transpose(Image.FLIP_LEFT_RIGHT)
- dogeIm = dogeIm.rotate(-roll)
- im.paste(dogeIm,(int(centerX-newDogeWidth/2),int(centerY-newDogeHeight/2)),dogeIm)
- im.save("dogifed.png", "PNG")
- return [len(jsonData["face"]),text]
- return [0,""]
- #dogify("http://apicloud.me/assets/facerect/image3.jpg")
- VAAS_APPLICATION = "DEV"
- VAAS_URL = "http://vaas.acapela-group.com/Services/Synthesizer"
- VAAS_LOGIN = "~VAAS_KIOSK"
- VAAS_PASSWORD = "8dbmslg8fpkl9fs"
- def text_to_speech(text,voice="alyona"):
- hash = {"prot_vers" : "2", "cl_env" : "APACHE_2.2.9_PHP_5.5", "cl_vers" : "1-00", "cl_login" : VAAS_LOGIN,
- "cl_app" : VAAS_APPLICATION, "cl_pwd" : VAAS_PASSWORD, "req_voice" : voice+"22k",
- "req_text" : text}#sharon
- req = requests.post(VAAS_URL,data=hash)
- print(req.text)
- for s in req.text.split("&"):
- if( s.split("=")[0] == "snd_url" ):
- return s.split("=")[1]
- return ""
- imageFindProg = '"ou":"([^"%&]*)"'
- proga = re.compile(imageFindProg)#'imgurl=([^"%&]*)')
- def image_search_fast(name):
- headers = {
- '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'
- }
- gogl = requests.get("https://www.google.ru/search?tbm=isch&q="+name,headers=headers)
- print("found")
- links = proga.findall(gogl.text) #str(gogl.text.encode('ascii', 'ignore'))
- print("parsed")
- #print(str(links).encode('ascii', 'ignore'))
- return links
- #image_search_fast("Doge")
- #print(image_search_fast("аниме девушка со странностями"))
- def image_search(query, amount=1, st=1):
- #returns 'amount' number of query results in a list.
- results = []
- #BASE_URL = 'https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=' + query + '&start=%d'
- #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
- 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
- r = requests.get(BASE_URL, timeout=6.0)
- #print(r.text)
- for image_info in json.loads(r.text)['items']:
- url = image_info['link']
- results.append([url,image_info["title"],image_info["image"]["contextLink"]])
- return results
- def embeddable_image(query, amount=1):
- #returns 'amount' number of
- results = []
- for image in image_search(query,amount):
- results.append('<img src = "{0}>'.format(image))
- return results
- class MLStripper(HTMLParser):
- def __init__(self):
- self.reset()
- self.strict = False
- self.convert_charrefs= True
- self.fed = []
- def handle_data(self, d):
- self.fed.append(d)
- def get_data(self):
- return ''.join(self.fed)
- def strip_tags(html):
- s = MLStripper()
- s.feed(html)
- return s.get_data()
- import json
- emptyChar = "-"
- shootedChar = "•"
- ourMap = {}
- enemyMap = {}
- ourShips = []
- enemyShips = []
- for x in range(0,10):
- ourMap[x] = {}
- enemyMap[x] = {}
- for y in range(0,10):
- ourMap[x][y] = emptyChar
- enemyMap[x][y] = emptyChar
- def blockEmpty(map, x, y):
- for xa in range(0,3):
- for ya in range(0,3):
- lx = x+xa-1
- ly = y+ya-1
- if(lx>=0 and ly>=0 and lx<10 and ly<10 and map[lx][ly]!=emptyChar):
- return 0
- return 1
- def shootAround(map, x, y):
- for xa in range(0,3):
- for ya in range(0,3):
- lx = x+xa-1
- ly = y+ya-1
- if(lx>=0 and ly>=0 and lx<10 and ly<10 and map[lx][ly]!="X"):
- map[lx][ly] = shootedChar
- def canPlace(map, x, y, size, orient):
- for i in range(0,size):
- if(orient==0):
- if( x+i>9 or not blockEmpty(map,x+i,y) ):
- return 0
- if( orient==1):
- if( x-i<0 or not blockEmpty(map,x-i,y) ):
- return 0
- if( orient==2):
- if( y+i>9 or not blockEmpty(map,x,y+i) ):
- return 0
- if( orient==3):
- if( y-i<0 or not blockEmpty(map,x,y-i) ):
- return 0
- return 1
- def populateMap(map,Wships):
- ships = [4,3,3,2,2,2,1,1,1,1]
- while(len(ships)>0):
- curship = ships.pop(0)
- found = False
- while not found:
- randx = random.randint(0,9)
- randy = random.randint(0,9)
- randor = random.randint(0,3)
- if(canPlace(map,randx,randy,curship,randor)):
- found = True
- Wships.append([curship,[]])
- #print("LEN "+Wships)
- for i in range(0,curship):
- if( randor==0):
- map[randx+i][randy] = "S"
- Wships[len(Wships)-1][1].append([randx+i,randy])
- if( randor==1):
- map[randx-i][randy] = "S"
- Wships[len(Wships)-1][1].append([randx-i,randy])
- if( randor==2):
- map[randx][randy+i] = "S"
- Wships[len(Wships)-1][1].append([randx,randy+i])
- if( randor==3):
- map[randx][randy-i] = "S"
- Wships[len(Wships)-1][1].append([randx,randy-i])
- def canConvert(stra):
- str = stra.upper()
- words = ["А","Б","В","Г","Д","Е","Ж","З","И","К"]
- numbers = ["0","1","2","3","4","5","6","7","8","9"]
- if(len(str) != 2 and len(str) != 3):
- return 0
- if(not (str[0] in words) ):
- return 0
- if(not (str[1] in numbers)):
- return 0
- if(len(str)==3 and (not (str[2] in numbers))):
- return 0
- return 1
- def convert(stra):
- str = stra.upper()
- words = ["А","Б","В","Г","Д","Е","Ж","З","И","К"]
- numbers = ["1","2","3","4","5","6","7","8","9"]
- n1 = words.index(str[0])
- n2 = -1
- if(len(str)==2):
- n2 = numbers.index(str[1])
- else:
- n2 = 9
- return [n2,n1]
- def shipIndexByPos(ships,pos):
- for i in range(0,len(ships)):
- for p in ships[i][1]:
- if(p[0]==pos[0] and p[1]==pos[1]):
- return i
- return -1
- def tryAttack(strattack):
- global isAiTurn
- if(not isAiTurn and canConvert(strattack)):
- apos = convert(strattack)
- if(enemyMap[apos[0]][apos[1]]=="S"):
- hasKilled = 0
- shipId = shipIndexByPos(enemyShips,apos)
- enemyShips[shipId][0]-=1
- if(enemyShips[shipId][0])==0:
- hasKilled = 1
- for p in enemyShips[shipId][1]:
- shootAround(enemyMap,p[0],p[1])
- enemyMap[apos[0]][apos[1]] = "X"
- printMapToFile()
- postSeaBattle()
- time.sleep(0.5)
- if(hasKilled):
- sendMessage("Ты убил")
- else:
- sendMessage("Ты попал")
- else:
- if(enemyMap[apos[0]][apos[1]]!="X"):
- enemyMap[apos[0]][apos[1]] = shootedChar
- sendMessage("Ты не попал")
- isAiTurn = 1
- isAiTurn = 0
- def processAi():
- global isAiTurn
- if isAiTurn:
- found = False
- while not found:
- xr = random.randint(0,9)
- yr = random.randint(0,9)
- if(ourMap[xr][yr]!="X" and ourMap[xr][yr]!=shootedChar):
- found = True
- if(ourMap[xr][yr]=="S"):
- ourMap[xr][yr] = "X"
- hasKilled = 0
- shipId = shipIndexByPos(ourShips,[xr,yr])
- ourShips[shipId][0]-=1
- if(ourShips[shipId][0])==0:
- hasKilled = 1
- if hasKilled:
- sendMessage("Бот убил")
- for p in ourShips[shipId][1]:
- shootAround(ourMap,p[0],p[1])
- else:
- sendMessage("Бот попал")
- else:
- isAiTurn = 0
- ourMap[xr][yr] = shootedChar
- printMapToFile()
- postSeaBattle()
- time.sleep(0.5)
- sendMessage("Бот не попал")
- def fogOfWar(ch):
- if(ch=="S"):
- return emptyChar
- return ch
- def printMapToFile():
- im = Image.new("RGB", (500, 360), "white")
- fnt = ImageFont.truetype('consola.ttf', 30)
- d = ImageDraw.Draw(im)
- d.text((0,10), " АБВГДЕЖЗИК АБВГДЕЖЗИК", font=fnt, fill=(0,0,0,255))
- d.text((0,20), " __________ __________", font=fnt, fill=(0,0,0,255))
- for x in range(0,10):
- numstr = str(x+1)
- if(len(numstr)==1):
- numstr = " "+numstr
- line = numstr + "|"
- for y in range(0,10):
- line = line + str(ourMap[x][y])
- line = line + " " + numstr + "|"
- for y in range(0,10):
- line = line + fogOfWar( str(enemyMap[x][y]) )
- #print(line)
- d.text((0,50+30*x), line, font=fnt, fill=(0,0,0,255))
- im.save("test.png", "PNG")
- def printMap():
- print(" АБВГДЕЖЗИК АБВГДЕЖЗИК")
- print(" __________ __________")
- for x in range(0,10):
- numstr = str(x+1)
- if(len(numstr)==1):
- numstr = " "+numstr
- line = numstr + "|"
- for y in range(0,10):
- line = line + str(ourMap[x][y])
- line = line + " " + numstr + " |"
- for y in range(0,10):
- line = line + str(enemyMap[x][y])
- print(line)
- #printMap()
- populateMap(ourMap,ourShips)
- populateMap(enemyMap,enemyShips)
- #printMap()
- printMapToFile()
- session = vk.AuthSession(app_id=myAppId,user_login=myUsername,user_password=myPassword)
- session.access_token = myToken
- vkapi = vk.API(session)
- import datetime
- def weather(town):
- info = requests.get("http://api.openweathermap.org/data/2.5/weather?lang=ru&q="+town+"&appid=2de143494c0b295cca9337e1e96b00e0")
- js = info.json()
- if(js["cod"]==200):
- response = requests.get("http://openweathermap.org/img/w/"+(js["weather"][0]["icon"])+".png")
- if response.status_code == 200:
- f = open("weather.png", 'wb')
- f.write(response.content)
- f.close()
- sendText = ""
- sendText = sendText + js["name"] + ", "+js["sys"]["country"] + "\n"
- sendText = sendText + "Температура: " + str(round(10*(js["main"]["temp"]-273))/10) + "\n"
- sendText = sendText + "Влажность: " + str(js["main"]["humidity"]) + "%\n"
- sendText = sendText + "Восход: " + str(datetime.datetime.fromtimestamp(js["sys"]["sunrise"]).time()) + "\n"
- sendText = sendText + "Закат: " + str(datetime.datetime.fromtimestamp(js["sys"]["sunset"]).time()) + "\n"
- sendText = sendText + js["weather"][0]["main"] + ": " + js["weather"][0]["description"]
- sendPictureText("weather.png",sendText)
- else:
- sendMessage("Город не найден")
- quoteGroup = "wisdomofgreat"
- quoteCountResp = vkapi.wall.get(domain=quoteGroup,count=1,filter="all")
- quoteCount = quoteCountResp[0]
- def postRandomQuote():
- quoteNum = random.randint(1,quoteCount-1)
- quoteCountResp = vkapi.wall.get(domain=quoteGroup,count=1,filter="all",offset=quoteNum)
- quoteText = quoteCountResp[1]["text"] + "\n" + "лайки: " + str(quoteCountResp[1]["likes"]["count"])
- quoteText = quoteText + " " + "репосты: " + str(quoteCountResp[1]["reposts"]["count"])
- sendMessage(quoteText)
- def findSong(name):
- audio = vkapi.audio.search(q=name,count=3)
- print(audio)
- #findSong("дейс")
- def findAndPost(name):
- try:
- randI = 0#random.randint(0,2)
- #if(random.randint(0,100)<10):
- # randI = random.randint(0,3)
- #if(random.randint(0,100)<30):
- # randI = random.randint(0,10)
- #stuff = image_search(name,10,randI)
- stuff = image_search_fast(name)
- if(len(stuff)==0):
- return
- selIm = random.randint(0,int((len(stuff)-1)*0.2))
- imageLink = '["'+stuff[selIm]+'"]'
- imageLink = json.loads(imageLink)[0]
- print(imageLink)
- #response = requests.get(stuff[selIm][0])
- response = requests.get(imageLink)
- if response.status_code == 200:
- f = open("doge.png", 'wb')
- f.write(response.content)
- f.close()
- img = {'photo': ('doge.png', open(r'doge.png', 'rb'))}
- saaa = requests.post(uploadServer, files=img)
- js = saaa.json()
- print(js["photo"])
- asdz = vkapi.photos.saveMessagesPhoto(server=js["server"], photo=js["photo"],hash = js["hash"])
- print(asdz[0]["id"])
- vkapi.messages.send(chat_id=myChatId,attachment=asdz[0]["id"])
- #vkapi.messages.send(chat_id=myChatId,attachment=asdz[0]["id"],message=stuff[selIm][1]+"\n"+stuff[selIm][2])
- except:
- print("Error while finding picture")
- #from pydub import AudioSegment
- #AudioSegment.converter = "ffmpeg/bin/ffmpeg.exe"
- '''def text_to_speech_post(text,voice="alyona"):
- try:
- voice = text_to_speech(fixStuff2(text),voice)
- if(voice==""):
- print("Error while getting voice url")
- return
- response = requests.get(voice)
- if response.status_code == 200:
- f = open("voice.mp3", 'wb')
- f.write(response.content)
- f.close()
- song = AudioSegment.from_file("voice.mp3", format="mp3")
- second_of_silence = AudioSegment.silent(duration=2000)
- song = song + second_of_silence
- file_handle = song.export("voice2.mp3", format="mp3")
- file_handle.close()
- img = {'file': ('voice.mp3', open(r'voice2.mp3', 'rb'))}
- saaa = requests.post(voiceUploadServer, files=img)
- js = saaa.json()
- print(saaa.json())
- asdz = vkapi.audio.save(server=js["server"], audio=js["audio"],hash = js["hash"])
- print(asdz)
- vkapi.audio.moveToAlbum(album_id="67775716",audio_ids=str(asdz["aid"]))
- print(("audio"+str(asdz["owner_id"])+"_"+str(asdz["aid"])))
- vkapi.messages.send(chat_id=myChatId,attachment=("audio"+str(asdz["owner_id"])+"_"+str(asdz["aid"])))
- except vk.exceptions.VkAPIError:
- print("Too short")
- #print(text_to_speech("do me trade?"))'''
- def fixStuff(message):
- return message.replace(""","\"").replace("<br />","").replace("<p>","").replace("</p>","\n").replace(" "," ").replace("«","«").replace("»","»")
- def fixStuff2(message):
- return message.replace("""," ").replace("<br />"," ").replace("<br/>"," ").replace("<br>"," ").replace("<br >"," ").replace("<p>"," ").replace("</p>"," ").replace(" "," ").replace("«"," ").replace("»"," ")
- def postSeaBattle():
- img = {'photo': ('test.png', open(r'test.png', 'rb'))}
- saaa = requests.post(uploadServer, files=img)
- js = saaa.json()
- asdz = vkapi.photos.saveMessagesPhoto(server=js["server"], photo=js["photo"],hash = js["hash"])
- vkapi.messages.send(chat_id=myChatId,attachment=asdz[0]["id"])
- global lastmessageid
- lastmessageid = vkapi.messages.getHistory(chat_id=myChatId, count = 1)[1]['mid']
- def sayChallenge():
- global lastmessageid
- if(currentChallange[0]=="flavor"):
- lastmessageid = sendMessage(currentChallange[1])
- return
- '''if(currentChallange[0]=="sounds"):
- song = AudioSegment.from_file(currentChallange[6], format="ogg")
- second_of_silence = AudioSegment.silent(duration=2000)
- song = song + second_of_silence
- file_handle = song.export("voiceChallenge.mp3", format="mp3")
- file_handle.close()
- img = {'file': ('voiceChallenge.mp3', open(r'voiceChallenge.mp3', 'rb'))}
- saaa = requests.post(voiceUploadServer, files=img)
- js = saaa.json()
- asdz = vkapi.audio.save(server=js["server"], audio=js["audio"],hash = js["hash"])
- vkapi.audio.moveToAlbum(album_id="67775716",audio_ids=str(asdz["aid"]))
- lastmessageid = vkapi.messages.send(chat_id=myChatId,message=currentChallange[1],attachment=("audio"+str(asdz["owner_id"])+"_"+str(asdz["aid"])))
- else:'''
- lastmessageid = sendPictureText("challenge2.png",currentChallange[1])
- def checkAnswer(user_id,message):
- global currentChallange
- global currentLives
- if(RepresentsInt(message)):
- if(int(message)==currentChallange[2]):
- sendMessage("Правильно!")
- addWin(user_id)
- currentLives = 2
- currentChallange = generateChallenge()
- generateChallengePic(currentChallange)
- time.sleep(3)
- sayChallenge()
- else:
- currentLives-=1
- addLose(user_id)
- if(currentLives<=0):
- sendPictureText("challenge1.png","Вы проиграли, правильный ответ: "+str(currentChallange[2]))
- currentLives = 2
- currentChallange = generateChallenge()
- generateChallengePic(currentChallange)
- time.sleep(3)
- sayChallenge()
- else:
- #currentLives-=1
- sendMessage("Не правильно, осталось жизней: "+str(currentLives))
- def encryptRiddle(str):
- newstr = ""
- shouldShow = 1
- for c in str:
- if(c.isalpha()):
- if(shouldShow==1):
- newstr = newstr + c
- shouldShow = 0
- else:
- newstr = newstr + "*"
- else:
- newstr = newstr + c
- shouldShow = 1
- return newstr
- def processMessage(message,photo,user_id):
- normalmessage = message
- message = message.lower()
- if message == "шутка":
- r = requests.get("http://www.umori.li/api/random?num=40")
- js = r.json()
- smallest = js[0]["elementPureHtml"]
- smallestL = len(smallest) + random.randint(0,len(smallest))*0.4
- for i in range(1,5):
- c = js[random.randint(0,39)]["elementPureHtml"]
- cl = len(c) + random.randint(0,len(c))*0.4
- if(cl<smallestL):
- smallestL = cl
- smallest = c
- sendMessage(fixStuff( smallest))
- if message == "doge":
- findAndPost("doge")
- '''if message == "морской бой":
- postSeaBattle()
- tryAttack(message)'''
- if(message == "список"):
- sendMessage(shopGenerateString([]))
- if(message == "категории"):
- sendMessage("\n".join(shopGenerateCategories()))
- #if(message == "квест"):
- # questStart()
- # sendMessage(questGenerateString())
- #if(message == "стопквест"):
- # questStop()
- global lastRiddle
- if(message == "hs quiz"):
- sayChallenge()
- #if(questMode):
- # if(questAnswer(message)):
- # sendMessage(questGenerateString())
- #else:
- checkAnswer(user_id,message)
- if message == "совет":
- postRandomQuote()
- if message == "стата":
- displayStats()
- if message == "загадка":
- sendMessage(lastRiddle[0])
- if (message == "сдаюсь" or message == "хз"):
- sendMessage("Ответ: "+lastRiddle[1])
- time.sleep(1)
- lastRiddle = generateRiddle()
- sendMessage(lastRiddle[0])
- if (message == "подсказка" or message == "хелп"):
- sendMessage(encryptRiddle(lastRiddle[1]))
- if message.strip() == lastRiddle[1].lower().strip():
- sendMessage("Правильно!")
- time.sleep(1)
- lastRiddle = generateRiddle()
- sendMessage(lastRiddle[0])
- if(photo!=""):
- #data = whatIsOnPicture(photo)
- #if(data[1]==""):
- # sendMessage("На картинке "+data[0])
- #else:
- # sendMessage("На картинке "+data[0]+" - "+data[1])
- dogifyData = dogify(photo)
- count = dogifyData[0]
- if(count>0):
- global lastmessageid
- lastmessageid = sendPictureText("dogifed.png",dogifyData[1])
- #if (photo!="" and (message == "dogify" or message == "dogefy" or message == "догефай")):
- # dogify(photo)
- # sendPicture("dogifed.png")
- ar = message.split(" ")
- normalAr = normalmessage.split(" ")
- if(len(ar)>1):
- if(ar[0]=="найди"):
- ar.pop(0)
- findAndPost(" ".join(ar))
- return 0
- if(ar[0]=="погода"):
- ar.pop(0)
- weather(" ".join(ar))
- return 0
- if(ar[0]=="скажи"):
- ar.pop(0)
- #text_to_speech_post(" ".join(ar))
- return 0
- if(ar[0]=="orc"):
- ar.pop(0)
- #text_to_speech_post(" ".join(ar),"willlittlecreature")
- return 0
- if(ar[0]=="добавь" or ar[0]=="добавить"):
- normalAr.pop(0)
- #addCitilinkId(" ".join(ar))
- for e in normalAr:
- addCitilinkId(e)
- saveShops()
- return 0
- if(ar[0]=="история"):
- normalAr.pop(0)
- if(generateChart(" ".join(normalAr))):
- lastmessageid = sendPictureText("lastplot.png",shopGenerateHistory(" ".join(normalAr)))
- else:
- sendMessage(shopGenerateHistory(" ".join(normalAr)))
- return 0
- if(ar[0]=="список"):
- ar.pop(0)
- sendMessage(shopGenerateString(ar))
- return 0
- #stoneProcessMessage(message)
- #vkapi.messages.send(chat_id=myChatId,message="123",attachment=stuff[0])
- #print(stuff[0])
- return 0
- def getNameById(id):
- d = vkapi.users.get(user_ids=id)
- return d[0]["first_name"]+" "+d[0]["last_name"]
- def getNamesById(ids):
- d = vkapi.users.get(user_ids=",".join(ids))
- res = []
- i = 0
- for id in ids:
- res.append(d[i]["first_name"]+" "+d[i]["last_name"])
- i+=1
- return res
- '''def processMessage(message):
- #print(message)
- if(RepresentsInt(message)):
- if(int(message)==lastans):
- sendMessage("Правильно")
- time.sleep(0.5)
- generateExpr()
- sendMessage(lastexpr+"?")
- return 1
- else:
- sendMessage("Не правильно")
- return 0'''
- def sendPicture(path):
- if 1:
- img = {'photo': ('pic.png', open(path, 'rb'))}
- saaa = requests.post(uploadServer, files=img)
- js = saaa.json()
- asdz = vkapi.photos.saveMessagesPhoto(server=js["server"], photo=js["photo"],hash = js["hash"])
- return vkapi.messages.send(chat_id=myChatId,attachment=asdz[0]["id"])
- def sendPictureText(path,text):
- if 1:
- img = {'photo': ('pic.png', open(path, 'rb'))}
- saaa = requests.post(uploadServer, files=img)
- js = saaa.json()
- asdz = vkapi.photos.saveMessagesPhoto(server=js["server"], photo=js["photo"],hash = js["hash"])
- return vkapi.messages.send(chat_id=myChatId,attachment=asdz[0]["id"],message=text)
- def sendMessage(message):
- if(len(message.strip())==0):
- print("Empty message was sent")
- return vkapi.messages.send(chat_id=myChatId,message=message)
- lastexpr = ""
- lastans = 0
- def generateExpr():
- global lastexpr
- global lastans
- lastexpr = ""
- bracketchancestart = 20
- bracketchance = 20
- bracketsdepth = 0
- if(random.randint(0,100)<bracketchancestart):
- lastexpr = "("
- bracketsdepth+=1
- lastexpr+=str(random.randint(1,20))
- count = random.randint(2,5)
- for i in range(0,count):
- op = random.randint(1,4)
- randn = 0
- if(bracketsdepth>0 and random.randint(0,100)<bracketchance):
- lastexpr+=')'
- bracketsdepth-=1
- if(op==1):
- randn = random.randint(1,20)
- lastexpr+='+'
- if(op==2):
- randn = random.randint(1,20)
- lastexpr+='-'
- if(op==3):
- randn = random.randint(2,3)
- lastexpr+='*'
- if(op==4):
- randn = random.randint(2,2)
- lastexpr+='/'
- if(i!=(count-1) and random.randint(0,100)<bracketchance):
- lastexpr+='('
- bracketsdepth+=1
- #lastans+=randn
- lastexpr+=str(randn)
- while(bracketsdepth>0):
- bracketsdepth-=1
- lastexpr+=')'
- lastans = int(eval(lastexpr))
- generateExpr()
- #print(lastexpr)
- #print(lastans)
- #print(eval('10+10()'))
- st = vkapi.photos.getMessagesUploadServer()
- uploadServer = st["upload_url"]
- st = vkapi.audio.getUploadServer()
- voiceUploadServer = st["upload_url"]
- #sendMessage(lastexpr+"?")
- #text_to_speech_post("do me trade?")
- #print(text_to_speech("trade?","willlittlecreature"))
- checkRssTime = 60*30
- curRssTime=60*2
- import traceback
- def test():
- pass
- print("init")
- while(1):
- curRssTime-=3
- if(curRssTime<=0):
- curRssTime = checkRssTime
- checkRss()
- try:
- messages = vkapi.messages.getHistory(chat_id=myChatId)
- for i in reversed(range(1,len(messages))):
- message = messages[i]
- mid = message['mid']
- if(mid>lastmessageid):
- lastmessageid = mid
- photo = ""
- if(("attachment" in message) and (message["attachment"]["type"]=="photo")):
- photo = message["attachment"]["photo"]["src_big"]
- if processMessage(message['body'],photo,message["uid"]): break
- processAi()
- rssMessageArray = []
- for mes in shopMessages:
- rssMessage = ""
- if(mes["type"]=="newItem"):
- rssMessage+="Товар "
- rssMessage+=str(mes["productname"])
- rssMessage+=" добавлен"
- if(mes["type"]=="hasItem"):
- rssMessage+="Товар "
- rssMessage+=str(mes["productid"])
- rssMessage+=" уже был добавлен"
- if(mes["type"]=="priceChange"):
- if(mes["newprice"]<mes["oldprice"]):
- rssMessage+="У "
- rssMessage+=str(mes["productid"])
- rssMessage+=" "
- rssMessage+=str(mes["productname"])
- rssMessage+=" уменьшилась цена с "
- rssMessage+=str(int(mes["oldprice"]))
- rssMessage+="руб. до "
- rssMessage+=str(int(mes["newprice"]))
- rssMessage+="руб."
- rssMessage+=shopGenerateDiff(mes["oldprice"],mes["newprice"])
- elif(mes["newprice"]>mes["oldprice"]):
- rssMessage+="У "
- rssMessage+=str(mes["productid"])
- rssMessage+=" "
- rssMessage+=str(mes["productname"])
- rssMessage+=" увеличилась цена с "
- rssMessage+=str(int(mes["oldprice"]))
- rssMessage+="руб. до "
- rssMessage+=str(int(mes["newprice"]))
- rssMessage+="руб."
- rssMessage+=shopGenerateDiff(mes["oldprice"],mes["newprice"])
- rssMessage+=", пидары"
- if(rssMessage!=""):
- rssMessageArray.append(rssMessage)
- shopMessages = []
- if(len(rssMessageArray)>0):
- sendMessage("\n--------------------\n".join(rssMessageArray))
- except requests.exceptions.ReadTimeout:
- print("Time out")
- except Exception as e:
- print(traceback.format_exc())
- print(str(e))
- time.sleep(3)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement