示例#1
0
 def _update_stats(self, message: discord.Message):
     """Increment wormhole's statistics"""
     current = repo_w.get_attribute(message.channel.id, "messages")
     repo_w.set(message.channel.id, "messages", current + 1)
     beam_name = repo_w.get_attribute(message.channel.id, "beam")
     if beam_name in self.transferred:
         self.transferred[beam_name] += 1
     else:
         self.transferred[beam_name] = 1
示例#2
0
    async def wormhole_edit(self, ctx, channel_id: int, key: str, value: str):
        """Edit wormhole"""
        if key in ("admin_id", "active", "readonly", "messages"):
            try:
                value = int(value)
            except ValueError:
                raise errors.BadArgument("Value has to be integer.")

        announce = True
        if key in ("invite", "messages", "admin_id"):
            announce = False

        channel = self._get_channel(ctx=ctx, channel_id=channel_id)

        beam_name = repo_w.get_attribute(channel_id, "beam")
        repo_w.set(discord_id=channel.id, key=key, value=value)
        await self.event.sudo(ctx,
                              f"{self._w2str_log(channel)}: {key} = {value}.")

        if not announce:
            return
        await self.announce(
            beam=beam_name,
            message=
            f"Womhole {self._w2str_out(channel)} updated: {key} is {value}.",
        )
示例#3
0
    async def wormhole_remove(self, ctx, channel_id: int = None):
        """Remove wormhole from database"""
        if channel_id is None:
            if hasattr(ctx.channel, "id"):
                channel_id = ctx.channel.id
            else:
                raise errors.BadArgument("Missing channel ID")

        channel = self._get_channel(ctx=ctx, channel_id=channel_id)
        if channel is not None:
            beam_name = repo_w.get_attribute(channel_id, "beam")
            repo_w.delete(discord_id=channel_id)
            await self.event.sudo(ctx, f"{self._w2str_log(channel)} removed.")
            await self.announce(
                beam=beam_name,
                message=f"Wormhole closed: {self._w2str_out(channel)}.")
            await channel.send(f"Wormhole closed: {self._w2str_out(channel)}.")
            return

        # channel is not available
        wormhole = repo_w.get(channel_id)
        if wormhole is not None:
            await self.event.sudo(ctx, f"Wormhole {channel_id} removed.")
            repo_w.delete(discord_id=channel_id)
            return

        await ctx.send("Not found.")
示例#4
0
    def _update_stats(self, message: discord.Message):
        """Increment wormhole's statistics"""
        # try to get author's home wormhole
        beam_name = repo_w.get_attribute(message.channel.id, "beam")
        channel_id = repo_u.get_attribute(message.author.id,
                                          f"home_id:{beam_name}")
        if channel_id is None:
            # user is not registered, use current wormhole
            channel_id = message.channel.id

        current = repo_w.get_attribute(channel_id, "messages")
        repo_w.set(channel_id, "messages", current + 1)

        beam_name = repo_w.get_attribute(message.channel.id, "beam")
        if beam_name in self.transferred:
            self.transferred[beam_name] += 1
        else:
            self.transferred[beam_name] = 1
    async def info(self, ctx: commands.Context):
        """Display information about wormholes"""
        public = hasattr(ctx.channel, "id") and repo_w.get(ctx.channel.id) is not None

        if public:
            await ctx.send(
                self._get_info(repo_w.get_attribute(ctx.channel.id, "beam")),
                delete_after=self.delay(),
            )
            return

        user_beams = repo_u.get_home(ctx.author.id).keys()
        for beam_name in user_beams:
            await ctx.send(self._get_info(beam_name, title=True))
示例#6
0
    async def replicate(
        self,
        wormhole,
        message,
        messages,
        users,
        text,
        files,
        db_b,
        manage_messages_perm,
    ):
        # skip not active wormholes
        if repo_w.get_attribute(wormhole.id, "active") == 0:
            return

        # skip source if message has attachments
        if wormhole.id == message.channel.id and len(files) > 0:
            return

        # skip source if bot hasn't got manage_messages permission
        if wormhole.id == message.channel.id and not manage_messages_perm:
            return

        # send message
        try:
            m = await wormhole.send(
                self._process_tags(
                    beam_name=db_b.name, wormhole_id=wormhole.id, users=users, text=text
                )
            )
            messages.append(m)
        except discord.Forbidden:
            await self.event.user(
                message,
                (
                    f"Forbidden to send message to {self.sanitise(message.guild.name)}"
                    f"/{self.sanitise(message.channel.name)}."
                ),
            )
        except Exception as e:
            await self.event.user(
                message,
                (
                    f"Could not send message to {self.sanitise(message.guild.name)}"
                    f"/{self.sanitise(message.channel.name)}:\n"
                    f">>>{type(e).__name__}\n{str(e)}"
                ),
            )
示例#7
0
    async def on_message_edit(self, before: discord.Message,
                              after: discord.Message):
        if before.content == after.content:
            return

        if after.author.bot:
            return

        if not repo_w.exists(after.channel.id):
            return

        # get forwarded messages
        forwarded = None
        for m in self.sent:
            if m[0].id == after.id:
                forwarded = m
                break
        if not forwarded:
            try:
                await after.add_reaction("❎")
                await asyncio.sleep(1)
                await after.remove_reaction("❎", self.bot.user)
            except discord.Forbidden:
                await after.channel.sent("_Edit not successful_ ❎",
                                         delete_after=1)
            return

        content = await self._process(after)
        beam_name = repo_w.get_attribute(after.channel.id, "beam")
        users = self._get_users_from_tags(beam_name=beam_name, text=content)
        for message in forwarded[1:]:
            await message.edit(content=self._process_tags(
                beam_name=beam_name,
                wormhole_id=after.channel.id,
                users=users,
                text=content,
            ))
        try:
            await after.add_reaction("✅")
            await asyncio.sleep(1)
            await after.remove_reaction("✅", self.bot.user)
        except discord.Forbidden:
            await after.channel.sent("_Edit successful_ ✅", delete_after=1)
    async def edit(self, ctx: commands.Context, *, text: str):
        """Edit last sent message

        text: A new text
        """
        if len(self.sent) == 0:
            return

        for msgs in self.sent[::-1]:
            # fmt: off
            if isinstance(msgs[0], discord.Member)  and ctx.author.id == msgs[0].id \
            or isinstance(msgs[0], discord.Message) and ctx.author.id == msgs[0].author.id:
                await self.delete(ctx.message)
                m = ctx.message
                m.content = m.content.split(" ", 1)[1]
                content = await self._process(m)

                beam_name = repo_w.get_attribute(m.channel.id, "beam")
                users = self._get_users_from_tags(beam_name=beam_name, text=content)
                for message in msgs[1:]:
                    try:
                        await message.edit(
                            content=self._process_tags(
                                beam_name=beam_name,
                                wormhole_id=message.channel.id,
                                users=users,
                                text=content,
                            )
                        )
                    except Exception as e:
                        self.event.user(
                            ctx, (
                                f"Could not edit message in {self.sanitise(message.guild.name)}"
                                f"/{self.sanitise(message.channel.name)}:\n>>> {e}"
                            )
                        )
                        await message.channel.send(
                            f"> **{self.sanitise(ctx.author.name)}**: " +
                            f"Could not replicate in **{self.sanitise(message.guild.name)}**.",
                            delete_after=0.5,
                        )
                break
示例#9
0
    async def invites(self, ctx):
        """Get invite links"""
        await self.delete(ctx)

        result = []
        template = "{logo} **{guild}**, {name}: {link}"
        for wormhole in repo_w.list_objects(repo_w.get_attribute(ctx.channel.id, "beam")):
            if wormhole.invite is None:
                continue
            channel = self.bot.get_channel(wormhole.discord_id)
            result.append(
                template.format(
                    logo=wormhole.logo if len(wormhole.logo) else "",
                    name=channel.name,
                    guild=channel.guild.name,
                    link=wormhole.invite,
                )
            )
        result = "\n".join(result) if len(result) else "No public invites."
        await self.smart_send(ctx, content=result)
示例#10
0
 async def announce_(self, ctx, *, message):
     """Send announcement"""
     await self.announce(beam=repo_w.get_attribute(ctx.channel.id, "beam"),
                         message=message)