async def avatar(self, ctx, *, person: discord.User = None): """Get someone's avatar.""" if person is None: person = ctx.author url = person.avatar_url_as(static_format='png') await ctx.send(url)
async def make_feels( self, user: discord.User, is_gif: bool ) -> Tuple[Optional[discord.File], int]: template_str = "https://i.imgur.com/4xr6cdw.png" template = Image.open(await self.dl_image(template_str)) colour = user.colour.to_rgb() if user.is_avatar_animated() and is_gif: avatar = Image.open( await self.dl_image(str(user.avatar_url_as(format="gif", size=64))) ) task = functools.partial( self.make_feels_gif, template=template, colour=colour, avatar=avatar ) else: avatar = Image.open( await self.dl_image(str(user.avatar_url_as(format="png", size=64))) ) task = functools.partial( self.make_feels_img, template=template, colour=colour, avatar=avatar ) task = self.bot.loop.run_in_executor(None, task) try: temp: BytesIO = await asyncio.wait_for(task, timeout=60) except asyncio.TimeoutError: avatar.close() template.close() return None, 0 avatar.close() template.close() temp.seek(0) filename = "feels.gif" if is_gif else "feels.png" file = discord.File(temp, filename=filename) file_size = temp.tell() temp.close() return file, file_size
async def avatar(self, ctx, *, user: discord.User = None): """ Displays what avatar user is using """ user = user or ctx.author Zenpa = self.bot.get_user(373863656607318018) embed = discord.Embed(color=self.bot.settings['colors']['embed_color']) embed.set_author(name=_("{0}'s Profile Picture!").format(user), icon_url=user.avatar_url) png = user.avatar_url_as(static_format='png') jpg = user.avatar_url_as(static_format='jpg') webp = user.avatar_url_as(static_format='webp') if user.is_avatar_animated(): gif = user.avatar_url_as(format='gif') else: gif = None embed.description = _( "[png]({0}) | [jpg]({1}) | [webp]({2}){3}").format( png, jpg, webp, _(' | [gif]({0})').format(gif) if gif else '') if user.id in [ self.bot.user.id, 667117267405766696, 576476937988472853 ]: embed.set_image(url=png) embed.set_footer( text=_('Huge thanks to {0} for this avatar').format(Zenpa)) await ctx.send(embed=embed) else: embed.set_image(url=png) await ctx.send(embed=embed)
async def make_feels(self, user: discord.User, is_gif: bool) -> Optional[BytesIO]: template = "https://i.imgur.com/4xr6cdw.png" template = Image.open(await self.dl_image(template)) colour = user.colour.to_rgb() if user.is_avatar_animated() and is_gif: avatar = Image.open(await self.dl_image( str(user.avatar_url_as(format="gif", size=64)))) task = functools.partial(self.make_feels_gif, template=template, colour=colour, avatar=avatar) else: avatar = Image.open(await self.dl_image( str(user.avatar_url_as(format="png", size=64)))) task = functools.partial(self.make_feels_img, template=template, colour=colour, avatar=avatar) task = self.bot.loop.run_in_executor(None, task) try: temp: BytesIO = await asyncio.wait_for(task, timeout=60) except asyncio.TimeoutError: return None temp.seek(0) return temp
async def make_beautiful(self, user: discord.User, is_gif: bool) -> Optional[BytesIO]: template_str = "https://i.imgur.com/kzE9XBE.png" template = Image.open(await self.dl_image(template_str)) if user.is_avatar_animated() and is_gif: avatar = Image.open(await self.dl_image( str(user.avatar_url_as(format="gif", size=128)))) task = functools.partial(self.make_beautiful_gif, template=template, avatar=avatar) else: avatar = Image.open(await self.dl_image( str(user.avatar_url_as(format="png", size=128)))) task = functools.partial(self.make_beautiful_img, template=template, avatar=avatar) task = self.bot.loop.run_in_executor(None, task) try: temp: BytesIO = await asyncio.wait_for(task, timeout=60) except asyncio.TimeoutError: avatar.close() template.close() return None avatar.close() template.close() temp.seek(0) return temp
async def rip(self, ctx, user: discord.User = None): user = user or ctx.author if str(user.avatar_url_as(static_format="png")).endswith("1024"): image = str(user.avatar_url_as(static_format="png"))[:-10] else: image = str(user.avatar_url_as(static_format="png")) await ctx.send("https://vacefron.nl/api/grave?user=" + image)
async def user(self, ctx, user:discord.User=None): if not user: user = ctx.author post = db.market.find_one({"owner": int(user.id)}) if post: embed = discord.Embed(colour=0xa82021, description=str(user)) embed.set_author(icon_url=user.avatar_url_as(format='png'), name="User Stats") embed.set_thumbnail(url=user.avatar_url_as(format='png')) embed.add_field(name="Restaurant", value=post['name'] + f" (Level {post['level']})") embed.add_field(name="Money", value="$" + str(post['money'])) await ctx.send(embed=embed) else: await ctx.send("<:RedTick:653464977788895252> This user doesn't have a restaurant")
async def user(self, ctx: commands.Context, user: discord.User): """Shows information about a user""" asset = user.avatar_url_as(format='png', size=32) dominant = await utils.dominant(asset) embed = discord.Embed(color=dominant) \ .set_thumbnail(url=user.avatar_url_as(size=256)) \ .set_author(name=str(user)) \ .add_field(name='ID', value=user.id) \ .add_field(name='Created at', value=user.created_at.strftime('%d.%m.%Y %H:%M')) if user.bot: embed.description = 'This is a bot account' msg = await ctx.send(embed=embed) await utils.wait_to_delete(self.bot, ctx.message, msg)
async def account(self, ctx, user: discord.User = None): """Shows a user's balance and message chance""" user = user or ctx.author q = "SELECT amount, chance FROM currency WHERE userid=?" cur = await self.bot.db.execute(q, (user.id, )) stat = await cur.fetchall() if stat: stat = stat[0] embed = discord.Embed( title=f"Account for {user}", description=f"${stat[0]}\n1/{stat[1]} chance", color=0x7289DA, ) embed.set_thumbnail(url=user.avatar_url_as(static_format="png")) embed.set_footer( text="chr1sBot", icon_url=ctx.bot.user.avatar_url_as(static_format="png"), ) await ctx.send(embed=embed) else: if user == ctx.author: await ctx.send("You don't got an account, loser") else: await ctx.send( "That person doesn't have an account, what a nerd")
def create_user(self, user: discord.User): session = self.session_manager() if self.config["local_avatars"]: r = requests.get(user.avatar_url_as(format='png')) with open(f"static/avatars/{user.id}.png", 'wb') as avatarfile: avatarfile.write(r.content) avatar_url = f"avatars/{user.id}.png" localized = True else: avatar_url = user.avatar_url localized = False new_user = db.User(id=user.id, name=user.name, discriminator=user.discriminator, is_bot=user.bot, avatar=str(avatar_url), created_at=user.created_at, last_updated=datetime.datetime.now(), localized_avatar=localized) session.merge(new_user) session.commit() session.close()
async def save_pfp(self, user: discord.User): """No return""" # Get url to the avatar as either webp or gif, gif if animated user_avatar_asset = user.avatar_url_as(format=None, static_format='webp', size=4096) # TODO: check for insert errors doc = { 'time': datetime.datetime.utcnow(), 'user': user.id, } # Upload data to server and get id file_name = str(self.db.pfp.insert_one(doc).inserted_id) # Check if path is valid full_path = mkdir_after(self.dat_pfp, file_name[:2]) if full_path is None: print("ERRO|{}|pfp_tracker|{}".format(time.ctime(), "bad dat_pfp path."), file=sys.stderr) # TODO: Fatal? or not exit() # TODO: make remove the await to make it async? # Save avatar try: byte_count = await user_avatar_asset.save(os.path.join(full_path, file_name)) print("INFO|{}|pfp_tracker|{}".format( time.ctime(), "Saved pfp: [{:>7}] {}".format(byte_count, file_name))) except Exception as e: print("ERRO|{}|pfp_tracker|{}".format(time.ctime(), e), file=sys.stderr)
async def profile(self, ctx, u: discord.User = None): if u is None: u = ctx.author if u.bot: await self.send(ctx, "Remember, bot's don't have profiles as they're dumb! (Except Villager Bot ofc)") return pp = discord.Embed(color=discord.Color.green()) pp.set_author(name=f"{u.display_name}'s Profile", icon_url=str(u.avatar_url_as(static_format="png"))) hh = ["<:heart_full:717535027604488243>", "<:heart_empty:717535027319144489>"] pp.add_field(name="Health", value=await self.db.calc_stat_bar(ceil(await self.db.get_health(u.id) / 2), 10, 10, hh[0], hh[1]), inline=False) user_items = await self.db.get_items(u.id) pp.add_field(name="Total Wealth", value=f"{await self.db.get_balance(u.id) + (await self.db.get_vault(u.id))[0] + sum([item[1] * item[2] for item in user_items])}{self.emerald}", inline=True) pp.add_field(name="\uFEFF", value="\uFEFF", inline=True) pp.add_field(name="CMDS Sent", value=self.g.command_leaderboard.get(u.id), inline=True) pp.add_field(name="Pickaxe", value=await self.db.get_pickaxe(u.id) + " pickaxe", inline=True) pp.add_field(name="\uFEFF", value="\uFEFF", inline=True) pp.add_field(name="Sword", value=await self.bot.get_cog("MobSpawning").get_sword(u.id), inline=True) await ctx.send(embed=pp)
async def unban(self, ctx: Context, *, user: User) -> None: """Unban a user.""" try: await ctx.guild.unban(user) embed = Embed( title="User Unbanned", description=textwrap.dedent( f""" **User**: {user.mention} (`{user.id}`) **Moderator**: {ctx.author.mention} (`{ctx.author.id}`) """ ), color=Color.green(), timestamp=datetime.utcnow(), ) embed.set_thumbnail(url=user.avatar_url_as(format="png", size=256)) await ctx.send(embed=embed) logger.debug(f"User <@{ctx.author.id}> has unbanned <@{user.id}> from {ctx.guild.id}") except NotFound: embed = Embed( title="Ban not Found!", description=textwrap.dedent( f""" There are no active bans on discord for {user.mention}. He isn't banned here. """ ), color=Color.red(), ) await ctx.send(embed=embed) logger.trace(f"User <@{ctx.author.id}> has tried to unban non-banned <@{user.id}> from {ctx.guild.id}")
async def fry(ctx, user: discord.User = None): await ctx.message.delete() endpoint = "https://nekobot.xyz/api/imagegen?type=deepfry&image=" if user is None: avatar = str(ctx.author.avatar_url_as(format="png")) endpoint += avatar r = requests.get(endpoint) res = r.json() try: async with aiohttp.ClientSession() as session: async with session.get(str(res['message'])) as resp: image = await resp.read() with io.BytesIO(image) as file: await ctx.send(file=discord.File(file, f"{user.name}_fry.png")) except: await ctx.send(res['message']) else: avatar = str(user.avatar_url_as(format="png")) endpoint += avatar r = requests.get(endpoint) res = r.json() try: async with aiohttp.ClientSession() as session: async with session.get(str(res['message'])) as resp: image = await resp.read() with io.BytesIO(image) as file: await ctx.send(file=discord.File(file, f"{user.name}_fry.png")) except: await ctx.send(res['message'])
async def generate_file_welcome(user: discord.User): try: welcome_settings = get_images_settings("welcome_settings") asset = user.avatar_url_as(size=welcome_settings["size"]) data = BytesIO(await asset.read()) im = Image.open(data) im = im.resize((welcome_settings["width"], welcome_settings["height"])) bigsize = (im.size[0] * 3, im.size[1] * 3) mask = Image.new('L', bigsize, 0) draw = ImageDraw.Draw(mask) draw.ellipse((0, 0) + bigsize, fill=255) mask = mask.resize(im.size, Image.ANTIALIAS) im.putalpha(mask) background = Image.open(welcome_settings["path"]) background.paste(im, (welcome_settings["x"], welcome_settings["y"]), im) background.save('__welcome__.png') return discord.File("__welcome__.png") except: traceback.print_exc() return None
async def inventory(self, ctx, u: discord.User): pick = await self.db.get_pickaxe(u.id) contents = f"**{pick} pickaxe**\n" inv = discord.Embed(color=discord.Color.green(), description=contents) contents = "" i = 0 rows = 10 items = await self.db.get_items(u.id) for item in items: i += 1 m = await self.db.get_item(u.id, item[0]) contents += f"{m[1]}x **{m[0]}** (sells for {m[2]}{self.emerald})\n" if i % rows == 0: if i <= rows: inv.add_field(name="Sellable Items", value=contents, inline=False) else: inv.add_field(name="\uFEFF", value=contents, inline=False) contents = "" if contents is not "": inv.add_field(name="\uFEFF", value=contents, inline=False) if not u.avatar_url: inv.set_author(name=f"{u.display_name}'s Inventory", url=discord.Embed.Empty) else: inv.set_author(name=f"{u.display_name}'s Inventory", icon_url=str(u.avatar_url_as(static_format="png"))) await ctx.send(embed=inv)
async def ban(self, ctx, user: discord.User, *, reason: str = None): admin = ctx.author member = ctx.guild.get_member( user.id) if user in ctx.guild.members else None if member: if member.top_role > admin.top_role: await ctx.send( "You can't ban someone with higher permissions than you.") return if user == admin: await ctx.send("You can't ban yourself.") return await ctx.guild.ban( user, reason= f"Banned by {longform_username(admin)}: {reason if reason else 'No reason specified'}", delete_message_days=0) embed = discord.Embed( title=f"Banned", description= f"{longform_username(user)} banned by {longform_username(admin)}: {reason if reason else 'No reason specified'}" ) embed.set_author(name=longform_username(user), icon_url=user.avatar_url_as(format="png")) await ctx.send(embed=embed)
async def meme_user(self, ctx, user: discord.User, line1: URLString, line2: URLString): """Generates a meme on a users avatar.""" await ctx.invoke(self.meme_custom, link=user.avatar_url_as(format="png"), line1=line1, line2=line2)
async def listcomments(self, ctx, Benutzer: discord.User): zaehler = 0 embed = discord.Embed() embed.title = f"Nachrichten von {Benutzer}" embed.set_thumbnail(url=Benutzer.avatar_url_as(static_format='png')) while zaehler < 25: try: insert = ' '.join(await self.config.user(Benutzer).comments.get_raw(str(zaehler), 'text')) embed.add_field(name=f"{zaehler}",value=f" {insert}",inline=False) zaehler +=1 except KeyError: zaehler +=1 await ctx.send(embed=embed) embed2 = discord.Embed() embed2.title = f"Nachrichten von {Benutzer}" embed2.set_thumbnail(url=Benutzer.avatar_url_as(static_format='png')) while zaehler < 50: try: insert = ' '.join(await self.config.user(Benutzer).comments.get_raw(str(zaehler), 'text')) embed2.add_field(name=f"{zaehler}",value=f" {insert}",inline=False) zaehler +=1 except KeyError: zaehler +=1 break await ctx.send(embed=embed2) embed3 = discord.Embed() embed3.title = f"Nachrichten von {Benutzer}" embed3.set_thumbnail(url=Benutzer.avatar_url_as(static_format='png')) while zaehler < 75: try: insert = ' '.join(await self.config.user(Benutzer).comments.get_raw(str(zaehler), 'text')) embed3.add_field(name=f"{zaehler}",value=f" {insert}",inline=False) zaehler +=1 except KeyError: zaehler +=1 break try: insert = ' '.join(await self.config.user(Benutzer).comments.get_raw(str(25), 'text')) except KeyError: return await ctx.send(embed=embed3)
async def trigger(self, ctx, target: User): await safe_delete(ctx) if ctx.message.author != target: await ctx.send(file=File(await trigger_pic(str(target.avatar_url_as(static_format='png'))), f"trigger_{target}.gif")) else: await ctx.send(file=File(await trigger_pic(str(ctx.message.author.avatar_url_as(static_format='png'))), f"trigger_{ctx.message.author}.gif"))
async def update_discord_entity_user(watcher: DiscordAsyncMemberState, discord_user: User): watcher._avatar_url = discord_user.avatar_url_as( format=None, static_format=image_format, size=1024).__str__() watcher._userid = discord_user.id watcher._member = discord_user.name + '#' + discord_user.discriminator watcher._user_name = discord_user.name watcher.async_schedule_update_ha_state(False)
async def showavatar(self, ctx, user: discord.User, size: int = 1024): """Affiche l'avatar de l'utilisateur visé [size] = Modifie la taille de l'avatar à afficher (def. 1024*1024)""" avatar_url = str(user.avatar_url_as(size=size)) em = discord.Embed(title=str(user), color=user.color, description="<" + avatar_url + ">") em.set_image(url=avatar_url) await ctx.send(embed=em)
async def avatar_changed_update(self, before: discord.User, after: discord.User): """Sends the appropriate logs on a User Avatar Changed Event""" event_type_avatar = "member_avatar_change" guilds = [ guild for guild in self.bot.guilds if before in guild.members ] if len(guilds) > 0: # get the pfp changed embed image and convert it to a discord.File avatar_changed_file_name = "avatarChanged.png" avatar_info = { "before name": before.name, "before id": before.id, "before pfp": before.avatar_url_as(format="png"), "after name": after.name, "after id": after.id, "after pfp": after.avatar_url_as(format="png") } # For Debugging with await get_avatar_changed_image( self.bot, before, after, avatar_info) as avatar_changed_bytes: # create the embed embed = user_avatar_update(before, after, avatar_changed_file_name) # loop through all the guilds the member is in and send the embed and image for guild in guilds: log_channel = await self.bot.get_event_or_guild_logging_channel( guild.id, event_type_avatar, after.id) if log_channel is not None: # The File Object needs to be recreated for every post, and the buffer needs to be rewound to the beginning # TODO: Handle case where avatar_changed_bytes could be None. avatar_changed_bytes.seek(0) avatar_changed_img = discord.File( filename=avatar_changed_file_name, fp=avatar_changed_bytes) # Send the embed and file # await log_channel.send(file=avatar_changed_img, embed=embed) await self.bot.send_log(log_channel, event_type_avatar, embed=embed, file=avatar_changed_img)
async def avatar(self, ctx, target: discord.User = None): """ Shows someone's avatar. If no arguments were passed, your avatar is shown. """ if target is None: target = ctx.message.author await ctx.send(target.avatar_url_as(format='png'))
async def avatar(self, ctx, *, user: discord.User = None): """Get user's profile picture.""" if user is None: user = ctx.author content = discord.Embed() content.set_author(name=str(user), url=user.avatar_url) content.set_image(url=user.avatar_url_as(static_format='png')) stats = await util.image_info_from_url(user.avatar_url) color = await util.color_from_image_url( str(user.avatar_url_as(size=128, format='png'))) content.colour = await util.get_color(ctx, color) content.set_footer( text= f"{stats['filetype']} | {stats['filesize']} | {stats['dimensions']}" ) await ctx.send(embed=content)
async def shared(self, ctx, *, user: discord.User = None): """See what servers you share with me. Just type the users name or use their id. You can also use their mention, but not recommended.""" if user is None: user = ctx.author shared = "\n".join([g.name for g in self.bot.guilds if user in g.members]) e = discord.Embed(color=0x36393E, description=f'```fix\n{shared}```') e.set_footer(text=f'Shared with {user}') e.set_thumbnail(url=user.avatar_url_as(format=None)) await ctx.send(embed=e)
async def pfp(self, ctx, *, user: discord.User = None): try: em = discord.Embed() if user is not None: em.set_image(url=user.avatar_url_as(static_format='png')) else: em.set_image(url=ctx.message.author.avatar_url_as( static_format='png')) await ctx.channel.send(embed=em) except discord.errors.Forbidden: await ctx.channel.send("Error: cannot send embeds")
async def on_user_update(self, before: discord.User, after: discord.User): """Called when a user changes their name, discriminator or avatar.""" if str(before) != str(after): await self.bot.db.execute( "UPDATE levels SET last_known_as = ? WHERE id = ?", str(after), after.id) elif str(before.avatar_url) != str(after.avatar_url): await self.bot.db.execute( "UPDATE levels SET last_known_avatar_url = ? WHERE id = ?", str(after.avatar_url_as(static_format="png", size=512)), after.id)
async def avatar(self, ctx, user: discord.User = None): if user is None: user = ctx.author avatar_url = user.avatar_url_as(static_format='png') embed = discord.Embed(colour=discord.Colour.blurple()) embed.title = f"Profilbild von {user.display_name}" embed.description = f"[LINK]({avatar_url})" embed.set_image(url=str(avatar_url)) await ctx.send(embed=embed)
async def on_member_remove(self, user: discord.User, guild: discord.Guild): conf = self.bot.get_config(guild) if conf.get('greet.leavemsg'): leavechan = conf.get('greet.leavechannel') leavemsg = conf.get('greet.leavemsg') if leavechan and leavemsg: vars = { '{user.mention}': user.mention, '{user}': discord.utils.escape_markdown(str(user)), '{user.name}': discord.utils.escape_markdown(user.name), '{user.discrim}': user.discriminator, '{server}': discord.utils.escape_markdown(str(guild)), '{guild}': discord.utils.escape_markdown(str(guild)), '{count}': str(guild.member_count) } message = leavemsg for var, value in vars.items(): message = message.replace(var, value) await leavechan.send(message, allowed_mentions=discord.AllowedMentions(users=True)) logch = conf.get('log.moderation') if logch: moderator = None action = None reason = None if guild.me.guild_permissions.view_audit_log: async for e in guild.audit_logs(limit=5): if e.action in [discord.AuditLogAction.kick, discord.AuditLogAction.ban] and e.target.id == user.id: moderator = e.user if moderator == guild.me: moderator = None break if e.action == discord.AuditLogAction.kick: action = 'Kicked' reason = e.reason if e.action == discord.AuditLogAction.ban: action = 'Banned' reason = e.reason break embed = discord.Embed(title='Member Left', url='https://i.giphy.com/media/5C0a8IItAWRebylDRX/source.gif', color=discord.Color.red(), timestamp=datetime.datetime.now(datetime.timezone.utc)) embed.set_author(name=f'{user}', icon_url=str( user.avatar_url_as(static_format='png', size=2048))) if moderator and action: embed.add_field( name=f'{action} By', value=f'{moderator} ({moderator.id})', inline=False) if action and reason: embed.add_field(name=f'{action} for', value=reason, inline=False) embed.set_footer(text=f'User ID: {user.id}') try: await logch.send(embed=embed) except Exception: pass
async def info(self, ctx, user: discord.User = None): """Gets information about a Discord user.""" if user is None: user = ctx.author shared = str(len([i for i in ctx.bot.guilds if i.get_member(user.id)])) em = discord.Embed(title=f'Information for {user.display_name}:') em.add_field(name='Name:', value=user.name) em.add_field(name='Discriminator:', value=user.discriminator) em.add_field(name='ID:', value=user.id) em.add_field(name='Bot:', value=user.bot) em.add_field(name='Created At:', value=user.created_at) em.add_field(name='Shared Servers:', value=shared) em.add_field(name='Avatar URL:', value=user.avatar_url) em.set_thumbnail(url=user.avatar_url_as(static_format='png')) await ctx.send(embed=em)