def _get_session_instance(cls) -> aiohttp.ClientSession: session = aiohttp.ClientSession() return session
async def download(url): async with aiohttp.ClientSession() as session: html = await get_content(session, url) parser_content(html)
async def capture_request(indexs, url, slot_path, slot_reserved, mask, cam_timeout, threshold): async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=cam_timeout)) as session: result = await asyncio.gather(*[capture(session, i, url, slot_path, slot_reserved, mask, cam_timeout, threshold) for i in indexs]) await session.close() return result
async def fetch_all(self, url_list, loop): async with aiohttp.ClientSession(loop=loop, headers=self.header) as session: results = await asyncio.gather( *[self.fetch(session, url) for url in url_list], return_exceptions=True) return results
async def upvote(ctx, url, weight): # only members of specified groups can use the bot. specified_groups = set(os.getenv("CURATOR_GROUPS").split(",")) user_roles = set([r.name for r in ctx.message.author.roles]) if not len(user_roles.intersection(specified_groups)): await bot.say("You don't have required permissions to do that.") return # check the channel is suitable if not channel_is_whitelisted( ctx.message.channel, os.getenv("CHANNEL_WHITELIST").split(",")): return # Try to parse author and permlink from the URL try: author, permlink = parse_author_and_permlink(url) except ValueError as e: await bot.say_error(e.args[0]) return # check the post availability (It might be deleted.) try: post_content = get_post_content( bot.lightsteem_client, author, permlink) except ValueError as e: await bot.say_error(e.args[0]) return # check the author is blacklisted in other communities. session = aiohttp.ClientSession() resp = await session.get( f"http://blacklist.usesteem.com/user/{author}") if resp.status != 200: print("Blacklist api returned non-200. Skipping the check.") else: response_in_json = await resp.json() if len(response_in_json["blacklisted"]): await bot.say( f":x: Caution. This author @{author} is on a blacklist " "and has **not** been upvoted." " Please select another winner." ) return # check if we already voted that post if already_voted(post_content, os.getenv("BOT_ACCOUNT")): await bot.say_error("Already voted on that post.") return # check the post in specified curation windows try: in_curation_window( post_content, max_age=os.getenv("LATE_CURATION_WINDOW"), min_age=os.getenv("EARLY_CURATION_WINDOW")) except Exception as e: await bot.say_error(e.args[0]) return # check the weight try: weight = int(weight) except ValueError as e: await bot.say_error("Invalid weight.") return if weight < 0 or weight > 100: await bot.say_error("Invalid weight. It must be between [0-100].") return bot.upvote(post_content, weight) await bot.say_success(f"Voted.")
async def yomomma(self): async with aiohttp.ClientSession() as cs: async with cs.get(self.base_api_link+"/yomomma", headers=self.headers) as r: r = await r.json() return r['joke']
async def chucknorris(self): async with aiohttp.ClientSession() as cs: async with cs.get(self.base_api_link+"/chucknorris", headers=self.headers) as r: r = await r.json() return r['joke']
async def on_message(message): author_id = message.author.mention.replace("<@","",).replace(">","").replace("!","") list_message = message.content.split(' ') prefix = '%' if message.content == f'{prefix}도움' or message.content == f'{prefix}도움말' or message.content == f'{prefix}help' or message.content == f'{prefix}명령어': log_info(message.guild,message.channel,message.author,message.content) embed = discord.Embed(color=0x0080ff) embed.set_author(icon_url=client.user.avatar_url,name='Music Bot') embed.add_field(name='음악',value='join,leave,play,skip,volume,pause,resume,shuffle,repeat,volume',inline=False) embed.add_field(name='관리',value='help,ping,information',inline=False) await message.channel.send(embed=embed) return if message.content == f'{prefix}ping': now = datetime.datetime.utcnow() embed = discord.Embed(title="Pong!", color=0x0080ff) msg = await message.channel.send(embed=embed) message_ping_c = msg.created_at - now message_ping = float(f'{message_ping_c.seconds}.{message_ping_c.microseconds}') embed = discord.Embed(title="Pong!",description=f"클라이언트 핑: {round(client.latency * 1000,2)}ms\n응답속도: {round(message_ping * 1000,2)}ms", color=0x0080ff) await msg.edit(embed=embed) return if message.content.startswith(f'{prefix}information'): log_info(message.guild,message.channel,message.author,message.content) total = 0 for i in client.guilds: total += len(i.members) embed = discord.Embed(title='Music Bot', color=0x00aaaa) embed.add_field(name='제작자',value='건유1019#0001',inline=True) embed.add_field(name='깃허브',value='[링크](https://github.com/gunyu1019/Music-Bot)',inline=True) embed.add_field(name='<:user:735138021850087476>서버수/유저수',value=f'{len(client.guilds)}서버/{total}명',inline=True) embed.add_field(name='<:discord:735135879990870086>discord.py',value=f'v{discord.__version__}',inline=True) embed.add_field(name='<:aiohttp:735135879634616351>aiohttp',value=f'v{aiohttp.__version__}',inline=True) embed.set_thumbnail(url=client.user.avatar_url) await message.channel.send(embed=embed) return if message.content == f'{prefix}join': log_info(message.guild,message.channel,message.author,message.content) if message.author.voice == None: embed = discord.Embed(title="MusicBot!",description="음성방에 들어가주세요!", color=0xaa0000) await message.channel.send(embed=embed) return channel = message.author.voice.channel voice = await channel.connect() voice_channels[voice] = [] voice_setting[voice] = { "shuffle": False, "repeat": False, "volume": 100 } embed = discord.Embed(description=f"{voice.channel}에 성공적으로 연결하였습니다!", color=0x0080ff) embed.set_author(name="Join",icon_url=client.user.avatar_url) await message.channel.send(embed=embed) return if message.content == f'{prefix}debug': log_info(message.guild,message.channel,message.author,message.content) voiceC = get_voice(message) if voiceC == None: embed = discord.Embed(title="MusicBot!",description="None", color=0x0080ff) await message.channel.send(embed=embed) return elif voiceC in voice_channels: embed = discord.Embed(title=f"{voiceC.channel.name}({voiceC.channel.id})", color=0x0080ff) embed.add_field(name='재생목록: ',value=f'{voice_channels[voiceC]}') embed.add_field(name='설정: ',value=f'{voice_setting[voiceC]}') await message.channel.send(embed=embed) return embed = discord.Embed(title="MusicBot!",description=f"None", color=0x0080ff) await message.channel.send(embed=embed) return if message.content == f'{prefix}leave': log_info(message.guild,message.channel,message.author,message.content) voiceC = get_voice(message) if voiceC == None or not voiceC in voice_channels: embed = discord.Embed(title="MusicBot!",description="음성채널방에 들어가있지 않습니다.", color=0xaa0000) await message.channel.send(embed=embed) return del voice_channels[voiceC] del voice_setting[voiceC] await voiceC.disconnect() embed = discord.Embed(description=f"{voiceC.channel}에 성공적으로 떠났습니다!", color=0x0080ff) embed.set_author(name="Leave",icon_url=client.user.avatar_url) await message.channel.send(embed=embed) return if message.content.startswith(f'{prefix}play'): log_info(message.guild,message.channel,message.author,message.content) voiceC = get_voice(message) if voiceC == None or not voiceC in voice_channels: embed = discord.Embed(title="MusicBot!",description="음성채널방에 들어가있지 않습니다.", color=0xaa0000) await message.channel.send(embed=embed) return if len(list_message) < 2: embed = discord.Embed(title="MusicBot!",description="URL 혹은 영상 링크를 넣어주세요.", color=0xaa0000) await message.channel.send(embed=embed) return music = " ".join(list_message[1:]) url_T = parse.urlparse(music) playlist_bool = False if url_T.netloc.endswith('youtube.com'): for i in url_T.query.split('&'): if i.startswith('list='): embed = discord.Embed(title="MusicBot!",description="재생목록을 다운로드받고 있습니다.\n상황에 따라 시간이 길게 소요될 수 있으니, 양해부탁드립니다.", color=0x0080ff) await message.channel.send(embed=embed) music = music.replace(i,'') await playlist(voiceC,i.split('list=')[1],message.author) playlist_bool = True if not playlist_bool: params = { "part":"snippet", "type":"vidoe", "maxResults":1, "key":key, "q":music } async with aiohttp.ClientSession() as session: async with session.get(f"https://www.googleapis.com/youtube/v3/search",params=params) as resp: html = await resp.json() if len(html['items']) == 0: embed = discord.Embed(title="MusicBot!",description="검색결과가 없습니다..", color=0xaa0000) await message.channel.send(embed=embed) return video = html['items'][0] video_id = video['id']['videoId'] title = video['snippet']['title'] thumbnail = f_thumbnail(video) author = message.author await download(video_id,f'https://www.youtube.com/watch?v={video_id}') voice_channels[voiceC].append((video_id,title,author,thumbnail)) embed = discord.Embed(description=f"[{title}](https://www.youtube.com/watch?v={video_id})가 정상적으로 추가되었습니다.", color=0x0080ff) embed.set_author(name="Play",icon_url=client.user.avatar_url) embed.set_footer(text=f'{author}가 등록하였습니다.',icon_url=author.avatar_url) await message.channel.send(embed=embed) if not voiceC.is_playing(): await m_play(message,voiceC) return if message.content == f'{prefix}skip': log_info(message.guild,message.channel,message.author,message.content) voiceC = get_voice(message) if voiceC == None or not voiceC in voice_channels: embed = discord.Embed(title="MusicBot!",description="음성채널방에 들어가있지 않습니다.", color=0xaa0000) await message.channel.send(embed=embed) return embed = discord.Embed(description="음악을 스킵합니다.", color=0x0080ff) embed.set_author(name="Skip",icon_url=client.user.avatar_url) await message.channel.send(embed=embed) voiceC.stop() return if message.content == f'{prefix}stop': log_info(message.guild,message.channel,message.author,message.content) voiceC = get_voice(message) if voiceC == None or not voiceC in voice_channels: embed = discord.Embed(title="MusicBot!",description="음성채널방에 들어가있지 않습니다.", color=0xaa0000) await message.channel.send(embed=embed) return embed = discord.Embed(description="재생을 멈춥니다!", color=0x0080ff) embed.set_author(name="Stop",icon_url=client.user.avatar_url) await message.channel.send(embed=embed) voice_channels[voiceC] = [] voiceC.stop() return if message.content == f'{prefix}shuffle': log_info(message.guild,message.channel,message.author,message.content) voiceC = get_voice(message) if voiceC == None or not voiceC in voice_channels: embed = discord.Embed(title="MusicBot!",description="음성채널방에 들어가있지 않습니다.", color=0xaa0000) await message.channel.send(embed=embed) return if voice_setting[voiceC]["shuffle"]: embed = discord.Embed(description="다시 정리...셔플모드를 끕니다.", color=0x0080ff) embed.set_author(name="Shuffle",icon_url=client.user.avatar_url) await message.channel.send(embed=embed) voice_setting[voiceC]["shuffle"] = False else: embed = discord.Embed(description="재생목록을 흔들어! 흔들어! 셔플모드를 켭니다.", color=0x0080ff) embed.set_author(name="Shuffle",icon_url=client.user.avatar_url) await message.channel.send(embed=embed) voice_setting[voiceC]["shuffle"] = True return if message.content == f'{prefix}repeat': log_info(message.guild,message.channel,message.author,message.content) voiceC = get_voice(message) if voiceC == None or not voiceC in voice_channels: embed = discord.Embed(title="MusicBot!",description="음성채널방에 들어가있지 않습니다.", color=0xaa0000) await message.channel.send(embed=embed) return if voice_setting[voiceC]["repeat"]: embed = discord.Embed(description="무한반복!~~ 반복재생을 끕니다.", color=0x0080ff) embed.set_author(name="Repeat",icon_url=client.user.avatar_url) await message.channel.send(embed=embed) voice_setting[voiceC]["repeat"] = False else: embed = discord.Embed(description="반복재생을 켭니다.", color=0x0080ff) embed.set_author(name="Repeat",icon_url=client.user.avatar_url) await message.channel.send(embed=embed) voice_setting[voiceC]["repeat"] = True return if message.content == f'{prefix}pause': log_info(message.guild,message.channel,message.author,message.content) voiceC = get_voice(message) if voiceC == None or not voiceC in voice_channels: embed = discord.Embed(title="MusicBot!",description="음성채널방에 들어가있지 않습니다.", color=0xaa0000) await message.channel.send(embed=embed) return voiceC.pause() embed = discord.Embed(description="잠시중지! 음악을 일시 정지합니다.", color=0x0080ff) embed.set_author(name="Pause",icon_url=client.user.avatar_url) await message.channel.send(embed=embed) return if message.content == f'{prefix}resume': log_info(message.guild,message.channel,message.author,message.content) voiceC = get_voice(message) if voiceC == None or not voiceC in voice_channels: embed = discord.Embed(title="MusicBot!",description="음성채널방에 들어가있지 않습니다.", color=0xaa0000) await message.channel.send(embed=embed) return voiceC.resume() embed = discord.Embed(description="다시 재생! 일시 정지를 해제합니다..", color=0x0080ff) embed.set_author(name="Resume",icon_url=client.user.avatar_url) await message.channel.send(embed=embed) return if message.content.startswith(f'{prefix}volume'): log_info(message.guild,message.channel,message.author,message.content) voiceC = get_voice(message) if voiceC == None or not voiceC in voice_channels: embed = discord.Embed(title="MusicBot!",description="음성채널방에 들어가있지 않습니다.", color=0xaa0000) await message.channel.send(embed=embed) return if len(list_message) < 2: embed = discord.Embed(description=f"볼륨값은 {voice_setting[voiceC]['volume']}%입니다.", color=0x0080ff) embed.set_author(name="Volume",icon_url=client.user.avatar_url) await message.channel.send(embed=embed) return try: vol_num = int(" ".join(list_message[1:])) except ValueError: embed = discord.Embed(title="MusicBot!",description="옳바른 숫자값을 입력해주세요.", color=0xaa0000) await message.channel.send(embed=embed) return voice_setting[voiceC]["volume"] = vol_num if voiceC.is_playing(): embed = discord.Embed(description=f"볼륨값을 {vol_num}%으로 설정하였습니다.\n**[주의]:** 볼륨값은 다음 곡부터 적용됩니다.", color=0x0080ff) else: embed = discord.Embed(description=f"볼륨값을 {vol_num}%으로 설정하였습니다.", color=0x0080ff) embed.set_author(name="Volume",icon_url=client.user.avatar_url) await message.channel.send(embed=embed) return if message.content == f'{prefix}queue': log_info(message.guild,message.channel,message.author,message.content) voiceC = get_voice(message) if voiceC == None or not voiceC in voice_channels: embed = discord.Embed(title="MusicBot!",description="음성채널방에 들어가있지 않습니다.", color=0xaa0000) await message.channel.send(embed=embed) return async def pg_queue(message,client,voiceC,queue_page): answer = '```css\n' if len(voice_channels[voiceC])%5 == 0: m_page = len(voice_channels[voiceC])/5 else: m_page = len(voice_channels[voiceC])/5 + 1 if len(voice_channels[voiceC]) - queue_page*5 > 5: c = voice_channels[voiceC][queue_page*5:queue_page*5+5] else: load = len(voice_channels[voiceC]) - queue_page*5 c = voice_channels[voiceC][queue_page*5:queue_page*5+load] for i in c: answer += f'[{voice_channels[voiceC].index(i) + 1}]: {i[1]}\n' answer += '```' if voice_setting[voiceC]["repeat"]: o1 = "켜짐" else: o1 = "꺼짐" if voice_setting[voiceC]["shuffle"]: o2 = "켜짐" else: o2 = "꺼짐" embed = discord.Embed(description=f"{answer}\n반복:{o1}, 셔플: {o2}", color=0x0080ff) embed.set_author(name="Queue",icon_url=client.user.avatar_url) embed.set_footer(text=f"{queue_page+1}/{int(m_page)}페이지") msg = await message.channel.send(embed=embed) if not queue_page == 0: await msg.add_reaction("\U00002B05") if not queue_page + 1 == int(m_page): await msg.add_reaction("\U000027A1") message_id = msg.id def check(reaction, user): if "\U000027A1" == reaction.emoji or "\U00002B05" == reaction.emoji: return user.id == message.author.id and message_id == reaction.message.id reaction,_ = await client.wait_for('reaction_add', check=check) if reaction.emoji == "\U000027A1": await msg.delete() await pg_queue(message,client,voiceC,queue_page+1) elif reaction.emoji == "\U00002B05": await msg.delete() await pg_queue(message,client,voiceC,queue_page-1) return await pg_queue(message,client,voiceC,0) return
async def on_server_remove(server): global headers, url payload = {"server_count": len(client.guilds)} async with aiohttp.ClientSession() as aioclient: await aioclient.post(url, data=payload, headers=headers)
async def test_server_context_manager(app, loop) -> None: async with _TestServer(app) as server: async with aiohttp.ClientSession() as client: async with client.head(server.make_url('/')) as resp: assert resp.status == 200
async def main(): async with aiohttp.ClientSession() as session: # Amount of IDs to be grabbed at a time s_target = 10 # Create the skills dictionary skills = await fetch_list(session, 'https://api.guildwars2.com/v2/skills') for i in range(len(skills)): if skills[i] in skills_dictionary: print('ID', skills[i], 'already found in file. Skipping to next.') elif (len(skills) - i) >= s_target: # Create a string with all the 10 IDs print('Grabbing', s_target, 'IDs.') multiple_ids = '' for a in range(0, s_target): multiple_ids += skills[i + a] multiple_ids += ',' html = 'https://api.guildwars2.com/v2/skills?ids=' + multiple_ids print(html) skill_names = await fetch_name(session, html) for a in range(0, s_target): skills_dictionary[skills[i + a]] = skill_names[a] save_to_file('skills.data', skills_dictionary) print(multiple_ids, 'saved to file.') time.sleep(5) else: s_target = len(items) - i print('Grabbing', s_target, 'IDs.') multiple_ids = '' for a in range(0, s_target): multiple_ids += skills[i + a] multiple_ids += ',' html = 'https://api.guildwars2.com/v2/skills?ids=' + multiple_ids print(html) skill_names = await fetch_name(session, html, s_target) for a in range(0, s_target): skills_dictionary[skills[i + a]] = skill_names[a] save_to_file('skills.data', skills_dictionary) print(multiple_ids, 'saved to file.') time.sleep(5) # Create the items dictionary items = await fetch_list(session, 'https://api.guildwars2.com/v2/items') # Amount of IDs to be grabbed at a time i_target = 10 for i in range(len(items)): if items[i] in item_dictionary: print('ID', items[i], 'already found in file. Skipping to next.') elif (len(items) - i) >= i_target: # Create a string with all the 10 IDs print('Grabbing', i_target, 'IDs.') multiple_ids = '' for a in range(0, i_target): multiple_ids += items[i + a] multiple_ids += ',' html = 'https://api.guildwars2.com/v2/items?ids=' + multiple_ids print(html) item_names = await fetch_name(session, html) for a in range(0, i_target): item_dictionary[items[i + a]] = item_names[a] save_to_file('items.data', item_dictionary) print(multiple_ids, 'saved to file.') time.sleep(5) else: i_target = len(items) - i print('Grabbing', i_target, 'IDs.') multiple_ids = '' for a in range(0, i_target): multiple_ids += items[i + a] multiple_ids += ',' html = 'https://api.guildwars2.com/v2/items?ids=' + multiple_ids print(html) item_names = await fetch_name(session, html, i_target) for a in range(0, i_target): item_dictionary[items[i + a]] = item_names[a] save_to_file('items.data', item_dictionary) print(multiple_ids, 'saved to file.') time.sleep(5)
async def avatar(ctx, user: discord.Member): async with aiohttp.ClientSession() as session: async with session.get(user.avatar_url) as resp: img = await resp.read() await ctx.send(file=discord.File(img, 'avatar.gif'))
async def request(self, query): async with aiohttp.ClientSession(headers=self.header) as session: async with session.get(query) as response: return await response.json()
def __init__(self, bot): self.bot = bot self.templates = parseManifest() self.session = aiohttp.ClientSession(loop=bot.loop)
def __session_init(self): """ Starts up the aiohttp session if one does not yet exist """ if self.session is None: self.session = aiohttp.ClientSession()
async def post(url, data): async with aiohttp.ClientSession() as session: async with session.post(url, json=data) as response: return await response.text()
async def dog(self): async with aiohttp.ClientSession() as cs: async with cs.get(self.base_api_link+"/dog", headers=self.headers) as r: f = await utils.get_image(self, r) return f
async def get(url): async with aiohttp.ClientSession() as session: async with session.get(url) as response: return await response.text()
async def cat(self): async with aiohttp.ClientSession() as cs: async with cs.get(self.base_api_link+"/cat", headers=self.headers) as r: r = await r.json() return r['cat']
async def transA(self, ctx, uri:str): async with aiohttp.ClientSession() as session: async with session.get(uri) as res: if res.status == 200: res_json = await res.json() await ctx.send(res_json['res'])
async def download_file(url, dest): if dest.exists(): return async with aiohttp.ClientSession() as session: async with session.get(url) as response: data = await response.read() with open(dest, 'wb') as f: f.write(data)
async def send_cmd(self, cmd: str): async with aiohttp.ClientSession() as session: async with session.post(config["post_namazu_addr"], data=cmd.encode('utf-8')) as resp: await resp.text()
def http_session(self): """Get or create async HTTP session""" if self._http_session is None: self._http_session = aiohttp.ClientSession() return self._http_session
async def download_single_page(self, url): async with aiohttp.ClientSession() as session: async with session.get(url) as resp: self._htmls.append(await resp.text())
async def _get(cls, *args, **kwargs): async with aiohttp.ClientSession() as session: async with session.get(*args, **kwargs) as resp: resp.raise_for_status() return await resp.json()
async def async_status(): self.session = aiohttp.ClientSession() async with self.session.get(self.url) as resp: await self.session.close() return resp
async def create_session(connector: aiohttp.BaseConnector, *, loop: asyncio.BaseEventLoop) -> aiohttp.ClientSession: """Creates an aiohttp session to make web requests.""" return aiohttp.ClientSession(loop=loop)
def _create_session(): # Use requests/certifi CA file ctx = ssl.create_default_context(cafile=requests.certs.where()) connector = aiohttp.TCPConnector(ssl_context=ctx) return aiohttp.ClientSession(connector=connector)
async def shutdown_request(indexs, url, slot_path, duration, cam_timeout): async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=cam_timeout)) as session: result = await asyncio.gather(*[shutdown(session, i, url, slot_path, duration, cam_timeout) for i in indexs]) await session.close() return result
@asyncio.coroutine def tick(dsf): print('Tick! The time is: %s' % datetime.now()) class Agent(object): def __init__(self, _client): self.network_checker = NetworkChecker() self.scheduler = AsyncIOScheduler() self._add_job(_client) def _add_job(self, _client): # self.scheduler.add_job(tick, 'interval', seconds=config.check_interval, args=[_client,]) self.scheduler.add_job(tick, 'interval', seconds=config.check_interval, args=[_client,]) if __name__ == '__main__': loop = asyncio.get_event_loop() with aiohttp.ClientSession() as client: _agent = Agent(client) _agent.scheduler.start() print('Press Ctrl+C to exit') # Execution will block here until Ctrl+C is pressed. try: loop.run_forever() except (KeyboardInterrupt, SystemExit): pass