本文整理汇总了Python中aiohttp.get方法的典型用法代码示例。如果您正苦于以下问题:Python aiohttp.get方法的具体用法?Python aiohttp.get怎么用?Python aiohttp.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类aiohttp
的用法示例。
在下文中一共展示了aiohttp.get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: alog
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import get [as 别名]
def alog(self, *, username):
"""Gets a users recent adventure log"""
username = username.replace(" ", "_")
if feedparser is None:
await self.bot.say("You'll need to run `pip3 install feedparser` "
"before you can get a user's adventure log.")
return
url = self.alog_url + username
try:
page = await aiohttp.get(url)
text = await page.text()
text = text.replace("\r", "")
except:
await self.bot.say("No user found.")
feed = feedparser.parse(text)
titles = [post.title for post in feed.entries]
await self.bot.say(self._fmt_alog(username, titles))
示例2: on_message
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import get [as 别名]
def on_message(message):
# we do not want the bot to reply to itself
if message.author == client.user:
return
for channel in RAID_IMAGE_CHANNELS:
if message.channel.id == channel:
print(message.attachments)
print(len(message.attachments))
print(message.attachments[0]['url'])
for attachment in message.attachments:
if attachment['url'] is not None:
async with aiohttp.get(attachment['url']) as r:
if r.status == 200:
img = await r.read()
with open(attachment['filename'], 'wb') as f:
f.write(img)
print(attachment['filename'], 'saved')
file_name_save = str(attachment['filename']).replace('_', '-')
save_path = SCREENSHOT_SAVE_PATH+'/'+file_name_save
print(save_path)
shutil.move(attachment['filename'], save_path)
示例3: setbanned_info
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import get [as 别名]
def setbanned_info(self, ctx):
"""Display settings."""
server = ctx.message.server
self.check_server_settings(server)
em = discord.Embed(title="Banned: Settings")
em.add_field(
name="Spreadsheet ID",
value=self.settings[server.id]["SHEET_ID"])
em.add_field(
name="Service Key Uploaded",
value=os.path.exists(SERVICE_KEY_JSON))
role_ids = self.settings[server.id]["ROLES"]
roles = [discord.utils.get(server.roles, id=id) for id in role_ids]
role_names = [r.name for r in roles]
if len(role_names):
em.add_field(
name="Roles with edit permission",
value=', '.join(role_names))
else:
em.add_field(
name="Roles with edit permission",
value="None")
await self.bot.say(embed=em)
示例4: setbanned_addrole
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import get [as 别名]
def setbanned_addrole(self, ctx, *, role):
"""Add roles allowed to edit bans."""
server = ctx.message.server
self.check_server_settings(server)
server_role = discord.utils.get(server.roles, name=role)
if server_role is None:
await self.bot.say(
'{} is not a valid role on this server.'.format(role))
return
self.check_server_settings(server)
if server_role.id in self.settings[server.id]["ROLES"]:
await self.bot.say(
'{} is already in the list.'.format(role))
return
self.settings[server.id]["ROLES"].append(server_role.id)
role_ids = self.settings[server.id]["ROLES"]
roles = [discord.utils.get(server.roles, id=id) for id in role_ids]
role_names = [r.name for r in roles]
await self.bot.say(
'List of roles updated: {}.'.format(
', '.join(role_names)))
dataIO.save_json(JSON, self.settings)
示例5: setcalendar_gapisecret
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import get [as 别名]
def setcalendar_gapisecret(self, ctx):
"""Set Google API service account Key.
This is a json file downloadable from the Google API Console.
"""
await self.bot.say(
"Please upload the Google API service account key (json).")
answer = await self.bot.wait_for_message(
timeout=30.0,
author=ctx.message.author)
if answer is None:
await self.bot.say("Time out.")
return
if not len(answer.attachments):
await self.bot.say("Cannot find attachments.")
return
attach = answer.attachments[0]
url = attach["url"]
async with aiohttp.get(url) as cred:
with open(SERVICE_KEY_JSON, "wb") as f:
f.write(await cred.read())
await self.bot.say(
"Attachment received: {}".format(SERVICE_KEY_JSON))
示例6: default
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import get [as 别名]
def default(self, *, channel: "channel"):
"""Default response."""
response = await (await aiohttp.get(
"https://beam.pro/api/v1/channels/{}".format(channel)
)).json()
if "id" in response:
data = await (await aiohttp.get(
self.BEAM_MANIFEST_URL.format(channel=response["id"])
)).json()
if "startedAt" in data:
time = datetime.datetime.utcnow() - datetime.datetime.strptime(
data["startedAt"], "%Y-%m-%dT%H:%M:%S.%fZ")
time -= datetime.timedelta(microseconds=time.microseconds)
return "Channel has been live for {}.".format(time)
return "Channel is offline."
示例7: nsfw
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import get [as 别名]
def nsfw(self, ctx):
'''Vergibt die Rolle um auf die NSFW Channel zugreifen zu können'''
if ctx.guild.id == loadconfig.__botserverid__:
if loadconfig.__selfassignrole__:
role = discord.utils.get(ctx.guild.roles, name=loadconfig.__selfassignrole__)
if role in ctx.author.roles:
try:
await ctx.author.remove_roles(role)
except:
pass
tmp = await ctx.send(f':x: Rolle **{role}** wurde entfernt')
else:
try:
await ctx.author.add_roles(role)
except:
pass
tmp = await ctx.send(f':white_check_mark: Rolle **{role}** wurde hinzugefügt')
else:
tmp = await ctx.send('**:no_entry:** Es wurde keine Rolle für den Bot eingestellt! Wende dich bitte an den Bot Admin')
else:
tmp = await ctx.send(f'**:no_entry:** This command don\'t work on this server!')
await asyncio.sleep(2 * 60)
await tmp.delete()
await ctx.message.delete()
示例8: emoji
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import get [as 别名]
def emoji(self, ctx, emojiname: str):
'''Gibt eine vergrößerte Version eines angegebenen Emojis zurück
Beispiel:
-----------
:emoji Emilia
'''
emoji = discord.utils.find(lambda e: e.name.lower() == emojiname.lower(), self.bot.emojis)
if emoji:
tempEmojiFile = 'tempEmoji.png'
async with aiohttp.ClientSession() as cs:
async with cs.get(emoji.url) as img:
with open(tempEmojiFile, 'wb') as f:
f.write(await img.read())
f = discord.File(tempEmojiFile)
await ctx.send(file=f)
os.remove(tempEmojiFile)
else:
await ctx.send(':x: Konnte das angegebene Emoji leider nicht finden :(')
示例9: check_sad
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import get [as 别名]
def check_sad(self, message):
# check if setting is on in this server
#let sadfaces happen in PMs always
server = message.server
if server != None:
if server.id not in self.servers:
#default off
self.servers[server.id] = False
# sadface is off, so ignore
if not self.servers[server.id]:
return
# comments explaining next section. seemed easier to read this way
# check for a phrase in message
# if sadface isn't downloaded yet, dl it
# try
# get image from url
# write image to file
# it worked \o/
# send it
# except
# there was a problem, print an error then try to send the url instead
# else sadface image already downloaded, send it
if "D:" in message.content.split():
if not self.sadLoaded:
try:
async with aiohttp.get(self.url) as r:
image = await r.content.read()
with open('data/sadface/sadface.png','wb') as f:
f.write(image)
self.sadLoaded = os.path.exists('data/sadface/sadface.png')
await self.bot.send_file(message.channel,self.image)
except Exception as e:
print(e)
print("Sadface error D: I couldn't download the file, so we're gonna use the url instead")
await self.bot.send_message(message.channel,self.url)
else:
await self.bot.send_file(message.channel,self.image)
示例10: _auto_color
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import get [as 别名]
def _auto_color(self, url:str, ranks):
phrases = ["Calculating colors..."] # in case I want more
#try:
await self.bot.say("**{}**".format(random.choice(phrases)))
clusters = 10
async with aiohttp.get(url) as r:
image = await r.content.read()
with open('data/leveler/temp_auto.png','wb') as f:
f.write(image)
im = Image.open('data/leveler/temp_auto.png').convert('RGBA')
im = im.resize((290, 290)) # resized to reduce time
ar = scipy.misc.fromimage(im)
shape = ar.shape
ar = ar.reshape(scipy.product(shape[:2]), shape[2])
codes, dist = scipy.cluster.vq.kmeans(ar.astype(float), clusters)
vecs, dist = scipy.cluster.vq.vq(ar, codes) # assign codes
counts, bins = scipy.histogram(vecs, len(codes)) # count occurrences
# sort counts
freq_index = []
index = 0
for count in counts:
freq_index.append((index, count))
index += 1
sorted_list = sorted(freq_index, key=operator.itemgetter(1), reverse=True)
colors = []
for rank in ranks:
color_index = min(rank, len(codes))
peak = codes[sorted_list[color_index][0]] # gets the original index
peak = peak.astype(int)
colors.append(''.join(format(c, '02x') for c in peak))
return colors # returns array
#except:
#await self.bot.say("```Error or no scipy. Install scipy doing 'pip3 install numpy' and 'pip3 install scipy' or read here: https://github.com/AznStevy/Maybe-Useful-Cogs/blob/master/README.md```")
# converts hex to rgb
示例11: setlevel
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import get [as 别名]
def setlevel(self, ctx, user : discord.Member, level:int):
'''Set a user's level. (What a cheater C:).'''
org_user = ctx.message.author
server = user.server
channel = ctx.message.channel
# creates user if doesn't exist
await self._create_user(user, server)
userinfo = db.users.find_one({'user_id':user.id})
if server.id in self.settings["disabled_servers"]:
await self.bot.say("Leveler commands for this server are disabled.")
return
if level < 0:
await self.bot.say("**Please enter a positive number.**")
return
# get rid of old level exp
old_server_exp = 0
for i in range(userinfo["servers"][server.id]["level"]):
old_server_exp += self._required_exp(i)
userinfo["total_exp"] -= old_server_exp
userinfo["total_exp"] -= userinfo["servers"][server.id]["current_exp"]
# add in new exp
total_exp = self._level_exp(level)
userinfo["servers"][server.id]["current_exp"] = 0
userinfo["servers"][server.id]["level"] = level
userinfo["total_exp"] += total_exp
db.users.update_one({'user_id':user.id}, {'$set':{
"servers.{}.level".format(server.id): level,
"servers.{}.current_exp".format(server.id): 0,
"total_exp": userinfo["total_exp"]
}})
await self.bot.say("**{}'s Level has been set to `{}`.**".format(self._is_mention(user), level))
await self._handle_levelup(user, userinfo, server, channel)
示例12: _valid_image_url
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import get [as 别名]
def _valid_image_url(self, url):
max_byte = 1000
try:
async with aiohttp.get(url) as r:
image = await r.content.read()
with open('data/leveler/test.png','wb') as f:
f.write(image)
image = Image.open('data/leveler/test.png').convert('RGBA')
os.remove('data/leveler/test.png')
return True
except:
return False
示例13: _process_user_top
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import get [as 别名]
def _process_user_top(self, ctx, username, gamemode: int):
key = self.osu_api_key["osu_api_key"]
channel = ctx.message.channel
user = ctx.message.author
server = user.server
# determine api to use
username, api = self._determine_api(server, list(username))
username = username[0]
# gives the final input for osu username
test_username = await self._process_username(ctx, username)
if test_username:
username = test_username
else:
return
# get userinfo
userinfo = list(await get_user(key, api, username, gamemode))
userbest = list(await get_user_best(key, api, username, gamemode, self.osu_settings['num_best_plays']))
if userinfo and userbest:
msg, top_plays = await self._get_user_top(ctx, api, userinfo[0], userbest, gamemode)
await self.bot.say(msg, embed=top_plays)
else:
await self.bot.say("**`{}` was not found or not enough plays.**".format(username))
## processes username. probably the worst chunck of code in this project so far. will fix/clean later
示例14: get_beatmap
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import get [as 别名]
def get_beatmap(key, api:str, beatmap_id):
url_params = []
url_params.append(parameterize_key(key))
url_params.append(parameterize_id("b", beatmap_id))
async with aiohttp.get(build_request(url_params, "https://{}/api/get_beatmaps?".format(api))) as resp:
return await resp.json()
# Gets the beatmap set
示例15: get_beatmapset
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import get [as 别名]
def get_beatmapset(key, api:str, set_id):
url_params = []
url_params.append(parameterize_key(key))
url_params.append(parameterize_id("s", set_id))
async with aiohttp.get(build_request(url_params, "https://{}/api/get_beatmaps?".format(api))) as resp:
return await resp.json()
# Grabs the scores