def test_delete(self): resp = yield from aiohttp.post( self.full_url(self.app.reverse('fruit_index')), data=json.dumps(dict(name='grape', colors=['purple'])), ) self.assertEqual(resp.status, 200) resp.close() resp = yield from aiohttp.get( self.full_url(self.app.reverse('fruit_item', id='grape')) ) self.assertEqual(resp.status, 200) jr = yield from resp.json() self.assertEqual(jr['body'], dict(colors=['purple'])) resp.close() resp = yield from aiohttp.delete( self.full_url(self.app.reverse('fruit_item', id='grape')) ) self.assertEqual(resp.status, 200) resp.close() resp = yield from aiohttp.get( self.full_url(self.app.reverse('fruit_item', id='grape')) ) self.assertEqual(resp.status, 404) resp.close()
async def ponyr(self, *text): """Retrieves a random result from Derpibooru""" if len(text) > 0: if len(text[0]) > 1 and len(text[0]) < 20: try: msg = "+".join(text) search = "https://derpiboo.ru/search.json?q=" + msg + "&random_image=y" async with aiohttp.get(search) as r: result = await r.json() if "id" in result: imgid = str(result["id"]) async with aiohttp.get("https://derpiboo.ru/images/" + imgid + ".json") as r: result = await r.json() url = "http:" + result["image"] await self.bot.say(url) else: await self.bot.say("Your search terms gave no results.") except: await self.bot.say("Error.") else: await self.bot.say("Invalid search.") else: async with aiohttp.get("https://derpiboo.ru/search.json?q=*&random_image=y") as r: result = await r.json() imgid = str(result["id"]) async with aiohttp.get("https://derpiboo.ru/images/" + imgid + ".json") as r: result = await r.json() url = result["image"] await self.bot.say("http:" + url )
def test_parent_url(self): resp = yield from aiohttp.get( self.full_url( self.app.reverse('singlestatsresource_index', fruit_id='orange') ) ) j = yield from resp.json() resp.close() assert j['parent'].endswith('/fruit/orange') resp2 = yield from aiohttp.get( self.full_url( self.app.reverse('globalstatsresource_index') ) ) j2 = yield from resp2.json() resp2.close() assert j2['parent'].endswith('/fruit') resp2 = yield from aiohttp.get( self.full_url( self.app.reverse('viewbasedstats') ) ) j2 = yield from resp2.json() resp2.close() assert j2['count'] == 3
def test_update(self): resp = yield from aiohttp.post( self.full_url(self.app.reverse('fruit_index')), data=json.dumps(dict(name='pear', colors=['green'])), ) self.assertEqual(resp.status, 200) resp.close() resp = yield from aiohttp.get( self.full_url(self.app.reverse('fruit_item', id='pear')) ) self.assertEqual(resp.status, 200) jr = yield from resp.json() self.assertEqual(jr['body'], dict(colors=['green'])) resp.close() resp = yield from aiohttp.put( self.full_url(self.app.reverse('fruit_item', id='pear')), data=json.dumps(dict(colors=['green', 'yellow'])), ) self.assertEqual(resp.status, 200) resp.close() resp = yield from aiohttp.get( self.full_url(self.app.reverse('fruit_item', id='pear')) ) self.assertEqual(resp.status, 200) jr = yield from resp.json() self.assertEqual(jr['body'], dict(colors=['green', 'yellow'])) resp.close()
async def getrecords(self, ctx, game: str=None): """Gets records for the specified game""" server = ctx.message.server record_list = [] if game is None: if server.id in self.settings["servers"]: game = self.settings["servers"][server.id] else: await self.bot.say("No game specified and no default for the server!") categories_url = "http://www.speedrun.com/api/v1/games/{}/categories".format(game) async with aiohttp.get(categories_url) as cat_req: cat_list = await cat_req.json() if "status" in cat_list and cat_list["status"] == 404: await self.bot.say(cat_list["message"]) else: for cat in cat_list["data"]: cat_record = {} record_url = "http://speedrun.com/api/v1/leaderboards/{}/category/{}".format(game, cat["id"]) async with aiohttp.get(record_url) as record_req: lead_list = await record_req.json() async with aiohttp.get("http://speedrun.com/api/v1/games/{}".format(game)) as game_get: game_info = await game_get.json() cat_record["game_name"] = game_info["data"]["names"]["international"] cat_record["cat_info"] = cat print(cat["id"]) if "data" in lead_list: if len(lead_list["data"]["runs"]) > 0: cat_record["record"] = lead_list["data"]["runs"][0] record_list.append(cat_record) await self.wr_menu(ctx, record_list, message=None, page=0, timeout=30)
async def ponyr(self, ctx, *text): """Retrieves a random result from Derpibooru""" server = ctx.message.server if server.id in self.activefilters: ponyfilter = self.activefilters[server.id] else: ponyfilter = "default" if len(text) > 0: try: msg = "+".join(text) search = "https://derpiboo.ru/search.json?q=" + msg + "&random_image=y&filter_id=" + self.availablefilters[ponyfilter] async with aiohttp.get(search) as r: result = await r.json() if "id" in result: imgid = str(result["id"]) async with aiohttp.get("https://derpiboo.ru/images/" + imgid + ".json") as r: result = await r.json() url = "http:" + result["image"] await self.bot.say(url) else: await self.bot.say("Your search terms gave no results.") except: await self.bot.say("Error.") else: async with aiohttp.get("https://derpiboo.ru/search.json?q=*&random_image=y&filter_id=" + self.availablefilters[ponyfilter]) as r: result = await r.json() imgid = str(result["id"]) async with aiohttp.get("https://derpiboo.ru/images/" + imgid + ".json") as r: result = await r.json() url = result["image"] await self.bot.say("http:" + url )
async def test_get_protocol_list(self): async with aiohttp.get('http://127.0.0.1:8080/api/v1/device_protocols') as r: self.assertEqual(r.status, 200) rst = await r.json() self.assertDictEqual(rst, DEVICE_PROTOCOLS) async with aiohttp.get('http://127.0.0.1:8080/api/v1/term_protocols') as r: self.assertEqual(r.status, 200) rst = await r.json() self.assertDictEqual(rst, TERM_PROTOCOLS)
async def gwent(self, ctx, *card: str): '''Gibt Informationen zu einer Gwent Karte aus Beispiel: ----------- :gwent Geralt ''' cardName = ' '.join(card) url = f'{self.APIURL}{cardName}' await self.bot.send_typing(ctx.message.channel) async with aiohttp.get(url) as firstResult: if firstResult.status == 200: json = await firstResult.json() async with aiohttp.get(json['results'][0]['href']) as r: json = await r.json() async with aiohttp.get(json['variations'][0]['href']) as image: imagejson = await r.json() image = imagejson['art']['thumbnailImage'] tempGwentCard = 'tmp\\tempGwent.png' async with aiohttp.get(image) as img: with open(tempGwentCard, 'wb') as f: f.write(await img.read()) with open(tempGwentCard, 'rb') as f: await self.bot.send_file(ctx.message.channel, f) os.remove(tempGwentCard) rarity = json['variations'][0]['rarity']['href'] if rarity == 'https://api.gwentapi.com/v0/rarities/u0zNKy4EULa_VU4JD5r4EA': color = 0xf1c40f #Legendary elif rarity == 'https://api.gwentapi.com/v0/rarities/-naHV1zlVuCFll-j-7T1ow': color = 0x5D92B1 #Rare elif rarity == 'https://api.gwentapi.com/v0/rarities/V_ImiYfTVhG_WaAOof9Rxg': color = 0x7D61BB #Epic else: color = 0xc0c0c0 #Common embed = discord.Embed(color=color) embed.set_footer(text='UUID: ' + json['uuid']) embed.set_thumbnail(url='https://i.imgur.com/WNYBsYp.png') embed.add_field(name='Name', value=json['name'], inline=True) if json['strength'] != '' and json['strength'] != None: embed.add_field(name='Stärke', value=json['strength'], inline=True) if json['group'] != '' and json['group'] != None: embed.add_field(name='Typ', value=json['group'], inline=True) if rarity != '' and rarity != None: embed.add_field(name='Seltenheit', value=rarity, inline=True) if json['faction'] != '' and json['faction'] != None: embed.add_field(name='Fraktion', value=json['faction']['name'], inline=True) if json['positions'] != '' and json['positions'] != None: embed.add_field(name='Reihe', value=', '.join(json['positions']), inline=True) embed.add_field(name='Text', value=json['info'], inline=False) await self.bot.say(embed=embed) else: msg = f':no_entry: Ich konnte keine Gwent Karte zu **{cardName}** finden :sweat:' await self.bot.say(msg)
async def test_device_CRUD(self): async with aiohttp.get('http://127.0.0.1:8080/api/v1/devices') as r: self.assertEqual(r.status, 200) rst = await r.json() self.assertSetEqual(set(rst), {'1', '2', '3'}) async with aiohttp.get('http://127.0.0.1:8080/api/v1/devices/1') as r: self.assertEqual(r.status, 200) rst = await r.json() self.assertDictEqual(rst, mock_data.device1) async with aiohttp.get('http://127.0.0.1:8080/api/v1/devices/99') as r: self.assertEqual(r.status, 404) rst = await r.text() self.assertEqual(rst, 'device_id not found!') async with aiohttp.post('http://127.0.0.1:8080/api/v1/devices', data=json.dumps(mock_data.test_device)) as r: self.assertEqual(r.status, 200) rst = self.redis_client.hgetall('HS:DEVICE:4') self.assertEqual(rst['name'], '测试集中器4') rst = self.redis_client.sismember('SET:DEVICE', 4) self.assertTrue(rst) async with aiohttp.post('http://127.0.0.1:8080/api/v1/devices', data=json.dumps(mock_data.test_device)) as r: self.assertEqual(r.status, 409) rst = await r.text() self.assertEqual(rst, 'device already exists!') mock_data.test_device['name'] = '测试集中器5' mock_data.test_device['id'] = 5 async with aiohttp.put('http://127.0.0.1:8080/api/v1/devices/4', data=json.dumps(mock_data.test_device)) as r: self.assertEqual(r.status, 200) rst = self.redis_client.exists('HS:DEVICE:4') self.assertFalse(rst) rst = self.redis_client.sismember('SET:DEVICE', 4) self.assertFalse(rst) rst = self.redis_client.hgetall('HS:DEVICE:5') self.assertEqual(rst['name'], '测试集中器5') rst = self.redis_client.sismember('SET:DEVICE', 5) self.assertTrue(rst) async with aiohttp.put('http://127.0.0.1:8080/api/v1/devices/99', data=json.dumps(mock_data.test_device)) as r: self.assertEqual(r.status, 404) rst = await r.text() self.assertEqual(rst, 'device_id not found!') async with aiohttp.delete('http://127.0.0.1:8080/api/v1/devices/5') as r: self.assertEqual(r.status, 200) rst = self.redis_client.exists('HS:DEVICE:5') self.assertFalse(rst) rst = self.redis_client.sismember('SET:DEVICE', 5) self.assertFalse(rst) devices = [1, 2, 3] async with aiohttp.post('http://127.0.0.1:8080/api/v2/devices/del', data=json.dumps(devices)) as r: self.assertEqual(r.status, 200) rst = self.redis_client.smembers('SET:DEVICE') self.assertEqual(len(rst), 0)
def check_xpath(loop, url): crawler = CraigsListCrawler() print('fetch and parse list request: %s...' % url) r = yield from aiohttp.get(url) body = yield from r.text() response = AiohttpResponse( request=ListRequest( url=url, session_id='xpath-check', city_code=urllib.parse.urlparse(url).netloc.split('.')[0], ), body=body, ) result_by_type = defaultdict(list) for item in crawler.extract_items(response): result_by_type[type(item)].append(item) for _type, items in result_by_type.items(): print('%s count: %s' % (_type.__name__, len(items))) item_requests = result_by_type[ItemRequest] if not item_requests: print('xpath: OUT OF DATE') return request = item_requests[0] print('\nfetch and parse item request %s...' % request.url) r = yield from aiohttp.get(request.url) body = yield from r.text() response = AiohttpResponse( request=request, body=body, ) result_by_type = defaultdict(list) for item in crawler.extract_items(response): result_by_type[type(item)].append(item) for _type, items in result_by_type.items(): print('%s count: %s' % (_type.__name__, len(items))) item = result_by_type[CraigsListItem][0] if not item: print('xpath: OUT OF DATE') return ItemLogPipeline().process(crawler, item) if not all((item.title, item.price, item.description)): print('xpath: OUT OF DATE') return print('\nxpath: ACTUAL')
async def test_get_data(self): async with aiohttp.get('http://127.0.0.1:8080/api/v1/devices/1/terms/10/items/1000/datas') as r: self.assertEqual(r.status, 200) rst = await r.json() self.assertDictEqual(rst, mock_data.device1_term10_item1000) async with aiohttp.get('http://127.0.0.1:8080/api/v1/devices/1/terms/10/items/1000/datas/-1') as r: self.assertEqual(r.status, 200) rst = await r.json() self.assertDictEqual(rst, {'2015-12-01T08:50:15.000003': '102.0'}) async with aiohttp.get('http://127.0.0.1:8080/api/v1/devices/99/terms/99/items/99/datas') as r: self.assertEqual(r.status, 200) rst = await r.json() self.assertEqual(len(rst), 0)
def getPicture(url): print("getting picture") if getProxyConfig("enable") == "1": # THE PROXY INFO proxy_uri = getProxyConfig('server') proxy_user = getProxyConfig('user') proxy_pwd = getProxyConfig('password') proxy_sever = 'http://'+proxy_uri conn = aiohttp.ProxyConnector(proxy=proxy_sever, proxy_auth=aiohttp.BasicAuth(proxy_user, proxy_pwd)) response = yield from aiohttp.get(url, connector=conn) else: response = yield from aiohttp.get(url) return (yield from response.read())
async def steam(self, ctx, appid: str): '''Gibt Informationen zu einem Spiel bei Steam aus Beispiel: ----------- :steam 570 ''' await self.bot.send_typing(ctx.message.channel) steamSpyURL = f'{self.steamSpyAPIURL}?request=appdetails&appid={appid}' async with aiohttp.get(steamSpyURL) as r: spyJSON = await r.json() steamCurrentPlayerURL = f'{self.steamCurrentPlayerAPIURL}{appid}' async with aiohttp.get(steamCurrentPlayerURL) as r: currentPlayerJSON = await r.json() steamMarketURL = f'{self.steamMarketAPIURL}{appid}' async with aiohttp.get(steamMarketURL) as r: marketJSON = await r.json() owner = '{:,}'.format(spyJSON['owners']).replace(',', '.') owner += ' ± ' owner += '{:,}'.format(spyJSON['owners_variance']).replace(',', '.') try: price = str(int(marketJSON[appid]['data']['price_overview']['final']) / 100) + '€' if marketJSON[appid]['data']['price_overview']['discount_percent'] != 0: price += ' (-{}%)'.format(marketJSON[appid]['data']['price_overview']['discount_percent']) except KeyError: price = 'Free' embed = discord.Embed(color=0x2F668D, title=spyJSON['name'], url=f'http://store.steampowered.com/app/{appid}') embed.set_footer(text='AppID: {}'.format(spyJSON['appid'])) embed.set_thumbnail(url=f'http://cdn.akamai.steamstatic.com/steam/apps/{appid}/header.jpg') embed.add_field(name='Name', value=spyJSON['name'], inline=True) embed.add_field(name='Score Rank', value=spyJSON['score_rank'], inline=True) embed.add_field(name='Preis', value=price, inline=True) embed.add_field(name='Besitzer', value=owner, inline=True) embed.add_field(name='Derzeitige Spieler', value=currentPlayerJSON['response']['player_count'], inline=True) embed.add_field(name='Durchschnittliche Spieler gestern', value=spyJSON['ccu'], inline=True) embed.add_field(name='Entwickler', value=spyJSON['developer'], inline=True) embed.add_field(name='Publisher', value=spyJSON['publisher'], inline=True) if marketJSON[appid]['data']['short_description'] != '' and marketJSON[appid]['data']['short_description'] != None: discription = re.sub(re.compile('<.*?>'), '', marketJSON[appid]['data']['short_description']) embed.add_field(name='Beschreibung', value=discription, inline=False) embed.add_field(name='Link', value=f'http://store.steampowered.com/app/{appid}', inline=False) await self.bot.say(embed=embed)
async def subreddit_info(self, ctx, subreddit: str): """Command for getting subreddit info""" url = "https://oauth.reddit.com/r/{}/about".format(subreddit) headers = { "Authorization": "bearer " + self.access_token, "User-Agent": "Red-DiscordBotRedditCog/0.1 by /u/palmtree5" } async with aiohttp.get(url, headers=headers) as req: resp_json = await req.json() if "data" not in resp_json and resp_json["error"] == 403: await self.bot.say("Sorry, the currently authenticated account does not have access to that subreddit") return resp_json = resp_json["data"] colour = ''.join([randchoice('0123456789ABCDEF') for x in range(6)]) colour = int(colour, 16) created_at = dt.utcfromtimestamp(resp_json["created_utc"]) created_at = created_at.strftime("%m/%d/%Y %H:%M:%S") em = discord.Embed(title=resp_json["url"], colour=discord.Colour(value=colour), url="https://reddit.com" + resp_json["url"], description=resp_json["header_title"]) em.add_field(name="Title", value=resp_json["title"]) em.add_field(name="Created at", value=created_at) em.add_field(name="Subreddit type", value=resp_json["subreddit_type"]) em.add_field(name="Subscriber count", value=resp_json["subscribers"]) if resp_json["over18"]: em.add_field(name="Over 18?", value="Yes") else: em.add_field(name="Over 18?", value="No") await self.bot.send_message(ctx.message.channel, embed=em)
async def enable_modmail(self, ctx, subreddit: str, channel: discord.Channel): """Enable posting modmail to the specified channel""" server = ctx.message.server await self.bot.say("WARNING: Anybody with access to " + channel.mention + " will be able to see " + "your subreddit's modmail messages." + "Therefore you should make sure that only " + "your subreddit mods have access to that channel") await asyncio.sleep(5) url = "https://oauth.reddit.com/r/{}/about".format(subreddit) headers = { "Authorization": "bearer " + self.access_token, "User-Agent": "Red-DiscordBotRedditCog/0.1 by /u/palmtree5" } async with aiohttp.get(url, headers=headers) as req: resp_json = await req.json() resp_json = resp_json["data"] if resp_json["user_is_moderator"]: obj_to_add = { "subreddit": subreddit, "channel": channel.id, "timestamp": int(time.time()) } if "modmail" not in self.settings: self.settings["modmail"] = {} self.settings["modmail"][server.id] = obj_to_add dataIO.save_json("data/reddit/settings.json", self.settings) await self.bot.say("Enabled modmail for " + subreddit) else: await self.bot.say("I'm sorry, this user does not appear to be " + "a mod of that subreddit")
async def async_check(self, host: str, **kwargs): protocol = kwargs.get('protocol', 'http') port = kwargs.get('port', '80') path = kwargs.get('path', '/') url = '%s://%s:%s%s' % (protocol, host, port, path) # print('Start http', host, url) extra = {'url': url} level = const.LEVEL_OK async with aiohttp.get(url) as response: extra['is_http_status_ok'] = response.status == kwargs.get('http_status', 200) if not extra['is_http_status_ok']: extra['http_status'] = response.status level = const.LEVEL_FAIL if kwargs.get('contains'): content = await response.read() content = content.decode('utf-8') extra['is_contains_ok'] = kwargs['contains'] in content if not extra['is_contains_ok']: extra['content'] = content level = const.LEVEL_FAIL check_result = TaskResult( level=level, extra=extra, ) return check_result
def proxy_test(): url = 'http://google.com' conn = aiohttp.ProxyConnector(proxy="http://localhost:8123") r = yield from aiohttp.get(url, connector=conn) raw = yield from r.text() r.close() print(raw)
def download_file(self, file_path, range=None): """ Download a file from Telegram servers """ headers = {"range": range} if range else None url = "{0}/file/bot{1}/{2}".format(API_URL, self.api_token, file_path) return aiohttp.get(url, headers=headers)
def get_rabbitmq_queues_stats(agent): yield from agent.run_event.wait() config = agent.config['rabbitmq'] logger.info('starting "get_rabbitmq_queues_stats" task for "%s"', config['hostname']) db_config = config['database'] monitored_queues = config['queues'].split(',') auth = BasicAuth(config['username'], config['password']) yield from agent.async_create_database(**db_config) while agent.run_event.is_set(): yield from asyncio.sleep(config['frequency']) api_url = config['api_url'] response = yield from aiohttp.get(api_url, auth=auth) if response.status == 200: data = yield from response.json() for queue_info in data: if queue_info['name'] in monitored_queues: print(queue_info) points = [{ 'measurement': 'queues', 'tags': { 'name': queue_info['name'] }, 'fields': { 'memory': queue_info['memory'] }}] yield from agent.async_push(points, db_config['name']) logger.info('get_rabbitmq_queues_stats terminated')
def test_morsel_with_attributes(test_client, loop): # A comment from original test: # # No cookie attribute should pass here # they are only used as filters # whether to send particular cookie or not. # E.g. if cookie expires it just becomes thrown away. # Server who sent the cookie with some attributes # already knows them, no need to send this back again and again @asyncio.coroutine def handler(request): assert request.cookies.keys() == {'test3'} assert request.cookies['test3'] == '456' return web.Response() c = http.cookies.Morsel() c.set('test3', '456', '456') c['httponly'] = True c['secure'] = True c['max-age'] = 1000 app = web.Application(loop=loop) app.router.add_get('/', handler) client = yield from test_client(lambda loop: app) resp = yield from aiohttp.get(client.make_url('/'), cookies={'test2': c}, loop=loop) assert 200 == resp.status resp.close()
async def download_image(url: str, local_path: str = None, safe: bool = True) -> str: """ Download image file and return its full path. If path is already exist, it will be overwritten. :param url: Url to download :param local_path: Path on local filesystem to download to. :param safe: If True, will not raise error, instead will return None if there are any troubles. :return: Path to downloaded file. """ # TODO: Use async fileio # TODO: Check url or downloaded file is actually an image try: with open(local_path, 'wb') as fd: async with aiohttp.get(url) as resp: # fixme: add timeout assert resp.status == 200 while True: chunk = await resp.content.read(CHUNK_SIZE) if not chunk: break fd.write(chunk) except (AssertionError, aiohttp.errors.ClientError, asyncio.TimeoutError, OSError, IOError): logger.error("Can't download url '%s' to path '%s", url, local_path, exc_info=True) if not safe: raise local_path = None return local_path
async def _timein_country(self, country_code): """Get time using country code country_code is a 2 letter country code from this list https://timezonedb.com/country-codes or a custom shortcut code Preset shortcuts: UK - United Kingdom (converts to GB) USE - United States East (New York) USW - United States West (Los Angeles) """ apiKey = self.settings['api_key'] if ".com" in apiKey: await self.bot.say("You have to set your API key, see data/timein/settings.json for details") return url = 'http://api.timezonedb.com/v2/list-time-zone?key=' + apiKey + '&format=xml' flag = ':flag_' if country_code.lower() == 'use': url += '&country=US&zone=*New_York*' flag += 'us: EAST ' elif country_code.lower() == 'usw': url += '&country=US&zone=*Los_Angeles*' flag += 'us: WEST ' elif country_code.lower() == 'test': url += '&zone=*auckland*' flag += 'nz: ' elif len(country_code) != 2 or ' ' in country_code == False: await self.bot.say("Country code must be 2 letters and from this list https://timezonedb.com/country-codes") return else: if country_code == 'UK' or country_code == 'uk': country_code = 'GB' url += '&country=' + country_code flag += country_code.lower() + ': ' async with aiohttp.get(url) as response: soupObject = BeautifulSoup(await response.text(), "html.parser") message = '' status = soupObject.find('status').get_text() if status != 'OK': message += 'Request failed. Details:\n```' message += status + '\n' message += soupObject.find('message').get_text() message += '```\nMake sure country code is from the list at https://timezonedb.com/country-codes' else: zones = soupObject.find_all('zone') for zone in zones: newmessage = '' newmessage += flag newmessage += zone.find('countryname').get_text() + '\n' newmessage += zone.find('zonename').get_text() + '\n' unixtime = zone.find('timestamp').get_text() prettyTime = datetime.datetime.fromtimestamp(int(unixtime)).strftime('%Y-%m-%d %H:%M:%S') newmessage += prettyTime + '\n' message += newmessage + '\n' await self.bot.say(message)
async def get_balance(self): payload = { 'key': self.key, 'action': 'getbalance' } async with aiohttp.get(self.response_url, params=payload) as response: print(await response.text())
async def add(self, ctx, prefix, github): """Add a new GitHub repo with the given prefix. Format for adding a new GitHub repo is \"Username/Repository\"""" server = ctx.message.server prefix = prefix.lower() # I'm Lazy okay :( if prefix in self.settings[server.id]: await self.bot.say('This prefix already exists in this server. Please use something else.') elif len(github.split('/')) != 2: await self.bot.say('Invalid format. Please use Username/Repository') else: # Confirm the User/Repo exits, We don't want to try and pull from a non existant repo async with aiohttp.get('https://api.github.com/repos/{}'.format(github)) as response: if response.status == 404: await self.bot.say('The repository cannot be found.\nMake sure its a public repository.') else: fields = { 'author': True, 'status': True, 'comments': True, 'description': True, 'mergestatus': True, 'labels': True, 'closedby': False, 'locked': False, 'assigned': False, 'createdat': False, 'milestone': False, 'reviews': True } self.settings[server.id][prefix] = {'gh': github, 'fields': fields} self.save_json() await self.bot.say('All done, you can now use "{}#issue number" to gather information of an issue\nOr use ``{}githubcards edit``'.format(prefix, ctx.prefix))
async def client_request(url): start = time() async with request_semaphore: async with get(url) as response: await response.text() duration = time() - start return duration
async def items(self, ctx, *, hero): """Gets the most popular items for a hero""" await self.bot.send_typing(ctx.message.channel) url = "http://www.dotabuff.com/heroes/" + hero.lower().replace(" ", "-") #for actual requests async with aiohttp.get(url, headers = {"User-Agent": "Red-DiscordBot"}) as response: soupObject = BeautifulSoup(await response.text(), "html.parser") items = soupObject.find_all("section")[3].find("tbody").find_all("tr") build = [] for item in items: build.append( [ item.find_all("td")[1].find("a").get_text(), item.find_all("td")[2].get_text(), item.find_all("td")[4].get_text() ] ) message = "The most popular items **at the moment**, according to Dotabuff:\n\n```" message += tabulate(build, headers=["Item", "Matches", "Winrate"], tablefmt="fancy_grid") message += "```" await self.bot.say(message)
def get_dorks(self): with aiohttp.Timeout(10.0): r = yield from aiohttp.get( 'http://{0}:8090/dorks'.format(self.run_args.tanner) ) dorks = yield from r.json() return dorks['response']['dorks']
def getImgWords(imgUrl): bImage = '' m = re.match(r'^http.+/(.+)', imgUrl) imgName = m.group(1) if m is not None else None if imgName is None: pass try: r = yield from aiohttp.get(imgUrl) except aiohttp.errors.ClientOSError as e: print('[error url:%s] %s' % (url, e)) else: bImage = yield from r.read() with open(dirBase+imgName, 'wb') as f: f.write(bImage) #百度OCR payload = {'fromdevice':'pc', 'clientip':'115.28.134.55', 'detecttype':'LocateRecognize', 'languagetype':'CHN_ENG', 'imagetype':'1', 'image': base64.b64encode(bImage).decode("utf-8") } headers = {"Content-Type": "application/x-www-form-urlencoded", "apikey": "0830a440f9e1b9a31c5e807fa2f0ab61" } url = 'http://apis.baidu.com/apistore/idlocr/ocr' rdd = yield from aiohttp.post(url,data=payload,headers=headers) return (yield from rdd.text())
def download_file(self, file_id, dest): f = yield from self.getFile(file_id) # `file_path` is optional in File object if 'file_path' not in f: raise TelegramError('No `file_path` returned', None, None) try: r = yield from asyncio.wait_for( aiohttp.get(self._fileurl(f['file_path'])), self._http_timeout) d = dest if isinstance(dest, io.IOBase) else open(dest, 'wb') while 1: chunk = yield from r.content.read(self._file_chunk_size) if not chunk: break d.write(chunk) d.flush() finally: if not isinstance(dest, io.IOBase) and 'd' in locals(): d.close() if 'r' in locals(): r.close()
def wget(url): try: response = yield from aiohttp.get(url) except aiohttp.errors.ClientOSError as e: print('[error url:%s] %s' % (url, e)) else: return (yield from response.text())
async def _advgoogle(self, ctx, text): """Its google, you search with it. Example: google A magical pug Special search options are available; Image, Images, Maps Example: google image You know, for kids! > Returns first image Another example: google maps New York Another example: google images cats > Returns a random image based on the query""" search_type = ctx.message.content[len(ctx.prefix + ctx.command.name) + 1:].lower().split(" ") option = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1' } regex = [ re.compile(",\"ou\":\"([^`]*?)\""), re.compile("<h3 class=\"r\"><a href=\"\/url\?url=([^`]*?)&"), re.compile("<h3 class=\"r\"><a href=\"([^`]*?)\""), re.compile("\/url?url=") ] search_valid = str( ctx.message.content[len(ctx.prefix + ctx.command.name) + 1:].lower()) # Start of Image if search_type[0] == "image" or search_type[0] == "images": if search_valid == "image" or search_valid == "images": await self.bot.say("Please actually search something") else: if search_type[0] == "image": url, error = await self.images(ctx, regex, option) elif search_type[0] == "images": url, error = await self.images(ctx, regex, option, images=True) if url and not error: await self.bot.say(url) elif error: await self.bot.say("Your search yielded no results.") # End of Image # Start of Maps elif search_type[0] == "maps": if search_valid == "maps": await self.bot.say("Please actually search something") else: uri = "https://www.google.com/maps/search/" quary = str( ctx.message.content[len(ctx.prefix + ctx.command.name) + 6:].lower()) encode = urllib.parse.quote_plus(quary, encoding='utf-8', errors='replace') uir = uri + encode await self.bot.say(uir) # End of Maps # Start of generic search else: uri = "https://www.google.com/search?hl=en&q=" quary = str( ctx.message.content[len(ctx.prefix + ctx.command.name) + 1:]) encode = urllib.parse.quote_plus(quary, encoding='utf-8', errors='replace') uir = uri + encode async with aiohttp.get(uir, headers=option) as resp: test = str(await resp.content.read()) query_find = regex[1].findall(test) if not query_find: query_find = regex[2].findall(test) try: query_find = self.parsed(query_find, regex) await self.bot.say("{}".format("\n".join(query_find))) except IndexError: await self.bot.say("Your search yielded no results.") elif regex[3].search(query_find[0]): query_find = self.parsed(query_find, regex) await self.bot.say("{}".format("\n".join(query_find))) else: query_find = self.parsed(query_find, regex, found=False) await self.bot.say("{}".format("\n".join(query_find)))
async def fetch_image(self, ctx, randomize: bool = False, tags: list = []): server = ctx.message.server self.filters = fileIO("data/dan/filters.json", "load") self.settings = fileIO("data/dan/settings.json", "load") #Initialize variables artist = "unknown artist" artists = "" artistList = [] embedLink = "" embedTitle = "" imageId = "" message = "" output = None rating = "" ratingColor = "FFFFFF" ratingWord = "unknown" search = "http://danbooru.donmai.us/posts.json?tags=" tagSearch = "" verbose = False # Set verbosity to true if the current server has it set as such if server.id in self.settings and self.settings[server.id]["verbose"]: verbose = True # Assign tags to URL if tags: tagSearch += "{} ".format(" ".join(tags)) if server.id in self.filters: tagSearch += " ".join(self.filters[server.id]) else: tagSearch += " ".join(self.filters["default"]) search += parse.quote_plus(tagSearch) # Randomize results if randomize: search += "&random=y" # Assign login information if self.settings["username"] != "" and self.settings["api_key"] != "": search += "&login={}&api_key={}".format(self.settings["username"], self.settings["api_key"]) # Inform users about image retrieval message = await self.bot.say("Fetching dan image...") # Fetch and display the image or an error try: async with aiohttp.get(search) as r: website = await r.json() if website != []: if "success" not in website: for index in range( len(website) ): # Goes through each result until it finds one that works if "file_url" in website[index]: # Sets the image URL imageURL = "https://danbooru.donmai.us{}".format( website[index].get('file_url')) if verbose: # Fetches the image ID imageId = website[index].get('id') # Sets the embed title embedTitle = "Danbooru Image #{}".format(imageId) # Sets the URL to be linked embedLink = "https://danbooru.donmai.us/posts/{}".format( imageId) # Checks for the rating and sets an appropriate color rating = website[index].get('rating') if rating == "s": ratingColor = "00FF00" ratingWord = "safe" elif rating == "q": ratingColor = "FF9900" ratingWord = "questionable" elif rating == "e": ratingColor = "FF0000" ratingWord = "explicit" # Grabs the artist(s) artistList = website[index].get( 'tag_string_artist').split() # Determine if there are multiple artists if len(artistList) == 1: artist = artistList[0].replace('_', ' ') elif len(artistList) > 1: artists = ", ".join(artistList).replace( '_', ' ') artist = "" # Sets the tags to be listed tagList = website[index].get('tag_string').replace( ' ', ', ').replace('_', '\_') # Initialize verbose embed output = discord.Embed( title=embedTitle, url=embedLink, colour=discord.Colour( value=int(ratingColor, 16))) # Sets the thumbnail and adds the rating and tag fields to the embed output.add_field(name="Rating", value=ratingWord) if artist: output.add_field(name="Artist", value=artist) elif artists: output.add_field(name="Artists", value=artists) output.add_field(name="Tags", value=tagList, inline=False) output.set_thumbnail(url=imageURL) # Edits the pending message with the results return await self.bot.edit_message(message, "Image found.", embed=output) else: # Edits the pending message with the result return await self.bot.edit_message( message, imageURL) return await self.bot.edit_message( message, "Cannot find an image that can be viewed by you.") else: # Edits the pending message with an error received by the server return await self.bot.edit_message( message, "{}".format(website["message"])) else: return await self.bot.edit_message( message, "Your search terms gave no results.") except: return await self.bot.edit_message(message, "Error.")
def one_request(self, url): logging.debug("issuing request to %s", url) r = yield from aiohttp.get(url, connector=self.connector) logging.debug("issued request to %s", url) yield from self.read_response(r, url)
async def shm(self): """Sends a random hentai""" url = "http://streamhentaimovies.com/?orderby=rand" async with aiohttp.get(url) as r: await self.bot.say(r.url)
async def _google(self, ctx, text=None): """Its google, you search with it. Example: google A french pug Special search options are available; Image, Images, Maps Example: google image You know, for kids! > Returns first image""" search_type = ctx.message.content[len(ctx.prefix + ctx.command.name) + 1:].lower().split(" ") option = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1' } regex = [ ",\"ou\":\"([^`]*?)\"", "<h3 class=\"r\"><a href=\"\/url\?url=([^`]*?)&", "<h3 class=\"r\"><a href=\"([^`]*?)\"" ] if text is None: embed = discord.Embed(title="Google", description="Google Anything!", colour=0x0000FF) embed.add_field(name="Example:", value=".google A french pug", inline=False) embed.add_field( name="Other Search Options:", value= ".google images\n.google image\n.google maps\n.google videos", inline=True) embed.add_field(name="Example:", value=".google images Cat", inline=False) embed.set_thumbnail( url= 'http://www.broutinwebpublishing.com/wp-content/uploads/2016/11/google.png' ) embed.set_image( url= 'http://www.google.com/logos/doodles/2015/googles-new-logo-5078286822539264.3-hp2x.gif' ) await self.bot.say(embed=embed) return #Start of Image elif search_type[0] == "image": search_valid = str( ctx.message.content[len(ctx.prefix + ctx.command.name) + 1:].lower()) if search_valid == "image": await self.bot.say(" Please actually search something :/") else: uri = "https://www.google.com/search?tbm=isch&tbs=isz:m&q=" quary = str( ctx.message.content[len(ctx.prefix + ctx.command.name) + 7:].lower()) encode = urllib.parse.quote_plus(quary, encoding='utf-8', errors='replace') uir = uri + encode async with aiohttp.get(uir, headers=option) as resp: test = await resp.content.read() unicoded = test.decode("unicode_escape") query_find = re.findall(regex[0], unicoded) try: url = query_find[0] await self.bot.say(url) except IndexError: await self.bot.say( ":interrobang: Your search yielded no results.") #End of Image #Start of Image random elif search_type[0] == "images": search_valid = str( ctx.message.content[len(ctx.prefix + ctx.command.name) + 1:].lower()) if search_valid == "image": await self.bot.say( ":neutralFace: Please ***actually search something*** :/") else: uri = "https://www.google.com/search?tbm=isch&tbs=isz:m&q=" quary = str( ctx.message.content[len(ctx.prefix + ctx.command.name) + 7:].lower()) encode = urllib.parse.quote_plus(quary, encoding='utf-8', errors='replace') uir = uri + encode async with aiohttp.get(uir, headers=option) as resp: test = await resp.content.read() unicoded = test.decode("unicode_escape") query_find = re.findall(regex[0], unicoded) try: url = query_find[0] await self.bot.say(url) except IndexError: await self.bot.say( ":interrobang: Your search yielded no results.") #End of Image random #Start of Maps elif search_type[0] == "maps": search_valid = str( ctx.message.content[len(ctx.prefix + ctx.command.name) + 1:].lower()) if search_valid == "maps": await self.bot.say( ":neutralFace: Please ***actually search something*** :/") else: uri = "https://www.google.com/maps/search/" quary = str( ctx.message.content[len(ctx.prefix + ctx.command.name) + 6:].lower()) encode = urllib.parse.quote_plus(quary, encoding='utf-8', errors='replace') uir = uri + encode await self.bot.say(uir) #End of Maps #Start of generic search else: uri = "https://www.google.com/search?q=" quary = str( ctx.message.content[len(ctx.prefix + ctx.command.name) + 1:]) encode = urllib.parse.quote_plus(quary, encoding='utf-8', errors='replace') uir = uri + encode async with aiohttp.get(uir, headers=option) as resp: test = str(await resp.content.read()) query_find = re.findall(regex[1], test) if query_find == []: query_find = re.findall(regex[2], test) try: if re.search("\/url?url=", query_find[0]) == True: query_find = query_find[0] m = re.search("\/url?url=", query_find) query_find = query_find[:m.start( )] + query_find[m.end():] decode = self.unescape(query_find) await self.bot.say( "Here is your link: {}".format(decode)) else: decode = self.unescape(query_find[0]) await self.bot.say( "Here is your link: {}".format(decode)) except IndexError: await self.bot.say("Your search yielded no results.") elif re.search("\/url?url=", query_find[0]) == True: query_find = query_find[0] m = re.search("\/url?url=", query_find) query_find = query_find[:m.start()] + query_find[m.end():] decode = self.unescape(query_find) await self.bot.say("Here is your link: {}".format(decode)) else: query_find = query_find[0] decode = self.unescape(query_find) await self.bot.say("Here is your link: {} ".format(decode))
async def on_message(msg): # We do not want the bot to respond to Bots or Webhooks if msg.author.bot: return # We want the bot to not answer to messages that have no content # (example only attachment messages) # Bot checks BOT_PREFIX if not msg.content or msg.content[0] != BOT_PREFIX: return # Bot ignore all system messages if msg.type is not discord.MessageType.default: return # Bot runs in #akroma-bot channel and private channels for everyone # Bot runs in all channels for specific roles if not (msg.channel.name == "akroma-bot" or msg.channel.type == discord.ChannelType.private or "Core-Team" in [role.name for role in msg.author.roles] or "Support-Team" in [role.name for role in msg.author.roles] or "Contributors" in [role.name for role in msg.author.roles]): message = f"{data['default']}" await client.send_message(msg.channel, message) return args = msg.content[1:].split() cmd = args[0].lower() # -------- <help> -------- if cmd == "help": message = "\n".join(data["help"]) # -------- <links> -------- elif cmd == "links": message = "\n".join(data["links"]) # -------- <netinfo> -------- elif cmd == "netinfo": avg_bt = getAverageBlockTime(6500) last_block = w3.eth.blockNumber async with get(data["akroma"]) as akroma: if akroma.status == 200: akroma_api = await akroma.json() else: print(f"{data['akroma']} is down") diff = akroma_api["difficulty"] hashrate = akroma_api["hashRate"] message = ( f"• Block Height• **{last_block:,}**\n• Avg Block Time• **{round(avg_bt, 2)} s**\n• Network Hashrate• **" + f"{hashrate} GH/s**\n• Network Difficulty• **{diff} Th**") # -------- <mninfo> -------- elif cmd == "mninfo": avg_bt = getAverageBlockTime(6500) last_block = w3.eth.blockNumber async with get(data["network"]["link"]) as network: if network.status == 200: network_api = await network.json() else: print(f"{data['network']['link']} is down") total_users = network_api["data"]["totalUsers"] remote_nodes = network_api["data"]["totalRemote"] full_nodes = network_api["data"]["totalFull"] boot_nodes = network_api["data"]["totalBoot"] balefire_nodes = network_api["data"]["totalBalefire"] total_nodes = network_api["data"]["totalNodes"] total_locked = network_api["data"]["totalLocked"] total_paid = network_api["data"]["totalPaid"] guide_link = data["network"]["guide_link"] for x in range(len(data["epoch"]["limit"])): if (float(data["epoch"]["limit"][x]) + 1 <= last_block and last_block < float(data["epoch"]["limit"][x + 1]) + 1): mn_rew = float(data["epoch"]["mn"][x]) f_roi_value = 0.6 * 3153600 / avg_bt * mn_rew / full_nodes / 5 r_roi_value = 0.2 * 3153600 / avg_bt * mn_rew / remote_nodes / 15 bo_roi_value = 0.2 * 3153600 / avg_bt * mn_rew / boot_nodes / 15 message = ( f"• Users • **{total_users:1.0f}**\n• Masternodes • F: **{full_nodes:1.0f}** | R: **" + f"{remote_nodes:1.0f}** | Bo: **{boot_nodes:1.0f}** | Ba: **{balefire_nodes:1.0f}** | T: **" + f"{total_nodes:1.0f}**\n• ROI • F: **{f_roi_value:1.3f}%** | R: **{r_roi_value:1.3f}%** | Bo: **" + f"{bo_roi_value:1.3f}%** | Ba: **0%**\n• Locked • **{total_locked} AKA**\n• Rewards • **" + f"{total_paid} AKA**\n{guide_link}") # -------- <hpow> -------- elif cmd == "hpow": avg_bt = getAverageBlockTime(6500) last_block = w3.eth.blockNumber async with get(data["cmc"]["cmc_aka"]) as cmc_aka: if cmc_aka.status == 200: cmc_aka_api = await cmc_aka.json() else: print(f"{data['cmc']['cmc_aka']} is down") aka_usd_price = float(cmc_aka_api["data"]["quotes"]["USD"]["price"]) async with get(data["akroma"]) as akroma: if akroma.status == 200: akroma_api = await akroma.json() else: print(f"{data['akroma']} is down") diff = float(akroma_api["difficulty"]) if len(args) < 2: message = f"{data['hpow']['default']}" await client.send_message(msg.channel, message) return cmd1 = args[1].lower() if not is_number(cmd1): message = f"{data['hpow']['default']}" elif cmd1 == "0": message = f"{data['hpow']['zero']}" elif is_number(cmd1) and float(cmd1) < 0: message = f"{data['hpow']['neg']}" elif is_number(cmd1): for x in range(len(data["epoch"]["limit"])): if (float(data["epoch"]["limit"][x]) + 1 <= last_block and last_block < float(data["epoch"]["limit"][x + 1]) + 1): mnr_rwd = data["epoch"]["mnr"][x] cmd1 = float(cmd1) message = ( f"Current network difficulty is **{diff} Th**.\nA hashrate of **{cmd1:1.0f} Mh/s** will get " + f"you approximately **{cmd1/diff*36*mnr_rwd/avg_bt/10**3:1.2f} AKA** _(***" + f"{cmd1/diff*36*mnr_rwd/avg_bt/10**3*aka_usd_price:1.2f}$***)_ per **hour** and **" + f"{cmd1/diff*36*mnr_rwd*24/avg_bt/10**3:1.2f} AKA** _(***" + f"{cmd1/diff*36*mnr_rwd*24/avg_bt/10**3*aka_usd_price:1.2f}$***)_ per **day** at current " + "network difficulty.") # -------- <mnrewards> -------- elif cmd == "mnrewards": avg_bt = getAverageBlockTime(6500) last_block = w3.eth.blockNumber async with get(data["cmc"]["cmc_aka"]) as cmc_aka: if cmc_aka.status == 200: cmc_aka_api = await cmc_aka.json() else: print(f"{data['cmc']['cmc_aka']} is down") aka_usd_price = float(cmc_aka_api["data"]["quotes"]["USD"]["price"]) async with get(data["network"]["link"]) as network: if network.status == 200: network_api = await network.json() else: print(f"{data['network']['link']} is down") remote_nodes = network_api["data"]["totalRemote"] full_nodes = network_api["data"]["totalFull"] boot_nodes = network_api["data"]["totalBoot"] balefire_nodes = network_api["data"]["totalBalefire"] if len(args) < 2: for x in range(len(data["epoch"]["limit"])): if (float(data["epoch"]["limit"][x]) + 1 <= last_block and last_block < float(data["epoch"]["limit"][x + 1]) + 1): mn_rwd = data["epoch"]["mn"][x] message = ( f"**1** Full Masternode will give you approximately **" + f"{0.6*3600*24/avg_bt*mn_rwd/full_nodes:1.3f} AKA** _(***" + f"{0.6*3600*24/avg_bt*mn_rwd/full_nodes*aka_usd_price:1.3f}$***)_ per **day**.\n**1** Remote" + f" Masternode will give you approximately **{0.2*3600*24/avg_bt*mn_rwd/remote_nodes:1.3f} AK" + f"A** _(***{0.2*3600*24/avg_bt*mn_rwd/remote_nodes*aka_usd_price:1.3f}$***)_ per **day**.\n*" + f"*1** Boot Masternode will give you approximately **" + f"{0.2*3600*24/avg_bt*mn_rwd/boot_nodes:1.3f} AKA** _(***" + f"{0.2*3600*24/avg_bt*mn_rwd/boot_nodes*aka_usd_price:1.3f}$***)_ per **day**." ) await client.send_message(msg.channel, message) return cmd1 = args[1].lower() if not is_number(cmd1): message = f"{data['mnrewards']['default']}" elif cmd1 == "0": message = f"{data['mnrewards']['zero']}" elif is_number(cmd1) and float(cmd1) < 0: message = f"{data['mnrewards']['neg']}" elif is_number(cmd1): for x in range(len(data["epoch"]["limit"])): if (float(data["epoch"]["limit"][x]) + 1 <= last_block and last_block < float(data["epoch"]["limit"][x + 1]) + 1): mn_rwd = data["epoch"]["mn"][x] cmd1 = float(cmd1) message = ( f"**{cmd1:1.0f}** Full Masternode will give you approximately **" + f"{cmd1*0.6*3600*24/avg_bt*mn_rwd/full_nodes:1.3f} AKA** _(***" + f"{cmd1*0.6*3600*24/avg_bt*mn_rwd/full_nodes*aka_usd_price:1.3f}$***)_ per **day**.\n**" + f"{cmd1:1.0f}** Remote Masternode will give you approximately **" + f"{cmd1*0.2*3600*24/avg_bt*mn_rwd/remote_nodes:1.3f} AKA** _(***" + f"{cmd1*0.2*3600*24/avg_bt*mn_rwd/remote_nodes*aka_usd_price:1.3f}$***)_ per **day**.\n**" + f"{cmd1:1.0f}** Boot Masternode will give you approximately **" + f"{cmd1*0.2*3600*24/avg_bt*mn_rwd/boot_nodes:1.3f} AKA** _(***" + f"{cmd1*0.2*3600*24/avg_bt*mn_rwd/boot_nodes*aka_usd_price:1.3f}$***)_ per **day**." ) # -------- <akausd> -------- elif cmd == "akausd": async with get(data["cmc"]["cmc_aka"]) as cmc_aka: if cmc_aka.status == 200: cmc_aka_api = await cmc_aka.json() else: print(f"{data['cmc']['cmc_aka']} is down") aka_usd_price = cmc_aka_api["data"]["quotes"]["USD"]["price"] if len(args) < 2: message = f"{data['akausd']['default']}{round(aka_usd_price, 3)}$***._" await client.send_message(msg.channel, message) return cmd1 = args[1].lower() if not is_number(cmd1): message = f"{data['akausd']['default']}{round(aka_usd_price, 3)}$***._" elif cmd1 == "0": message = f"{data['akausd']['zero']}" elif is_number(cmd1) and float(cmd1) < 0: message = f"{data['akausd']['neg']}" elif is_number(cmd1): message = ( f"**{round(float(cmd1),2):,} AKA** = **{round(float(aka_usd_price)*float(cmd1),2):,}$**\n" + f"{data['akausd']['default']}{round(aka_usd_price, 3)}$***_") # -------- <roadmap> -------- elif cmd == "roadmap": message = f"{data['roadmap']}" # -------- <awesome> -------- elif cmd == "awesome": message = f"{data['awesome']}" # -------- <markets> -------- elif cmd == "markets": async with get(data["cmc"]["cmc_aka1"], headers=HEADERS) as cmc_aka: if cmc_aka.status == 200: cmc_aka_api = await cmc_aka.json() aka_usd_price = float( cmc_aka_api["data"]["AKA"]["quote"]["USD"]["price"]) else: print(f"{data['cmc']['cmc_aka1']} is down") async with get(data["cmc"]["cmc_btc1"], headers=HEADERS) as cmc_btc: if cmc_btc.status == 200: cmc_btc_api = await cmc_btc.json() btc_usd_price = float( cmc_btc_api["data"]["BTC"]["quote"]["USD"]["price"]) else: print(f"{data['cmc']['cmc_aka1']} is down") message_list = [] message_list.append("**Akroma** is listed on the following exchanges:") for a in range(len(markets)): message_list.append(f"{a+1}. <{markets[a]['link']}>") message_list.append("\n_Use `!markets info` for stats of the markets_") if len(args) < 2 or args[1].lower() != "info": message = "\n".join(message_list) else: vol_total = 0 for a in range(len(markets)): if markets[a]["link"] == "https://graviex.net/markets/akabtc": async with get(markets[a]["api"]) as api: if api.status == 200: markets_api = await api.json() markets[a]["volume_24h"] = aka_usd_price * float( markets_api["ticker"]["vol"]) usd_price = btc_usd_price * float( markets_api["ticker"]["last"]) markets[a]["price"] = usd_price else: print(f"{markets[a]['api']} is down") vol_total = vol_total + float(markets[a]["volume_24h"]) elif markets[a][ "link"] == "https://app.stex.com/en/basic-trade/pair/BTC/AKA/1D": async with get(markets[a]["api"]) as api: if api.status == 200: markets_api = await api.json() for i in range(len(markets_api)): if markets_api[i]["market_name"] == "AKA_BTC": markets[a][ "volume_24h"] = aka_usd_price * float( markets_api[i]["vol"]) usd_price = btc_usd_price * float( markets_api[i]["last"]) markets[a]["price"] = usd_price else: print(f"{markets[a]['api']} is down") vol_total = vol_total + float(markets[a]["volume_24h"]) max_source = 0 for a in range(len(markets)): markets[a]["vol_percent"] = float( markets[a]["volume_24h"]) / vol_total * 100 max_source = max(6, max_source, len(markets[a]["source"])) markets.sort(key=lambda x: x["volume_24h"], reverse=True) with open("market.json", "w") as file: json.dump(markets, file, indent=2) message = """ ``` +--+-------{a}-+-----------+-------------+----------+---------+ | #| Source{0} | Pair | Vol (24h) | Price | Vol (%) | +--+-------{a}-+-----------+-------------+----------+---------+ {markets} +--+-------{a}-+-----------+-------------+----------+---------+ ``` """.format( " " * (max_source - 6), a="-" * (max_source - 6), markets="\n".join( "|{:>2d}| {:<{max_source}} | {:<9} | {:>10.2f}$ | {:>7.3f}$ | {:>6.2f}% |" .format( i + 1, markets[i]["source"], markets[i]["pair"], markets[i]["volume_24h"], markets[i]["price"], markets[i]["vol_percent"], max_source=max_source, ) for i in range(len(markets))), ) # -------- <pool> -------- elif cmd == "pool": with open("pool.json") as data_file: pools = json.load(data_file) with open("check_time.json") as data_file: check_time = json.load(data_file) async with get(data["akroma"]) as akroma: if akroma.status == 200: akroma_api = await akroma.json() else: print(f"{data['akroma']} is down") hashrate = float(akroma_api["hashRate"]) solo = float(hashrate) message_list = [] message_list.append(f"Network hash: **{float(hashrate)} GH/s**") for a in range(len(pools)): procent = float(pools[a]["hash"]) / 10**9 / float(hashrate) * 100 solo = solo - float(pools[a]["hash"]) / 10**9 if float(pools[a]["hash"]) / 10**9 < 1: message_list.append( f"<{pools[a]['link']}>: **{float(pools[a]['hash'])/10**6:1.2f} MH/s** ({procent:1.2f}%)" ) else: message_list.append( f"<{pools[a]['link']}>: **{float(pools[a]['hash'])/10**9:1.2f} GH/s** ({procent:1.2f}%)" ) soloproc = solo / float(hashrate) * 100 message_list.append( f"Unknown Pools | Solo miners: **{solo:1.2f} GH/s** ({soloproc:1.2f}%)" ) message_list.append( f"\n_Last API request on {check_time['last_check']}_") message = "\n".join(message_list) # -------- <epoch> -------- elif cmd == "epoch": avg_bt = getAverageBlockTime(6500) last_block = w3.eth.blockNumber for x in range(len(data["epoch"]["limit"])): if (float(data["epoch"]["limit"][x]) + 1 <= last_block and last_block < float(data["epoch"]["limit"][x + 1]) + 1): total = float(data["epoch"]["mnr"][x]) + float( data["epoch"]["mn"][x]) + float(data["epoch"]["dev"][x]) time_left = (float(data["epoch"]["limit"][x + 1]) - last_block + 1) * avg_bt / 86.4 / 10**3 message = ( f"{data['epoch']['bh']}{last_block}{data['epoch']['nesb']}" + f"{float(data['epoch']['limit'][x+1])+1:1.0f}{data['epoch']['ech']}{time_left:1.3f}" + f"{data['epoch']['brew']}{data['epoch']['mnr'][x]:5.2f} |{data['epoch']['mn'][x]:5.2f} |" + f"{data['epoch']['dev'][x]:5.2f} | **{total:5.2f} {data['epoch']['policy']}" ) # -------- <coininfo> -------- elif cmd == "coininfo": async with get(data["network"]["link"]) as network: if network.status == 200: network_api = await network.json() else: print(f"{data['network']['link']} is down") async with get(data["cmc"]["cmc_btc"]) as cmc_btc: if cmc_btc.status == 200: cmc_btc_api = await cmc_btc.json() else: print(f"{data['cmc']['cmc_btc']} is down") async with get(data["cmc"]["cmc_aka"]) as cmc_aka: if cmc_aka.status == 200: cmc_aka_api = await cmc_aka.json() else: print(f"{data['cmc']['cmc_aka']} is down") total_locked = network_api["data"]["totalLocked"] aka_usd_price = cmc_aka_api["data"]["quotes"]["USD"]["price"] btc_usd_price = cmc_btc_api["data"]["quotes"]["USD"]["price"] aka_24vol = cmc_aka_api["data"]["quotes"]["USD"]["volume_24h"] aka_mcap = cmc_aka_api["data"]["quotes"]["USD"]["market_cap"] aka_circ_supply = cmc_aka_api["data"]["circulating_supply"] aka_24change = cmc_aka_api["data"]["quotes"]["USD"][ "percent_change_24h"] message = ( f"• Current Price•**{aka_usd_price/btc_usd_price:22.8f} BTC ** | **{aka_usd_price:8.4f}$**\n• 24h Volume •" + f"**{aka_24vol/btc_usd_price:18.3f} BTC ** | **{aka_24vol:10.2f}$**\n• Market Cap•**{aka_mcap:21.0f}$**" + f"\n• Circulating Supply• **{aka_circ_supply:10.0f} AKA **\n• Locked Coins• **" + f"{total_locked} AKA **\n• 24h Change•**{aka_24change:19.2f} % **") # -------- <about> -------- elif cmd == "about": message = "\n".join(data["about"]) # -------- <members(Core-Team only)> -------- elif (cmd == "members" and msg.channel.type != discord.ChannelType.private and "Core-Team" in [role.name for role in msg.author.roles]): members = msg.author.server.member_count message = f"Current number of members: {members}" else: message = f"{data['unknown']}" await client.send_message(msg.channel, message)
async def mal(self, ctx): message = ctx.message if message.content.lower().split()[0] == '!mal' and len( message.content.split()) == 1: await self.bot.say('https://myanimelist.net/') return import xml.etree.ElementTree as ET anime = message.content.lower()[5:].replace(' ', '%20') if 'cory in the house' in message.content.lower(): #this is meme embed = discord.Embed() embed.title = 'Cory in the House' embed.url = 'https://en.wikipedia.org/wiki/Cory_in_the_House' embed.color = 1983641 embed.description = "**Name: **{}\n**Status: **{}\n**Air Date: **{}\n**Episodes: **{}\n**Score: **{}\n**Description: **{}".format( 'コーリー ホワイトハウスでチョー大変! ', 'Finished', '2007-01-12', '34', '10.00', 'Cory in the House is an American television series broadcast on the Disney Channel from 2007 to 2008 as a spin-off of the Disney series That’s So Raven, which focused on the exploits of the character Cory Baxter as he and his father take up residence in the White House. The series has since gained an ironic fandom online, including a running joke in which the series is erroneously referred to as an anime. Additionally, members of 4chan’s /v/ (video games) board have attempted to get the Cory in the House Nintendo DS game a most-wanted FAQ page on GameFAQs.' ) embed.set_image( url= 'http://img.lum.dolimg.com/v1/images/open-uri20150422-12561-zuhjen_2fc6aec3.jpeg?region=0%2C0%2C1000%2C1161' ) embed.set_footer(text='MyAnimeList', icon_url='http://i.imgur.com/8VjfkIQ.png') await self.bot.say(embed=embed) return async with aiohttp.get( 'https://myanimelist.net/api/anime/search.xml?q=' + anime, auth=aiohttp.BasicAuth(malinfo['User Name'], malinfo['Password'])) as r: if r.status == 200: ent = 0 if anime.lower().replace('%20', ' ') == 'orange': ent = 9 resp = await r.text() tree = ET.fromstring(resp) aUrl = 'https://myanimelist.net/anime/' + tree[ent][0].text try: aName = tree[ent][2].text except: aName = 'None' try: aJp = tree[ent][1].text except: aJp = 'None' aScore = tree[ent][5].text aEp = tree[ent][4].text aStat = tree[ent][7].text aDate = tree[ent][8].text aImg = tree[ent][-1].text try: aDesc = re.tree[ent][10].text.replace( '—', '—').replace('&', '&').replace( '<', '<').replace('>', '>').replace( '"', '"').replace(''', "'").replace( '<br />', '').replace('[i]', '').replace('[/i]', '') except: try: #root = ET.fromstring(resp)[0] aDesc = tree[ent][10].text.replace( '&', '&').replace('—', '—').replace( '<', '<').replace('>', '>').replace( '"', '"').replace(''', "'").replace( '<br />', '').replace('[i]', '').replace('[/i]', '') except: aDesc = 'None' embed = discord.Embed() embed.title = aName embed.url = aUrl embed.color = 1983641 embed.description = "**Name: **{}\n**Status: **{}\n**Air Date: **{}\n**Episodes: **{}\n**Score: **{}\n**Description: **{}".format( aJp, aStat, aDate, aEp, aScore, aDesc) embed.set_image(url=aImg) embed.set_footer(text='MyAnimeList', icon_url='http://i.imgur.com/8VjfkIQ.png') await self.bot.say(embed=embed) elif r.status == 204: await self.bot.say( "I couldnt find an anime with that name in MyAnimeList") else: await self.bot.say("MyAnimeList is down, NOOOOOOOO :(")
async def save_brawl(self, ctx, profiletag : str, member: discord.Member = None): """ save your Brawl Stars Profile Tag ` Example: !save brawl #LJQ2GGR !save brawl #LJQ2GGR @GR8 Type !contact to ask for help. """ server = ctx.message.server author = ctx.message.author profiletag = profiletag.strip('#').upper().replace('O', '0') check = ['P', 'Y', 'L', 'Q', 'G', 'R', 'J', 'C', 'U', 'V', '0', '2', '8', '9'] if any(i not in check for i in profiletag): await self.bot.say("The ID you provided has invalid characters. Please try again.") return allowed = False if member is None: allowed = True elif member.id == author.id: allowed = True else: botcommander_roles = [discord.utils.get(server.roles, name=r) for r in BOTCOMMANDER_ROLES] botcommander_roles = set(botcommander_roles) author_roles = set(author.roles) if len(author_roles.intersection(botcommander_roles)): allowed = True if not allowed: await self.bot.say("You dont have enough permissions to set tags for others.") return if member is None: member = ctx.message.author url = "https://brawlstats.io/players/" + profiletag refresh = "https://brawlstats.io/players/" + profiletag + "/refresh" requests.get(refresh) async with aiohttp.get(url) as response: soupObject = BeautifulSoup(await response.text(), "html.parser") try: band = soupObject.find('div', {'class':'band-info'}).get_text() if band == 'No Band': band_tag = '#' else: band_link = soupObject.find('div', {'class':'band-info'}).find('a') band_tag = band_link['href'][7:].strip() tagUsername = soupObject.find('div', {'class':'player-name brawlstars-font'}).get_text() self.brawl.update({member.id: {'tag': profiletag, 'band_tag': band_tag}}) dataIO.save_json('data/BrawlStats/tags.json', self.brawl) await self.bot.say(tagUsername + ' has been successfully saved. Now you can use ``!brawlProfile`` ``!band``') except: await self.bot.say("We cannot find your ID in our database, please try again.")
async def pacman(self, ctx, cmd=None, *, query=None): """Pacman commands. ``` ```tex Commands : # -Ss [query] > searches the arch and aur repositories.""" if cmd == '-Ss': if query is None: return await self.bot.say('Invalid amount of arguments passed.' ) print('Searching for {0} in Arch repositories and the AUR.'.format( query)) await self.bot.say( 'Searching for {0} in Arch repositories and the AUR.'.format( query)) pkgs = [['Name', 'Repo', 'Arch']] pkgsinfos = [[ 'Name', 'Repo', 'Arch', 'Version', 'Description', 'URL' ]] async with aiohttp.get( 'https://www.archlinux.org/packages/search/json/?q={0}'. format(query)) as r: ar = await r.json() ar = ar['results'] print(len(ar)) for count, res in enumerate(ar): if count < 10: if not res['pkgname'] in pkgs: pkgs.append( [res['pkgname'], res['repo'], res['arch']]) pkgsinfos.append([ res['pkgname'], res['repo'], res['arch'], res['pkgver'] + "-" + res['pkgrel'], res['pkgdesc'], res['url'] ]) else: count -= 1 async with aiohttp.get( 'http://aur4.archlinux.org/rpc.php?type=search&arg={0}'. format(query)) as u: au = await u.json() au = au['results'] print(len(au)) for count, res in enumerate(au): if count < 10: if not res['Name'] in pkgs: pkgs.append([res['Name'], 'AUR', 'any']) pkgsinfos.append([ res['Name'], 'AUR', 'any', res['Version'], res['Description'], res['URL'] ]) else: count -= 1 print(pkgs) if (len(pkgs) > 1): result = '```tex\n' for cnt, i in enumerate(pkgs): if cnt < 20: for _cnt, ii in enumerate(pkgsinfos): if _cnt < 20: result += '# ' + 'Repo : ' + i[ 1] + ' | Arch : ' + i[ 2] + '| Name : ' + i[0] + '\n' #result += '' + i[1] + '/' + i[0] + ' (' + i[2] + ') \n'; await self.bot.say( 'Reply with the name of one of the following package names within 20 seconds to get more information.' ) await self.bot.say(result + '\n```') def reply_check(m): print('Content of m : ' + m) if m in pkgs: return True userReply = await self.bot.wait_for_message( timeout=20.0, author=ctx.message.author) try: replyMatch = reply_check(userReply.content) except Exception as error: print(error) print('Most likely a time-out.') if userReply is None: await self.bot.say('Timed out.') return elif replyMatch == True: for j in pkgsinfos: print('Ready to send info. Find data.') if userReply.content in j: print('Found package!') print(j) pName = userReply.content if 'AUR' in j: print('IS IN AUR') pVersion = j[3] pDescription = j[4] pSourceURL = j[5] pURL = 'https://aur.archlinux.org/packages/' + pName await self.bot.say( 'Info on : {0}\n```tex\n# Package Name : {0}\n# Version : {1}\n# Description : {2}\n# Source : {3}\n# AUR : {4}```' .format(pName, pVersion, pDescription, pSourceURL, pURL)) return else: print('IS IN ARCH REPO') pVersion = j[3] pDescription = j[4] pArch = j[2] pRepo = j[1] pSourceURL = j[5] await self.bot.say( 'Info on : {0}\n```tex\n# Package Name : {0}\n# Version : {1}\n# Description : {2}\n# Arch : {3}\n# Repo : {4}\n# Source : {5}```' .format(pName, pVersion, pDescription, pArch, pRepo, pSourceURL)) return else: return await self.bot.say('Previous search was exited.' ) else: return await self.bot.say('No results found.') elif cmd != "-Ss" or cmd == None: return await self.bot.say('Invalid arguments passed.')
def download(req): with aiohttp.Timeout(_timeout): return aiohttp.get(_fileurl(req))
async def trans(q, pair): url = APERTIUM.format(q=q, pair=pair) async with aiohttp.get(url) as s: response = await s.json() return response['responseData']['translatedText']
async def hero(self, ctx, *, hero): """Shows some info about hero""" # Get and parse the required hero reqHero = urllib.parse.quote(hero.lower()) # Moved hero table builder to separate function for a more clean code # TODO: Probably should make it a more "global" function and pass down the ctx into it async def buildHeroInfo(payload): herojson = payload if herojson["Range"] == 128: herotype = "Melee" else: herotype = "Ranged" # Generate the needed table table = [[ "HP", herojson["HP"], "%.2f" % (float(herojson["StrGain"]) * 19) ], [ "MP", herojson["Mana"], "%.2f" % (float(herojson["IntGain"]) * 19) ], ["AGI", herojson["BaseAgi"], herojson["AgiGain"]], ["STR", herojson["BaseStr"], herojson["StrGain"]], ["INT", herojson["BaseInt"], herojson["IntGain"]], ["Damage", "53~61", ""], [ "Armor", herojson["Armor"], "%.2f" % (float(herojson["AgiGain"]) * 0.14) ], ["Movespeed", herojson["Movespeed"], herojson["AgiGain"]]] table[1 + herojson["PrimaryStat"]][0] = "[" + table[ 1 + herojson["PrimaryStat"]][0] + "]" # Compose the final message message = "" message += "**" + hero.title() + "** (" + herotype + ")\n" message += "This hero's stats:\n\n" message += "```" message += tabulate(table, headers=["Stat", "Value", "Gain/lvl"], tablefmt="fancy_grid") message += "```\n" # Legs are fun if (herojson["Legs"] > 0): message += "Also you might consider buying " + str( herojson["Legs"] ) + " boots, because this hero, apparently, has " + str( herojson["Legs"]) + " legs! ;)" else: message += "Talking about boots... this hero seems to have no legs, so you might consider playing without any ;)" await self.bot.say(message) # Get the proper hero name url = "http://api.herostats.io/heroes/" + reqHero try: # Get the info async with aiohttp.get(url) as r: data = await r.json() if "error" not in data.keys(): # Build the data into a nice table and send await buildHeroInfo(data) else: await self.bot.say(data["error"]) except: # Nothing can be done await self.bot.say('Dota API is offline')
async def get_google_entries(self, query): params = {'q': query, 'safe': 'on', 'lr': 'lang_en', 'hl': 'en'} headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64)'} # list of URLs entries = [] # the result of a google card, an embed card = None async with aiohttp.get('https://www.google.com/search', params=params, headers=headers) as resp: if resp.status != 200: raise RuntimeError('Google somehow failed to respond.') root = etree.fromstring(await resp.text(), etree.HTMLParser()) # with open('google.html', 'w', encoding='utf-8') as f: # f.write(etree.tostring(root, pretty_print=True).decode('utf-8')) """ Tree looks like this.. sort of.. <div class="g"> ... <h3> <a href="/url?q=<url>" ...>title</a> </h3> ... <span class="st"> <span class="f">date here</span> summary here, can contain <em>tag</em> </span> </div> """ card_node = root.find(".//div[@id='topstuff']") card = self.parse_google_card(card_node) search_nodes = root.findall(".//div[@class='g']") for node in search_nodes: url_node = node.find('.//h3/a') if url_node is None: continue url = url_node.attrib['href'] if not url.startswith('/url?'): continue url = parse_qs( url[5:])['q'][0] # get the URL from ?q query string # if I ever cared about the description, this is how entries.append(url) # short = node.find(".//span[@class='st']") # if short is None: # entries.append((url, '')) # else: # text = ''.join(short.itertext()) # entries.append((url, text.replace('...', ''))) return card, entries
def call_url(url): print('Starting {}'.format(url)) response = yield from aiohttp.get(url) #aiohttp.get method was deprecated data = yield from response.text() """
async def hd(self): """Sends a random hentai""" url = "http://hentaidream.me/random" async with aiohttp.get(url) as r: await self.bot.say(r.url)
async def stream_listener(self, before: discord.Member, after: discord.Member): conn = sqlite3.connect("streaminfo.db") conn.text_factory = str cursor = conn.cursor() sql = "SELECT * FROM streams where disName=?" memVar = str(before) cursor.execute(sql, [(memVar)]) data2 = cursor.fetchall() print(data2[0][0]) print(data2[0][1]) strName = data2[0][1] url = "https://mixer.com/api/v1/channels/" + strName print(url) if before.server.id not in self.settings: self.settings[before.server.id] = deepcopy(default_settings) dataIO.save_json(self.settings_path, self.settings) elif "only" not in self.settings[before.server.id]: self.settings[before.server.id]["only"] = None dataIO.save_json(self.settings_path, self.settings) server_settings = self.settings[before.server.id] if server_settings["enabled"] and server_settings["role"] is not None: streamer_role = find(lambda m: m.id == server_settings["role"], before.server.roles) only_role = find(lambda l: l.id == server_settings["only"], before.server.roles) if streamer_role is None: return # is streaming if (after.game is not None and streamer_role not in after.roles): if (only_role is None or only_role in after.roles): async with aiohttp.get(url) as r: data = await r.json(encoding='utf-8') if r.status == 200: if data["online"] is True: try: await self.bot.add_roles(after, streamer_role) except discord.Forbidden: print( "StreamRole: forbidden error\n" "Server: {}, Role: {}, Member: {}".format( before.server.id, streamer_role.id, after.id)) else: await self.bot.remove_roles(after, streamer_role) elif r.status == 404: raise StreamNotFound() else: raise APIError() # is not elif ((after.game is None) and streamer_role in after.roles): async with aiohttp.get(url) as r: data = await r.json(encoding='utf-8') if r.status == 200: if data["online"] is True: try: await self.bot.add_roles(after, streamer_role) except discord.Forbidden: print("StreamRole: forbidden error\n" "Server: {}, Role: {}, Member: {}".format( before.server.id, streamer_role.id, after.id)) else: await self.bot.remove_roles(after, streamer_role) elif r.status == 404: raise StreamNotFound() else: raise APIError()
async def process_always(self, message): _twitch_re = re.compile( r'(.*:)//(twitch.tv|www.twitch.tv)(:[0-9]+)?(.*)', re.I) _youtube_re = re.compile( r'(?:youtube.*?(?:v=|/v/)|youtu\.be/|yooouuutuuube.*?id=)([-_a-zA-Z0-9]+)', re.I) _youtube_match = _youtube_re.search(message.content) _twitch_match = _twitch_re.match(message.content) if _twitch_match: channel = _twitch_match.group(4).split('#')[0].split(' ')[0].split( '/')[1] async with aiohttp.get( 'https://api.twitch.tv/kraken/streams/{}'.format( channel)) as resp: assert resp.status == 200 resp_parsed = await resp.json() if resp_parsed['stream']: resp_msg = '**{}** - **{}** is playing **{}** and **{}** are watching it!'.format( resp_parsed['stream']['channel']['display_name'], resp_parsed['stream']['channel']['status'], resp_parsed['stream']['channel']['game'], resp_parsed['stream']['viewers']) await self.bot.send_message(message.channel, str(resp_msg)) elif not resp_parsed['stream']: await self.bot.send_message( message.channel, '**{}** channel at the moment is offline'.format( channel)) elif _youtube_match: _id = _youtube_match.group(1) session = aiohttp.ClientSession() async with session.get( 'https://www.googleapis.com/youtube/v3/videos?part=contentDetails%2C+snippet%2C+statistics&id={}&key={}' .format( _id, 'AIzaSyBeN3PHoLnDg0VrMej568SNr--vv8CVTjA')) as resp: assert resp.status == 200 resp_parsed = await resp.json() if resp_parsed.get('error'): if resp_parsed['error']['code'] == 403: await self.bot.send_message( message.channel, 'Failed to fetch content from youtube :(') else: pass items = resp_parsed['items'][0] snippet = items['snippet'] statistics = items['statistics'] content_details = items['contentDetails'] title = snippet['title'] length = parse_duration(content_details['duration']) intervals = ( ('w', 604800), # 60 * 60 * 24 * 7 ('d', 86400), # 60 * 60 * 24 ('h', 3600), # 60 * 60 ('m', 60), ('s', 1), ) def display_time(seconds, granularity=2): result = [] for name, count in intervals: value = seconds // count if value: seconds -= value * count result.append("{:.0f} {}".format(value, name)) return ' '.join(result[:granularity]) likes = float(statistics['likeCount']) dislikes = float(statistics['dislikeCount']) total_votes = likes + dislikes total_percent = 100 * (likes / total_votes) views = statistics['viewCount'] author = snippet['channelTitle'] upload_time = time.strptime(snippet['publishedAt'], "%Y-%m-%dT%H:%M:%S.000Z") await self.bot.send_message( message.channel, '**{}** – length **{}** – likes **{}**, dislikes **{}** (**{:.1f}%**) – **{}** views – **{}** on **{}** \n\nPosted by **{}**' .format(title, display_time(length.total_seconds(), 4), likes, dislikes, total_percent, views, author, time.strftime("%Y.%m.%d", upload_time), message.author.name)) channel = discord.utils.get(self.bot.get_all_channels(), name='youtubestuff') if message.channel.id != channel.id: await self.bot.send_message( channel, 'https://{}'.format(_youtube_match.group(0)))
async def hero(self, ctx, *, heroReq): """Return requested hero's stats""" # Gamepedia hero attributes api url (it's static) url = "http://dota2.gamepedia.com/api.php?action=parse&format=json&pageid=178308" try: async with aiohttp.get(url, headers={"User-Agent": "Red-DiscordBot"}) as response: data = await response.json() unescaped = html.unescape(data["parse"]["text"]["*"]) soupObject = BeautifulSoup(unescaped, "html.parser") #print(soupObject) rows = soupObject.find( class_='wikitable sortable').find_all('tr') # find our hero heroIndex = None for row in enumerate(rows[1:]): heroName = row[1].find_all('td')[0].getText()[:-2] if heroReq.lower() in heroName.lower(): # found it! heroIndex = row[0] + 1 if not heroIndex: return await self.bot.say('Couldn\'t find requested hero') heroStats = rows[heroIndex].find_all('td') # dotabuff base url baseUrl = 'https://www.dotabuff.com/heroes' # collect hero info hero = { 'name': heroStats[0].getText()[:-2], 'img': heroStats[0].find('img')['src'], 'url': baseUrl + heroStats[0].find('a')['href'].lower().replace('_', '-'), 'attribute': heroStats[1].find('a')['title'], 'str': [ heroStats[2].getText()[1:-1], heroStats[3].getText()[1:-1] ], # stripping the text with [1:-1] 'agi': [ heroStats[4].getText()[1:-1], heroStats[5].getText()[1:-1] ], 'int': [ heroStats[6].getText()[1:-1], heroStats[7].getText()[1:-1] ], 'ms': heroStats[11].getText()[1:-1], 'armor': heroStats[12].getText()[1:-1], 'attack': [ heroStats[13].getText()[1:-1], heroStats[14].getText()[1:-1] ], 'range': heroStats[15].getText()[1:-1], 'vision': [ heroStats[19].getText()[1:-1], heroStats[20].getText()[1:-1] ], 'regen': heroStats[23].getText()[1:-1] } # set embed color based on primary attribute if hero['attribute'] == 'Strength': hero['color'] = 0xF24A0B elif hero['attribute'] == 'Agility': hero['color'] = 0x55C156 else: hero['color'] = 0x2F668D # build embed em = discord.Embed(title='{} ({})'.format( hero['name'], hero['attribute']), url=hero['url'], colour=hero['color']) em.set_thumbnail(url=hero['img']) em.add_field(name='Strength', value='{} (+{}/lvl)'.format( hero['str'][0], hero['str'][1]), inline=True) em.add_field(name='Agility', value='{} (+{}/lvl)'.format( hero['agi'][0], hero['agi'][1]), inline=True) em.add_field(name='Intelligence', value='{} (+{}/lvl)'.format( hero['int'][0], hero['int'][1]), inline=True) em.add_field(name='Movement speed', value=hero['ms'], inline=True) em.add_field(name='Armor', value=hero['armor'], inline=True) em.add_field(name='Regen', value=hero['regen'], inline=True) em.add_field(name='Attack', value='{}-{}'.format(hero['attack'][0], hero['attack'][1]), inline=True) em.add_field(name='Range', value=hero['range'], inline=True) em.add_field(name='Vision (day/night)', value='{}/{}'.format(hero['vision'][0], hero['vision'][1]), inline=True) em.set_footer(text='<3 Dota cog, Gamepedia & Dotabuff') # send embed await self.bot.send_message(ctx.message.channel, embed=em) except: await self.bot.say('Couldn\'t get info from Gamepedia API :(')
async def catfact(self): """Random Cat Facts!""" async with aiohttp.get(r'https://catfact.ninja/fact') as r: res = await r.json() fact = res['fact'] await self.bot.say(fact)
async def build(self, ctx, *, hero): """Gets most popular skillbuild for a hero""" # Build an url url = "http://www.dotabuff.com/heroes/" + hero.lower().replace( " ", "-") async with aiohttp.get(url, headers={"User-Agent": "Red-DiscordBot"}) as response: soupObject = BeautifulSoup(await response.text(), "html.parser") # "build" will contain a final table # "headers" will contain table headers with lvl numbers build = [] headers = "" try: skillSoup = soupObject.find(class_='skill-choices') # Generate skill tree for skill in enumerate(skillSoup.find_all(class_='skill')): # Get skill names for the first row build.append([ skill[1].find(class_='line').find( class_='icon').find('img').get('alt') ]) # Generate build order for entry in enumerate( skill[1].find(class_='line').find_all(class_='entry')): if "choice" in entry[1].get("class"): build[skill[0]].append("X") else: build[skill[0]].append(" ") # Get a part of the table def getPartialTable(table, start, end): tables = [] for row in enumerate(table): if start == 0: result = [] else: result = [table[row[0]][0]] result[1:] = row[1][start:end] tables.append(result) return tables # Generate 2 messages (for a splitted table) # TODO: Convert into one "for" cycle message = "The most popular build **at the moment**, according to Dotabuff:\n\n" message += "```" headers = ["Skill/Lvl"] headers[len(headers):] = range(1, 7) message += tabulate(getPartialTable(build, 1, 7), headers=headers, tablefmt="fancy_grid") message += "```\n" message += "```" headers = ["Skill/Lvl"] headers[len(headers):] = range(7, 13) message += tabulate(getPartialTable(build, 7, 13), headers=headers, tablefmt="fancy_grid") message += "```\n" # Send first part await self.bot.say(message) message = "```" headers = ["Skill/Lvl"] headers[len(headers):] = range(13, 19) message += tabulate(getPartialTable(build, 13, 19), headers=headers, tablefmt="fancy_grid") message += "```\n" # Send second part await self.bot.say(message) except: # Nothing can be done await self.bot.say("Error parsing Dotabuff, maybe try again later")
async def on_message(message): # we do not want the bot to reply to itself if message.author == client.user: return #help command. if message.content.startswith('{}help'.format(cmd)): await client.send_message(message.channel, ':mailbox_with_mail: {0.author.mention}'.format(message)) msg = '```Heres a list of my commands:'\ '\n\n-ping - Bot simply replies ping (unless your special) useful for knowing whether or not It\'s online'\ '\n\n-cat - Bot posts a random cat picture'\ '\n\n-say [message] - Bot echos your message'\ '\n\n-trump - Bot posts a random Trump gif'\ '\n\n-hillary - Bot posts a random Hillary gif'\ '\n\n-bernie - Bot posts a random Bernie gif'\ '\n\n-horse - Bot posts a random horse gif'\ '\n\n-dog - Bot posts a random dog gif'\ '\n\n-restart - restarts the bot (only works for Blake and Zach aka the bot devs)'\ '\n\n-shutdown - turns the bot off (again only works for Blake and Zach)'\ '\n\n-leave [server name] - gets the bot to leave a server (Only works for Blake)'\ '\n\n-guess - starts the guessing game'\ '\n\n-mark - a special song written by Bahar for Mark'\ '\n\n-invite - get an invite link for the bot so it can join your server!'\ '\n\nBot coded by Blake with help from Zach.```'\ await client.send_message(message.author, msg) #Ping command. elif message.content.startswith('{}ping'.format(cmd)): if message.author.id == '129437909131591680': msg = 'Bang, Bang! {0.author.mention}'.format(message) await client.send_message(message.channel, msg) elif message.author.id == '183790956754108416': msg = 'Hello Master! :wave: {0.author.mention}'.format(message) await client.send_message(message.channel, msg) elif message.author.id == '129439119737749505': msg = 'You\'re a nerd. you ain\'t got no balls! {0.author.mention}'.format(message) await client.send_message(message.channel, msg) elif message.author.id == '238469392155803649': msg = 'Hello Queen Alexis! :wave: {0.author.mention}'.format(message) await client.send_message(message.channel, msg) elif message.author.id == '230196465807392769': msg = 'My Queen! :heart: {0.author.mention}'.format(message) await client.send_message(message.channel, msg) elif message.author.id == '192664155348533248': msg = 'Mr. Pattems! :grin: {0.author.mention}'.format(message) await client.send_message(message.channel, msg) else: msg = 'PONG! {0.author.mention}'.format(message) await client.send_message(message.channel, msg) #cat command elif message.content.startswith('{}cat'.format(cmd)): async with aiohttp.get('http://random.cat/meow') as r: if r.status == 200: js = await r.json() await client.send_message(message.channel,js['file']) #Trump command elif message.content.startswith('{}trump'.format(cmd)): img = translate('Trump', api_key='dc6zaTOxFJmzC') await client.send_message(message.channel,img) #Hillary command elif message.content.startswith('{}hillary'.format(cmd)): img = translate('Hillary', api_key='dc6zaTOxFJmzC') await client.send_message(message.channel,img) #Bernie command elif message.content.startswith('{}bernie'.format(cmd)): img = translate('Bernie', api_key='dc6zaTOxFJmzC') await client.send_message(message.channel,img) #Horse command elif message.content.startswith('{}horse'.format(cmd)): img = translate('Horse', api_key='dc6zaTOxFJmzC') await client.send_message(message.channel,img) #Dog command elif message.content.startswith('{}dog'.format(cmd)): img = translate('Dog', api_key='dc6zaTOxFJmzC') await client.send_message(message.channel,img) #Say command elif message.content.startswith('{}say'.format(cmd)): messageToTTS = message.content[5:] await client.send_message(message.channel, content=messageToTTS) #Restart command elif message.content.startswith('{}restart'.format(cmd)): if message.author.id == '183790956754108416': msg = '```Restarting!!```' await client.send_message(message.channel, msg) os.execl(sys.executable, sys.executable, *sys.argv) elif message.author.id == '129437909131591680': msg = '```Restarting!!```' await client.send_message(message.channel, msg) os.execl(sys.executable, sys.executable, *sys.argv) else: msg = '```ERROR: What the F**K do you think you\'re doing?!```' await client.send_message(message.channel, msg) #shutdown command elif message.content.startswith('{}shutdown'.format(cmd)): if message.author.id == '183790956754108416': await client.send_message(message.channel, 'Peace out guys! :v:') await client.logout() elif message.author.id == '129437909131591680': await client.send_message(message.channel, 'Peace out guys! :v:') await client.logout() else: msg = '```ERROR: What the F**K do you think you\'re doing?!```' await client.send_message(message.channel, msg) #leave command elif message.content.startswith('{}leave'.format(cmd)): if message.author.id == '183790956754108416': await client.send_message(message.channel, 'Ok, I\'ll leave that server! :ok_hand:') await client.leave_server(discord.utils.get(client.servers)) else: msg = '```ERROR: What the F**K do you think you\'re doing?!```' await client.send_message(message.channel, msg) #invite command elif message.content.startswith('{}invite'.format(cmd)): msg = 'use this link to invite me to your server! :smiley:'\ '\n\nhttps://discordapp.com/oauth2/authorize?&client_id=223249543578255360&scope=bot&permissions=0'\ '\n\nNote from the Developer: I reserve the right to remove my bot from your server for any reason without any prior notice, enjoy my bot!'\ await client.send_message(message.channel, msg) #Mark command elif message.content.startswith('{}mark'.format(cmd)): msg = '```Mark is a nerd. He ain\'t got no balls.'\ '\n\nHis dick isn\'t big and his asshole\'s not small.'\ '\n\nThem weird ol voices make you wanna die.'\ '\n\nSingin\' pen pinapple until the day that I die.'\ '\n\nSingin\' pen pineapple until the day I die.```'\ await client.send_message(message.channel, msg) #Guess command elif message.content.startswith('{}guess'.format(cmd)): await client.send_message(message.channel, 'Guess a number between 1 to 10') def guess_check(m): return m.content.isdigit() guess = await client.wait_for_message(timeout=5.0, author=message.author, check=guess_check) answer = random.randint(1, 10) if guess is None: fmt = 'Sorry, you took too long. It was {}.' await client.send_message(message.channel, fmt.format(answer)) return if int(guess.content) == answer: await client.send_message(message.channel, 'You are right!') else: await client.send_message(message.channel, 'Sorry. It is actually {}.'.format(answer))
async def async_refresh(self, url): async with aiohttp.get(url) as r: response = await r.json() return response
async def download_image(self, image_url): async with aiohttp.get(image_url) as r: if r.status == 200: image_data = await r.read() return image_data return None
async def draw_user_small(self, user, gamemode: int, background: str): font = 'Tahoma' # get urls if background in bgs.keys() and background != 'random': bg_url = bgs[background] else: bg_url = random.choice(list(bgs.values())) profile_url = 'http://s.ppy.sh/a/{}.png'.format(user['user_id']) osu_logo_url = 'http://puu.sh/pT7JR/577b0cc30c.png' icons_url = [ 'http://puu.sh/pT2wd/4009301880.png', 'http://puu.sh/pT7XO/04a636cd31.png', 'http://puu.sh/pT6L5/3528ea348a.png', 'http://puu.sh/pT6Kl/f5781e085b.png' ] gamemode_url = icons_url[gamemode] flag_url = 'https://new.ppy.sh//images/flags/{}.png'.format( user['country']) try: async with aiohttp.get(bg_url) as r: image = await r.content.read() with open('data/osu/temp_bg.png', 'wb') as f: f.write(image) async with aiohttp.get(profile_url) as r: image = await r.content.read() with open('data/osu/temp_profile.png', 'wb') as f: f.write(image) async with aiohttp.get(osu_logo_url) as r: image = await r.content.read() with open('data/osu/temp_osu_logo.png', 'wb') as f: f.write(image) async with aiohttp.get(profile_url) as r: image = await r.content.read() with open('data/osu/temp_profile.png', 'wb') as f: f.write(image) async with aiohttp.get(gamemode_url) as r: image = await r.content.read() with open('data/osu/temp_gamemode.png', 'wb') as f: f.write(image) async with aiohttp.get(flag_url) as r: image = await r.content.read() with open('data/osu/temp_flag.png', 'wb') as f: f.write(image) success = True except Exception as e: success = False print(e) if success: with Image(filename='data/osu/temp_bg.png') as base_img: # background cropping as base image base_img.resize(600, 600) base_img.crop(0, 0, 488, 170) # draw transparent black rectangle with Drawing() as draw: draw.fill_color = Color('#000000') draw.fill_opacity = 0.6 draw.rectangle(left=10, top=10, right=478, bottom=160) draw(base_img) # create level graphic with Drawing() as draw: level_int = int(float(user['level'])) level_percent = float(user['level']) - level_int full_length = 458 level_length = full_length * level_percent draw.fill_color = Color('#FFF') draw.fill_opacity = 0.6 draw.rectangle(left=15, top=145, width=level_length, bottom=155) draw(base_img) with Drawing() as draw: draw.fill_opacity = 1 draw.text_alignment = 'center' draw.font_size = 13 draw.font_weight = 500 draw.fill_color = Color('#FFF') draw.text(int(base_img.width / 2), 155, "Lvl {}".format(str(level_int))) draw(base_img) # grab user profile image with Image( filename='data/osu/temp_profile.png') as profile_img: # user_profile image resizing profile_img.resize(130, 130) base_img.composite(profile_img, left=10, top=10) # writes lables with Drawing() as draw: draw.text_alignment = 'right' draw.font_size = 20 draw.font_weight = 500 draw.font_family = font draw.fill_color = Color('#FFFFFF') x = 255 # x offset draw.text(x, 60, "Rank: ") draw.text(x, 85, "PP: ") draw.text(x, 110, "Playcount: ") draw.text(x, 135, "Accuracy: ") draw(base_img) # write user information with Drawing() as draw: draw.font_size = 26 draw.font_weight = 500 draw.font_family = font draw.text_alignment = 'center' draw.fill_color = Color('#FFFFFF') draw.text_decoration = 'underline' draw.text(310, 35, user['username']) draw(base_img) with Drawing() as draw: draw.font_size = 20 draw.font_weight = 500 draw.font_family = font draw.fill_color = Color('#FFFFFF') draw.text_decoration = 'no' x = 255 # x offset draw.text( x, 60, "#{} (#{})".format(user['pp_rank'], user['pp_country_rank'])) draw.text(x, 85, "{}".format(user['pp_raw'])) draw.text(x, 110, "{}".format(user['playcount'])) draw.text(x, 135, "{}%".format(user['accuracy'][0:5])) draw(base_img) # draw osu with correct gamemode with Image(filename='data/osu/temp_osu_logo.png') as osu_icon: osu_icon.resize(45, 45) base_img.composite(osu_icon, left=430, top=95) # puts on gamemode, yes, they are in order [standard, taiko, ctb, mania] with Image(filename='data/osu/temp_gamemode.png') as mode_icon: mode_icon.resize(43, 43) base_img.composite(mode_icon, left=385, top=95) # puts on country flag with Image(filename='data/osu/temp_flag.png') as flag_icon: flag_icon.resize(30, 20) # arbitrary flag size base_img.composite(flag_icon, left=440, top=17) # save the image base_img.save(filename='data/osu/user.png') os.remove('data/osu/temp_bg.png') os.remove('data/osu/temp_profile.png') os.remove('data/osu/temp_osu_logo.png') os.remove('data/osu/temp_gamemode.png') os.remove('data/osu/temp_flag.png') else: await self.bot.say("Problem generating image.")
async def steam(self, ctx, appid: str): '''Gibt Informationen zu einem Spiel bei Steam aus Beispiel: ----------- :steam 570 ''' await self.bot.send_typing(ctx.message.channel) steamSpyURL = f'{self.steamSpyAPIURL}?request=appdetails&appid={appid}' async with aiohttp.get(steamSpyURL) as r: spyJSON = await r.json() steamCurrentPlayerURL = f'{self.steamCurrentPlayerAPIURL}{appid}' async with aiohttp.get(steamCurrentPlayerURL) as r: currentPlayerJSON = await r.json() steamMarketURL = f'{self.steamMarketAPIURL}{appid}' async with aiohttp.get(steamMarketURL) as r: marketJSON = await r.json() owner = '{:,}'.format(spyJSON['owners']).replace(',', '.') owner += ' ± ' owner += '{:,}'.format(spyJSON['owners_variance']).replace(',', '.') try: price = str( int(marketJSON[appid]['data']['price_overview']['final']) / 100) + '€' if marketJSON[appid]['data']['price_overview'][ 'discount_percent'] != 0: price += ' (-{}%)'.format( marketJSON[appid]['data']['price_overview'] ['discount_percent']) except KeyError: price = 'Free' embed = discord.Embed(color=0x2F668D, title=spyJSON['name'], url=f'http://store.steampowered.com/app/{appid}') embed.set_footer(text='AppID: {}'.format(spyJSON['appid'])) embed.set_thumbnail( url= f'http://cdn.akamai.steamstatic.com/steam/apps/{appid}/header.jpg') embed.add_field(name='Name', value=spyJSON['name'], inline=True) embed.add_field(name='Score Rank', value=spyJSON['score_rank'], inline=True) embed.add_field(name='Preis', value=price, inline=True) embed.add_field(name='Besitzer', value=owner, inline=True) embed.add_field(name='Derzeitige Spieler', value=currentPlayerJSON['response']['player_count'], inline=True) embed.add_field(name='Durchschnittliche Spieler gestern', value=spyJSON['ccu'], inline=True) embed.add_field(name='Entwickler', value=spyJSON['developer'], inline=True) embed.add_field(name='Publisher', value=spyJSON['publisher'], inline=True) if marketJSON[appid]['data']['short_description'] != '' and marketJSON[ appid]['data']['short_description'] != None: discription = re.sub( re.compile('<.*?>'), '', marketJSON[appid]['data']['short_description']) embed.add_field(name='Beschreibung', value=discription, inline=False) embed.add_field(name='Link', value=f'http://store.steampowered.com/app/{appid}', inline=False) await self.bot.say(embed=embed)
async def draw_user_profile(self, user, userbest, gamemode: int, background: str): font = 'Verdana, Geneva, sans-serif' key = self.osu_api_key["osu_api_key"] # get best plays map information and scores best_beatmaps = [] best_acc = [] for i in range(len(userbest)): beatmap = list(await get_beatmap( key, beatmap_id=userbest[i]['beatmap_id']))[0] score = list(await get_scores(key, userbest[i]['beatmap_id'], user['user_id'], gamemode))[0] best_beatmaps.append(beatmap) best_acc.append(self.calculate_acc(score, gamemode)) # get urls if background in bgs.keys() and background != 'random': bg_url = bgs[background] else: bg_url = random.choice(list(bgs.values())) profile_url = 'http://s.ppy.sh/a/{}.png'.format(user['user_id']) osu_logo_url = 'http://puu.sh/pT7JR/577b0cc30c.png' icons_url = [ 'http://puu.sh/pT2wd/4009301880.png', 'http://puu.sh/pT7XO/04a636cd31.png', 'http://puu.sh/pT6L5/3528ea348a.png', 'http://puu.sh/pT6Kl/f5781e085b.png' ] gamemode_url = icons_url[gamemode] flag_url = 'https://new.ppy.sh//images/flags/{}.png'.format( user['country']) try: async with aiohttp.get(bg_url) as r: image = await r.content.read() with open('data/osu/temp_bg.png', 'wb') as f: f.write(image) async with aiohttp.get(profile_url) as r: image = await r.content.read() with open('data/osu/temp_profile.png', 'wb') as f: f.write(image) async with aiohttp.get(osu_logo_url) as r: image = await r.content.read() with open('data/osu/temp_osu_logo.png', 'wb') as f: f.write(image) async with aiohttp.get(profile_url) as r: image = await r.content.read() with open('data/osu/temp_profile.png', 'wb') as f: f.write(image) async with aiohttp.get(gamemode_url) as r: image = await r.content.read() with open('data/osu/temp_gamemode.png', 'wb') as f: f.write(image) async with aiohttp.get(flag_url) as r: image = await r.content.read() with open('data/osu/temp_flag.png', 'wb') as f: f.write(image) success = True except Exception as e: success = False print(e) if success: with Image(filename='data/osu/temp_bg.png') as base_img: # background cropping base_img.resize(600, 600) base_img.crop(0, 0, 488, 488) # draw transparent black rectangle with Drawing() as draw: draw.fill_color = Color('#000000') draw.fill_opacity = 0.6 draw.rectangle(left=10, top=10, right=478, bottom=160) draw(base_img) # create level graphic with Drawing() as draw: level_int = int(float(user['level'])) level_percent = float(user['level']) - level_int full_length = 458 level_length = full_length * level_percent draw.fill_color = Color('#FFF') draw.fill_opacity = 0.6 draw.rectangle(left=15, top=145, width=level_length, bottom=155) draw(base_img) with Drawing() as draw: draw.fill_opacity = 1 draw.text_alignment = 'center' draw.font_size = 13 draw.font_weight = 500 draw.fill_color = Color('#FFF') draw.text(int(base_img.width / 2), 155, "Lvl {}".format(str(level_int))) draw(base_img) # draw transparent white rectangle with Drawing() as draw: draw.fill_color = Color('#FFFFFF') draw.fill_opacity = 0.6 draw.rectangle(left=10, top=160, right=478, bottom=478) draw(base_img) with Image( filename='data/osu/temp_profile.png') as profile_img: # user_profile image resizing profile_img.resize(130, 130) base_img.composite(profile_img, left=10, top=10) # writes lables with Drawing() as draw: draw.text_alignment = 'right' draw.font_size = 20 draw.font_weight = 500 draw.fill_color = Color('#FFFFFF') x = 255 # x offset draw.text(x, 60, "Rank: ") draw.text(x, 85, "PP: ") draw.text(x, 110, "Playcount: ") draw.text(x, 135, "Accuracy: ") draw(base_img) # write user information with Drawing() as draw: draw.font_size = 26 draw.font_weight = 500 draw.font_family = font draw.text_alignment = 'center' draw.fill_color = Color('#FFFFFF') draw.text_decoration = 'underline' draw.text(310, 35, user['username']) draw(base_img) with Drawing() as draw: draw.font_size = 20 draw.font_weight = 500 draw.font_family = font draw.fill_color = Color('#FFFFFF') draw.text_decoration = 'no' x = 255 # x offset draw.text( x, 60, "#{} (#{})".format(user['pp_rank'], user['pp_country_rank'])) draw.text(x, 85, "{}".format(user['pp_raw'])) draw.text(x, 110, "{}".format(user['playcount'])) draw.text(x, 135, "{}%".format(user['accuracy'][0:5])) draw(base_img) # draw osu icon with Image(filename='data/osu/temp_osu_logo.png') as osu_icon: osu_icon.resize(45, 45) base_img.composite(osu_icon, left=430, top=95) # puts on gamemode with Image(filename='data/osu/temp_gamemode.png') as mode_icon: mode_icon.resize(43, 43) base_img.composite(mode_icon, left=385, top=95) # puts on country flag with Image(filename='data/osu/temp_flag.png') as flag_icon: flag_icon.resize(30, 20) # arbitrary flag size base_img.composite(flag_icon, left=440, top=17) # writes best performances with Drawing() as draw: draw.font_size = 28 draw.font_weight = 1000 draw.font_family = font draw.text_alignment = 'center' draw.fill_color = Color('#555') draw.fill_opacity = 0.6 draw.text(244, 195, "{}".format('Best Performances')) draw(base_img) # create tiles for best plays using top_play_beatmaps and userbest. Includes rank, title, diff, mods, pp, timestamp left_align = 20 top_initial = 210 spacing = 53 # draw transparent white rectangles for i in range(len(userbest)): with Drawing() as draw: draw.fill_color = Color('#CCC') draw.fill_opacity = 0.6 draw.rectangle(left=left_align + 2, top=top_initial + spacing * i - 2, width=445, height=45) draw(base_img) for i in range(len(userbest)): with Drawing() as draw: draw.font_size = 18 draw.font_weight = 500 # rank image rank_url = 'https://new.ppy.sh/images/badges/score-ranks/{}.png'.format( userbest[i]['rank']) try: async with aiohttp.get(rank_url) as r: image = await r.content.read() with open('data/osu/temp_rank.png', 'wb') as f: f.write(image) except Exception as e: print(e) with Image(filename='data/osu/temp_rank.png' ) as rank_icon: rank_icon.resize(45, 45) base_img.composite(rank_icon, left=left_align + 10, top=top_initial + (i) * spacing) left_text_margin = left_align + 62 right_text_margin = 370 first_line = 17 second_line = first_line + 20 draw.text( left_text_margin, top_initial + first_line + (i) * spacing, "{} ({:0.2f}%)".format( self.truncate_text(best_beatmaps[i]['title']), best_acc[i])) draw.text( left_text_margin, top_initial + second_line + (i) * spacing, "[{}]".format( self.truncate_text( best_beatmaps[i]['version']))) draw.text(right_text_margin, top_initial + first_line + (i) * spacing, "{:0.2f}pp".format(float(userbest[i]['pp']))) # handle mod images mods = self.mod_calculation( userbest[i]['enabled_mods']) if len(mods) > 0: for j in range(len(mods)): # puts on mod images mod_url = 'https://new.ppy.sh/images/badges/mods/{}.png'.format( mods[j]) try: async with aiohttp.get(mod_url) as r: image = await r.content.read() with open('data/osu/temp_mod.png', 'wb') as f: f.write(image) except Exception as e: print('Issue grabbing mods.' + e) with Image(filename='data/osu/temp_mod.png' ) as mod_icon: mod_icon.resize(30, 22) side_ways_spacing = 32 base_img.composite( mod_icon, left=right_text_margin + side_ways_spacing * (j), top=top_initial + first_line + 3 + (i) * spacing) # because image os.remove('data/osu/temp_mod.png') draw(base_img) os.remove('data/osu/temp_rank.png') # save the image base_img.save(filename='data/osu/user_profile.png') os.remove('data/osu/temp_bg.png') os.remove('data/osu/temp_profile.png') os.remove('data/osu/temp_osu_logo.png') os.remove('data/osu/temp_gamemode.png') os.remove('data/osu/temp_flag.png') else: await self.bot.say("Problem generating image.")
async def wr_menu(self, ctx, wr_list: list, message: discord.Message = None, page=0, timeout: int = 30): """menu control logic for this taken from https://github.com/Lunar-Dust/Dusty-Cogs/blob/master/menu/menu.py""" cur_page = wr_list[page] colour =\ ''.join([randchoice('0123456789ABCDEF') for x in range(6)]) colour = int(colour, 16) created_at = cur_page["record"]["run"]["submitted"] post_url = cur_page["record"]["run"]["weblink"] submit_time = "Submitted at " + created_at runner_url = cur_page["record"]["run"]["players"][0]["uri"] async with aiohttp.get(runner_url) as runner_get: runner_data = await runner_get.json() if "names" in runner_data["data"]: runner = runner_data["data"]["names"]["international"] else: runner = "Anonymous" desc = "" if cur_page["record"]["run"]["comment"] is None: desc = "No comments" else: desc = cur_page["record"]["run"]["comment"] emb = discord.Embed(title=cur_page["game_name"], colour=discord.Colour(value=colour), url=post_url, description=desc) emb.add_field(name="Category", value=cur_page["cat_info"]["name"]) emb.add_field(name="Runner", value=runner) emb.add_field( name="Time", value=str( datetime.timedelta( seconds=cur_page["record"]["run"]["times"]["primary_t"]))) emb.set_footer(text=submit_time) if not message: message =\ await self.bot.send_message(ctx.message.channel, embed=emb) await self.bot.add_reaction(message, "⬅") await self.bot.add_reaction(message, "❌") await self.bot.add_reaction(message, "➡") else: message = await self.bot.edit_message(message, embed=emb) react = await self.bot.wait_for_reaction(message=message, user=ctx.message.author, timeout=timeout, emoji=["➡", "⬅", "❌"]) if react is None: await self.bot.remove_reaction(message, "⬅", self.bot.user) await self.bot.remove_reaction(message, "❌", self.bot.user) await self.bot.remove_reaction(message, "➡", self.bot.user) return None reacts = {v: k for k, v in numbs.items()} react = reacts[react.reaction.emoji] if react == "next": next_page = 0 if page == len(wr_list) - 1: next_page = 0 # Loop around to the first item else: next_page = page + 1 return await self.wr_menu(ctx, wr_list, message=message, page=next_page, timeout=timeout) elif react == "back": next_page = 0 if page == 0: next_page = len(wr_list) - 1 # Loop around to the last item else: next_page = page - 1 return await self.wr_menu(ctx, wr_list, message=message, page=next_page, timeout=timeout) else: return await\ self.bot.delete_message(message)
async def imdb(self, ctx, *title): """Search for movies on imdb""" if title == (): await send_cmd_help(ctx) return else: if self.settings["api_key"] == "": getKeyUrl = "http://www.myapifilms.com/token.do" await self.bot.say("` This cog wasn't configured properly. If you're the owner, add your API key available from '{}', and use '{}apikey_imdb' to setup`".format(getKeyUrl, ctx.prefix)) return try: await self.bot.send_typing(ctx.message.channel) movieTitle = "+".join(title) search = "http://api.myapifilms.com/imdb/title?format=json&title=" + movieTitle + "&token=" + self.settings["api_key"] async with aiohttp.get(search) as r: result = await r.json() title = result['data']['movies'][0]['title'] year = result['data']['movies'][0]['year'] if year == "": year = "????" rating = result['data']['movies'][0]['rating'] rating = rating.replace("," , ".") if rating == "": rating = "-" else: rating = float(rating) urlz = result['data']['movies'][0]['urlIMDB'] urlPoster = result['data']['movies'][0]['urlPoster'] if urlPoster == "": urlPoster = "http://instagram.apps.wix.com/bundles/wixinstagram/images/ge/no_media.png" simplePlot = result['data']['movies'][0]['simplePlot'] if simplePlot == "": simplePlot = "Everyone died...." #data = discord.Embed(colour=discord.Colour.yellow()) data = discord.Embed(colour=0xE4BA22) data.add_field(name="Title:", value=str(title), inline=True) data.add_field(name="Released on:", value=year) if type(rating) is float: emoji = ":poop:" if float(rating) > 3.5: emoji = ":thumbsdown:" if float(rating) > 5.2: emoji = ":thumbsup:" if float(rating) > 7.0: emoji = ":ok_hand:" else: emoji = "" rating= "{} {}".format(rating, emoji) data.add_field(name="IMDB Rating:", value=rating) if urlz != "": moreinfo = ("{}\n[Read more...]({})".format(simplePlot, urlz)) data.add_field(name="Plot:", value=moreinfo) data.set_footer(text="\n\n") data.set_thumbnail(url=urlPoster) await self.bot.say(embed=data) #Big image, will break soon™ #find = "._V1_"; #split_pos = urlPoster.find(find) #urlPoster = urlPoster[0:split_pos+5]+".jpg" #response = await self.bot.wait_for_message(timeout=20, author=ctx.message.author) #if response is None: # pass #else: # response = response.content.lower().strip() #if response.startswith(("bigpic", "cover", "big", ":eyeglasses:")): # await self.bot.say(urlPoster) except discord.HTTPException: await self.bot.say("I need the `Embed links` permission to send this") except Exception as e: print(e) await self.bot.say("` Error getting a result.`")
async def post_issue(self, message, prefix, number): api = 'https://api.github.com/repos/{}/issues/{}'.format(self.settings[message.server.id][prefix]['gh'], number) fields = self.settings[message.server.id][prefix]['fields'] async with aiohttp.request("GET", api, headers={'Accept': 'application/vnd.github.black-cat-preview+json'}) as r: # Check is the issue exists if r.status == 404: return False result = await r.json() # Check if the issue is a PR if 'pull_request' in result: issue_type = "pr" pr_api = 'https://api.github.com/repos/{}/pulls/{}'.format(self.settings[message.server.id][prefix]['gh'], number) async with aiohttp.get(pr_api, headers={'Accept': 'application/vnd.github.black-cat-preview+json'}) as r: pr_result = await r.json() else: issue_type = "issue" # Check if the issue is open, closed or merged. if result['state'] == 'open': colour = self.colour['open'] elif issue_type == 'pr' and pr_result['merged'] is True: colour = self.colour['merged'] else: colour = self.colour['closed'] # Check for title and description if fields['description'] is True: description = result['body'] embed_description = (description[:175] + '...') if len(description) > 175 else description embed = discord.Embed(title='{} #{}'.format(result['title'], result['number']), description=embed_description, url=result['html_url'], colour=colour) else: embed = discord.Embed(title='{} #{}'.format(result['title'], result['number'], url=result['html_url'], colour=colour)) if fields['author'] is True: embed.set_author(name=result['user']['login'], icon_url=result['user']['avatar_url'], url=result['user']['html_url']) # Check for assigned users if fields['assigned'] is True and len(result['assignees']) != 0: desc = '' for assigned in result['assignees']: desc = desc + ('[{}]({})\n'.format(assigned['login'], assigned['html_url'])) embed.add_field(name='Assigned', value=desc) # Check for Created at, Closed at and Closed By if fields['createdat'] is True or fields['closedby'] is True: desc = '' if fields['closedby'] is True and result['state'] == 'closed': closed_user_avatar = result['closed_by']['avatar_url'] closed_at = datetime.strptime(result['closed_at'], '%Y-%m-%dT%H:%M:%SZ') closed_at = closed_at.strftime('%-d %b %Y, %-H:%M') desc = desc + 'Closed by {} on {}'.format(result['closed_by']['login'], closed_at) if fields['createdat'] is True: created_at = datetime.strptime(result['created_at'], '%Y-%m-%dT%H:%M:%SZ') created_at = created_at.strftime('%-d %b %Y, %-H:%M') if result['state'] == 'closed' and fields['closedby'] is True: desc = desc + ' | Created on {}'.format(created_at) else: desc = desc + 'Created on {}'.format(created_at) if result['state'] == 'closed' and fields['closedby'] is True: embed.set_footer(icon_url=closed_user_avatar, text=desc) else: embed.set_footer(text=desc) # Check for Labels if fields['labels'] is True and len(result['labels']) != 0: label_list = [] for label in result['labels']: label_list.append('{}'.format(label['name'])) embed.add_field(name='Labels [{}]'.format(len(result['labels'])), value=', '.join(label_list)) # Check for locked Issues if fields['locked'] is True: if result['locked'] is True: embed.add_field(name='Locked', value='Yes') else: embed.add_field(name='Locked', value='No') # Check for Merge Status if fields['mergestatus'] is True and issue_type == 'pr': if pr_result['merged'] is True: merge_status = 'Merged' elif pr_result['mergeable_state'] == 'dirty': merge_status = 'Conflicting' else: merge_status = 'Not Merged' embed.add_field(name='Merge Status', value=merge_status) # Milestones: TODO lololololol # Check for Reviews if fields['reviews'] is True and issue_type == 'pr': # Need to make another connection *ugh*. Goodbye quick loading times. review_api = 'https://api.github.com/repos/{}/pulls/{}/reviews'.format(self.settings[message.server.id][prefix]['gh'], number) async with aiohttp.get(review_api, headers={'Accept': 'application/vnd.github.black-cat-preview+json'}) as r: review_result = await r.json() review_list = [] for review in review_result: if review['state'] == 'APPROVED': review_list.append([review['user']['login'], 'Approved']) elif review['state'] == 'CHANGES_REQUESTED': review_list.append([review['user']['login'], 'Requested Changes']) if len(review_list) > 0: desc = '' for user in review_list: desc = desc + '{}: {}'.format(*user) embed.add_field(name='Reviews', value=desc) await self.bot.send_message(message.channel, embed=embed)
async def wanted(self, ctx, user: discord.Member = None): """Show your wanted poster""" self.nicks = fileIO("data/wanted/nicks.json", "load") if not user: user = ctx.message.author #WANTED POSTER if user.id in self.bounties or user.id in self.Fbounties: wanted = "data/wanted/wanted.png" wanted_heigh = 283 wanted_width = 200 result = Image.open(wanted).convert('RGBA') process = Image.new('RGBA', (wanted_width, wanted_heigh), (0, 0, 0)) #PFP avatar_url = user.avatar_url avatar_image = Image try: async with aiohttp.get(avatar_url) as r: image = await r.content.read() with open('data/wanted/temp_avatar', 'wb') as f: f.write(image) success = True except Exception as e: success = False print(e) if success: if len(avatar_url) == 0: avatar_image = Image.open( 'data/wanted/avatar.png').convert('RGBA') else: avatar_image = Image.open( 'data/wanted/temp_avatar').convert('RGBA') avatar_image = avatar_image.resize(size=(120, 120)) result.paste(avatar_image, (39, 63)) #NAME fnt = ImageFont.truetype('data/wanted/western.ttf', 30) if user.id not in self.nicks: if len(user.name) > 14: text = user.name[:14] else: text = user.name await self.bot.say( "Pro tip : If you want a personalized name for your wanted, poster, then just type " + fileIO("data/red/settings.json", "load")["PREFIXES"][0] + "wanted_name name! :wink:") else: text = self.nicks[user.id] text_width = fnt.getsize(text)[0] text_heigh = fnt.getsize(text)[1] d = ImageDraw.Draw(result) d.text((wanted_width / 2 - text_width / 2, 200), text, font=fnt, fill=(0, 0, 0, 0)) d = ImageDraw.Draw(result) #BOUNTY fnt2 = ImageFont.truetype('data/wanted/bounty.ttf', 26) bounty = self.getBounty(user.id) if bounty == 0: text2 = "50" else: text2 = self.virgule(bounty) text2_width = fnt2.getsize(text2)[0] text_heigh = fnt2.getsize(text2)[1] d = ImageDraw.Draw(result) d.text((wanted_width / 2 - text_width / 2, 200), text, font=fnt, fill=(0, 0, 0, 0)) d.text(((wanted_width / 2 - text2_width / 2) + 15, 225), text2, font=fnt2, fill=(0, 0, 0, 0)) d = ImageDraw.Draw(result) #RESULT result.save('data/wanted/temp.jpg', 'JPEG', quality=100) await self.bot.send_file(ctx.message.channel, 'data/wanted/temp.jpg') os.remove('data/wanted/temp.jpg') else: await self.bot.say( "This member need to use **" + fileIO("data/red/settings.json", "load")["PREFIXES"][0] + "register_wanted** to get this feature!")