Ejemplo n.º 1
0
            sys.stdout = stdout
            yield stdout
            sys.stdout = old

        with stdoutIO() as s:
            exec(msg['argument'], local_globals, {})

        text = s.getvalue().replace(' ', ' ').replace('    ', ' ')
        print(
            kb.vkapi('messages.send', {
                "message": text,
                "peer_id": msg['peer_id']
            }))


kb.reg_command(ExecuteCmd())


class PyExec:
    level = 555
    keywords = ['ебал', 'exec']

    def handler(self, msg):
        msg = libkb.fix_names(msg)
        exec(msg['user_text'].replace('»', '	'))


kb.reg_command(PyExec())


class terminal:
Ejemplo n.º 2
0
		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())
		
kb.reg_command(citgen())
Ejemplo n.º 3
0
import kb


def f():
    pass


kb.reg_handler('first1', f)


class SuperCmd:
    level = 1
    keywords = ['йцй']

    def handler(self, msg):
        #print(msg)
        print(kb.vkapi('users.get', {'user_ids': 1}))
        print(
            kb.vkapi('messages.send', {
                "message": 'test',
                "peer_id": msg['peer_id']
            }))


kb.reg_command(SuperCmd())

#kb.log_write('sos')

#print(kb.vkapi('groups.getTokenPermissions'))

#print(config)
Ejemplo n.º 4
0
import kb, random, requests
import libkbot as libkb

class rip:
	level = 1
	keywords = ['rip','рип']
	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'])

kb.reg_command(rip())
Ejemplo n.º 5
0
            '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'])


kb.reg_command(findimg())
Ejemplo n.º 6
0
import re
import libkbot as libkb


class dvach:
    level = 1
    keywords = ['двач', '2ch', 'сосач', 'харкач']

    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)


kb.reg_command(dvach())
Ejemplo n.º 7
0
            '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'])


kb.reg_command(music())
Ejemplo n.º 8
0
import kb, requests
import libkbot as libkb


class cum:
    level = 1
    keywords = ['кончи', 'кончил', 'cum']

    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'])


kb.reg_command(cum())
Ejemplo n.º 9
0
            'count': '0',
            'access_token': kb.config['user_token']
        }
        count = requests.post('https://api.vk.com/method/docs.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',
            'access_token': kb.config['user_token']
        }
        items = requests.post('https://api.vk.com/method/docs.search',
                              data=param).json()['response']['items']

        attachment = ''
        if len(items) != 0:
            for item in items:
                attachment += 'doc' + str(item['owner_id']) + '_' + str(
                    item['id']) + ','
            libkb.apisay('Документы по вашему запросу',
                         msg['toho'],
                         attachment=attachment)
        else:
            libkb.apisay('Документы по запросу не найдены :(', msg['toho'])


kb.reg_command(docs())
Ejemplo n.º 10
0
import kb, random, requests, untangle, traceback, time
import libkbot as libkb

class r34:
	level = 1
	keywords = ['арт','хентай','art','hentai','бура','booru']
	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'])
kb.reg_command(r34())
Ejemplo n.º 11
0
                    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'])


kb.reg_command(weather())
Ejemplo n.º 12
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']
            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'])


kb.reg_command(vietnam())
Ejemplo n.º 13
0
            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()


kb.reg_command(kek())
Ejemplo n.º 14
0
		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'])
kb.reg_command(punto())
Ejemplo n.º 15
0
import kb, random, requests, re
import libkbot as libkb
from bs4 import BeautifulSoup as bs


class bash:
    level = 1
    keywords = ['баш', 'bash']

    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'])


kb.reg_command(bash())
Ejemplo n.º 16
0
import kb, json, os
import libkbot as libkb


class quote:
    level = 1
    keywords = ['цитата', 'цит']

    def handler(self, msg):
        msg = libkb.fix_names(msg)

        msg['config'] = kb.config
        arg = json.dumps(msg)
        os.system("python3 plugins/quote/quote.py '" + arg + "'")


kb.reg_command(quote())
Ejemplo n.º 17
0
    keywords = ['говнокод', 'govnokod', 'гв']

    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'])


kb.reg_command(govnokod())
Ejemplo n.º 18
0
class video:
    level = 1
    keywords = ['видео', 'video']

    def handler(self, msg):
        msg = libkb.fix_names(msg)

        param = {
            'v': '5.90',
            'q': msg['user_text'],
            'offset': random.randint(0, 100),
            'count': '10',
            'access_token': kb.config['user_token']
        }
        items = requests.post('https://api.vk.com/method/video.search',
                              data=param).json()['response']['items']

        attachment = ''
        if len(items) != 0:
            for item in items:
                attachment += 'video' + str(item['owner_id']) + '_' + str(
                    item['id']) + ','
            libkb.apisay('Видео по вашему запросу',
                         msg['toho'],
                         attachment=attachment)
        else:
            libkb.apisay('Видео по запросу не найдены :(', msg['toho'])


kb.reg_command(video())
Ejemplo n.º 19
0
        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'])


kb.reg_command(help())