Python discord.Guild() Examples

The following are 30 code examples of discord.Guild(). 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: modlog.py    From bot with MIT License 7 votes vote down vote up
def on_member_unban(self, guild: discord.Guild, member: discord.User) -> None:
        """Log member unban event to mod log."""
        if guild.id != GuildConstant.id:
            return

        if member.id in self._ignored[Event.member_unban]:
            self._ignored[Event.member_unban].remove(member.id)
            return

        member_str = escape_markdown(str(member))
        await self.send_log_message(
            Icons.user_unban, Colour.blurple(),
            "User unbanned", f"{member_str} (`{member.id}`)",
            thumbnail=member.avatar_url_as(static_format="png"),
            channel_id=Channels.mod_log
        ) 
Example #2
Source File: infractions.py    From bot with MIT License 6 votes vote down vote up
def _pardon_action(self, infraction: utils.Infraction) -> t.Optional[t.Dict[str, str]]:
        """
        Execute deactivation steps specific to the infraction's type and return a log dict.

        If an infraction type is unsupported, return None instead.
        """
        guild = self.bot.get_guild(constants.Guild.id)
        user_id = infraction["user"]
        reason = f"Infraction #{infraction['id']} expired or was pardoned."

        if infraction["type"] == "mute":
            return await self.pardon_mute(user_id, guild, reason)
        elif infraction["type"] == "ban":
            return await self.pardon_ban(user_id, guild, reason)

    # endregion

    # This cannot be static (must have a __func__ attribute). 
Example #3
Source File: leave_move_log.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def leave_move_log(ev, pld):
    """
    :param ev: The event object referenced in the event.
    :type ev: sigma.core.mechanics.event.SigmaEvent
    :param pld: The event payload data to process.
    :type pld: sigma.core.mechanics.payload.GuildPayload
    """
    owner = pld.guild.owner
    bot_count = 0
    user_count = 0
    for user in pld.guild.members:
        if user.bot:
            bot_count += 1
        else:
            user_count += 1
    log_lines = f'Guild: {pld.guild.name} [{pld.guild.id}] | '
    log_lines += f'Owner: {owner.name} [{owner.id}] | '
    log_lines += f'Members: {user_count} | Bots: {bot_count}'
    ev.log.info(log_lines)
    if ev.bot.cfg.pref.movelog_channel:
        move_data = make_move_log_data(pld.guild, False, user_count, bot_count)
        await ev.db[ev.db.db_nam].Movements.insert_one(move_data) 
Example #4
Source File: data_store.py    From DHV3 with GNU Affero General Public License v3.0 6 votes vote down vote up
def set_pref(self, channel, pref, value):
        if isinstance(channel, discord.Guild):
            raise Exception("Guild used in place of channel")
        if channel in self._settings_cache.keys():
            self._settings_cache.pop(channel)

        await self.ensure_channel_exist(channel)

        self.bot.logger.debug(f"-> (set_pref) {channel.id}, {pref}, {value}")
        headers = self.headers
        async with aiohttp.ClientSession() as cs:
            async with cs.patch(self.channels_endpoint + f'{channel.id}/', data={pref: value}, headers=headers) as r:
                res = (await r.json())[:75]
                self.bot.logger.debug(f"<- ({r.status}) {res}")

        await self.bot.log(level=2, title="Setting changed", message=f"{pref} now set to {value}", where=channel)

    # > Admins < # 
Example #5
Source File: data_store.py    From DHV3 with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_pref(self, channel, pref):

        if isinstance(channel, discord.Guild):
            raise Exception("Guild used in place of channel")
        if channel in self._settings_cache.keys():
            return await self._settings_cache[channel][pref]

        await self.enable_channel(channel)

        # #self.bot.logger.debug(f"get_pref for {guild.id} pref {pref}")

        res = await self.request_json(self.channels_endpoint + f'{channel.id}/')
        self.bot.logger.debug(res)
        self._settings_cache[channel] = res
        value = res[pref]
        return value 
Example #6
Source File: incident.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def report(self, guild, incident_embed):
        """
        Reports the incident's contents to the guild's incident channel.
        :param guild: The guild that the incident happened in.
        :type guild: discord.Guild
        :param incident_embed: The incident embed to send to the guild's incident channel.
        :type incident_embed: discord.Embed
        :return:
        :rtype:
        """
        incident_channel_id = await self.db.get_guild_settings(guild.id, 'log_incidents_channel')
        incident_channel = guild.get_channel(incident_channel_id)
        if incident_channel:
            try:
                await incident_channel.send(embed=incident_embed)
            except (discord.Forbidden, discord.NotFound):
                pass 
Example #7
Source File: setup_wizzard.py    From DHV3 with GNU Affero General Public License v3.0 6 votes vote down vote up
def on_guild_join(self, guild: discord.Guild):
        _ = self.bot._

        for channel in guild.channels:
            if isinstance(channel, discord.TextChannel):
                if channel.permissions_for(guild.me).send_messages:
                    channel_used = channel
                    break

        else:
            return  # Nowhere to speak

        await self.bot.send_message(where=channel_used, message=_("Hello!\n "
                                                                  "Thanks for adding me in there! I'm almost ready to start the game!\n "
                                                                  "Could we please go into the channel where you want the game to be ? "
                                                                  "Please invoke me there by using `dh!setup`"
                                                                  "<:event_GuildAdded_01:439550913112309781>")) 
Example #8
Source File: roleswithpermission.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def check_perm_validity(gld: discord.Guild, requested: list):
    """

    :param gld:
    :type gld:
    :param requested:
    :type requested:
    :return:
    :rtype:
    """
    invalid_perms = []
    for req in requested:
        valid = False
        for perm in gld.roles[0].permissions:
            if perm[0].replace('_', ' ').lower() == req.lower():
                valid = True
                break
        if not valid:
            invalid_perms.append(req)
    return invalid_perms 
Example #9
Source File: raffleicon.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def get_matching_emote(guild, emote):
    """
    Gets a matching emote from the given guild.
    :param guild: The guild to search.
    :type guild: discord.Guild
    :param emote: The full emote string to look for.
    :type emote: str
    :return:
    :rtype: discord.Emoji
    """
    emote_name = emote.split(':')[1]
    matching_emote = None
    for emote in guild.emojis:
        if emote.name == emote_name:
            matching_emote = emote
    return matching_emote 
Example #10
Source File: interaction_mechanics.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def update_data(db, data, user, guild):
    """
    Updates the static data of an interaction
    if the guild and member that submitted it are found.
    :param db: The main database handler reference.
    :type db: sigma.core.mechanics.database.Database
    :param data: The interaction data document.
    :type data: dict
    :param user: The user that submitted it.
    :type user: discord.Member
    :param guild: The guild that submitted it.
    :type guild: discord.Guild
    """
    if user:
        unam = data.get('user_name')
        if unam is None or unam != user.name:
            await db[db.db_nam].Interactions.update_many(
                {'user_id': data.get('user_id')}, {'$set': {'user_name': user.name}}
            )
    if guild:
        snam = data.get('server_name')
        if snam is None or snam != guild.name:
            await db[db.db_nam].Interactions.update_many(
                {'server_id': data.get('server_id')}, {'$set': {'server_name': guild.name}}
            ) 
Example #11
Source File: incident.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def get_all(self, guild_id, identifier=None, identifier_id=None):
        """
        Gets all incidents with the given criteria.
        :param guild_id: The Guild ID.
        :type guild_id: int
        :param identifier: The identifier lookup key.
        :type identifier: int or str
        :param identifier_id: The identifier lookup value.
        :type identifier_id: int or str
        :return:
        :rtype: list[sigma.core.mechanics.incident.Incident]
        """
        incidents = []
        lookup = {'guild.id': guild_id} if identifier is None else {'guild.id': guild_id, identifier: identifier_id}
        incident_docs = await self.coll.find(lookup).to_list(None)
        for incident_doc in incident_docs:
            incident = Incident(incident_doc)
            incidents.append(incident)
        return incidents 
Example #12
Source File: greetmessage.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def make_greet_embed(data: dict, greeting: str, guild: discord.Guild):
    """

    :param data:
    :type data:
    :param greeting:
    :type greeting:
    :param guild:
    :type guild:
    :return:
    :rtype:
    """
    guild_icon = str(guild.icon_url) if guild.icon_url else discord.Embed.Empty
    guild_color = await get_image_colors(guild_icon)
    greeting = discord.Embed(color=data.get('color') or guild_color, description=greeting)
    greeting.set_author(name=guild.name, icon_url=guild_icon)
    if data.get('thumbnail'):
        greeting.set_thumbnail(url=data.get('thumbnail'))
    if data.get('image'):
        greeting.set_image(url=data.get('image'))
    return greeting 
Example #13
Source File: bot.py    From bot with MIT License 6 votes vote down vote up
def on_guild_available(self, guild: discord.Guild) -> None:
        """
        Set the internal guild available event when constants.Guild.id becomes available.

        If the cache appears to still be empty (no members, no channels, or no roles), the event
        will not be set.
        """
        if guild.id != constants.Guild.id:
            return

        if not guild.roles or not guild.members or not guild.channels:
            msg = "Guild available event was dispatched but the cache appears to still be empty!"
            log.warning(msg)

            try:
                webhook = await self.fetch_webhook(constants.Webhooks.dev_log)
            except discord.HTTPException as e:
                log.error(f"Failed to fetch webhook to send empty cache warning: status {e.status}")
            else:
                await webhook.send(f"<@&{constants.Roles.admin}> {msg}")

            return

        self._guild_available.set() 
Example #14
Source File: byemessage.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def make_bye_embed(data: dict, goodbye: str, guild: discord.Guild):
    """

    :param data:
    :type data:
    :param goodbye:
    :type goodbye:
    :param guild:
    :type guild:
    :return:
    :rtype:
    """
    guild_icon = str(guild.icon_url) if guild.icon_url else discord.Embed.Empty
    guild_color = await get_image_colors(guild_icon)
    goodbye = discord.Embed(color=data.get('color') or guild_color, description=goodbye)
    goodbye.set_author(name=guild.name, icon_url=guild_icon)
    if data.get('thumbnail'):
        goodbye.set_thumbnail(url=data.get('thumbnail'))
    if data.get('image'):
        goodbye.set_image(url=data.get('image'))
    return goodbye 
Example #15
Source File: bot.py    From modmail with GNU Affero General Public License v3.0 6 votes vote down vote up
def modmail_guild(self) -> typing.Optional[discord.Guild]:
        """
        The guild that the bot is operating in
        (where the bot is creating threads)
        """
        modmail_guild_id = self.config["modmail_guild_id"]
        if modmail_guild_id is None:
            return self.guild
        try:
            guild = discord.utils.get(self.guilds, id=int(modmail_guild_id))
            if guild is not None:
                return guild
        except ValueError:
            pass
        self.config.remove("modmail_guild_id")
        logger.critical("Invalid MODMAIL_GUILD_ID set.")
        return self.guild 
Example #16
Source File: guild.py    From bot with MIT License 6 votes vote down vote up
def get_badges(self, guild: discord.Guild):
        badges = []
        if guild.id == 564052798044504084:
            badges.append(
                str(discord.utils.get(self.bot.emojis, id=671243744774848512))
            )
        if 'PARTNERED' in guild.features:
            badges.append(
                str(discord.utils.get(self.bot.emojis, id=647400542775279629))
            )
        elif 'VERIFIED' in guild.features:
            badges.append(
                str(discord.utils.get(self.bot.emojis, id=647400543018287114))
                )
        if guild.id in self.bot.premium_guilds:
            badges.append(
                str(discord.utils.get(self.bot.emojis, id=680519037704208466))
            )
        if badges:
            badges.append(u'\u200b')  # Prevents huge emojis on mobile
        return badges 
Example #17
Source File: guild.py    From bot with MIT License 6 votes vote down vote up
def get_info(self, ctx: commands.Context, guild: discord.Guild):
        # This takes both context and guild to allow for showing public
        # guilds in the future
        created = guild.created_at.strftime('%b %-d %Y @ %I:%M %p')
        cdelta = humanfriendly.format_timespan(
            datetime.datetime.utcnow() - guild.created_at,
            max_units=2
        ) + ' ago'
        info = [
            f'**Created by {guild.owner or "Unknown#0000"} {cdelta}**',
            f'**Members:** {guild.member_count:,d}',
            f'**Region:** {region.get(str(guild.region), "❓ Deprecated Region")}'
        ]
        is_cached = len(guild.members) / guild.member_count
        if is_cached > 0.98 and guild.get_member(ctx.author):
            # is_cached should be 1.0 if cached but allow for discrepancies
            joinpos = sorted(
                guild.members,
                key=lambda m: m.joined_at or m.created_at
            ).index(ctx.author) + 1
            info.append(f'**Your Join Position:** {joinpos:,d}')
        return info 
Example #18
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 #19
Source File: incident.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def get(self, guild_id, identifier, value):
        """
        Gets a single incident from a guild's document
        storage based on the incident identifier key and value.
        :param guild_id: The Guild ID.
        :type guild_id: int
        :param identifier: The lookup identifier key.
        :type identifier: str
        :param value: The value of the lookup identifier.
        :type value: str or int
        :return:
        :rtype: sigma.core.mechanics.incident.Incident
        """
        incident = None
        lookup = {identifier: value, 'guild.id': guild_id}
        incident_doc = await self.coll.find_one(lookup)
        if incident_doc is not None:
            incident = Incident(incident_doc)
        return incident 
Example #20
Source File: information.py    From bot with MIT License 6 votes vote down vote up
def get_staff_channel_count(self, guild: Guild) -> int:
        """
        Get the number of channels that are staff-only.

        We need to know two things about a channel:
        - Does the @everyone role have explicit read deny permissions?
        - Do staff roles have explicit read allow permissions?

        If the answer to both of these questions is yes, it's a staff channel.
        """
        channel_ids = set()
        for channel in guild.channels:
            if channel.type is ChannelType.category:
                continue

            everyone_can_read = self.role_can_read(channel, guild.default_role)

            for role in constants.STAFF_ROLES:
                role_can_read = self.role_can_read(channel, guild.get_role(role))
                if role_can_read and not everyone_can_read:
                    channel_ids.add(channel.id)
                    break

        return len(channel_ids) 
Example #21
Source File: removewarning.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def make_incident(db: Database, gld: discord.Guild, ath: discord.Member, trg: discord.Member):
    """

    :param db:
    :type db:
    :param gld:
    :type gld:
    :param ath:
    :type ath:
    :param trg:
    :type trg:
    """
    icore = get_incident_core(db)
    inc = icore.generate('unwarn')
    inc.set_location(gld)
    inc.set_moderator(ath)
    inc.set_target(trg)
    await icore.save(inc)
    await icore.report(gld, inc.to_embed('⚠', 0xFFCC4D)) 
Example #22
Source File: bot.py    From rhinobot_heroku with MIT License 5 votes vote down vote up
def on_guild_remove(self, guild:discord.Guild):
        log.info("Bot has been removed from guild: {}".format(guild.name))
        log.debug('Updated guild list:')
        [log.debug(' - ' + s.name) for s in self.guilds]

        if guild.id in self.players:
            self.players.pop(guild.id).kill() 
Example #23
Source File: incident.py    From apex-sigma-core with GNU General Public License v3.0 5 votes vote down vote up
def count_incidents(self, guild_id):
        """
        Counts all incidents for the given guild.
        :param guild_id: The Guild ID.
        :type guild_id: int
        :return:
        :rtype: int
        """
        return await self.coll.count_documents({'guild.id': guild_id}) 
Example #24
Source File: incident.py    From apex-sigma-core with GNU General Public License v3.0 5 votes vote down vote up
def from_obj(self, obj):
        """
        Parses the location data from an object.
        :param obj: The object from which to get the data from.
        :type obj: discord.TextChannel or discord.Guild
        :return:
        :rtype:
        """
        self.id = obj.id
        self.name = obj.name
        if isinstance(obj, discord.TextChannel):
            self.variant = 'channel'
        else:
            self.variant = 'guild' 
Example #25
Source File: incident.py    From apex-sigma-core with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, entity=None):
        """
        :param entity: The entity to get the location data from.
        :type entity: dict or discord.TextChannel or discord.Guild
        """
        self.entity = entity
        self.variant = None
        if isinstance(entity, dict):
            self.from_dict(entity)
        elif isinstance(entity, discord.TextChannel) or isinstance(entity, discord.Guild):
            self.from_obj(entity)
        else:
            self.id = None
            self.name = None 
Example #26
Source File: sigma.py    From apex-sigma-core with GNU General Public License v3.0 5 votes vote down vote up
def on_guild_update(self, before, after):
        """
        Starts events when a guild, or a guild settings entry, is updated/changed.
        :type before: discord.Guild
        :type after: discord.Guild
        :param before: The guild as it was before the change.
        :param after: The guild as it is after the change.
        :return:
        """
        self.loop.create_task(self.queue.event_runner('guild_update', GuildUpdatePayload(self, before, after))) 
Example #27
Source File: sigma.py    From apex-sigma-core with GNU General Public License v3.0 5 votes vote down vote up
def on_guild_remove(self, guild):
        """
        Starts events when this client leaves, or is removed from, a guild.
        :type guild: discord.Guild
        :param guild: The guild that the client left.
        :return:
        """
        self.loop.create_task(self.queue.event_runner('guild_remove', GuildPayload(self, guild))) 
Example #28
Source File: sigma.py    From apex-sigma-core with GNU General Public License v3.0 5 votes vote down vote up
def on_guild_join(self, guild):
        """
        Starts events when this client joins a guild.
        :type guild: discord.Guild
        :param guild: The guild that the client joined.
        :return:
        """
        self.loop.create_task(self.queue.event_runner('guild_join', GuildPayload(self, guild))) 
Example #29
Source File: sigma.py    From apex-sigma-core with GNU General Public License v3.0 5 votes vote down vote up
def on_member_ban(self, guild, user):
        """
        Starts events when a member is banned from a guild.
        :type guild: discord.Guild
        :type user: discord.Member or discord.User
        :param guild: The guild on which the member was banned.
        :param user: The user that was banned.
        :return:
        """
        if not user.bot:
            self.loop.create_task(self.queue.event_runner('member_ban', BanPayload(self, guild, user))) 
Example #30
Source File: sigma.py    From apex-sigma-core with GNU General Public License v3.0 5 votes vote down vote up
def get_guild(self, gid, cached=False, fetched=True):
        """
        Gets a guild from the core client
        or form teh cache if one exists in the Cacher class.
        :param gid: The Guild ID of the requested guild.
        :type gid: int
        :param cached: Should the guild be cached/obtained from the cache.
        :type cached: bool
        :return:
        :param fetched: Should the guild fetched.
        :type fetched: bool
        :rtype:
        """
        cacheable = False
        cache_key = f'get_gld_{gid}'
        fh = get_fetch_helper(self)
        if cached and self.cfg.cache.type not in ['mixed', 'redis']:
            cacheable = True
            out = await self.cache.get_cache(cache_key)
            if not out:
                out = super().get_guild(gid)
        else:
            out = super().get_guild(gid)
        if not out and fetched:
            try:
                out = await fh.fetch_guild(gid)
            except Exception:
                out = None
        if out:
            await fh.save_object_doc('guild', fh.make_guild_data(out))
        if out and cacheable:
            await self.cache.set_cache(cache_key, out)
        return out