Python discord.Channel() Examples

The following are 30 code examples of discord.Channel(). 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: vcutil.py    From SML-Cogs with MIT License 6 votes vote down vote up
def vcutil_addvc(self, ctx, vc: discord.Channel):
        """Add a Voice Channel to monitor."""
        server = ctx.message.server
        if server.id not in self.settings:
            self.settings[server.id] = {}
        if vc is None:
            await self.bot.say("{} is not a valid channel.".format(vc))
            return
        if vc.type != discord.ChannelType.voice:
            await self.bot.say("{} is not a voice channel".format(vc))
            return
        if "vc" not in self.settings[server.id]:
            self.settings[server.id]["vc"] = []
        vclist = self.settings[server.id]["vc"]
        if vc.id not in vclist:
            vclist.append(vc.id)
        await self.bot.say(
            "Added {} to list of channels to monitor.".format(vc))
        dataIO.save_json(JSON, self.settings) 
Example #2
Source File: hockey.py    From Trusty-cogs-archive with MIT License 6 votes vote down vote up
def remove_goals(self, ctx, team, channel:discord.Channel=None):
        """Removes a teams goal updates from a channel"""
        if team.lower() == "all":
            team = "all"
        else:
            try:
                team = [team_name for team_name in self.teams if team.lower() in team_name.lower()][0]
            except IndexError:
                await self.bot.say("{} is not an available team!".format(team))
                return
        if channel is None:
            channel = ctx.message.channel
        if team not in self.settings:
            await self.bot.send_message(ctx.message.channel, "I am not posting {} goals in {}".format(team, channel.mention))
            return
        if channel.id in self.settings[team]["channel"]:
            self.settings[team]["channel"].remove(channel.id)
            dataIO.save_json("data/hockey/settings.json", self.settings)
            await self.bot.say("{} goals will stop being posted in {}".format(team, channel.mention)) 
Example #3
Source File: hockey.py    From Trusty-cogs-archive with MIT License 6 votes vote down vote up
def add_goals(self, ctx, team, channel:discord.Channel=None):
        """Adds a hockey team goal updates to a channel"""
        if team.lower() == "all":
            team = "all"
        else:
            try:
                team = [team_name for team_name in self.teams if team.lower() in team_name.lower()][0]
            except IndexError:
                await self.bot.say("{} is not an available team!".format(team))
                return
        if channel is None:
            channel = ctx.message.channel
        if team not in self.settings:
            self.settings[team] = {"channel":[channel.id], "goal_id": {}}
        if channel.id in self.settings[team]["channel"]:
            await self.bot.send_message(ctx.message.channel, "I am already posting {} goals in {}!".format(team, channel.mention))
            return
        self.settings[team]["channel"].append(channel.id)
        dataIO.save_json("data/hockey/settings.json", self.settings)
        await self.bot.say("{} goals will be posted in {}".format(team, channel.mention)) 
Example #4
Source File: tweets.py    From Trusty-cogs-archive with MIT License 6 votes vote down vote up
def _del(self, ctx, account, channel:discord.Channel=None):
        """Removes a twitter account to the specified channel"""
        account = account.lower()
        api = await self.authenticate()
        if channel is None:
            channel = ctx.message.channel
        try:
            for status in tw.Cursor(api.user_timeline, id=account).items(1):
                user_id = str(status.user.id)      
        except tw.TweepError as e:
            print("Whoops! Something went wrong here. \
                    The error code is " + str(e) + account)
            await self.bot.say("That account does not exist! Try again")
            return
        removed = await self.del_account(channel, user_id)
        if removed:
            await self.bot.say("{} has been removed from {}".format(account, channel.mention))
        else:
            await self.bot.say("{0} doesn't seem to be posting in {1}!"
                               .format(account, channel.mention)) 
Example #5
Source File: __init__.py    From dismock with MIT License 6 votes vote down vote up
def _display_stats(self, channel: discord.Channel) -> None:
		''' Display the status of the various tests. '''
		# NOTE: An emoji is the width of two spaces
		response = '```\n'
		longest_name = max(map(lambda t: len(t.name), self._tests))
		for test in self._tests:
			response += test.name.rjust(longest_name) + ' '
			if test.needs_human:
				response += '✋ '
			else:
				response += '   '
			if test.result is TestResult.UNRUN:
				response += '⚫ Not run\n'
			elif test.result is TestResult.SUCCESS:
				response += '✔️ Passed\n'
			elif test.result is TestResult.FAILED:
				response += '❌ Failed\n'
		response += '```\n'
		await self.send_message(channel, response) 
Example #6
Source File: tweets.py    From Trusty-cogs-archive with MIT License 6 votes vote down vote up
def _add(self, ctx, account, channel:discord.Channel=None):
        """Adds a twitter account to the specified channel"""
        api = await self.authenticate()
        try:
            for status in tw.Cursor(api.user_timeline, id=account).items(1):
                user_id = str(status.user.id)
                screen_name = status.user.screen_name
                last_id = status.id
        
        except tw.TweepError as e:
            print("Whoops! Something went wrong here. \
                    The error code is " + str(e) + account)
            await self.bot.say("That account does not exist! Try again")
            return
        if channel is None:
            channel = ctx.message.channel
        added = await self.add_account(channel, user_id, screen_name)
        if added:
            await self.bot.say("{0} Added to {1}!".format(account, channel.mention))
        else:
            await self.bot.say("{} is already posting or could not be added to {}".format(account, channel.mention)) 
Example #7
Source File: __init__.py    From dismock with MIT License 6 votes vote down vote up
def run_test(self,
		               test: Test,
		               channel: discord.Channel,
		               stop_error: bool = False) -> TestResult:
		''' Run a single test in a given channel.
			Updates the test with the result, and also returns it.
		'''
		interface = Interface(
			self,
			channel,
			self._find_target(channel.server))
		try:
			await test.func(interface)
		except TestRequirementFailure:
			test.result = TestResult.FAILED
			if not stop_error:
				raise
		else:
			test.result = TestResult.SUCCESS
		return test.result 
Example #8
Source File: star.py    From Trusty-cogs-archive with MIT License 6 votes vote down vote up
def setup_starboard(self, ctx, channel: discord.Channel=None, emoji="⭐", role:discord.Role=None):
        """Sets the starboard channel, emoji and role"""
        server = ctx.message.server
        if channel is None:
            channel = ctx.message.channel
        if "<" in emoji and ">" in emoji:
            emoji = await self.check_server_emojis(server, emoji)
            if emoji is None:
                await self.bot.send_message(ctx.message.channel, "That emoji is not on this server!")
                return
            else:
                emoji = ":" + emoji.name + ":" + emoji.id
        
        if role is None:
            role = await self.get_everyone_role(server)
        self.settings[server.id] = {"emoji": emoji, 
                                    "channel": channel.id, 
                                    "role": [role.id],
                                    "threshold": 0,
                                    "messages": [],
                                    "ignore": []}
        dataIO.save_json("data/star/settings.json", self.settings)
        await self.bot.say("Starboard set to {}".format(channel.mention)) 
Example #9
Source File: activity.py    From Trusty-cogs-archive with MIT License 6 votes vote down vote up
def add_server(self, ctx, channel:discord.Channel=None, role:discord.Role=None, invite_link=None):
        """Set the server for activity checking"""
        server = ctx.message.server
        if channel is None:
            channel = ctx.message.channel
        if role is not None:
            role = role.id
        if role is None:
            role = await self.get_everyone_role(server)
        if server.id in self.log:
            await self.bot.say("This server is already checking for activity!")
            return
        if invite_link is None:
            await self.bot.say("You'll need to supply an invite link if you want one for members to rejoin")
        self.settings[server.id] = {"channel": channel.id,
                                    "check_roles": [role],
                                    "time": 604800,
                                    "invite": True,
                                    "link": invite_link,
                                    "rip_count": 0}
        dataIO.save_json(self.settings_file, self.settings)
        await self.build_list(ctx, server)
        await self.bot.send_message(ctx.message.channel, "Sending activity check messages to {}".format(channel.mention)) 
Example #10
Source File: activitylog.py    From calebj-cogs with GNU General Public License v3.0 6 votes vote down vote up
def set_channel(self, ctx, on_off: bool, channel: discord.Channel = None):
        """
        Sets channel logging on or off (channel optional)

        To enable or disable all channels at once, use `logset server`.
        """
        if channel is None:
            channel = ctx.message.channel

        server = channel.server

        if server.id not in self.settings:
            self.settings[server.id] = {}

        self.settings[server.id][channel.id] = on_off

        if on_off:
            await self.bot.say('Logging enabled for %s' % channel.mention)
        else:
            await self.bot.say('Logging disabled for %s' % channel.mention)

        self.save_json() 
Example #11
Source File: activitylog.py    From calebj-cogs with GNU General Public License v3.0 6 votes vote down vote up
def format_overwrite(target, channel, before, after):
        target_str = 'Channel overwrites: {0.name} ({0.id}): '.format(channel)
        target_str += 'role' if isinstance(target, discord.Role) else 'member'
        target_str += ' {0.name} ({0.id})'.format(target)

        if before:
            bpair = [x.value for x in before.pair()]

        if after:
            apair = [x.value for x in after.pair()]

        if before and after:
            fmt = ' updated to values %i, %i (was %i, %i)'
            return target_str + fmt % tuple(apair + bpair)
        elif after:
            return target_str + ' added with values %i, %i' % tuple(apair)
        elif before:
            return target_str + ' removed (was %i, %i)' % tuple(bpair) 
Example #12
Source File: embedwiz.py    From calebj-cogs with GNU General Public License v3.0 6 votes vote down vote up
def embedwiz_channel(self, ctx, channel: discord.Channel, *, specification):
        """
        Posts an embed in another channel according to the spec.

        See [p]help embedwiz for more information.
        """
        member = channel.server and channel.server.get_member(ctx.message.author.id)
        override = self._check_override(member)

        if channel != ctx.message.channel and not member:
            await self.bot.say(error("Channel is private or you aren't in the server that channel belongs to."))
            return
        elif not channel.permissions_for(member).send_messages:
            msg = error("You don't have permissions to post there!")
            await self.bot.say(msg)
            return

        embed = await self._parse_embed(ctx, specification, force_author=not override)

        if embed:
            await self.bot.send_message(channel, embed=embed)

            if channel != ctx.message.channel:
                await self.bot.say("Embed sent to %s." % channel.mention) 
Example #13
Source File: welcome.py    From Dumb-Cogs with MIT License 6 votes vote down vote up
def channel(self, ctx, channel : discord.Channel=None):
        """Sets the channel to send the welcome message

        If channel isn't specified, the server's default channel will be used"""
        server = ctx.message.server
        if channel is None:
            channel = ctx.message.server.default_channel
        if not server.get_member(self.bot.user.id
                                 ).permissions_in(channel).send_messages:
            await self.bot.say("I do not have permissions to send "
                               "messages to {0.mention}".format(channel))
            return
        self.settings[server.id]["CHANNEL"] = channel.id
        dataIO.save_json(settings_path, self.settings)
        channel = self.get_welcome_channel(server)
        await self.bot.send_message(channel, "I will now send welcome "
                                    "messages to {0.mention}".format(channel))
        await self.send_testing_msg(ctx) 
Example #14
Source File: serverquotes.py    From calebj-cogs with GNU General Public License v3.0 6 votes vote down vote up
def quote_add_msg(self, ctx, message_id: int, channel: discord.Channel = None):
        """
        Adds a message to the server quote database

        The full text of the message is used. If the message belongs to
        another channel, specify it as the second argument.
        """
        try:
            msg = await self.bot.get_message(channel or ctx.message.channel, str(message_id))
        except discord.errors.NotFound:
            await self.bot.say(warning("Couldn't find that message in %s."
                                       % (channel.mention if channel else 'this channel')))
            return

        if msg.content or msg.attachments or (msg.embeds and msg.embeds[0].get('type') == 'image'):
            self._update_member(ctx.message.author)
            self._update_member(msg.author)
            ret = self._add_quote(ctx, message=msg)
            await self.bot.say(okay("Quote #%i added." % ret['server_quote_id']))
        else:
            await self.bot.say(warning("Cannot add a quote with no text, attachments or embed images.")) 
Example #15
Source File: logstash.py    From SML-Cogs with MIT License 6 votes vote down vote up
def get_channel_params(self, channel: Channel):
        """Return extra fields for channel."""
        extra = {
            'id': channel.id,
            'name': channel.name,
            'server': self.get_server_params(channel.server),
            'position': channel.position,
            'is_default': channel.is_default,
            'created_at': channel.created_at.isoformat(),
            'type': {
                'text': channel.type == ChannelType.text,
                'voice': channel.type == ChannelType.voice,
                'private': channel.type == ChannelType.private,
                'group': channel.type == ChannelType.group
            }
        }
        return extra 
Example #16
Source File: ga.py    From SML-Cogs with MIT License 6 votes vote down vote up
def log_message(
            self, client_id,
            server: Server, channel: Channel, member: Member):
        """Log messages."""
        server_name = self.url_escape(server.name)
        self.gmp_report_event(
            client_id,
            '{}: Messages'.format(server_name),
            server_name,
            label=server_name,
            value=1)

        log_params = OrderedDict([
            ('server', server)
        ])
        self.log_pageview_names(client_id, log_params)
        self.log_pageview_ids(client_id, log_params) 
Example #17
Source File: feedback.py    From SML-Cogs with MIT License 6 votes vote down vote up
def setfeedback_status(self, ctx: Context):
        """Display list of roles allowed to use feedback."""
        server = ctx.message.server
        if server.id not in self.settings:
            return
        s = self.settings[server.id]
        if "send_roles" in s:
            roles = [
                discord.utils.get(
                    server.roles, id=id).name for id in s["send_roles"]]
            await self.bot.say(
                "List of roles allowed to send feedback: {}"
                "".format(", ".join(roles)))
        if "read_roles" in s:
            roles = [
                discord.utils.get(
                    server.roles, id=id).name for id in s["read_roles"]]
            await self.bot.say(
                "List of roles allowed to read feedback: {}"
                "".format(", ".join(roles)))
        if "channel" in s:
            channel = discord.utils.get(server.channels, id=s["channel"])
            await self.bot.say("Channel: {}".format(channel))
        if "feedbacks" in s:
            await self.bot.say("Feedbacks: {}".format(len(s["feedbacks"]))) 
Example #18
Source File: trigger.py    From 26-Cogs with GNU General Public License v3.0 6 votes vote down vote up
def channels(self, ctx, trigger_name : str, *channels : discord.Channel):
        """Sets the channel(s) in which the trigger will be active

        Not entering any channel will revert the trigger to server-wide"""
        author = ctx.message.author
        server = author.server
        trigger = self.get_trigger_by_name(trigger_name)
        if not await self.settings_check(trigger, author):
            return
        if channels:
            channels = [c.id for c in channels]
            trigger.channels[server.id] = list(channels)
            self.save_triggers()
            if trigger.server is not None:
                await self.bot.say("The trigger will be enabled only on "
                                   "those channels.")
            else:
                await self.bot.say("In this server the trigger will be "
                                   "enabled only on those channels")
        else:
            trigger.channels[server.id] = []
            self.save_triggers()
            await self.bot.say("The trigger will be active in all channels.") 
Example #19
Source File: scheduler.py    From Squid-Plugins with MIT License 6 votes vote down vote up
def run_coro(self, event):
        channel = self.bot.get_channel(event.channel)
        try:
            server = channel.server
            prefix = self.bot.settings.get_prefixes(server)[0]
        except AttributeError:
            log.debug("Channel no longer found, not running scheduled event.")
            return
        data = {}
        data['timestamp'] = time.strftime("%Y-%m-%dT%H:%M:%S%z", time.gmtime())
        data['id'] = randint(10**(17), (10**18) - 1)
        data['content'] = prefix + event.command
        data['channel'] = self.bot.get_channel(event.channel)
        data['author'] = {'id': event.author}
        data['nonce'] = randint(-2**32, (2**32) - 1)
        data['channel_id'] = event.channel
        data['reactions'] = []
        fake_message = discord.Message(**data)
        # coro = self.bot.process_commands(fake_message)
        log.info("Running '{}' in {}".format(event.name, event.server))
        # self.bot.loop.create_task(coro)
        self.bot.dispatch('message', fake_message) 
Example #20
Source File: permissions.py    From Squid-Plugins with MIT License 6 votes vote down vote up
def channel_reset(self, ctx, command, channel: discord.Channel=None):
        """Resets permissions of [command/cog] on [channel] to the default"""
        server = ctx.message.server
        try:
            command_obj = self._get_command(command)
        except BadCommand as e:
            try:
                self.bot.cogs[command]
                command_obj = command
            except KeyError:
                raise e
        if channel is None:
            channel = ctx.message.channel
        await self._reset_permission(command_obj, server, channel=channel)

        await self.bot.say("Channel {} permissions for {} reset.".format(
            channel.mention, command)) 
Example #21
Source File: permissions.py    From Squid-Plugins with MIT License 6 votes vote down vote up
def channel_deny(self, ctx, command, channel: discord.Channel=None):
        """Explicitly denies [command/cog] usage in [channel]

        Overridden by role based permissions"""
        server = ctx.message.server
        try:
            command_obj = self._get_command(command)
        except BadCommand as e:
            try:
                self.bot.cogs[command]
                command_obj = command
            except KeyError:
                raise e
        if channel is None:
            channel = ctx.message.channel
        await self._set_permission(command_obj, server, channel=channel,
                                   allow=False)

        await self.bot.say("Channel {} denied use of {}.".format(
            channel.mention, command)) 
Example #22
Source File: permissions.py    From Squid-Plugins with MIT License 6 votes vote down vote up
def channel_allow(self, ctx, command, channel: discord.Channel=None):
        """Explicitly allows [command/cog] to be used in [channel].

        Not really useful because role perm overrides channel perm"""
        server = ctx.message.server
        try:
            command_obj = self._get_command(command)
        except BadCommand as e:
            try:
                self.bot.cogs[command]
                command_obj = command
            except KeyError:
                raise e
        if channel is None:
            channel = ctx.message.channel
        await self._set_permission(command_obj, server, channel=channel)

        await self.bot.say("Channel {} allowed use of {}.".format(
            channel.mention, command)) 
Example #23
Source File: serverquotes.py    From calebj-cogs with GNU General Public License v3.0 6 votes vote down vote up
def gquote_add_msg(self, ctx, message_id: int, channel: discord.Channel = None):
        """
        Adds a message to the server global quote database

        The full text of the message is used. If the message belongs to
        another channel, specify it as the second argument.
        """
        try:
            msg = await self.bot.get_message(channel or ctx.message.channel, str(message_id))
        except discord.errors.NotFound:
            await self.bot.say(warning("Couldn't find that message in %s."
                                       % (channel.mention if channel else 'this channel')))
            return

        if msg.content or msg.attachments or (msg.embeds and msg.embeds[0].get('type') == 'image'):
            self._update_member(ctx.message.author)
            self._update_member(msg.author)
            ret = self._add_quote(ctx, message=msg, is_global=True, server=False)
            await self.bot.say(okay("Global quote #g%i added." % ret['quote_id']))
        else:
            await self.bot.say(warning("Cannot add a quote with no text, attachments or embed images.")) 
Example #24
Source File: gallery.py    From calebj-cogs with GNU General Public License v3.0 6 votes vote down vote up
def cleanup_task(self, channel: discord.Channel) -> None:
        try:
            to_delete = []
            settings = self.settings_for(channel)
            now = datetime.utcnow()
            before = now - timedelta(seconds=settings["EXPIRATION"])
            after = now - timedelta(days=14, seconds=-30)

            check = self.get_message_check(channel, settings=settings)

            while True:
                async for message in self.bot.logs_from(channel, before=before, after=after):
                    before = message
                    if await check(message):
                        to_delete.append(message)
                else:
                    break

            while to_delete and to_delete[-1].timestamp < after:
                to_delete.pop()

            if to_delete:
                await self.mass_purge(to_delete)
        except Exception as e:
            raise CleanupError(channel, e) 
Example #25
Source File: archive.py    From SML-Cogs with MIT License 5 votes vote down vote up
def archive_channel(self, ctx, channel: discord.Channel, count=1000):
        """Archive channel messages."""
        await self.save_channel(channel, count)
        await self.log_channel(ctx, channel)

        await self.bot.say("Channel logged.") 
Example #26
Source File: trade.py    From SML-Cogs with MIT License 5 votes vote down vote up
def enable_auto_trade_channel(self, ctx, channel: discord.Channel):
        """Set channel for auto trade listings."""
        server = ctx.message.server
        self.settings.enable_auto(server.id, channel.id)
        await self.bot.say("Auto sending trade list.") 
Example #27
Source File: feedback.py    From SML-Cogs with MIT License 5 votes vote down vote up
def setfeedback_channel(
            self, ctx: Context, channel: discord.Channel=None):
        """Set feedback channel."""
        if channel is None:
            channel = ctx.message.channel
        server = ctx.message.server
        if server.id not in self.settings:
            self.init_server_settings(server)
        self.settings[server.id]["channel"] = channel.id
        dataIO.save_json(JSON, self.settings)
        await self.bot.say(
            "Feedback channel set to {}".format(channel.name)) 
Example #28
Source File: archive.py    From SML-Cogs with MIT License 5 votes vote down vote up
def log_channel(self, ctx, channel: discord.Channel):
        """Write channel messages from a channel."""
        server = ctx.message.server

        channel_messages = self.settings[server.id][channel.id]
        for message in channel_messages:
            author_id = message['author_id']
            author = server.get_member(author_id)
            author_mention = author_id
            if author is not None:
                author_mention = author.mention
            content = message['content']
            timestamp = message['timestamp']
            message_id = message['id']

            description = '{}: {}'.format(author_mention, content)

            em = discord.Embed(
                title=channel.name,
                description=description)

            for reaction in message['reactions']:
                em.add_field(name=reaction['emoji'], value=reaction['count'])

            em.set_footer(text='{} - ID: {}'.format(timestamp, message_id))
            await self.bot.say(embed=em) 
Example #29
Source File: archive.py    From SML-Cogs with MIT License 5 votes vote down vote up
def save_channel(self, channel: discord.Channel, count=1000, before=None, after=None, reverse=False):
        """Save channel messages."""
        server = channel.server
        if server.id not in self.settings:
            self.settings[server.id] = {}

        channel_messages = []

        async for message in self.bot.logs_from(
                channel, limit=count, before=before, after=after, reverse=reverse):
            msg ={
                'author_id': message.author.id,
                'content': message.content,
                'timestamp': message.timestamp.isoformat(),
                'id': message.id,
                'reactions': []
            }
            for reaction in message.reactions:
                r = {
                    'custom_emoji': reaction.custom_emoji,
                    'count': reaction.count
                }
                if reaction.custom_emoji:
                    # <:emoji_name:emoji_id>
                    r['emoji'] = '<:{}:{}>'.format(
                        reaction.emoji.name,
                        reaction.emoji.id)
                else:
                    r['emoji'] = reaction.emoji
                msg['reactions'].append(r)
            channel_messages.append(msg)

        channel_messages = sorted(
            channel_messages, key=lambda x: x['timestamp'])

        self.settings[server.id][channel.id] = channel_messages
        dataIO.save_json(JSON, self.settings) 
Example #30
Source File: acceptrules.py    From Trusty-cogs-archive with MIT License 5 votes vote down vote up
def channel(self, ctx, channel: discord.Channel):
        """Set the rules channel to be accepted in"""
        server = ctx.message.server
        if server.id not in self.settings:
            await self.bot.say("Please use the rules set command to change the rules channel")
            return
        self.settings[ctx.message.server.id]["channel"] = channel.id
        await self.bot.say("Channel changed to {}".format(channel.mention))
        self.savefile()