Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # database adress
- host = "localhost"
- # database login
- user = " "
- # database password
- password = " "
- # vk app id (const)
- appId = "6765696"
- # group id
- groupId = ""
- # group token
- token = "0"
- # vk login
- VKlogin = "0"
- # vk password
- VKpassword = "0"
- # time on one selled lot
- timeOneAuction = 60
- # api version
- v="5.40"
- # delay price
- delaySumm = 10
- def getPrice(text):
- price = 0
- count = 0
- for word in text.split():
- if word.isdigit():
- count += 1
- price = int(word)
- return count == 1, price
- def randomStr(length=10):
- chars = ["q", 'w','e','r','t','y','u','i','o','p','a','G','E','V','Q','b','B']
- s = ''
- for i in range(length):
- s += chars[randint(0, len(chars)-1)]
- return s
- def newPost(text, attachments):
- global api, groupId
- try:
- api.wall.post(owner_id="-"+groupId, message=text, v=v, attachments=attachments, guid=randomStr(10), from_group=1)
- return True
- except:
- return False
- def addUser(id, type, permissions):
- global cursor, users, connection
- try:
- cursor.execute("INSERT INTO user VALUES ({v3}, {v2}, {v1);".format(v3=id, v2=type, v1=permissions))
- connection.commit()
- except:
- return False
- users[id] = user(id, type, permissions)
- return True
- connection = psycopg2.connect(host=host, user=user, password=password, )
- cursor = connection.cursor()
- try:
- cursor.execute("""CREATE TABLE walls (
- id serial PRIMARY KEY,
- price serial NOT NULL,
- selled serial NOT NULL,
- selled_id serial NOT NULL,
- type serial NOT NULL,
- last_update_time serial NOT NULL
- );""")
- print("Таблица постов создана")
- cursor.fetchone()
- except Exception as e:
- pass
- connection.commit()
- def newPost(post_id, text, mark):
- postType = 0
- price = 0
- selled = 0
- selled_id = 0
- last_update_time = int(time.time())
- text = text.lower().split()
- if ("#реклама" in text) or (mark==1):
- postType = 2
- price = 0
- elif ("#аукцион" in text) and ("#лот" in text):
- postType = 1
- price = 0
- cursor.execute("""INSERT INTO walls VALUES(
- """ + str(post_id) + """,
- """ + str(price) + """,
- """ + str(selled) + """,
- """ + str(selled_id) + """,
- """ + str(postType) + """,
- """ + str(last_update_time) + """
- );""")
- connection.commit()
- return postType, price
- api = vk.create_api(login=VKlogin, password=VKpassword, scope=1384448, app_id=appId)
- while True:
- try:
- connVk = req.get("https://api.vk.com/method/groups.getLongPollServer",
- params={'access_token': token, 'v':v, 'group_id':groupId}).json()['response']
- print("Connected")
- while True:
- try:
- q = "SELECT id, price, selled_id FROM walls WHERE last_update_time < "+str(int(time.time() - timeOneAuction))+" AND selled = 0 AND type = 1;"
- cursor.execute(q)
- data = cursor.fetchall()
- for post in data:
- post_id = post[0]
- price = post[1]
- selled_id = post[2]
- if selled_id != 0:
- q = "UPDATE walls SET selled = 1 WHERE id = "+str(post_id)+";"
- cursor.execute(q)
- users = api.users.get(user_ids=selled_id,name_case='nom')[0]
- name = users['first_name'] + " " + users['last_name']
- api.wall.createComment(owner_id="-"+groupId, post_id=post_id, from_group=1, message="Победителем лота оказался [id"+str(selled_id)+"|"+name+"], он выставил цену в "+str(price)+" рублей! Поздравляем! За покупкой обращаться к администратору сообщества.")
- data = req.get("https://api.vk.com/method/messages.send",
- params={'access_token': token, 'v':v, 'user_id':selled_id, 'attachment':"wall-"+groupId+"_"+str(post_id),
- 'message':"Поздравляю!nnВы выиграли данный лот.nЗа получением контактов хозяина лота обращаться к администратору.",'random_id':randint(1,9999)})
- else:
- q = "UPDATE walls SET last_update_time = "+str(int(time.time()))+" WHERE id = "+str(post_id)+";"
- cursor.execute(q)
- connection.commit()
- except Exception as e:
- print(e)
- response = req.get(connVk['server'],params={'act':'a_check','key':connVk['key'],'ts':connVk['ts'],'wait':2}).json()
- for update in response['updates']:
- if update['type']=='wall_reply_new':
- update = update['object']
- cursor.execute("SELECT last_update_time, type, price FROM walls WHERE id = '"+str(update['post_id'])+"'")
- data = cursor.fetchall()
- test = True
- while test:
- if (update['from_id'] != update['post_owner_id']) and (data[0][1] == 1) and (update['from_id']>0):
- if len(data)>0:
- flag, price = getPrice(update['text'])
- if (time.time()-data[0][0])<=timeOneAuction:
- if flag and (price >= data[0][2] + delaySumm):
- cursor.execute("SELECT selled_id FROM walls WHERE id = '"+str(update['post_id'])+"'")
- data = cursor.fetchall()
- if (data[0][0] != 0) and (data[0][0] != update['from_id']):
- users = api.users.get(user_ids=data[0][0],name_case='nom')[0]['first_name']
- message = "[id"+str(data[0][0])+"|" + users + "], Ваша ставка перебита другой. Новая ставка: " + str(price)
- api.wall.createComment(owner_id=update['post_owner_id'], post_id=update['post_id'], from_group=1, message=message)
- cursor.execute("UPDATE walls SET last_update_time = "+str(int(time.time()))+", selled_id = "+str(update['from_id'])+", price = "+str(price)+" WHERE id = "+str(update['post_id'])+"")
- connection.commit()
- mess = 'Готово! Новая ставка: '+str(price)+' рублей'
- test = False
- elif flag and (price < data[0][2]+delaySumm):
- mess = "Ваша цена недостаточна для её установки. nУстановите цену большую, чем сейчас, и Вы станете претендентом на победу!nСейчас ставка " + str(data[0][2]) + " рублей"
- test = False
- elif not flag and (price > 0):
- mess = "Так сколько Вы готовы заплатить за товар?"
- test = False
- else:
- mess = ""
- test = False
- else:
- mess = 'Товар продан, извините.'
- test = False
- else:
- print("-"+groupId+"_"+str(update['post_id']))
- post = api.wall.getById(posts="-"+groupId+"_"+str(update['post_id']))
- print(post)
- typePost, price = newPost(post['item'][0]['id'], post['item'][0]['text'], post['item'][0]['marked_as_ads'])
- if typePost == 1:
- continue
- else:
- mess = ""
- test = False
- if mess != "":
- api.wall.createComment(owner_id=update['post_owner_id'], post_id=update['post_id'], from_group=1, reply_to_comment=update['id'], message=mess)
- else:
- test = False
- elif update['type'] == 'wall_post_new':
- update = update['object']
- postType, price = newPost(update['id'], update['text'], update['marked_as_ads'])
- if postType == 1:
- try:
- api.wall.createComment(owner_id="-"+groupId, post_id=update['id'], from_group=1, message="Стартовая цена: "+str(price+delaySumm)+" рублей.")
- except Exception as e:
- print(e)
- connVk['ts'] = response['ts']
- except Exception as e:
- print(e)
Add Comment
Please, Sign In to add comment