Esempio n. 1
0
 async def _members(self):
     members = []
     for member in await self._state._members_get_all("guild",
                                                      key_id=self.id,
                                                      name="member"):
         members.append(Member(guild=self, state=self._state, data=member))
     return members
Esempio n. 2
0
 async def message(self, content, channel, author=None, **kwargs):
     if not author:
         author = self.make_member(channel.guild, self.make_user())
     author_data = {
         'user': author._user._to_minimal_user_json(),
         'nick': author.nick,
         'roles': author._roles,
         'joined_at': author.joined_at.isoformat(),
     }
     member = Member(state=self.client._connection,
                     data=author_data,
                     guild=channel.guild)
     data = {
         'id': '0',
         'channel_id': channel.id,
         'reactions': [],
         'attachments': [],
         'embeds': [],
         'mention_roles': [],
         'application': None,
         'activity': None,
         'edited_timestamp': '1970-01-01T00:00:01+00:00',
         'type': 0,
         'pinned': False,
         'flags': 0,
         'mention_everyone': False,
         'tts': False,
         'content': content,
         'nonce': None,
         'message_reference': None,
         'author': author._user._to_minimal_user_json(),
         'member': author_data
     }
     data.update(kwargs)
     self.client._connection.parse_message_create(data)
Esempio n. 3
0
 def make_member(self, guild, user):
     data = {
         'user': user._to_minimal_user_json(),
         'nick': None,
         'roles': [],
         'joined_at': '1970-01-01T00:00:01+00:00'
     }
     member = Member(data=data, state=self.client._connection, guild=guild)
     guild._add_member(member)
     guild._member_count = len(guild._members)
     return member
Esempio n. 4
0
 async def member(self):
     try:
         member = self._data["member"]
         author = await self.author()
         try:
             author._update_from_message(member)
         except AttributeError:
             author = Member._from_message(message=self, data=member)
         return author
     except KeyError:
         return None
Esempio n. 5
0
 async def parse_guild_member_update(self, data, old):
     guild = await self._get_guild(int(data["guild_id"]))
     if old and guild:
         member = await guild.get_member(int(data["user"]["id"]))
         if member:
             old_member = Member._copy(member)
             old_member._update(old)
             user_update = old_member._update_inner_user(data["user"])
             if user_update:
                 self.dispatch("user_update", user_update[1],
                               user_update[0])
             self.dispatch("member_update", old_member, member)
Esempio n. 6
0
 async def parse_presence_update(self, data, old):
     guild = await self._get_guild(utils._get_as_snowflake(
         data, "guild_id"))
     if not guild:
         return
     old_member = None
     member = await guild.get_member(int(data["user"]["id"]))
     if member and old:
         old_member = Member._copy(member)
         user_update = old_member._presence_update(data=old,
                                                   user=old["user"])
         if user_update:
             self.dispatch("user_update", user_update[1], user_update[0])
     self.dispatch("member_update", old_member, member)
Esempio n. 7
0
    async def edit_webhook(
        self,
        ctx: commands.Context,
        chan: Optional[discord.TextChannel],
        service: ServiceConverter,
        webhook: bool,
    ):
        """Set whether or not to use webhooks for status updates.

        Using a webhook means that the status updates will be sent with the avatar as the service's
        logo and the name will be `[service] Status Update`, instead of my avatar and name.

        If you don't specify a channel, I will use the current channel.
        """
        if TYPE_CHECKING:
            channel = GuildChannel()
            me = Member()
        else:
            channel = chan or ctx.channel
            me = ctx.me

        old_conf = await self.config.channel(channel).feeds()
        if service.name not in old_conf.keys():
            return await ctx.send(
                f"It looks like I don't send {service.friendly} status updates to "
                f"{channel.mention}")

        if old_conf[service.name]["webhook"] == webhook:
            word = "use" if webhook else "don't use"
            return await ctx.send(
                f"It looks like I already {word} webhooks for {service.friendly} status updates "
                f"in {channel.mention}")

        if webhook and not channel.permissions_for(me).manage_webhooks:
            return await ctx.send(
                "I don't have manage webhook permissions so I can't do that.")

        old_conf[service.name]["edit_id"] = {}
        old_conf[service.name]["webhook"] = webhook
        await self.config.channel(channel).feeds.set_raw(  # type:ignore
            service.name, value=old_conf[service.name])

        word = "use" if webhook else "not use"
        await ctx.send(
            f"{service.friendly} status updates in {channel.mention} will now {word} webhooks."
        )
Esempio n. 8
0
 async def mentions(self):
     try:
         mentions = self._data["mentions"]
         members = []
         guild = self.guild
         state = self._state
         if not isinstance(guild, Guild):
             members = [state.store_user(m) for m in mentions]
         else:
             for mention in filter(None, mentions):
                 id_search = int(mention["id"])
                 member = await guild.get_member(id_search)
                 if member is not None:
                     members.append(member)
                 else:
                     members.append(
                         Member._try_upgrade(data=mention,
                                             guild=guild,
                                             state=state))
         return members
     except KeyError:
         return []
Esempio n. 9
0
    async def on_message(self, message: Message) -> None:
        author = message.author.name
        avatar = message.author.avatar_url
        id = message.author.id

        try:
            count = self.session.query(DBMember).filter(
                DBMember.id == id).count()
            if count < 1:
                member = Member(id=id,
                                name=author,
                                avatar=avatar,
                                level=1,
                                experience=0)
                self.session.add(member)

            await self.add_exp(id)
            await self.level_up(message.author, message.channel)

        except Exception as error:
            await self.bot.say('Could not complete your command')
            self.logger.error(error)
Esempio n. 10
0
 async def parse_message_reaction_add(self, data, old):
     emoji = PartialEmoji.with_state(
         self,
         id=utils._get_as_snowflake(data["emoji"], "id"),
         animated=data["emoji"].get("animated", False),
         name=data["emoji"]["name"],
     )
     raw = RawReactionActionEvent(data, emoji, "REACTION_ADD")
     member = data.get("member")
     if member:
         guild = await self._get_guild(raw.guild_id)
         if guild:
             raw.member = Member(guild=guild, state=self, data=member)
     self.dispatch("raw_reaction_add", raw)
     message = await self._get_message(raw.message_id)
     if message:
         reaction = Reaction(message=message,
                             data=data,
                             emoji=await self._upgrade_partial_emoji(emoji))
         user = raw.member or await self._get_reaction_user(
             message.channel, raw.user_id)
         if user:
             self.dispatch("reaction_add", reaction, user)
Esempio n. 11
0
 async def get_member(self, user_id):
     result = await self._state._get(f"member:{self.id}:{user_id}")
     if result:
         result = Member(guild=self, state=self._state, data=result)
     return result
Esempio n. 12
0
 async def parse_guild_member_remove(self, data, old):
     if old:
         guild = await self._get_guild(int(data["guild_id"]))
         if guild:
             member = Member(guild=guild, data=old, state=self)
             self.dispatch("member_remove", member)
Esempio n. 13
0
 async def parse_guild_member_add(self, data, old):
     guild = await self._get_guild(int(data["guild_id"]))
     if guild:
         member = Member(guild=guild, data=data, state=self)
         self.dispatch("member_join", member)
Esempio n. 14
0
    async def statusset_preview(self, ctx: commands.Context,
                                service: ServiceConverter, mode: ModeConverter,
                                webhook: bool):
        """
        Preview what status updates will look like.

        You can also see this at https://vex-cogs.rtfd.io/en/latest/cogs/statusref.html

        **<service>**

            The service you want to preview. There's a list of available services in the
            `[p]help statusset` command.

        **<mode>**

            **all**: Every time the service posts an update on an incident, I will send
            a new message containing the previous updates as well as the new update. Best
            used in a fast-moving channel with other users.

            **latest**: Every time the service posts an update on an incident, I will send
            a new message containing only the latest update. Best used in a dedicated status
            channel.

            **edit**: Naturally, edit mode can't have a preview so won't work with this command.
            The message content is the same as the `all` mode.
            When a new incident is created, I will sent a new message. When this
            incident is updated, I will then add the update to the original message. Best
            used in a dedicated status channel.

        **<webhook>**

            Using a webhook means that the status updates will be sent with the avatar
            as the service's logo and the name will be `[service] Status Update`, instead
            of my avatar and name.
        """
        if TYPE_CHECKING:
            me = Member()
            channel = TextChannel()
        else:
            me = ctx.me
            channel = ctx.channel

        if webhook and not channel.permissions_for(me).manage_messages:
            return await ctx.send("I don't have permission to manage webhook.")

        incidentdata, extra_info = await self.config_wrapper.get_latest(
            service.name)

        if (incidentdata is None or extra_info is None
                or (time() - extra_info.get("checked", 0) >
                    300)):  # its older than 3 mins
            try:
                json_resp, etag, status = await self.statusapi.incidents(
                    service.id)
            except Exception:
                return await ctx.send("Hmm, I couldn't preview that.")
            if status != 200:
                return await ctx.send("Hmm, I couldn't preview that.")
            incidentdata_list = process_json(json_resp, "incidents")
            await self.config_wrapper.update_incidents(service.name,
                                                       incidentdata_list[0])
            incidentdata = incidentdata_list[0]

        update = Update(incidentdata, [incidentdata.fields[-1]])

        await SendUpdate(
            self.bot,
            self.config_wrapper,
            update,
            service.name,
            SendCache(update, service.name),
            False,
            True,
        ).send({
            ctx.channel.id: {
                "mode": mode,
                "webhook": webhook,
                "edit_id": {}
            }
        })