Python aiohttp.get() Examples
The following are 30
code examples of aiohttp.get().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
aiohttp
, or try the search function
.
Example #1
Source File: utility.py From discord_bot with MIT License | 6 votes |
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 :(')
Example #2
Source File: utility.py From discord_bot with MIT License | 6 votes |
def ping(self, ctx): '''Misst die Response Time''' ping = ctx.message pong = await ctx.send('**:ping_pong:** Pong!') delta = pong.created_at - ping.created_at delta = int(delta.total_seconds() * 1000) await pong.edit(content=f':ping_pong: Pong! ({delta} ms)\n*Discord WebSocket Latenz: {round(self.bot.latency, 5)} ms*') # @commands.command() # @commands.cooldown(1, 2, commands.cooldowns.BucketType.guild) # async def github(self, ctx): # '''In progress''' # url = 'https://api.github.com/repos/Der-Eddy/discord_bot/stats/commit_activity' # async with aiohttp.get(url) as r: # if r.status == 200: # content = await r.json() # commitCount = 0 # for week in content: # commitCount += week['total'] # # embed = discord.Embed(title='GitHub Repo Stats', type='rich', color=0xf1c40f) #Golden # embed.set_thumbnail(url='https://assets-cdn.github.com/images/modules/logos_page/GitHub-Mark.png') # embed.add_field(name='Commits', value=commitCount, inline=True) # embed.add_field(name='Link', value='https://github.com/Der-Eddy/discord_bot') # await ctx.send(embed=embed) # else: # await ctx.send(':x: Konnte nicht aufs GitHub API zugreifen\nhttps://github.com/Der-Eddy/discord_bot')
Example #3
Source File: anime.py From discord_bot with MIT License | 6 votes |
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()
Example #4
Source File: rssbot.py From PGSS with GNU General Public License v3.0 | 6 votes |
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)
Example #5
Source File: runescape.py From Squid-Plugins with MIT License | 6 votes |
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))
Example #6
Source File: uptime.py From CactusBot with MIT License | 6 votes |
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."
Example #7
Source File: banned.py From SML-Cogs with MIT License | 6 votes |
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)
Example #8
Source File: banned.py From SML-Cogs with MIT License | 6 votes |
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)
Example #9
Source File: calendar.py From SML-Cogs with MIT License | 6 votes |
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))
Example #10
Source File: test_urlscraper.py From cjworkbench with GNU Affero General Public License v3.0 | 5 votes |
def __init__(self, dataframe: pd.DataFrame): self.result = ProcessResult(dataframe) # this replaces aiohttp.get. Wait for a lag, then a test response # If the status is an error, throw the appropriate exception
Example #11
Source File: sadface.py From Dumb-Cogs with MIT License | 5 votes |
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)
Example #12
Source File: firebase.py From SML-Cogs with MIT License | 5 votes |
def setfirebase_service_key(self, ctx): """Set Firebase Service key. This is generated by the Firebase Console. You can get it here: https://console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk """ TIMEOUT = 30.0 await self.bot.say( "Please upload the Firebase service account key (json). " "[Timeout: {} seconds]".format(TIMEOUT)) attach_msg = await self.bot.wait_for_message( timeout=TIMEOUT, author=ctx.message.author) if attach_msg is None: await self.bot.say("Operation time out.") return if not len(attach_msg.attachments): await self.bot.say("Cannot find attachments.") return attach = attach_msg.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 and saved as {}".format(SERVICE_KEY_JSON)) self.settings['SERVICE_ACCOUNT'] = SERVICE_KEY_JSON dataIO.save_json(JSON, self.settings) # Delete uploaded attachment await self.bot.delete_message(attach_msg)
Example #13
Source File: firebase.py From SML-Cogs with MIT License | 5 votes |
def setfirebase_server_key(self, ctx, key): """Set Firebase Cloud Messaging Server Key. This is generated by the Firebase Console You can get it here: https://console.firebase.google.com/project/_/settings/cloudmessaging """ self.settings["SERVER_KEY"] = key dataIO.save_json(JSON, self.settings) await self.bot.say("Saved Firebase Cloud Messaging Server Key.") await self.bot.delete_message(ctx.message)
Example #14
Source File: banned.py From SML-Cogs with MIT License | 5 votes |
def setbanned_servicekey(self, ctx): """Set Google API service account key. This is a json file downloaable from the Google API Console. """ TIMEOUT = 30.0 await self.bot.say( "Please upload the Google API service account key (json). " "[Timeout: {} seconds]".format(TIMEOUT)) attach = await self.bot.wait_for_message( timeout=TIMEOUT, author=ctx.message.author) if attach is None: await self.bot.say("Operation time out.") return if not len(attach.attachments): await self.bot.say("Cannot find attachments.") return attach = attach.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 and saved as {}".format(SERVICE_KEY_JSON))
Example #15
Source File: calendar.py From SML-Cogs with MIT License | 5 votes |
def calendar_list(self, ctx, max_results=5): """List events on a calendar.""" credentials = ServiceAccountCredentials.from_json_keyfile_name( SERVICE_KEY_JSON, scopes=SCOPES) http = credentials.authorize(httplib2.Http()) service = discovery.build('calendar', 'v3', http=http) now = dt.datetime.utcnow().isoformat() + 'Z' await self.bot.say( "Getting the upcoming {} events:".format(max_results)) eventsResult = service.events().list( calendarId=RACF_CALENDAR_ID, timeMin=now, maxResults=max_results, singleEvents=True, orderBy='startTime').execute() events = eventsResult.get('items', []) if not events: await self.bot.say("No upcoming events found.") out = [] for event in events: start = event['start'].get('dateTime', event['start'].get('date')) out.append(start) out.append(event['summary']) for page in pagify('\n'.join(out), shorten_by=24): await self.bot.say(page)
Example #16
Source File: search.py From SML-Cogs with MIT License | 5 votes |
def search_google( self, ctx: Context, search_str: str, lang='english', stop=1): """Google search and return URL results.""" out = [] await self.bot.send_typing(ctx.message.channel) for url in google.search(search_str, num=5, stop=stop): await self.bot.send_typing(ctx.message.channel) async with aiohttp.get(url) as response: soup = BeautifulSoup(await response.text(), "html.parser") out.append(soup.title.string) out.append("<{}>\n".format(url)) # out.append(gout) for page in pagify('\n'.join(out)): await self.bot.say(page)
Example #17
Source File: search.py From SML-Cogs with MIT License | 5 votes |
def search_google_images( self, ctx: Context, search_str: str, stop=1): """Google search images.""" out = [] await self.bot.send_typing(ctx.message.channel) for url in google.search_images(search_str, num=5, stop=stop): await self.bot.send_typing(ctx.message.channel) async with aiohttp.get(url) as response: soup = BeautifulSoup(await response.text(), "html.parser") out.append(soup.title.string) out.append("<{}>\n".format(url)) # out.append(gout) for page in pagify('\n'.join(out)): await self.bot.say(page)
Example #18
Source File: emotes.py From Squid-Plugins with MIT License | 5 votes |
def check_messages(self, message): if message.author.id == self.bot.user.id: return if message.channel.is_private: return if not self._is_enabled(message.server): return valid_emotes = self.available_emotes[message.server.id] splitted = message.content.split(' ') count = 0 for word in splitted: for emote in valid_emotes: if word == emote.get("name", ""): fname = 'data/emotes/{}/{}'.format( emote["chan_id"], emote["file_name"]) if not os.path.exists(fname): break img = Image.open(fname) if self.get_scale(message.server) != 1.0: scale = self.get_scale(message.server) img = img.resize((int(img.width * scale), int(img.height * scale)), Image.ANTIALIAS) tmpfile = BytesIO() fmt = os.path.splitext(emote["file_name"])[1].replace('.', '') img.save(tmpfile, format=fmt) tmpfile.seek(0) await self.bot.send_file(message.channel, tmpfile, filename=emote["file_name"]) tmpfile.close() count += 1 if self.get_limit_per_message(message.server) != 0 and \ count >= \ self.get_limit_per_message(message.server): return break
Example #19
Source File: api.py From ooi3 with GNU Affero General Public License v3.0 | 5 votes |
def world_image(self, request): """ 显示正确的镇守府图片。 舰娘游戏中客户端FLASH请求的镇守府图片是根据FLASH本身的URL生成的,需要根据用户所在的镇守府IP为其显示正确的图片。 :param request: aiohttp.web.Request :return: aiohttp.web.HTTPFound or aiohttp.web.HTTPBadRequest """ size = request.match_info['size'] session = yield from get_session(request) world_ip = session['world_ip'] if world_ip: ip_sections = map(int, world_ip.split('.')) image_name = '_'.join([format(x, '03') for x in ip_sections]) + '_' + size if image_name in self.worlds: body = self.worlds[image_name] else: url = 'http://203.104.209.102/kcs/resources/image/world/' + image_name + '.png' coro = aiohttp.get(url, connector=self.connector) try: response = yield from asyncio.wait_for(coro, timeout=5) except asyncio.TimeoutError: return aiohttp.web.HTTPBadRequest() body = yield from response.read() self.worlds[image_name] = body return aiohttp.web.Response(body=body, headers={'Content-Type': 'image/png', 'Cache-Control': 'no-cache'}) else: return aiohttp.web.HTTPBadRequest()
Example #20
Source File: api.py From ooi3 with GNU Affero General Public License v3.0 | 5 votes |
def api(self, request): """ 转发客户端和游戏服务器之间的API通信。 :param request: aiohttp.web.Request :return: aiohttp.web.Response or aiohttp.web.HTTPBadRequest """ action = request.match_info['action'] session = yield from get_session(request) world_ip = session['world_ip'] if world_ip: if action == 'api_start2' and self.api_start2 is not None: return aiohttp.web.Response(body=self.api_start2, headers=aiohttp.MultiDict({'Content-Type': 'text/plain'})) else: referrer = request.headers.get('REFERER') referrer = referrer.replace(request.host, world_ip) referrer = referrer.replace('https://', 'http://') url = 'http://' + world_ip + '/kcsapi/' + action headers = aiohttp.MultiDict({ 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko', 'Origin': 'http://' + world_ip + '/', 'Referer': referrer, }) data = yield from request.post() coro = aiohttp.post(url, data=data, headers=headers, connector=self.connector) try: response = yield from asyncio.wait_for(coro, timeout=5) except asyncio.TimeoutError: return aiohttp.web.HTTPBadRequest() body = yield from response.read() if action == 'api_start2' and len(body) > 100000: self.api_start2 = body return aiohttp.web.Response(body=body, headers=aiohttp.MultiDict({'Content-Type': 'text/plain'})) else: return aiohttp.web.HTTPBadRequest()
Example #21
Source File: trust.py From CactusBot with MIT License | 5 votes |
def check_user(username): if username.startswith('@'): username = username[1:] async with aiohttp.get(BASE_URL.format(username=username)) as response: if response.status == 404: raise NameError return (username, (await response.json())["id"])
Example #22
Source File: spam.py From CactusBot with MIT License | 5 votes |
def get_user_id(username): async with aiohttp.get(BASE_URL.format(username=username)) as response: if response.status == 404: return 0 return (await response.json())["id"]
Example #23
Source File: oboobs.py From Mash-Cogs with GNU General Public License v3.0 | 5 votes |
def boobs(self, ctx): """Shows some boobs.""" author = ctx.message.author dis_nsfw = None for a in self.settings["nsfw_channels"]: if a == ctx.message.channel.id: if self.settings["invert"]: dis_nsfw = False else: dis_nsfw = True break if dis_nsfw is None and not self.settings["invert"]: dis_nsfw = False else: dis_nsfw = True try: rdm = random.randint(0, self.settings["ama_boobs"]) search = ("http://api.oboobs.ru/boobs/{}".format(rdm)) async with aiohttp.get(search) as r: result = await r.json() boob = random.choice(result) boob = "http://media.oboobs.ru/{}".format(boob["preview"]) except Exception as e: await self.bot.reply("Error getting results.") return if not dis_nsfw: await self.bot.say("{}".format(boob)) else: await self.bot.send_message(ctx.message.author, "{}".format(boob)) if self.settings["nsfw_msg"]: await self.bot.reply("nsfw content is not allowed in this channel, instead I have send you a DM.") # Ass
Example #24
Source File: oboobs.py From Mash-Cogs with GNU General Public License v3.0 | 5 votes |
def ass(self, ctx): """Shows some ass.""" author = ctx.message.author dis_nsfw = None for a in self.settings["nsfw_channels"]: if a == ctx.message.channel.id: if self.settings["invert"]: dis_nsfw = False else: dis_nsfw = True break if dis_nsfw is None and not self.settings["invert"]: dis_nsfw = False else: dis_nsfw = True try: rdm = random.randint(0, self.settings["ama_ass"]) search = ("http://api.obutts.ru/butts/{}".format(rdm)) async with aiohttp.get(search) as r: result = await r.json() ass = random.choice(result) ass = "http://media.obutts.ru/{}".format(ass["preview"]) except Exception as e: await self.bot.reply("Error getting results.") return if not dis_nsfw: await self.bot.say("{}".format(ass)) else: await self.bot.send_message(ctx.message.author, "{}".format(ass)) if self.settings["nsfw_msg"]: await self.bot.reply("nsfw content is not allowed in this channel, instead I have send you a DM.")
Example #25
Source File: weatherMs.py From Mash-Cogs with GNU General Public License v3.0 | 5 votes |
def temp(self, *, weather_station): """Make sure to get your own API key and put it into data/weather/settings.json \nYou can get an API key from: www.wunderground.com/weather/api/""" target = weather_station.split(".") #print(target) #print(len(target)) country = None location = None if len(target) == 2: country = target[0].replace(" ", "_") location = target[1].replace(" ", "_") #print(country, location) if len(target) == 1: location = target[0].replace(" ", "_") #print(country, location) elif country == None or location == None: await self.bot.say("`Please use a US zip code or format like: NY.new york, fr.paris\nIf the default country is set to your requesting location just '!temp city' will do.\nThe the default country is set to: {} `".format(self.settings["defCountry"])) return if country is None: country = self.settings["defCountry"] url = "http://api.wunderground.com/api/" + self.settings['api_key'] + "/conditions/q/" + country + "/" + location +".json" #print(url) async with aiohttp.get(url) as r: data = await r.json() if "current_observation" in data: tempCO = data["current_observation"].get("temperature_string", False) tempW = data["current_observation"].get("weather", " ") tempC = data["current_observation"].get("temp_c", " ") tempF = data["current_observation"].get("temp_f", " ") tempH = data["current_observation"].get("relative_humidity", " ") if tempCO != False: if self.settings["unit"] == "C": await self.bot.say("**Weather **{} **Temp.** {}{} **Hum. **{} ".format(tempW, str(tempC), u"\u2103", tempH)) elif self.settings["unit"] == "F": await self.bot.say("**Weather **{} **Temp.** {}F **Hum. **{} ".format(tempW, str(tempF), tempH)) else: await self.bot.say("No temperature found") else: await self.bot.say("`Please use a US zip code or format like: NY.new york, fr.paris\nIf the default country is set to your requesting location just '!temp city' will do.\nThe the default country is set to: {} `".format(self.settings["defCountry"]))
Example #26
Source File: admin.py From discord_bot with MIT License | 5 votes |
def avatar(self, ctx, url: str): '''Setzt einen neuen Avatar (BOT OWNER ONLY)''' tempAvaFile = 'tempAva.png' async with aiohttp.get(''.join(url)) as img: with open(tempAvaFile, 'wb') as f: f.write(await img.read()) f = discord.File(tempAvaFile) await self.bot.edit_profile(avatar=f.read()) os.remove(tempAvaFile) asyncio.sleep(2) await ctx.send('**:ok:** Mein neuer Avatar!\n %s' % self.bot.user.avatar_url)
Example #27
Source File: emotes.py From Squid-Plugins with MIT License | 5 votes |
def update_emote_list(self): async with self.session.get(self.emote_url) as r: resp = await r.json() data = resp.get("emoticons", {}) self.emote_list = data
Example #28
Source File: osu.py From Maybe-Useful-Cogs with MIT License | 5 votes |
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
Example #29
Source File: leveler.py From Maybe-Useful-Cogs with MIT License | 5 votes |
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
Example #30
Source File: leveler.py From Maybe-Useful-Cogs with MIT License | 5 votes |
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)