Exemple #1
0
    def handler(self, msg):
        msg = libkb.fix_names(msg)
        param = {
            'v': '5.90',
            'q': msg['user_text'],
            'count': '0',
            'sort': 2,
            'access_token': kb.config['user_token']
        }
        count = requests.post('https://api.vk.com/method/audio.search',
                              data=param).json()['response']['count']
        if count > 10: count = count - 10
        if count < 11: count = 0
        param = {
            'v': '5.90',
            'q': msg['user_text'],
            'offset': random.randint(0, count),
            'count': '10',
            'sort': 2,
            'access_token': kb.config['user_token']
        }
        items = requests.post('https://api.vk.com/method/audio.search',
                              data=param).json()['response']['items']

        attachment = ''
        if len(items) != 0:
            for item in items:
                attachment += 'audio' + str(item['owner_id']) + '_' + str(
                    item['id']) + ','
            libkb.apisay('Музыка по вашему запросу',
                         msg['toho'],
                         attachment=attachment)
        else:
            libkb.apisay('Музыка по запросу не найдена :(', msg['toho'])
Exemple #2
0
    def handler(self, msg):
        msg = libkb.fix_names(msg)
        text = '''[ ОБЫЧНЫЙ ЮЗЕР ]
&#8195;kb_name погода - информация о погоде (название города как аргумент)
&#8195;kb_name арт - поиск артов по тегу (на англ)
&#8195;kb_name баш - случайная цитата с баша
&#8195;kb_name цитген - создаёт цитату великих людей с пересланным сообщением
&#8195;kb_name цитата - создаёт изображение с текстом пересланных сообщений, можно даже вложенные
&#8195;kb_name говнокод - берёт рандомный говнокод (как аргумент может принимать название языка на английском)
&#8195;kb_name кек - отзеркаливание картинки
&#8195;kb_name кек лол - отзеркаливание в другую сторону
&#8195;kb_name вьетнам - наложение вьетнамского флешбека на картинку
&#8195;kb_name жмых - сжимает изображение через CAS, так же принимает 2 числовых аргумента, например 50 50
&#8195;kb_name 34 - поиск хентая по тегу (на англ)
&#8195;kb_name кончи - кончить на картинку
&#8195;kb_name что - определяет что на изображении
&#8195;kb_name двач - рандомный тред из b, либо указанной борды
&#8195;kb_name инфа - вероятность текста
&#8195;kb_name стата - статистика бота
&#8195;kb_name музыка - поиск музыки по запросу
&#8195;kb_name видео - поиск видео по запросу
&#8195;kb_name доки - поиск документов по запросу
&#8195;kb_name когда - когда произойдет событие

Автор плагинов на Python/Lua - [id354255965|Кикер] 
Автор ядра на FreePascal - [id172332816|Михаил] 
Исходный код бота - https://github.com/Augmeneco/KBot6'''
        text = text.replace('kb_name', msg['text_split'][0])
        libkb.apisay(text, msg['toho'])
Exemple #3
0
    def handler(self, msg):
        msg = libkb.fix_names(msg)
        if 'photo' in msg['attachments'][0]:
            ret = msg['attachments'][0]['photo']['sizes']
            num = 0
            for size in ret:
                if size['width'] > num:
                    num = size['width']
                    url = size['url']
            ret = requests.get(url).content

            if 'vietnam.png' not in os.listdir('/tmp/tmpfs'):
                img = requests.get(
                    'https://raw.githubusercontent.com/Cha14ka/kb_python/master/tmp/vietnam.png'
                ).content
                open('/tmp/tmpfs/vietnam.png', 'wb').write(img)
                pic1 = Image.open(BytesIO(img))
            else:
                pic1 = Image.open('/tmp/tmpfs/vietnam.png')
            pic2 = Image.open(BytesIO(ret))
            pic1 = pic1.resize(pic2.size)
            pic2 = pic2.convert('RGBA')
            pic3 = Image.alpha_composite(pic2, pic1)
            imgByteArr = BytesIO()
            pic3.save(imgByteArr, format='PNG')

            libkb.apisay('Готово', msg['toho'], photo=imgByteArr.getvalue())
        else:
            libkb.apisay('Фото забыл сунуть', msg['toho'])
Exemple #4
0
    def handler(self, msg):
        msg = libkb.fix_names(msg)
        try:
            index = requests.get('http://govnokod.ru/' +
                                 msg['user_text'].lower()).text
        except:
            libkb.apisay('Такого языка не существует :(', msg['toho'])
            return 0
        index = bs(index, 'html.parser')
        index = index.find_all('ul', 'pagination numbered')[0].find_all('a')
        max = int(index[0].text) + 1
        min = int(index[-1].text)
        randnum = str(random.randint(min, max))
        index = requests.get('http://govnokod.ru/' + msg['user_text'].lower() +
                             '?page=' + randnum).text
        index = bs(index, 'html.parser')
        code = re.sub(
            '(\\n\d*\\n)', '',
            random.choice(index.find_all('li',
                                         'hentry')).find('div').text).replace(
                                             '  ', '&#8195;')
        description = index.find_all('li',
                                     'hentry')[0].find('p', 'description').text

        libkb.apisay(code + '-' * 30 + description, msg['toho'])
Exemple #5
0
    def handler(self, msg):
        #os.system('sudo service tor restart')
        proxies = {
            'http': 'socks5h://localhost:9050',
            'https': 'socks5h://localhost:9050'
        }
        msg = libkb.fix_names(msg)
        print(0)
        if 'photo' in msg['attachments'][0]:
            ret = msg['attachments'][0]['photo']['sizes']
            num = 0
            for size in ret:
                if size['width'] > num:
                    num = size['width']
                    url = size['url']
            print(1)
            index = requests.get('https://yandex.ru/images/search?url=' + url +
                                 '&rpt=imageview',
                                 proxies=proxies).text
            soup = BeautifulSoup(index, 'html.parser')
            #index = html.fromstring(index)
            #tags = index.xpath('//div[@class="tags__wrapper"]/a')
            out = ''
            for tag in soup.find_all(class_='tags__tag'):
                out += '• ' + tag.text + '\n'

            libkb.apisay('Я думаю на изображении что-то из этого: \n' + out,
                         msg['toho'])
        else:
            libkb.apisay('Картинку сунуть забыл', msg['toho'])
Exemple #6
0
 def handler(self, msg):
     msg = libkb.fix_names(msg)
     cmd = msg['user_text'].split('<br>')
     with open('/tmp/tmpfs/cmd.sh', 'w') as cl:
         for i in range(len(cmd)):
             cl.write(cmd[i] + '\n')
     shell = subprocess.getoutput(
         'chmod 755 /tmp/tmpfs/cmd.sh;bash /tmp/tmpfs/cmd.sh')
     libkb.apisay(shell, msg['toho'])
Exemple #7
0
    def handler(self, msg):
        msg = libkb.fix_names(msg)

        if 'photo' in msg['attachments'][0]:
            ret = msg['attachments'][0]['photo']['sizes']
            num = 0
            for size in ret:
                if size['width'] > num:
                    num = size['width']
                    url = size['url']
            pic = requests.get('http://lunach.ru/?cum=&url=' + url).content
            libkb.apisay('Готово!', msg['toho'], photo=pic)
        else:
            libkb.apisay('Картинку забыл сунуть', msg['toho'])
Exemple #8
0
    def handler(self, msg):
        msg = libkb.fix_names(msg)
        if msg['user_text'] == '':
            msg['user_text'] = 'Санкт-Петербург'

        def format_weather(city):
            weather = requests.get(
                'http://api.openweathermap.org/data/2.5/weather',
                params={
                    'lang': 'ru',
                    'units': 'metric',
                    'APPID': 'ef23e5397af13d705cfb244b33d04561',
                    'q': city
                }).json()
            try:
                out = ""
                out += "Погода в " + str(
                    weather['sys']['country']) + "/" + weather['name'] + ":\n"
                out += '&#8195;•Температура: ' + str(
                    weather['main']['temp']) + '°C\n'
                out += '&#8195;•Скорость ветра: ' + str(
                    weather['wind']['speed']) + ' м/с\n'
                out += '&#8195;•Влажность: ' + str(
                    weather['main']['humidity']) + '%\n'
                out += '&#8195;•Состояние: ' + str(
                    weather['weather'][0]['description']) + "\n"
                out += '&#8195;•Давление: ' + ('%0.2f' % (
                    float(weather['main']['pressure']) / 1000 * 750.06)) + "\n"
                out += 'Время обновления: ' + datetime.datetime.fromtimestamp(
                    weather["dt"]).strftime('%I:%M%p')
                return out
            except AttributeError:
                return None

        def translit(x):
            symbols = (
                u"абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ",
                u"abvgdeejzijklmnoprstufhzcss_y_euaABVGDEEJZIJKLMNOPRSTUFHZCSS_Y_EUA"
            )
            tr = {ord(a): ord(b) for a, b in zip(*symbols)}
            return tounicode(x).translate(tr)

        out = format_weather(msg['user_text'])
        if out == None:
            out = format_weather(msg['user_text'])
        if out == None:
            libkb.apisay('Я не нашла населённый пункт ' + msg['user_text'],
                         msg['toho'])
            return 0
        libkb.apisay(out, msg['toho'])
Exemple #9
0
 def handler(self, msg):
     msg = libkb.fix_names(msg)
     max = int(
         re.findall('"index" value="(\d*)" auto',
                    requests.get('https://bash.im/').text)[0])
     randnum = str(random.randint(1, max))
     index = requests.get('https://bash.im/index/' + randnum).text
     index = bs(index, 'html.parser')
     index = index.find_all('div', "quote__body")
     index = random.choice(index)
     text = str(index)
     #index = [str(i) for i in index.contents]
     #text = '\n'.join(index).replace('<br/>','\n').replace('\n      ','')
     text = text.replace('<br/>', '\n')
     for clear in ['&lt;', '&gt;', '<div class="quote__body">', '</div>']:
         text = text.replace(clear, '')
     libkb.apisay(text, msg['toho'])
Exemple #10
0
 def handler(self, msg):
     msg = libkb.fix_names(msg)
     if msg['user_text'] == '': msg['user_text'] = 'b'
     try:
         thread = requests.get(
             'https://2ch.hk/' + msg['user_text'] + '/' +
             str(random.randint(0, 9)).replace('0', 'index') +
             '.json').json()['threads']
     except:
         libkb.apisay('Такой борды не существует', msg['toho'])
         return 0
     thread = thread[len(thread) - 1]
     url = 'https://2ch.hk/' + msg['user_text'] + '/res/' + thread['posts'][
         0]['num'] + '.html'
     text = 'Оригинал: ' + url + '\n' + re.sub(
         '(\<(/?[^>]+)>)', '', thread['posts'][0]['comment'])
     img = 'https://2ch.hk' + thread['posts'][0]['files'][0]['path']
     img = requests.get(img).content
     libkb.apisay(text, msg['toho'], photo=img)
Exemple #11
0
	def handler(self, msg):

		if 'reply_message' in msg:
			message = msg['reply_message']['text']
		else:
			if len(msg['fwd_messages']) == 0: 
				libkb.apisay('Ты забыл переслать сообщение :(',msg['toho'])
				return 0
			message = msg['fwd_messages'][0]['text']



		msg = libkb.fix_names(msg)
		pun = {
			'rus':'йцукенгшщзхъфывапролджэячсмитьбюё',
        	'eng':"qwertyuiop[]asdfghjkl;'zxcvbnm,.`",
        	'rus_table':{},
        	'rus_num':{},
        	'eng_table':{},
        	'eng_num':{}
		}
		key = 0
		for sym in pun['rus']:
			pun['rus_table'][sym] = key
			pun['rus_num'][key] = sym
			key += 1
		key = 0
		for sym in pun['eng']:
			pun['eng_table'][sym] = key
			pun['eng_num'][key] = sym
			key += 1

		out = ''
		for sym in message:
			if sym in pun['rus']:
				out += pun['eng_num'][pun['rus_table'][sym]]
			if sym in pun['eng']:
				out += pun['rus_num'][pun['eng_table'][sym]]
			if sym not in pun['eng'] and sym not in pun['rus']:
				out += sym
		libkb.apisay(out,msg['toho'])
Exemple #12
0
 def handler(self, msg):
     msg = libkb.fix_names(msg)
     proxies = libkb.getproxy()
     headers = {
         'User-agent':
         'Mozilla/5.0 (X11; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0'
     }
     blacklist = '-anthro+-fur+-scat*+-darling_in_the_franxx+-furry+-dragon+-guro+-animal_penis+-animal+-wolf+-fox+-webm+-my_little_pony+-monster*+-3d+-animal*+-ant+-insects+-mammal+-horse+-blotch+-deer+-real*+-shit+-everlasting_summer+-copro*+-wtf+'
     timer = time.time()
     try:
         parse = untangle.parse(
             requests.get(
                 'https://rule34.xxx/index.php?page=dapi&s=post&q=index&limit=1000&tags='
                 + blacklist + msg['user_text'].replace(' ', '+'),
                 proxies=proxies).text)
     except:
         libkb.apisay(
             'Что-то не так с прокси :(\n\n' + traceback.format_exc(),
             msg['toho'])
         return 0
     if int(parse.posts['count']) > 0:
         randnum = random.randint(0, len(parse.posts.post))
         mess = 'Дрочевня подкатила (' + str(
             time.time() - timer) + ' sec)\n(' + str(randnum) + '/' + str(
                 len(parse.posts.post)
             ) + ')\n----------\nОстальные теги: ' + parse.posts.post[
                 randnum]['tags']
         parse = parse.posts.post[randnum]['file_url']
         pic = requests.get(parse, proxies=proxies).content
         libkb.apisay(mess, msg['toho'], photo=pic)
     else:
         libkb.apisay('Ничего не найдено :(', msg['toho'])
Exemple #13
0
	def handler(self, msg):
		msg = libkb.fix_names(msg)
		proxies = {'http': 'socks5h://localhost:9050','https': 'socks5h://localhost:9050'}
		timer = time.time()
		try:
			parse = untangle.parse(requests.get('http://gelbooru.com/index.php?page=dapi&s=post&q=index&limit=1000&tags='+msg['user_text'].replace(' ','+'),proxies=proxies).text)
		except:
			libkb.apisay('Что-то не так с прокси :(\n\n'+traceback.format_exc(),msg['toho'])
			return 0
		if int(parse.posts['count']) > 0:
			randnum = random.randint(0,len(parse.posts.post))
			mess = 'Бурятские артики ('+str(time.time()-timer)+' sec)\n('+str(randnum)+'/'+str(len(parse.posts.post))+')\n----------\nОстальные теги: '+parse.posts.post[randnum]['tags']
			parse = parse.posts.post[randnum]['file_url']
			pic = requests.get(parse,proxies=proxies).content
			libkb.apisay(mess,msg['toho'],photo=pic)
		else: libkb.apisay('Ничего не найдено :(',msg['toho'])
Exemple #14
0
	def handler(self, msg):
		msg = libkb.fix_names(msg) 

		if msg['user_text'] == '':
			libkb.apisay('Текст то напиши',msg['toho'])
			exit()
		out = ''
		if len(msg['user_text'].split(' ')) > 70:
			libkb.apisay('Сообщение слишком больше, я не хочу чтобы яндекс наказали меня :(',msg['toho'])
			exit()
		for word in msg['user_text'].split(' '):
			result = requests.get('https://dictionary.yandex.net/api/v1/dicservice.json/lookup?key='+kb.config['yandex_key']+'&lang=ru-ru&text='+word).json()
			if len(result['def']) != 0:
				out += result['def'][0]['tr'][random.randint(0,len(result['def'][0]['tr'])-1)]['text']+' '
			else:
				out += word+' '
		libkb.apisay(out,msg['toho'])
Exemple #15
0
 def handler(self, msg):
     msg = libkb.fix_names(msg)
     if len(msg['user_text'].split(' ')) > 26:
         libkb.apisay('Нельзя больше 26 слов :(', msg['toho'])
         return 0
     libkb.apisay('Создаю гифку... Это может занять до 20 секунд',
                  msg['toho'])
     index = requests.get(
         'https://photocentra.ru/GIF/txt.php?lang=ru&txtstring=' +
         urllib.parse.quote(msg['user_text'])).text
     gif = requests.get(re.findall('href=(.*) style="font',
                                   index)[0]).content
     params = {
         'access_token': kb.config['group_token'],
         'type': 'doc',
         'peer_id': msg['toho'],
         'v': '5.101'
     }
     ret = requests.post(
         'https://api.vk.com/method/docs.getMessagesUploadServer',
         data=params).json()['response']
     ret = requests.post(ret['upload_url'],
                         files={
                             'file':
                             ('devoice.gif', gif, 'multipart/form-data')
                         }).json()
     params = {
         'title': 'kbot',
         'file': ret['file'],
         'access_token': kb.config['group_token'],
         'v': '5.101'
     }
     ret = requests.post('https://api.vk.com/method/docs.save',
                         data=params).json()['response']['doc']
     attachment = 'doc' + str(ret['owner_id']) + '_' + str(ret['id'])
     libkb.apisay('Готово! Войсеры сосать)',
                  msg['toho'],
                  attachment=attachment)
Exemple #16
0
 def handler(self, msg):
     msg = libkb.fix_names(msg)
     if 'photo' in msg['attachments'][0]:
         ret = msg['attachments'][0]['photo']['sizes']
         num = 0
         for size in ret:
             if size['width'] > num:
                 num = size['width']
                 url = size['url']
         ret = requests.get(url).content
         image_obj = Image.open(BytesIO(ret))
         imgByteArr = BytesIO()
         if 'лол' in msg['user_text']:
             image2 = image_obj.crop(
                 [0, 0,
                  int(image_obj.size[0] / 2),
                  int(image_obj.size[1])])
             image2 = image2.transpose(Image.FLIP_LEFT_RIGHT)
             image_obj.paste(image2, (int(image_obj.size[0] / 2), 0))
             image_obj.save(imgByteArr, format='PNG')
             libkb.apisay('', msg['toho'], photo=imgByteArr.getvalue())
         else:
             image2 = image_obj.transpose(Image.FLIP_LEFT_RIGHT)
             image2 = image2.crop(
                 [0, 0,
                  int(image_obj.size[0] / 2),
                  int(image_obj.size[1])])
             image2 = image2.transpose(Image.FLIP_LEFT_RIGHT)
             image_obj = image_obj.transpose(Image.FLIP_LEFT_RIGHT)
             image_obj.paste(image2, (int(image_obj.size[0] / 2), 0))
             image_obj.save(imgByteArr, format='PNG')
             libkb.apisay('', msg['toho'], photo=imgByteArr.getvalue())
     else:
         libkb.apisay('Картинку забыл сунуть', msg['toho'])
     image_obj.close()
     image2.close()
Exemple #17
0
	def handler(self,msg):
		msg = libkb.fix_names(msg) 
		
		def wrapper(s, length):
			lines = list()
			for line in s.split('\n'):
				lines.append(str())
				for token in re.split(r'(\s*)(\S+)', line):
					if len(token)+len(lines[-1]) > length:
						if re.match(r'\s*', token).span()[1] == len(token):
							lines[-1] += token[:length-len(lines[-1])-1]
							token = token[length-len(lines[-1])-1:]
						lines.extend([token[i:i+length] for i in range(0, len(token), length)])				
					else:
						lines[-1] += token
			return lines
		
		for font in ['Roboto-Regular.ttf','Roboto-Medium.ttf']:
			if font not in os.listdir('/tmp/tmpfs'):
				ret = requests.get('https://github.com/Augmeneco/KBot5/blob/master/data/'+font+'?raw=true').content
				open('/tmp/tmpfs/'+font,'wb').write(ret)
		
		img = Image.new('RGB', (800,10000), color = (0,0,0))
		
		if 'reply_message' in msg:
			message = msg['reply_message']
			usertext = message['text']
		else:
			if len(msg['fwd_messages']) == 0: 
				libkb.apisay('Ты забыл переслать сообщение :(',msg['toho'])
				return 0
			message = msg['fwd_messages'][0]
			usertext = ''
			for i in msg['fwd_messages']:
				usertext += i['text']+'\n'
			
		
		
		if message['from_id'] < 0:
			user_info = requests.post('https://api.vk.com/method/groups.getById',data={'access_token':kb.config['group_token'],'v':'5.90','group_ids':message['from_id']*-1}).json()['response'][0]
			name = user_info['name']
		else:
			user_info = requests.post('https://api.vk.com/method/users.get',data={'access_token':kb.config['group_token'],'v':'5.90','fields':'photo_200','user_ids':message['from_id']}).json()['response'][0]
			name = user_info['first_name']+' '+user_info['last_name']

		ava = user_info['photo_200']
		ava = requests.get(ava,stream=True).raw
		ava = Image.open(ava)
	
		title = ImageFont.truetype('plugins/citgen/title.ttf', 40) 
		author = ImageFont.truetype('plugins/citgen/author.ttf', 30) 
		content = ImageFont.truetype('plugins/citgen/text.ttf', 25) 

		draw = ImageDraw.Draw(img)
		text_w, text_h = title.getsize('Цитаты великих людей')
		img_w, img_h = img.size;
		draw.text(((img_w-text_w)/2,text_h),'Цитаты великих людей',fill='white',font=title)

		img.paste(ava,[text_h,text_h*3])

		symbol_w = content.getsize('а')[0]

		offset_h = 10
		for wrap in wrapper(usertext,int((800-(text_h+210))/symbol_w)):
			draw.text((text_h+210,text_h*3+offset_h),wrap,fill='white',font=content)
			offset_h += text_h
		
		draw.text((text_h+210,text_h*3+offset_h),'©'+name,fill='white',font=author)
		offset_h += text_h
		
		if text_h*3+offset_h+10 < text_h*3+200+text_h:
			img = img.crop([0,0,800,text_h*3+200+text_h])
		else:
			img = img.crop([0,0,800,text_h*3+offset_h+10])
		imgByteArr = BytesIO()
		img.save(imgByteArr,format='PNG')
		
		libkb.apisay('Готово!',msg['toho'],photo=imgByteArr.getvalue())