Python discord.Invite() Examples

The following are 8 code examples of discord.Invite(). 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 discord , or try the search function .
Example #1
Source File: settings.py    From bot with MIT License 6 votes vote down vote up
def on_invite_create(self, invite: discord.Invite):
		guild = invite.guild
		if guild.id in self.bot.premium_guilds:
			await self.load_invites(guild.id)
		if not isinstance(guild, discord.Guild):
			return
		logch = self.bot.get_config(guild).get('log.action')
		if logch:
			embed = discord.Embed(color=discord.Color.green(), timestamp=datetime.datetime.now(datetime.timezone.utc), description=f'**An invite was created**')
			embed.set_author(name=guild.name, icon_url=str(guild.icon_url_as(static_format='png', size=2048)))
			embed.add_field(name='Invite Code', value=invite.code, inline=False)
			embed.add_field(name='Max Uses', value=invite.max_uses, inline=False)
			embed.add_field(name='Temporary', value=invite.temporary, inline=False)
			if invite.temporary:
				delta = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(seconds=invite.max_age)
				if isinstance(delta, datetime.timedelta):
					embed.add_field(name='Expires in', value=humanfriendly.format_timespan(delta), inline=False)
			if isinstance(invite.channel, discord.abc.GuildChannel):
				embed.add_field(name='Channel', value=f'#{invite.channel.name}({invite.channel.id})', inline=False)
			if invite.inviter:
				embed.set_footer(text=f'Created by: {invite.inviter} ({invite.inviter.id})')
			try:
				await logch.send(embed=embed)
			except Exception:
				pass 
Example #2
Source File: settings.py    From bot with MIT License 6 votes vote down vote up
def on_invite_delete(self, invite: discord.Invite):
		guild = invite.guild
		if guild.id in self.bot.premium_guilds:
			await self.load_invites(guild.id)
		if not isinstance(guild, discord.Guild):
			return
		whodidit = None
		async for a in guild.audit_logs(action=discord.AuditLogAction.invite_delete, limit=1):
			if a.target.code == invite.code:
				whodidit = a.user
		logch = self.bot.get_config(guild).get('log.action')
		if logch:
			embed = discord.Embed(color=discord.Color.red(), timestamp=datetime.datetime.now(datetime.timezone.utc), description=f'**An invite was deleted**')
			embed.set_author(name=guild.name, icon_url=str(guild.icon_url_as(static_format='png', size=2048)))
			embed.add_field(name='Invite Code', value=invite.code, inline=False)
			if isinstance(invite.channel, discord.abc.GuildChannel):
				embed.add_field(name='Channel', value=f'#{invite.channel.name}({invite.channel.id})', inline=False)
			if whodidit:
				embed.set_footer(text=f'Deleted by: {whodidit} ({whodidit.id})')
			try:
				await logch.send(embed=embed)
			except Exception:
				pass 
Example #3
Source File: converter.py    From discord.py with MIT License 5 votes vote down vote up
def convert(self, ctx, argument):
        try:
            invite = await ctx.bot.fetch_invite(argument)
            return invite
        except Exception as exc:
            raise BadArgument('Invite is invalid or expired') from exc 
Example #4
Source File: bound_role_cacher.py    From apex-sigma-core with GNU General Public License v3.0 5 votes vote down vote up
def update_invites(guild, invites):
    """
    :param guild: The guild that the invites are from.
    :type guild: discord.Guild
    :param invites: The list of invites.
    :type invites: list[discord.Invite]
    """
    cache_key = f'invite_cache_{guild.id}'
    cache = await invite_cache.get_cache(cache_key) or {}
    cache.update({guild.id: invites})
    await invite_cache.set_cache(cache_key, cache) 
Example #5
Source File: bound_role_cacher.py    From apex-sigma-core with GNU General Public License v3.0 5 votes vote down vote up
def get_changed_invite(guild_id, bound_list, invites):
    """
    Checks for invite count changes to get the one that triggered.
    :param guild_id: The ID of the guild.
    :type guild_id: int
    :param bound_list: A list of bound roles.
    :type bound_list: list
    :param invites: A list of the guild's invites.
    :type invites: list[discord.Invite]
    :return:
    :rtype: discord.Invite
    """
    invite = None
    cache_key = f'invite_cache_{guild_id}'
    cache = await invite_cache.get_cache(cache_key) or {}
    cached = cache.get(guild_id)
    if cached is None:
        cached = []
    cache.update({guild_id: invites})
    await invite_cache.set_cache(cache_key, cache)
    if invites is None:
        invites = []
    if invites:
        for cached_inv in cached:
            for curr_inv in invites:
                if cached_inv.id == curr_inv.id:
                    if cached_inv.uses != curr_inv.uses:
                        if curr_inv.id in bound_list:
                            invite = curr_inv
                            break
    return invite 
Example #6
Source File: eventmixin.py    From Trusty-cogs with MIT License 5 votes vote down vote up
def on_invite_delete(self, invite: discord.Invite) -> None:
        """
            New in discord.py 1.3
        """
        guild = invite.guild
        if guild.id not in self.settings:
            return
        if not self.settings[guild.id]["invite_deleted"]["enabled"]:
            return
        try:
            channel = await self.modlog_channel(guild, "invite_deleted")
        except RuntimeError:
            return
        embed_links = (
            channel.permissions_for(guild.me).embed_links
            and self.settings[guild.id]["invite_deleted"]["embed"]
        )
        invite_attrs = {
            "code": _("Code: "),
            "inviter": _("Inviter: "),
            "channel": _("Channel: "),
            "max_uses": _("Max Uses: "),
            "uses": _("Used: "),
        }
        try:
            invite_time = invite.created_at.strftime("%H:%M:%S")
        except AttributeError:
            invite_time = datetime.datetime.utcnow().strftime("%H:%M:%S")
        msg = _("{emoji} `{time}` Invite deleted ").format(
            emoji=self.settings[guild.id]["invite_deleted"]["emoji"], time=invite_time,
        )
        embed = discord.Embed(
            title=_("Invite Deleted"),
            colour=await self.get_event_colour(guild, "invite_deleted")
        )
        worth_updating = False
        for attr, name in invite_attrs.items():
            before_attr = getattr(invite, attr)
            if before_attr:
                worth_updating = True
                msg += f"{name} {before_attr}\n"
                embed.add_field(name=name, value=str(before_attr))
        if not worth_updating:
            return
        if embed_links:
            await channel.send(embed=embed)
        else:
            await channel.send(escape(msg, mass_mentions=True)) 
Example #7
Source File: eventmixin.py    From Trusty-cogs with MIT License 4 votes vote down vote up
def on_member_join(self, member: discord.Member):
        guild = member.guild
        if guild.id not in self.settings:
            return
        if not self.settings[guild.id]["user_join"]["enabled"]:
            return
        # if not await self.config.guild(guild).user_join.enabled():
        # return
        try:
            channel = await self.modlog_channel(guild, "user_join")
        except RuntimeError:
            return
        embed_links = (
            channel.permissions_for(guild.me).embed_links
            and self.settings[guild.id]["user_join"]["embed"]
        )
        time = datetime.datetime.utcnow()
        users = len(guild.members)
        # https://github.com/Cog-Creators/Red-DiscordBot/blob/develop/cogs/general.py
        since_created = (time - member.created_at).days
        user_created = member.created_at.strftime("%d %b %Y %H:%M")

        created_on = "{}\n({} days ago)".format(user_created, since_created)

        possible_link = await self.get_invite_link(guild)
        if embed_links:
            embed = discord.Embed(
                description=member.mention,
                colour=await self.get_event_colour(guild, "user_join"),
                timestamp=member.joined_at if member.joined_at else datetime.datetime.utcnow(),
            )
            embed.add_field(name=_("Total Users:"), value=str(users))
            embed.add_field(name=_("Account created on:"), value=created_on)
            embed.set_footer(text=_("User ID: ") + str(member.id))
            embed.set_author(
                name=_("{member} ({m_id}) has joined the guild").format(
                    member=member, m_id=member.id
                ),
                url=member.avatar_url,
                icon_url=member.avatar_url,
            )
            if possible_link:
                embed.add_field(name=_("Invite Link"), value=possible_link)
            embed.set_thumbnail(url=member.avatar_url)
            await channel.send(embed=embed)
        else:
            time = datetime.datetime.utcnow()
            msg = _(
                "{emoji} `{time}` **{member}**(`{m_id}`) "
                "joined the guild. Total members: {users}"
            ).format(
                emoji=self.settings[guild.id]["user_join"]["emoji"],
                time=time.strftime("%H:%M:%S"),
                member=member,
                m_id=member.id,
                users=users,
            )
            await channel.send(msg) 
Example #8
Source File: eventmixin.py    From Trusty-cogs with MIT License 4 votes vote down vote up
def on_invite_create(self, invite: discord.Invite) -> None:
        """
            New in discord.py 1.3
        """
        guild = invite.guild
        if guild.id not in self.settings:
            return
        if not self.settings[guild.id]["invite_created"]["enabled"]:
            return
        try:
            channel = await self.modlog_channel(guild, "invite_created")
        except RuntimeError:
            return
        embed_links = (
            channel.permissions_for(guild.me).embed_links
            and self.settings[guild.id]["invite_created"]["embed"]
        )
        invite_attrs = {
            "code": _("Code:"),
            "inviter": _("Inviter:"),
            "channel": _("Channel:"),
            "max_uses": _("Max Uses:"),
        }
        try:
            invite_time = invite.created_at.strftime("%H:%M:%S")
        except AttributeError:
            invite_time = datetime.datetime.utcnow().strftime("%H:%M:%S")
        msg = _("{emoji} `{time}` Invite created ").format(
            emoji=self.settings[guild.id]["invite_created"]["emoji"], time=invite_time,
        )
        embed = discord.Embed(
            title=_("Invite Created"),
            colour=await self.get_event_colour(guild, "invite_created")
        )
        worth_updating = False
        for attr, name in invite_attrs.items():
            before_attr = getattr(invite, attr)
            if before_attr:
                worth_updating = True
                msg += f"{name} {before_attr}\n"
                embed.add_field(name=name, value=str(before_attr))
        if not worth_updating:
            return
        if embed_links:
            await channel.send(embed=embed)
        else:
            await channel.send(escape(msg, mass_mentions=True))