Advertisement
Guest User

python vk bot

a guest
Apr 3rd, 2018
667
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 16.53 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. import time
  3. from os import listdir
  4. from random import choice
  5. import requests
  6. from teacher import *
  7. import vk_api
  8. from psutil import cpu_percent as usage_cpu
  9. from json import loads
  10. from random import randint
  11. spamfilter = []
  12. def getcpuu():
  13.     return round(usage_cpu())
  14. def remove_signs(spams):
  15.     spa = spams
  16.     return list(set(spa))
  17.     return spa
  18. def isAdmin(uid):
  19.     amd = open('admins')
  20.     admins = amd.read().split("\n")
  21.     amd.close()
  22.     return admins.count(str(uid)) >= 1
  23. def isUser(uid):
  24.     f = open('users')
  25.     dst = f.read().split()
  26.     f.close()
  27.  
  28.     return dst.count(uid) >= 1
  29. def addmoney(uid, count):
  30.     try:
  31.         f = open('db/users/balance/{}.bot'.format(uid))
  32.     except FileNotFoundError:
  33.         create_newUser(uid)
  34.         f = open('db/users/balance/{}.bot'.format(uid))
  35.     bal = int(f.read())
  36.     newbalance = bal + int(count)
  37.     f.close()
  38.     f = open('db/users/balance/{}.bot'.format(uid), 'w')
  39.     f.write(str(newbalance))
  40.     f.close()
  41. def create_newUser(uid):
  42.     f = open('db/users/balance/{}.bot'.format(uid), 'w+')
  43.     f.write('2000')
  44.     f.close()
  45.     return True
  46. def temp_encrypt(m):
  47.     string = ""
  48.     for i in m:
  49.         string += chr(ord(i) ^ 399)
  50.     return string
  51. def temp_decrypt(m):
  52.     string = ""
  53.     for i in m:
  54.         string += chr(ord(i) ^ 399)
  55.     return string
  56. def inFilter(family):
  57.     f = open('filtres/filter.bot')
  58.     vir =  f.read().lower().split("\n").count(family) >= 1
  59.     f.close()
  60.     return vir
  61. def getsex(u):
  62.     if u == 1:
  63.         return 'она'
  64.     elif u == 2:
  65.         return 'он'
  66.     else:
  67.         return 'оно'
  68. def teach_bot(command, react):
  69.     f = open('db/reaction/teacher.bot')
  70. def getbalance(uid):
  71.     try:
  72.         f = open('db/users/balance/{}.bot'.format(uid))
  73.     except FileNotFoundError:
  74.         create_newUser(uid)
  75.     else:
  76.         balance = f.read()
  77.         f.close()
  78.         return balance
  79. from os import system
  80. vk = vk_api.VkApi(login = input('login: '), password = input('password: '))
  81. vk.auth()
  82. check_auth(vk)
  83. values = {'out': 0,'count': 100,'time_offset': 60}
  84. def get_weather():
  85.     pass
  86. def write_msg(user_id, s):
  87.     global mid
  88.     vk.method('messages.send', {'user_id':user_id,'message':s, 'forward_messages':mid})
  89. def write_msgg(gid, s):
  90.     global mid
  91.     vk.method('messages.send', {'chat_id':gid,'message':s, 'forward_messages':mid})
  92. def write_msggp(gid, s):
  93.     a = vk.method('photos.getMessagesUploadServer')
  94.     b = requests.post(a['upload_url'], files={'photo': open("pr/"+choice(listdir("pr")), 'rb')}).json()
  95.     c = vk.method('photos.saveMessagesPhoto', {'photo': b['photo'], 'server': b['server'], 'hash': b['hash']})[0]
  96.     d = 'photo{}_{}'.format(c['owner_id'], c['id'])
  97.     vk.method('messages.send', {'chat_id': gid, 'attachment': d})
  98.  
  99. while True:
  100.  
  101.     response = vk.method('messages.get', values)
  102.     if response['items']:
  103.             values['last_message_id'] = response['items'][0]['id']
  104.     for item in response['items']:
  105.         print(item)
  106.         mid = item['id']
  107.         amd = open('admins')
  108.         admins = amd.read().split("\n")
  109.         amd.close()
  110.         if item['body'] == 'сасатб':
  111.             print('[-] Bad message сасатб')
  112.             if 'chat_id' in item:
  113.                 write_msgg(item['chat_id'], 'Твоя работа')
  114.             else:
  115.                 write_msg(item['user_id'], 'Твоя работа')
  116.         elif item['body'].lower().split(' ')[0] == 'порнушка':
  117.             print('[-] Bad message порнушка')
  118.             if 'chat_id' in item:
  119.                 write_msggp(item['chat_id'], 'ДРАЧИТЬ')
  120.         elif item['body'].lower() == 'admins':
  121.             if 'chat_id' in item:
  122.                 adminlist = ""
  123.                 for ss in admins:
  124.                     adminlist += "[id"+ss+"|Он]\n"
  125.                     print('[~] User selector {}'.foramt('id'+str(ss)))
  126.                 write_msgg(item['chat_id'], adminlist)
  127.             else:
  128.                 print('[~] Admin list')
  129.                 adminlist = ""
  130.                 for ss in admins:
  131.                     adminlist += "[id"+ss+"|Он]\n"
  132.                 write_msg(item['user_id'], adminlist)
  133.         elif item['body'].lower().split(' ')[0] == 'addadmin':
  134.             print('[_] Admin checking.... for uid {}'.format(item['user_id']))
  135.             if isAdmin(item['user_id']):
  136.                 print('[~] Admin checked!')
  137.                 f = open('admins', 'a+')
  138.                 fss = open('admins')
  139.                 data = fss.read().split('\n').count(item['body'].split(' ')[1])
  140.                 fss.close()
  141.                 if data >= 1:
  142.                     if 'chat_id' in item:
  143.                         write_msgg(item['chat_id'], 'пользователь существует')
  144.                         continue
  145.                     else:
  146.                         write_msgg(item['chat_id'], 'пользователь существует')
  147.                         continue
  148.                 dds = "\n"+str(item['body'].split(' ')[1])
  149.                 f.write(dds)
  150.                 f.close()
  151.                 if 'chat_id' in item:
  152.                     print('[~] Adding admin!')
  153.                     write_msgg(item['chat_id'], 'Администратор добавлен')
  154.                 else:
  155.                     print('[~] Adding admin!')
  156.                     write_msg(item['user_id'], 'Администратор добавлен')
  157.             else:
  158.                 print('[-] User not admin')
  159.                 if 'chat_id' in item:
  160.                     write_msgg(item['chat_id'], '[X] Ты не админ')
  161.                 else:
  162.                     write_msg(item['user_id'], '[X] Ты не админ')
  163.         elif item['body'].lower() == 'загруженность':
  164.             if 'chat_id' in item:
  165.                 write_msgg(item['chat_id'], 'Загруженность - {}%'.format(getcpuu()))
  166.             else:
  167.                 write_msg(item['user_id'], 'Загруженность - {}%'.format(getcpuu()))
  168.         elif item['body'].split(" ")[0].lower() == 'кто':
  169.             if 'chat_id' in item:
  170.                 if item['body'].lower().count("саня") >= 1:
  171.                     print('[-] Filter find admin name')
  172.                     write_msgg(item['chat_id'], 'тссс, админ тебя не слышит')
  173.                     continue
  174.                 elif item['body'].lower().count("sanya") >= 1 or item['body'].lower().count("саня") >= 1 or item['body'].lower().count("Саша") >= 1 or item['body'].lower().count("Александр") >= 1 or item['body'].lower().count("са-на") >= 1 or item['body'].lower().count("са-ня") >= 1 or item['body'].lower().count("с а н я") >= 1:
  175.                     print('[-] Filter find admin name')
  176.                     write_msgg(item['chat_id'], 'тссс, админ тебя не слышит')
  177.                     continue
  178.                 user = choice(vk.method("messages.getChat", {"chat_id":item['chat_id']})['users'])
  179.                 name = loads(requests.get("https://api.vk.com/method/users.get?user_id={}&fields=sex,first_name,last_name&v=5.52".format(user)).text)
  180.                 #print(name)
  181.  
  182.                 if name['response'][0]['first_name'].lower()+" "+name['response'][0]['last_name'].lower() == 'саня федотов':
  183.                     print('[~] Replaceing admin name to Artyr Chernyu :D')
  184.                     name['response'][0]['first_name'] = 'Артур'
  185.                     name['response'][0]['last_name'] = 'Чёрный'
  186.                     user = 260415263;
  187.                     name['response'][0]['sex'] = 2
  188.                 print('[~] Random user selector')
  189.                 write_msgg(item['chat_id'], "Я думаю что это - [id{1}|{0}] {2}, да, точно {2}".format(name['response'][0]['first_name']+" "+name['response'][0]['last_name'], user, getsex(name['response'][0]['sex'])))
  190.                
  191.             else:
  192.                 print('[-] Group chat not defined')
  193.                 write_msg(item['user_id'], 'Это только в групповой беседе')
  194.         elif item['body'].lower().split(' ')[0] == 'вероятность':
  195.             spamfilter.append(item['user_id'])
  196.             if inFilter(item['body']):
  197.                 print('[-] Filter find admin name')
  198.                 write_msgg(item['chat_id'], 'тссс, админ тебя не слышит')
  199.                 continue
  200.             if spamfilter.count(item['user_id']) >= 5:
  201.                 print('[-] Spam filter required more id')
  202.                 spamfilter = remove_signs(spamfilter)
  203.                 time.sleep(1.4)
  204.                 continue
  205.             if 'chat_id' in item:
  206.                 write_msgg(item['chat_id'], 'Вероятность этого события равна - {}%'.format(randint(0, 100)))
  207.             else:
  208.                 write_msg(item['user_id'], 'Вероятность этого события равна - {}%'.format(randint(0, 100)))
  209.         elif item['body'].lower() == 'баланс':
  210.             if 'chat_id' in item:
  211.                 write_msgg(item['chat_id'], 'Ваш баланс - {} Рублей'.format(getbalance(item['user_id'])))
  212.             else:
  213.                 write_msg(item['user_id'], 'Ваш баланс - {} Рублей'.format(getbalance(item['user_id'])))
  214.         elif item['body'].lower().split(' ')[0] == 'ставка':
  215.             if 'chat_id' in item:
  216.                 print('[~] Money price checking')
  217.                 if int(getbalance(item['user_id'])) <= 0:
  218.                     write_msgg(item['chat_id'], 'Ваш баланс равен нулю')
  219.                     print('[-] Balance equals 0')
  220.                 try:
  221.                     bal = int(item['body'].split(' ')[1])
  222.                 except IndexError:
  223.                     if 'chat_id' in item:
  224.                         write_msgg(item['chat_id'], 'Введи ставку')
  225.                         continue
  226.                     else:
  227.                         write_msg(item['user_id'], 'Введи ставку')
  228.                         continue
  229.                 if False:
  230.                     pass
  231.                 elif int(getbalance(item['user_id'])) < int(item['body'].split(' ')[1]):
  232.                     print('[-] Balance not equals number stavka')
  233.                     write_msgg(item['chat_id'], 'Не достаточно денег')
  234.                     continue
  235.                 #except IndexError:
  236.                     #write_msgg(item['chat_id'], 'Ошибка введите ставку')
  237.                     #continue
  238.                 else:
  239.                     try:
  240.                         aww = int(item['body'].split(' ')[1])
  241.                     except:
  242.                         if 'chat_id' in item:
  243.                             write_msgg(item['chat_id'], 'Выберите сумму ставки')
  244.                             print('[-] Stavka not selected')
  245.                         else:
  246.                             write_msg(item['user_id'], 'Выберите сумму ставки')
  247.                             print('[-] Stavka not selected')
  248.                         continue
  249.                     if randint(0, 2) == 1:
  250.                         try:
  251.                             award = randint(0, int(item['body'].split(' ')[1]) * 3)
  252.                         except:
  253.                             print('[-] number not selected')
  254.                             write_msgg('Введите число')
  255.                             continue
  256.                         write_msgg(item['chat_id'], 'Ваш выигрышь составил - {} Рублей'.format(award))
  257.                         print('[~] User {1} Win {0}'.format(award, item['user_id']))
  258.                         addmoney(item['user_id'], award)
  259.                     else:
  260.                         addmoney(item['user_id'], -1 * int(item['body'].split(' ')[1]))
  261.                         write_msgg(item['chat_id'], 'Упс, вы проиграли, ваш баланс - {} Рублей'.format(getbalance(item['user_id'])))
  262.                         print('[-] User {1} Lose'.format(item['user_id']))
  263.             else:
  264.                 if getbalance(item['user_id']) <= 0:
  265.                     write_msgg('Ваш баланс равен нулю')
  266.                     print('[-] Balance equals 0')
  267.                 elif getbalance(item['user_id']) < int( item['body'].split(' ')[1]):
  268.                     write_msgg('Ваш баланс меньше чем сумма ставки')
  269.                     print('[-] Balance equals 0')
  270.                 else:
  271.                     if randint(0, 2) == 1:
  272.                         try:
  273.                             award = randint(0, item['body'].split(' ')[1] * 3)
  274.                         except:
  275.                             write_msgg('Введите число'.format(award))
  276.                             print('[-] Number not selected')
  277.                             continue
  278.                         write_msgg('Ваш выигрышь составил - {}'.format(award))
  279.                         addmoney(item['user_id'], award)
  280.                     else:
  281.                         addmoney(item['user_id'], -2 * int(item['body'].split(' ')[1]))
  282.                         write_msg(item['user_id'], 'Упс, вы проиграли, ваш баланс - {} Рублей'.format(getbalance(item['user_id'])))
  283.         elif item['body'].lower().split(' ')[0] == 'add_money':
  284.             if int(getbalance(item['user_id'])) <= 0:
  285.                 addmoney(item['user_id'], int(2000))
  286.                 if 'chat_id' in item:
  287.                     write_msgg(item['chat_id'], 'Баланс пополнен, теперь он составляет - {}'.format(getbalance(item['user_id'])))
  288.                 else:
  289.                     write_msg(item['user_id'], 'Баланс пополнен, теперь он составляет - {}'.format(getbalance(item['user_id'])))
  290.             else:
  291.                 if 'chat_id' in item:
  292.                     write_msgg(item['chat_id'], 'У вас не нулевой счёт')
  293.                 else:
  294.                     write_msg(item['user_id'], 'У вас не нулевой счёт')
  295.         elif item['body'].lower() == 'рандом':
  296.             if 'chat_id' in item:
  297.                 write_msgg(item['chat_id'], 'Твоё рандомное число - {} 😎'.format(randint(0, 10000)))
  298.             else:
  299.                 write_msg(item['user_id'], 'Твоё рандомное число - {} 😎'.format(randint(0, 10000)))
  300.         elif item['body'].lower().split(' ')[0] == 'зашифровать':
  301.             print('[~] Encrrypt message start')
  302.             key = randint(0, 1000)
  303.             #print('else')
  304.             string = ""
  305.             ccs = 0
  306.             for i in item['body']:
  307.                 if ccs == 0:
  308.                     ccs += 1
  309.                     continue
  310.                 else:
  311.                     string += i+""
  312.                    
  313.             crp = ""
  314.             for i in string:
  315.                 crp += chr(ord(i) ^ key)
  316.             crp = temp_encrypt(str(key))+":"+str(crp)
  317.             if 'chat_id' in item:
  318.                 write_msgg(item['chat_id'], 'Зашифрованное сообщение:\n{}'.format(crp))
  319.                 print('[~] Crypting message, crypted - {0}, decrypted - {1}'.format(crp, item['body'][10:]))
  320.             else:
  321.                 write_msg(item['user_id'], 'Зашифрованное сообщение:\n{}'.format(crp))
  322.         elif item['body'].lower().split(' ')[0] == 'дешифровать':
  323.             print('[~] decrypt message stage')
  324.             encstr = ""
  325.             ccs = 0
  326.             for i in item['body'].split(' '):
  327.                 if ccs == 0:
  328.                     ccs += 1
  329.                     continue
  330.                 encstr += i
  331.             decstring = ""
  332.             key = temp_decrypt(encstr.split(":")[0])
  333.             realenc = encstr.split(":")[1]
  334.             for i in realenc:
  335.                 decstring += chr(ord(i) ^ int(key))
  336.  
  337.             if 'chat_id' in item:
  338.                 try:
  339.                     write_msgg(item['chat_id'], 'Расшифрованно - {}'.format(decstring[10:]))
  340.                 except IndexError:
  341.                     write_msgg(item['chat_id'], 'Неправильный шифр')
  342.                     continue
  343.             else:
  344.                 try:
  345.                     write_msg(item['user_id'], 'Расшифрованно - {}'.format(decstring[10:]))
  346.                 except IndexError:
  347.                     write_msgg(item['user_id'], 'Неправильный шифр')
  348.                     continue
  349.         elif item['body'].lower().split(' ')[0] == 'скажи':
  350.             if isAdmin(item['user_id']):
  351.                 arr = item['body'].split(' ')
  352.                 del arr[0]
  353.                 string = ""
  354.                 for i in arr:
  355.                     string += i+" "
  356.                 if 'chat_id' in item:
  357.                     write_msgg(item['chat_id'], string)
  358.                 else:
  359.                     write_msgg(item['user_id'], string)
  360.             else:
  361.                 if 'chat_id' in item:
  362.                     write_msgg(item['chat_id'], '[X] Вы не админ')
  363.                 else:
  364.                     write_msgg(item['user_id'], '[X] Вы не админ')
  365.         elif item['body'].split(' ')[0] == 'учи':
  366.             print('teach')
  367.             try:
  368.                 addreaction(item['body'].split('-;-')[0][3:], item['body'].split('-;-')[1])
  369.             except IndexError:
  370.                 if 'chat_id' in item:
  371.                     write_msgg(item['chat_id'], 'Не правильное заполнение')
  372.                     continue
  373.                 else:
  374.                     write_msg(item['user_id'], 'Не правильное заполнение')
  375.                     continue
  376.             if 'chat_id' in item:
  377.                 write_msgg(item['chat_id'], 'Реакция добавлена')
  378.             else:
  379.                 write_msg(item['user_id'], 'Реакция добавлена')
  380.         elif item['body'].lower() == 'помощь':
  381.             if 'chat_id' in item:
  382.                 write_msgg(item['chat_id'], '''
  383. Команды для бота:
  384. 1)Кто (Условие) - работает только в групповой беседе, выбирает случайного участника
  385. 2)Ставка (Сумма ставки) - Попытать удачу на рандоме
  386. 3)Рандом - случайное число от 0 до 10000
  387. 4)Зашифровать (что шифровать) - шифрует то что вы напишите
  388. 5)Дешифровать (что дешифровать) - дешифрует то зашифрованный текст
  389. 6)Скажи (что сказать) (Доступно только админам) скажет текст
  390. 7)admins - посмотреть админов
  391. 8)Вероятность (событие)- вычисляет вероятность в процентах события
  392. 9)баланс - узнать свой баланс
  393.                 ''')
  394.             else:
  395.                 write_msg(item['user_id'], '''
  396. Команды для бота:
  397. 1)Кто (Условие) - работает только в групповой беседе, выбирает случайного участника
  398. 2)Ставка (Сумма ставки) - Попытать удачу на рандоме
  399. 3)Рандом - случайное число от 0 до 10000
  400. 4)Зашифровать (что шифровать) - шифрует то что вы напишите
  401. 5)Дешифровать (что дешифровать) - дешифрует то зашифрованный текст
  402. 6)Скажи (что сказать) (Доступно только админам) скажет текст
  403. 7)admins - посмотреть админов
  404. 8)Вероятность (событие)- вычисляет вероятность в процентах события
  405. 9)баланс - узнать свой баланс
  406.                 ''')
  407.         else:
  408.             while True:
  409.                 reactiond = get_reaction(item['body'])
  410.                 if reactiond.strip() != '':
  411.                     break
  412.             if reactiond == '...':
  413.                 continue
  414.             if 'chat_id' in item:
  415.                 write_msgg(item['chat_id'], reactiond)
  416.             else:
  417.                 write_msg(item['user_id'], reactiond)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement