Guest User

Untitled

a guest
Jan 3rd, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.28 KB | None | 0 0
  1. # database adress
  2. host = "localhost"
  3.  
  4. # database login
  5. user = " "
  6.  
  7. # database password
  8. password = " "
  9.  
  10. # vk app id (const)
  11. appId = "6765696"
  12.  
  13. # group id
  14. groupId = ""
  15.  
  16. # group token
  17. token = "0"
  18.  
  19. # vk login
  20. VKlogin = "0"
  21.  
  22. # vk password
  23. VKpassword = "0"
  24.  
  25. # time on one selled lot
  26. timeOneAuction = 60
  27.  
  28. # api version
  29. v="5.40"
  30.  
  31. # delay price
  32. delaySumm = 10
  33.  
  34.  
  35. def getPrice(text):
  36. price = 0
  37. count = 0
  38. for word in text.split():
  39. if word.isdigit():
  40. count += 1
  41. price = int(word)
  42. return count == 1, price
  43.  
  44.  
  45. def randomStr(length=10):
  46. chars = ["q", 'w','e','r','t','y','u','i','o','p','a','G','E','V','Q','b','B']
  47. s = ''
  48. for i in range(length):
  49. s += chars[randint(0, len(chars)-1)]
  50. return s
  51.  
  52.  
  53. def newPost(text, attachments):
  54. global api, groupId
  55. try:
  56. api.wall.post(owner_id="-"+groupId, message=text, v=v, attachments=attachments, guid=randomStr(10), from_group=1)
  57. return True
  58. except:
  59. return False
  60.  
  61.  
  62. def addUser(id, type, permissions):
  63. global cursor, users, connection
  64. try:
  65. cursor.execute("INSERT INTO user VALUES ({v3}, {v2}, {v1);".format(v3=id, v2=type, v1=permissions))
  66. connection.commit()
  67. except:
  68. return False
  69. users[id] = user(id, type, permissions)
  70. return True
  71.  
  72.  
  73. connection = psycopg2.connect(host=host, user=user, password=password, )
  74. cursor = connection.cursor()
  75.  
  76.  
  77. try:
  78. cursor.execute("""CREATE TABLE walls (
  79. id serial PRIMARY KEY,
  80. price serial NOT NULL,
  81. selled serial NOT NULL,
  82. selled_id serial NOT NULL,
  83. type serial NOT NULL,
  84. last_update_time serial NOT NULL
  85. );""")
  86. print("Таблица постов создана")
  87. cursor.fetchone()
  88. except Exception as e:
  89. pass
  90.  
  91. connection.commit()
  92.  
  93. def newPost(post_id, text, mark):
  94. postType = 0
  95. price = 0
  96. selled = 0
  97. selled_id = 0
  98. last_update_time = int(time.time())
  99. text = text.lower().split()
  100. if ("#реклама" in text) or (mark==1):
  101. postType = 2
  102. price = 0
  103. elif ("#аукцион" in text) and ("#лот" in text):
  104. postType = 1
  105. price = 0
  106. cursor.execute("""INSERT INTO walls VALUES(
  107. """ + str(post_id) + """,
  108. """ + str(price) + """,
  109. """ + str(selled) + """,
  110. """ + str(selled_id) + """,
  111. """ + str(postType) + """,
  112. """ + str(last_update_time) + """
  113. );""")
  114. connection.commit()
  115. return postType, price
  116.  
  117.  
  118. api = vk.create_api(login=VKlogin, password=VKpassword, scope=1384448, app_id=appId)
  119. while True:
  120. try:
  121. connVk = req.get("https://api.vk.com/method/groups.getLongPollServer",
  122. params={'access_token': token, 'v':v, 'group_id':groupId}).json()['response']
  123. print("Connected")
  124. while True:
  125. try:
  126. q = "SELECT id, price, selled_id FROM walls WHERE last_update_time < "+str(int(time.time() - timeOneAuction))+" AND selled = 0 AND type = 1;"
  127. cursor.execute(q)
  128. data = cursor.fetchall()
  129. for post in data:
  130. post_id = post[0]
  131. price = post[1]
  132. selled_id = post[2]
  133. if selled_id != 0:
  134. q = "UPDATE walls SET selled = 1 WHERE id = "+str(post_id)+";"
  135. cursor.execute(q)
  136. users = api.users.get(user_ids=selled_id,name_case='nom')[0]
  137. name = users['first_name'] + " " + users['last_name']
  138. api.wall.createComment(owner_id="-"+groupId, post_id=post_id, from_group=1, message="Победителем лота оказался [id"+str(selled_id)+"|"+name+"], он выставил цену в "+str(price)+" рублей! Поздравляем! За покупкой обращаться к администратору сообщества.")
  139. data = req.get("https://api.vk.com/method/messages.send",
  140. params={'access_token': token, 'v':v, 'user_id':selled_id, 'attachment':"wall-"+groupId+"_"+str(post_id),
  141. 'message':"Поздравляю!nnВы выиграли данный лот.nЗа получением контактов хозяина лота обращаться к администратору.",'random_id':randint(1,9999)})
  142. else:
  143. q = "UPDATE walls SET last_update_time = "+str(int(time.time()))+" WHERE id = "+str(post_id)+";"
  144. cursor.execute(q)
  145. connection.commit()
  146. except Exception as e:
  147. print(e)
  148. response = req.get(connVk['server'],params={'act':'a_check','key':connVk['key'],'ts':connVk['ts'],'wait':2}).json()
  149. for update in response['updates']:
  150. if update['type']=='wall_reply_new':
  151. update = update['object']
  152. cursor.execute("SELECT last_update_time, type, price FROM walls WHERE id = '"+str(update['post_id'])+"'")
  153. data = cursor.fetchall()
  154. test = True
  155. while test:
  156. if (update['from_id'] != update['post_owner_id']) and (data[0][1] == 1) and (update['from_id']>0):
  157. if len(data)>0:
  158. flag, price = getPrice(update['text'])
  159. if (time.time()-data[0][0])<=timeOneAuction:
  160. if flag and (price >= data[0][2] + delaySumm):
  161. cursor.execute("SELECT selled_id FROM walls WHERE id = '"+str(update['post_id'])+"'")
  162. data = cursor.fetchall()
  163. if (data[0][0] != 0) and (data[0][0] != update['from_id']):
  164. users = api.users.get(user_ids=data[0][0],name_case='nom')[0]['first_name']
  165. message = "[id"+str(data[0][0])+"|" + users + "], Ваша ставка перебита другой. Новая ставка: " + str(price)
  166. api.wall.createComment(owner_id=update['post_owner_id'], post_id=update['post_id'], from_group=1, message=message)
  167. 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'])+"")
  168. connection.commit()
  169. mess = 'Готово! Новая ставка: '+str(price)+' рублей'
  170. test = False
  171. elif flag and (price < data[0][2]+delaySumm):
  172. mess = "Ваша цена недостаточна для её установки. nУстановите цену большую, чем сейчас, и Вы станете претендентом на победу!nСейчас ставка " + str(data[0][2]) + " рублей"
  173. test = False
  174. elif not flag and (price > 0):
  175. mess = "Так сколько Вы готовы заплатить за товар?"
  176. test = False
  177. else:
  178. mess = ""
  179. test = False
  180. else:
  181. mess = 'Товар продан, извините.'
  182. test = False
  183. else:
  184. print("-"+groupId+"_"+str(update['post_id']))
  185. post = api.wall.getById(posts="-"+groupId+"_"+str(update['post_id']))
  186. print(post)
  187. typePost, price = newPost(post['item'][0]['id'], post['item'][0]['text'], post['item'][0]['marked_as_ads'])
  188. if typePost == 1:
  189. continue
  190. else:
  191. mess = ""
  192. test = False
  193. if mess != "":
  194. api.wall.createComment(owner_id=update['post_owner_id'], post_id=update['post_id'], from_group=1, reply_to_comment=update['id'], message=mess)
  195. else:
  196. test = False
  197. elif update['type'] == 'wall_post_new':
  198. update = update['object']
  199. postType, price = newPost(update['id'], update['text'], update['marked_as_ads'])
  200. if postType == 1:
  201. try:
  202. api.wall.createComment(owner_id="-"+groupId, post_id=update['id'], from_group=1, message="Стартовая цена: "+str(price+delaySumm)+" рублей.")
  203. except Exception as e:
  204. print(e)
  205. connVk['ts'] = response['ts']
  206. except Exception as e:
  207. print(e)
Add Comment
Please, Sign In to add comment