Esempio n. 1
0
    async def set_news_channel(self, ctx, channel: discord.TextChannel):
        """
        Adds channel to publish list

        To remove, please use `[p]publishset removenews channel-name`
        """
        if not channel.is_news():
            return await ctx.send("{} is not a News Channel.".format(
                channel.mention))

        if channel.permissions_for(ctx.guild.me).manage_messages is False:
            return await ctx.send(
                "I do not have `manage_messages` in {} to publish. Please adjust my permissions."
                .format(channel.mention))

        if await self.is_in_list(guild=ctx.guild, channel=channel):
            return await ctx.send(
                "{} is already in the publish list. Nothing for me to add.".
                format(channel.mention))

        async with self.config.guild(ctx.guild).news_channels() as news:
            news.append(channel.id)

        await ctx.send("Added {} to publish watchlist.".format(channel.mention)
                       )
Esempio n. 2
0
 async def channel(self, ctx, *, channel: discord.TextChannel = None):
     channel = ctx.channel if not channel else channel
     embed = discord.Embed(title=f"關於頻道內容",
                           colour=random.randint(0, 0xffffff),
                           timestamp=datetime.datetime.utcnow())
     embed.add_field(name="📛頻道名稱", value=channel.name, inline=True)
     embed.add_field(name="🆔️頻道ID", value=channel.id, inline=True)
     embed.add_field(
         name="📁頻道類別",
         value=
         f"{'{}'.format(channel.category.name) if channel.category else '這個頻道不在任何類別內'}",
         inline=True)
     embed.add_field(name="🌏頻道位置", value=channel.position, inline=True)
     embed.add_field(
         name="🔸️頻道主題",
         value=f"{channel.topic if channel.topic else '此頻道沒有主題'}",
         inline=True)
     embed.add_field(name="⏱頻道慢數時間",
                     value=channel.slowmode_delay,
                     inline=True)
     embed.add_field(name="🔞NSFW", value=channel.is_nsfw(), inline=True)
     embed.add_field(name="📣NEWS", value=channel.is_news(), inline=True)
     embed.add_field(
         name="🕒頻道創建時間",
         value=channel.created_at.__format__("%Y/%m/%d %H:%M:%S"),
         inline=True)
     embed.add_field(name="Channel Permissions Synced",
                     value=channel.permissions_synced,
                     inline=True)
     embed.add_field(name="Channel Hash", value=hash(channel), inline=True)
     await ctx.send(embed=embed)
Esempio n. 3
0
    async def set_game_publish_updates(self, ctx: commands.Context,
                                       channel: discord.TextChannel,
                                       *state: HockeyStates) -> None:
        """
        Set what type of game updates will be published in the designated news channel.

        Note: Discord has a limit on the number of published messages per hour.
        This does not error on the bot and can lead to waiting forever for it to update.

        `<channel>` is a text channel for the updates.
        `<state>` must be any combination of `preview`, `live`, `final`, and `periodrecap`.

        `preview` updates are the pre-game notifications 60, 30, and 10 minutes
        before the game starts and the pre-game notification at the start of the day.

        Note: This may disable pickems if it is not selected.
        `live` are the period start notifications.
        `final` is the final game update including 3 stars.
        `periodrecap` is a recap of the period at the intermission.
        """
        if not channel.is_news():
            return await ctx.send(
                _("The designated channel is not a news channel that I can publish in."
                  ))
        await self.config.channel(channel).publish_states.set(list(set(state)))
        await ctx.send(
            _("{channel} game updates set to publish {states}").format(
                channel=channel.mention,
                states=humanize_list(list(set(state)))))
        if not await self.config.channel(channel).team():
            await ctx.send(
                _("You have not setup any team updates in {channel}. "
                  "You can do so with `{prefix}hockeyset add`.").format(
                      channel=channel.mention, prefix=ctx.prefix))
Esempio n. 4
0
 async def channelinfo(self, ctx, channel: discord.TextChannel = None):
     """Shows info on a channel."""
     async with ctx.typing():
         channel = channel or ctx.channel
         td = {
             True: "<:nsfw:730852009032286288>",
             False: "<:text_channel:703726554018086912>",
         }
         if channel.overwrites_for(
                 ctx.guild.default_role).read_messages is False:
             url = "<:text_locked:730929388832686090>"
         else:
             if channel.is_news():
                 url = "<:news:730866149109137520>"
             else:
                 url = td[channel.is_nsfw()]
         embed = discord.Embed(colour=self.bot.colour)
         embed.title = f"{url} {channel.name} | {channel.id}"
         last_message = await channel.fetch_message(channel.last_message_id)
         pins = await channel.pins()
         embed.description = (
             f"{channel.topic or ''}\n{f'<:category:716057680548200468> **{channel.category}**' if channel.category else ''} "
             f"<:member:731190477927219231> **{len(channel.members):,}** "
             f"{f'<:pin:735989723591344208> **{len(pins)}**' if pins else ''} <:msg:735993207317594215> [Last Message]({last_message.jump_url})"
         )
         embed.description = f"{channel.topic or ''}\n{f'<:category:716057680548200468> **{channel.category}**' if channel.category else ''} <:member:731190477927219231> **{len(channel.members):,}** {f'<:pin:735989723591344208> **{len([*await channel.pins()])}**' if await channel.pins() else ''} <:msg:735993207317594215> [Last Message]({last_message.jump_url})"
         embed.set_footer(
             text=f'Channel created {nt(dt.utcnow() - channel.created_at)}')
     await ctx.send(embed=embed)
Esempio n. 5
0
 async def post_period_recap(
     self, channel: discord.TextChannel, embed: discord.Embed, publish: bool
 ):
     """
     Posts the period recap in designated channels
     """
     if not channel.permissions_for(channel.guild.me).send_messages:
         log.debug(
             _("No permission to send messages in {channel} ({id})").format(
                 channel=channel, id=channel.id
             )
         )
         return
     try:
         msg = await channel.send(embed=embed)
         if publish and channel.is_news():
             pass
             # await msg.publish()
     except Exception:
         log.error(
             _("Could not post goal in {channel} ({id})").format(
                 channel=channel, id=channel.id
             ),
             exc_info=True,
         )
Esempio n. 6
0
	async def autopublish(self, ctx, channel: discord.TextChannel=None):
		"""
		Enables automatically publishing in an announcement channel.
		Idea from eek's bot MegaPhone
		"""
		db = await self.bot.dbquery("autopublish_channels", "data", "guildid=" + str(ctx.guild.id))
		chanlist = []
		if db:
			chanlist = json.loads(db[0][0])
		if channel is None:
			return await ctx.send(embed=discord.Embed(title=f"**{ctx.guild}**'s Autopublish Channels", description=f"{' `||` '.join([ctx.guild.get_channel(c).mention for c in chanlist]) if chanlist else 'None configured'}", color=self.bot.colors['darkgreen']))
		if channel.is_news() or channel.id in chanlist:
			action = f"Added {channel.mention} to"
			if db:
				await self.bot.dbexec("DELETE FROM autopublish_channels WHERE guildid=" + str(ctx.guild.id))
			if channel.id in chanlist:
				chanlist.remove(channel.id)
				action = f"Removed {channel.mention} from"
			else:
				chanlist.append(channel.id)
			total = []
			for c in chanlist:
				if ctx.guild.get_channel(c):
					if ctx.guild.get_channel(c).is_news():
						total.append(f"<#{c}>")
					else:
						chanlist.remove(channel.id)
				else:
					chanlist.remove(channel.id)
			await self.bot.dbexec(("INSERT INTO autopublish_channels VALUES (?, ?)", (str(ctx.guild.id), str(chanlist))))
			await ctx.send(f"{self.bot.const_emojis['yes']} {action} the list of channels that will have their messages autopublished!\nNew total list: {' `||` '.join(total)}")
		else:
			await ctx.send(f"{self.bot.const_emojis['no']} {channel.mention} is not an announcement channel!")
Esempio n. 7
0
 async def track(self, ctx, channel: discord.TextChannel):
     """Add announcement channels to track and auto publish announcements"""
     if not channel.is_news():
         return await ctx.send(
             f"{channel.mention} is not an announcement channel to track!")
     doc = await self.coll.find_one({"_id": ctx.guild.id})
     if doc:
         channels = doc["channels"]
         if not channel.id in channels:
             channels.append(channel.id)
             await self.coll.update_one({"_id": ctx.guild.id},
                                        {"$set": {
                                            "channels": channels
                                        }})
         else:
             await ctx.send(f"Already tracking {channel.mention}!")
     else:
         channels = [channel.id]
         await self.coll.insert_one({
             "_id": ctx.guild.id,
             "channels": channels
         })
     return await ctx.send(
         f"Successfully added {channel.mention} to tracking list! All the messages sent there will now be auto published."
     )
Esempio n. 8
0
 def __init__(self, channel: discord.TextChannel):
     self._chn = channel
     self.guild = SafeAccessGuild(channel.guild) if channel.guild else VP_NONE
     self.id = channel.id
     self.nsfw = channel.is_nsfw()
     self.news = channel.is_news()
     self.topic = channel.topic
     self.mention = channel.mention
Esempio n. 9
0
 async def get_threads(channel: TextChannel) -> list[tuple[Thread, bool]]:
     out_ = channel.threads.copy()
     out_ += await channel.archived_threads(limit=None).flatten()
     if channel.permissions_for(ctx.guild.me).manage_threads and not channel.is_news():
         out_ += await channel.archived_threads(limit=None, private=True).flatten()
     return [
         (thread_, any(member.id == ctx.author.id for member in await thread_.fetch_members()))
         for thread_ in out_
     ]
Esempio n. 10
0
 def __init__(self, runner, channel: discord.TextChannel):
     self._chn = channel
     self._runner = runner
     self.guild = SafeAccessGuild(
         runner, channel.guild) if channel.guild else runner.null
     self.id = viper.Integer(channel.id, -1, runner)
     self.nsfw = viper.Boolean(channel.is_nsfw(), -1, runner)
     self.news = viper.Boolean(channel.is_news(), -1, runner)
     self.topic = viper.String(channel.topic, -1, runner)
     self.mention = viper.String(channel.mention, -1, runner)
Esempio n. 11
0
 async def post_period_recap(self, channel: discord.TextChannel,
                             embed: discord.Embed, publish: bool) -> None:
     """
     Posts the period recap in designated channels
     """
     if not channel.permissions_for(channel.guild.me).send_messages:
         log.debug("No permission to send messages in %s", repr(channel))
         return
     try:
         msg = await channel.send(embed=embed)
         if publish and channel.is_news():
             pass
             # await msg.publish()
     except Exception:
         log.exception("Could not post goal in %s", repr(channel))
Esempio n. 12
0
    async def actually_post_state(
        self, bot: Red, channel: discord.TextChannel, state_embed: discord.Embed, state_text: str
    ) -> Optional[Tuple[discord.TextChannel, discord.Message]]:
        guild = channel.guild
        if not channel.permissions_for(guild.me).send_messages:
            log.debug("No permission to send messages in %s", repr(channel))
            return None
        config = bot.get_cog("Hockey").config
        guild_settings = await config.guild(guild).all()
        channel_settings = await config.channel(channel).all()
        game_day_channels = guild_settings["gdc"]
        can_embed = channel.permissions_for(guild.me).embed_links
        publish_states = []  # await config.channel(channel).publish_states()
        # can_manage_webhooks = False  # channel.permissions_for(guild.me).manage_webhooks

        if self.game_state == "Live":

            guild_notifications = guild_settings["game_state_notifications"]
            channel_notifications = channel_settings["game_state_notifications"]
            state_notifications = guild_notifications or channel_notifications
            # TODO: Something with these I can't remember what now
            # guild_start = guild_settings["start_notifications"]
            # channel_start = channel_settings["start_notifications"]
            # start_notifications = guild_start or channel_start
            # heh inclusive or
            allowed_mentions = {}
            home_role, away_role = await get_team_role(guild, self.home_team, self.away_team)
            if version_info >= VersionInfo.from_str("3.4.0"):
                if state_notifications:
                    allowed_mentions = {"allowed_mentions": discord.AllowedMentions(roles=True)}
                else:
                    allowed_mentions = {"allowed_mentions": discord.AllowedMentions(roles=False)}
            if self.game_type == "R" and "OT" in self.period_ord:
                if not guild_settings["ot_notifications"]:
                    if version_info >= VersionInfo.from_str("3.4.0"):
                        allowed_mentions = {
                            "allowed_mentions": discord.AllowedMentions(roles=False)
                        }
                    else:
                        allowed_mentions = {}
            if "SO" in self.period_ord:
                if not guild_settings["so_notifications"]:
                    if version_info >= VersionInfo.from_str("3.4.0"):
                        allowed_mentions = {
                            "allowed_mentions": discord.AllowedMentions(roles=False)
                        }
                    else:
                        allowed_mentions = {}
            if game_day_channels is not None:
                # We don't want to ping people in the game day channels twice
                if channel.id in game_day_channels:
                    home_role, away_role = self.home_team, self.away_team
            msg = _("**{period} Period starting {away_role} at {home_role}**").format(
                period=self.period_ord, away_role=away_role, home_role=home_role
            )
            try:
                if not can_embed:
                    msg = await channel.send(msg + "\n{}".format(state_text), **allowed_mentions)
                else:
                    msg = await channel.send(msg, embed=state_embed, **allowed_mentions)
                if self.game_state in publish_states:
                    try:
                        if channel.is_news():
                            # allows backwards compatibility still
                            # await msg.publish()
                            pass
                    except Exception:
                        pass
            except Exception:
                log.exception("Could not post goal in %s", repr(channel))

        else:
            if self.game_state == "Preview":
                if game_day_channels is not None:
                    # Don't post the preview message twice in the channel
                    if channel.id in game_day_channels:
                        return None
            try:
                if not can_embed:
                    preview_msg = await channel.send(state_text)
                else:
                    preview_msg = await channel.send(embed=state_embed)

                if self.game_state in publish_states:
                    try:
                        if channel.is_news():
                            # allows backwards compatibility still
                            # await preview_msg.publish()
                            pass
                    except Exception:
                        pass

                # Create new pickems object for the game
                if self.game_state == "Preview":
                    bot.dispatch("hockey_preview_message", channel, preview_msg, self)
                    if channel.permissions_for(guild.me).add_reactions:
                        try:
                            await preview_msg.add_reaction(self.away_emoji[2:-1])
                            await preview_msg.add_reaction(self.home_emoji[2:-1])
                        except Exception:
                            log.debug("Could not add reactions")
                        return channel, preview_msg
            except Exception:
                log.exception("Could not post goal in %s", repr(channel))
        return None