Beispiel #1
0
 async def log(self, mode, connection_id, message: discord.Message = None):
     '''Logs the message in support-logs'''
     channel = self.bot.get_guild(445194262947037185).get_channel(
         597068935829127168)
     if mode.startswith('log'):
         log_type = mode.split('-')[1]
         embed = Embed(title='Support DMs',
                       color=Colour.from_rgb(177, 252, 129))
         embed.add_field(name="ID", value=f"{connection_id}", inline=True)
         embed.add_field(name='Author', value=f'{log_type}', inline=True)
         embed.add_field(name='Content',
                         value=f'{message.content}',
                         inline=False)
         await channel.send(embed=embed)
     elif mode == 'new':
         embed = Embed(title='New Ticket', color=Colour.from_rgb(0, 0, 255))
         embed.add_field(name='ID', value=f"{connection_id}", inline=True)
         await channel.send(embed=embed)
     elif mode.startswith('delete'):
         log_type = mode.split('-')[1]
         embed = Embed(title='Ticket Ended',
                       color=Colour.from_rgb(255, 0, 0))
         embed.add_field(name='ID', value=f"{connection_id}", inline=True)
         embed.add_field(name='Initiator', value=f'{log_type}', inline=True)
         await channel.send(embed=embed)
Beispiel #2
0
 async def _change_avatar(self):
     info = choice(avatars)
     avatar = open(info['path'], 'rb').read()
     rgb = info['rgb']
     self.lite.color = [Colour.from_rgb(*rgb[0]), Colour.from_rgb(*rgb[1])]
     await self.lite.user.edit(avatar=avatar)
     self.lite.log.info('Avatar alterado')
Beispiel #3
0
    async def _change_avatar(self):
        if not self.avatars:  # significa que todos os avatares já foram usados
            self.avatars = avatars  # repor os avatares

        info = self.avatars.pop(0)  # pegar o avatar na ordem
        avatar = open(info['path'], 'rb').read()
        rgb = info['rgb']  # alterar a cor dos embeds, baseado na cor do avatar
        self.lite.color = [Colour.from_rgb(*rgb[0]), Colour.from_rgb(*rgb[1])]
        await self.lite.user.edit(avatar=avatar)
        self.lite.log.info('Avatar alterado')
Beispiel #4
0
    async def steamMatch(self, ctx: Context, *users):
        """Hledá shody ve knihovnách zmíněných hráčů."""
        try:
            await ctx.trigger_typing()
            sm = SteamMatch(*users)
            data = sm.compare()

            libs = ', '.join(
                map(lambda x: f'**{x}** *({data["users"][x]} games)*',
                    data['users']))

            def build_item(game):
                pt = sum(game["info"]["u"].values())
                is_mins = pt < 60
                t = pt if is_mins else pt / 60
                return f'- **[{game["info"]["name"]}]({game["url"]})**, *playtime of everyone ' \
                       f'`{t:.1f} {"min" if is_mins else "hour"}{"" if t < 2.0 else "s"}`*;'
                pass

            body = "" + \
                   f"There are {len(data['games'])} matches from {libs} players libraries.\n\n" + \
                   '\n'.join(map(build_item, data['games']))

            if len(body) > 2048:
                buff = ""
                msgs = []
                for l in body.splitlines():
                    if len(buff + l + "\n") <= 2048:
                        buff += l + "\n"
                        pass
                    else:
                        msgs.append(buff)
                        buff = l + "\n"
                        pass
                    pass

                if buff:
                    msgs.append(buff)

                for i, n in enumerate(msgs):
                    await ctx.send(embed=Embed(
                        title=f"Steam Matcher Result - Part {i + 1}",
                        color=Colour.from_rgb(66, 244, 125),
                        description=n))
                pass
            else:
                await ctx.send(embed=Embed(title="Steam Matcher Result",
                                           color=Colour.from_rgb(66, 244, 125),
                                           description=body))
                pass
            pass
        except SteamMatchException as e:
            await self.generic_error(ctx, e.args[0])
        pass
Beispiel #5
0
    async def on_message_delete(self, message: discord.Message) -> None:

        ctx = await self.bot.get_context(message
                                         )  # needed to fetch ref message

        channel = await self.get_log_channel(ctx, "message")
        if channel is None or (
                message.author.id == self.bot.user.id and not message.content
        ):  # Don't log in the logs if logs dont exist or bot deleting own embed pages
            return

        embeds = []
        chunks = ceil(len(message.content) / 1024)

        for i in range(1, chunks + 1):
            embed = Embed(title=":information_source: Message Deleted",
                          color=Colour.from_rgb(172, 32, 31))
            embed.add_field(
                name="User",
                value=f"{str(message.author)} ({message.author.id})"
                or "undetected",
                inline=True)
            embed.add_field(name="Message ID", value=message.id, inline=True)
            embed.add_field(name="Channel",
                            value=message.channel.mention,
                            inline=True)
            embed.add_field(name=f"Message {f'part {i}' if i > 1 else ''}",
                            value=message.content[1024 * (i - 1):1024 * i] if
                            (hasattr(message, "content") and message.content)
                            else "(No detected text content)",
                            inline=False)
            embed.set_footer(
                text=self.bot.correct_time().strftime(self.bot.ts_format))

            embeds.append(embed)

        [await channel.send(embed=embed) for embed in embeds]

        if message.reference:  # intended mainly for replies, can be used in other contexts (see docs)
            ref = await ctx.fetch_message(message.reference.message_id)
            reference = Embed(
                title=":arrow_upper_left: Reference of deleted message",
                color=Colour.from_rgb(172, 32, 31))
            reference.add_field(name="Author of reference",
                                value=f"{str(ref.author)} ({ref.author.id})",
                                inline=True)
            reference.add_field(name="Message ID", value=ref.id, inline=True)
            reference.add_field(name="Channel",
                                value=ref.channel.mention,
                                inline=True)
            reference.add_field(name="Jump Link", value=ref.jump_url)

            await channel.send(embed=reference)
Beispiel #6
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.loaded = False
     self.data = Config()
     self.cache = Cache()
     self.db = Database(letty=self)
     self.lang = Files(source='pt_BR')
     self.session = aiohttp.ClientSession(loop=self.loop)
     self.color = [
         Colour.from_rgb(*self.data.config.color.embed.normal),
         Colour.from_rgb(*self.data.config.color.embed.error)
     ]
Beispiel #7
0
    async def trivia_end_leaderboard(self,
                                     member: discord.Member = None,
                                     reset: bool = True,
                                     msg_content: str = "") -> None:
        """
        Method that displays a current, or finishing (if `reset` is True), leaderboard for the current trivia session. This method also sets `self.running` = `not reset`.
        """

        self.running = not reset
        color = member.color if member else Colour.from_rgb(177, 252, 129)
        embed = Embed(title="Trivia results" if reset else "Trivia scores",
                      color=color)
        total_score = sum([self.scores[indv] for indv in self.scores])

        for member_id in self.scores:
            name = self.channel.guild.get_member(
                member_id).display_name if self.channel.guild.get_member(
                    member_id) else await self.bot.fetch_user(member_id
                                                              ).display_name
            embed.add_field(
                name=name,
                value=
                f"{round(self.scores[member_id]*100/total_score, 1)}% ({self.scores[member_id]})",
                inline=True)
        if reset:
            embed.set_footer(
                text=
                f"This trivia took {(datetime.utcnow()-self.started_at).seconds} seconds to complete."
            )
        await self.channel.send(msg_content, embed=embed)
Beispiel #8
0
 async def color(self, ctx, name: str, code: str = None):
     """
     Create a color role
     ?color name Hex
     """
     if ctx.invoked_subcommand is None:
         if code is None:
             await ctx.send(embed=Embed(
                 title="Color picker tool", color=0xfc4e03,
                 description="Pick the hex code for your color here",
                 url='https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Colors/Color_picker_tool'
             ).set_thumbnail(url='https://developer.mozilla.org/static/img/opengraph-logo.72382e605ce3.png'))
             return
         code = code.strip("#")
         code = tuple(int(code[i:i + 2], 16) for i in (0, 2, 4))
         clr = Colour.from_rgb(*code)
         await ctx.message.add_reaction(self.tick)
         role = get(ctx.guild.roles, name=name)
         if role is not None:
             await role.edit(color=clr)
             await ctx.send(embed=Embed(
                 title=f"Edited Role {name} to {clr}", color=clr, timestamp=dt.now()
             ))
             return
         await ctx.guild.create_role(name=name, colour=clr)
         await ctx.send(embed=Embed(
             title=f"Created Role {name} of {clr}", color=clr, timestamp=dt.now()
         ))
Beispiel #9
0
async def listening(bot, message):
    api_token = bot.config['lastfm']['API_KEY']

    db = LastFMDB(testing=bot.testing)
    username = db.fetch_lastfm_user(message.author.id)
    if username is None:
        await message.channel.send(
            f'<@!{message.author.id}> has not registered a last.fm username!')
        await message.channel.send(
            'Run `@bossbot lastfm <username>` or dm bossbot the same command first to use this command'
        )
        return

    track = fetch_latest_track(api_token, username)
    if not track.now_playing:
        await message.channel.send(
            f'<@!{message.author.id}> is not currently listening to anything!')
        return

    embed = Embed(
        title=f'Now playing - {track.name}',  # TODO: mention author
        description=f'<@!{message.author.id}> is currently listening to...',
        colour=Colour.from_rgb(185, 0, 0),
        url=track.url,
    ).add_field(
        name=track.name,
        value=f'by **{track.artist}** from **{track.album}**',
        inline=True,
    ).set_thumbnail(url=track.image, ).set_footer(
        text='via last.fm',
        icon_url=
        'http://images1.wikia.nocookie.net/__cb20130411230810/logopedia/images/1/1d/Last_fm_logo.png',
    )
    await message.channel.send(' ', embed=embed)
Beispiel #10
0
 async def token(self, ctx, region: str = None):
     """
     Get the WoW token price of your region
     """
     if region is None and ctx.guild:
         guild_server = GuildServer.objects.filter(guild_id=ctx.guild.id, default=True).first()
         if guild_server:
             region = guild_server.get_region_display()
         else:
             raise commands.BadArgument(_('You are required to type the region. Supported regions are: NA/EU/CN/TW/KR'))
     token_request = requests.get("https://data.wowtoken.info/snapshot.json")
     token_json = token_request.json()
     if region.upper() == "US":
         region = "NA"
     if region.upper() in token_json:
         region_json = token_json[region.upper()]['formatted']
         embed = Embed(title=_("Price for 1 WoW Token in the {region} region").format(region=region.upper()),
                       color=Colour.from_rgb(255, 215, 0))
         embed.set_footer(text=_("Information taken from https://wowtoken.info"),
                          icon_url="http://wow.zamimg.com/images/wow/icons/large/wow_token01.jpg")
         embed.set_thumbnail(url="http://wow.zamimg.com/images/wow/icons/large/wow_token01.jpg")
         embed.add_field(name=_("Current Price"), value=region_json['buy'], inline=True)
         embed.add_field(name=_("Minimum 24H"), value=region_json['24min'], inline=True)
         embed.add_field(name=_("Maximum 24H"), value=region_json['24max'], inline=True)
         embed.add_field(name=_("Percentage 24H Range"), value="%s %%" % region_json['24pct'])
         await ctx.send(embed=embed)
     else:
         raise commands.BadArgument(_('Region not found. Supported regions are: NA/EU/CN/TW/KR'))
    def fromDict(cls, rmDict : dict, **kwargs) -> ReactionRolePicker:
        """Reconstruct a ReactionRolePicker from its dictionary-serialized representation.

        :param dict rmDict: A dictionary containing all information needed to construct the desired ReactionRolePicker
        :return: A new ReactionRolePicker object as described in rmDict
        :rtype: ReactionRolePicker
        """
        if "msg" in kwargs:
            raise NameError("Required kwarg not given: msg")
        msg = kwargs["msg"]

        dcGuild = msg.guild

        reactionRoles = {}
        for reaction in rmDict["options"]:
            reactionRoles[lib.emojis.dumbEmojiFromStr(reaction)] = dcGuild.get_role(rmDict["options"][reaction]["role"])

        timeoutTT = None
        if "timeout" in rmDict:
            expiryTime = datetime.utcfromtimestamp(rmDict["timeout"])
            bbGlobals.reactionMenusTTDB.scheduleTask(TimedTask.TimedTask(expiryTime=expiryTime, expiryFunction=ReactionMenu.markExpiredMenu, expiryFunctionArgs=msg.id))


        return ReactionRolePicker(msg, reactionRoles, dcGuild,
                                    titleTxt=rmDict["titleTxt"] if "titleTxt" in rmDict else "",
                                    desc=rmDict["desc"] if "desc" in rmDict else "",
                                    col=Colour.from_rgb(rmDict["col"][0], rmDict["col"][1], rmDict["col"][2]) if "col" in rmDict else Colour.blue(),
                                    footerTxt=rmDict["footerTxt"] if "footerTxt" in rmDict else "",
                                    img=rmDict["img"] if "img" in rmDict else "",
                                    thumb=rmDict["thumb"] if "thumb" in rmDict else "",
                                    icon=rmDict["icon"] if "icon" in rmDict else "",
                                    authorName=rmDict["authorName"] if "authorName" in rmDict else "",
                                    timeout=timeoutTT,
                                    targetMember=dcGuild.get_member(rmDict["targetMember"]) if "targetMember" in rmDict else None,
                                    targetRole=dcGuild.get_role(rmDict["targetRole"]) if "targetRole" in rmDict else None)
Beispiel #12
0
    async def _rand_colour(self, ctx: NewCtx):
        """Generates a random colour, displaying its representation in Hex, RGB and HSV values"""
        col = Colour.from_rgb(*[random.randint(0, 255) for _ in range(3)])
        hex_v = hex(col.value).replace('0x', '#')

        r, g, b = col.r, col.g, col.b
        h, s, v = colorsys.rgb_to_hsv(r, g, b)

        h = round((h * 360))
        s = round((s * 100))
        v = round((h * 100))

        image_obj = Image.new('RGB', (125, 125), (r, g, b))
        new_obj = BytesIO()
        image_obj.save(new_obj, format='png')
        new_obj.seek(0)
        fileout = File(new_obj, filename='file.png')

        embed = Embed(colour=col, title='`Random colour: `')
        embed.description = f'Hex : {hex_v} / {hex(col.value)}\nRGB : {r}, {g}, {b}\nHSV : {h}, {s}, {v//1000}'
        embed.set_image(url="attachment://file.png")
        embed.set_author(name=ctx.author.display_name,
                         icon_url=ctx.author.avatar_url)

        await ctx.send(embed=embed, file=fileout)
Beispiel #13
0
    async def set(self, ctx: commands.Context,
                  user: discord.Member | discord.User, rep: str) -> None:
        """
        Sets a specific members reps to a given value.
        """

        if not rep.isdigit():
            await self.bot.DefaultEmbedResponses.error_embed(
                self.bot, ctx, "The reputation points must be a number!")
            return
        new_reps = await self.set_rep(user.id, ctx.guild.id, int(rep))
        await self.bot.DefaultEmbedResponses.success_embed(
            self.bot,
            ctx,
            f"{user.display_name}'s reputation points have been changed!",
            desc=f"{user.display_name} now has {new_reps} reputation points!",
            thumbnail_url=get_user_avatar_url(user)[0])

        channel_id = await self.bot.get_config_key(ctx, "log_channel")
        if channel_id is None:
            return
        channel = self.bot.get_channel(channel_id)
        embed = Embed(title="Reputation Points Set",
                      color=Colour.from_rgb(177, 252, 129))
        embed.add_field(name="Member", value=str(user))
        embed.add_field(name="Staff", value=str(ctx.author))
        embed.add_field(name="New Rep", value=new_reps)
        embed.set_footer(
            text=self.bot.correct_time().strftime(self.bot.ts_format))
        await channel.send(embed=embed)
async def fromDict(rmDict):
    dcGuild = bbGlobals.client.get_guild(rmDict["guild"])
    msg = await dcGuild.get_channel(rmDict["channel"]).fetch_message(rmDict["msg"])

    reactionRoles = {}
    for reaction in rmDict["options"]:
        reactionRoles[bbUtil.dumbEmojiFromStr(reaction)] = dcGuild.get_role(rmDict["options"][reaction]["role"])

    timeoutTT = None
    if "timeout" in rmDict:
        expiryTime = datetime.utcfromtimestamp(rmDict["timeout"])
        bbGlobals.reactionMenusTTDB.scheduleTask(TimedTask.TimedTask(expiryTime=expiryTime, expiryFunction=ReactionMenu.markExpiredMenu, expiryFunctionArgs=msg.id))


    return ReactionRolePicker(msg, reactionRoles, dcGuild,
                                titleTxt=rmDict["titleTxt"] if "titleTxt" in rmDict else "",
                                desc=rmDict["desc"] if "desc" in rmDict else "",
                                col=Colour.from_rgb(rmDict["col"][0], rmDict["col"][1], rmDict["col"][2]) if "col" in rmDict else Colour.default(),
                                footerTxt=rmDict["footerTxt"] if "footerTxt" in rmDict else "",
                                img=rmDict["img"] if "img" in rmDict else "",
                                thumb=rmDict["thumb"] if "thumb" in rmDict else "",
                                icon=rmDict["icon"] if "icon" in rmDict else "",
                                authorName=rmDict["authorName"] if "authorName" in rmDict else "",
                                timeout=timeoutTT,
                                targetMember=dcGuild.get_member(rmDict["targetMember"]) if "targetMember" in rmDict else None,
                                targetRole=dcGuild.get_role(rmDict["targetRole"]) if "targetRole" in rmDict else None)
Beispiel #15
0
    async def hackban(self, ctx, user_id, *args):
        '''Bans a given user.
Moderator role needed'''
        if args:
            timeperiod, reason = separate_args(args)
            if not reason:
                reason = f'No reason - banned by {str(ctx.author)}'
            if timeperiod:
                await self.timer(2, timeperiod, member.id)
        else:
            reason = None

        await member.ban(reason=reason, delete_message_days=0)
        emoji = get(ctx.message.guild.emojis, name="banned")
        await ctx.send(f'{member.mention} has been banned. {emoji}')

        embed = Embed(title='Hackban', color=Colour.from_rgb(255, 255, 255))
        embed.add_field(name='Member', value=f'{member.mention} ({member.id})')
        embed.add_field(name='Moderator', value=str(ctx.author))
        embed.add_field(name='Reason', value=reason)
        embed.set_thumbnail(url=member.avatar_url)
        embed.set_footer(text=(datetime.utcnow() -
                               timedelta(hours=1)).strftime('%x'))
        await get(ctx.guild.text_channels,
                  name='adambot-logs').send(embed=embed)
Beispiel #16
0
    async def delete(self, ctx: commands.Context, *question_ids: str) -> None:
        async with self.bot.pool.acquire() as connection:
            for question_id in question_ids:
                try:
                    await connection.execute(
                        "DELETE FROM qotd WHERE id = ($1) AND guild_id = $2",
                        int(question_id), ctx.guild.id)
                    await ctx.send(
                        f"QOTD ID **{question_id}** has been deleted.")

                    log_channel_id = await self.bot.get_config_key(
                        ctx, "log_channel")
                    if log_channel_id is not None:
                        log = self.bot.get_channel(log_channel_id)
                        embed = Embed(title=":grey_question: QOTD Deleted",
                                      color=Colour.from_rgb(177, 252, 129))
                        embed.add_field(name="ID", value=question_id)
                        embed.add_field(name="Staff", value=str(ctx.author))
                        embed.set_footer(text=self.bot.correct_time().strftime(
                            self.bot.ts_format))
                        await log.send(embed=embed)

                except ValueError:
                    await ctx.send("Question ID must be an integer!")
                except Exception as e:
                    await ctx.send(
                        f"Error whilst deleting question ID {question_id}: {e}"
                    )
Beispiel #17
0
def create_map_embed(map_data: dict):
    """
    Creates embed for map information display
    :param map_data: Dictionary of data pertaining to a certain map
    :return: Embed displaying map information
    """
    map_name, map_url, map_levelshot_url = [map_data[datum] for datum in ['name', 'url', 'levelshot_url']]
    map_embed = Embed(title=map_name, url=map_url, color=Colour.from_rgb(155, 4, 52))
    map_embed.set_image(url=map_levelshot_url)
    thumbnail_url = "https://cdn.discordapp.com/attachments/788239274361356309/790741876285374544/defrag_3_40x40.png"
    map_embed.set_thumbnail(url=thumbnail_url, )
    map_embed.set_author(name="Worldspawn Archive")
    optional_fields = map_data['fields'].pop('optional', {})

    # Add optional embed fields
    for key, value in map_data['fields'].items():
        map_embed.add_field(name=key, value=value, inline=False if key == 'Author' else True)
    for key, value in optional_fields.items():
        value = value.replace(',', '')
        map_embed.add_field(name=key, value=value, inline=False)

    # Add world record data if map has the Timer function
    if 'Functions' in optional_fields and 'timer' in optional_fields['Functions'].lower():
        try:
            from mdd.records import get_wrs
            wr_data = get_wrs(map_name)
            for physics, wr_entry in wr_data.items():
                country_string = turn_country_ids_to_emojis([wr_entry['country']])[0].replace("flag_??", "pirate_flag")
                display_string = f"{country_string} {wr_entry['player']} [{wr_entry['time']}]"
                map_embed.add_field(name=f"{physics} record:", value=display_string, inline=True)
        except:
            pass

    return map_embed
Beispiel #18
0
    async def get_leaderboard(self, ctx: commands.Context) -> None:
        async with self.bot.pool.acquire() as connection:
            leaderboard = await connection.fetch(
                "SELECT member_id, reps FROM rep WHERE guild_id = $1 ORDER BY reps DESC",
                ctx.guild.id)

        if len(leaderboard) == 0:
            await self.bot.DefaultEmbedResponses.error_embed(
                self.bot, ctx,
                f"There aren't any reputation points in {ctx.guild.name} yet! "
            )
            return

        embed = self.bot.EmbedPages(
            self.bot.PageTypes.REP,
            leaderboard,
            f"{ctx.guild.name}'s Reputation Leaderboard",
            Colour.from_rgb(177, 252, 129),
            self.bot,
            ctx.author,
            ctx.channel,
            thumbnail_url=get_guild_icon_url(ctx.guild),
            icon_url=get_user_avatar_url(ctx.author, mode=1)[0],
            footer=f"Requested by: {ctx.author.display_name} ({ctx.author})\n"
            + self.bot.correct_time().strftime(self.bot.ts_format))
        await embed.set_page(1)  # Default first page
        await embed.send()
Beispiel #19
0
async def profil(ctx, username):
    async with aiohttp.ClientSession(headers=headers) as session:
        response = await fetch(session, '/user/{}'.format(username))
    data = response['data']

    embed = Embed(
        title='[Profil] {}'.format(data['info']['username']),
        description=data['info']['description'],
        colour=Colour.from_rgb(0, 144, 255),
        url=data['url'],
    )

    info = """
    **Rola:** {}
    **Aktywny:** {}
    **Napisanych komentarzy:** {}
    **Oddanych diamentów:** {}
    """.format(data['info']['role'], data['info']['last_logged_relative'], data['stats']['written_comments'],
               data['stats']['given_diamonds'])

    embed.add_field(name='Informacje', value=info, inline=True)

    stats = """
    <:diax:589865302100017172> Diamenty: {}
    <:gwiazdka:589865302230040576> Obserwujących: {}
    <:mapa:589865302020456456> Wrzuconych map: {}
    """.format(data['stats']['diamond_sum'], data['stats']['follower_count'], data['stats']['map_count'])

    embed.add_field(name='Statystyki', value=stats, inline=True)

    embed.set_thumbnail(url=data['info']['avatar_url'])
    embed.set_footer(text='Invoked by {}#{} • {}'.format(ctx.author.name, ctx.author.discriminator, ctx.author.id),
                     icon_url=ctx.author.avatar_url)

    await ctx.send(embed=embed)
Beispiel #20
0
    async def all(self, ctx: commands.Context) -> None:
        """
        Resets everyone's reps.
        """

        async with self.bot.pool.acquire() as connection:
            await connection.execute("DELETE from rep WHERE guild_id = $1",
                                     ctx.guild.id)

        await self.bot.DefaultEmbedResponses.success_embed(
            self.bot,
            ctx,
            "Reputation reset completed!",
            desc=f"All reputation points in {ctx.guild.name} have been removed"
        )

        channel_id = await self.bot.get_config_key(ctx, "log_channel")
        if channel_id is None:
            return
        channel = self.bot.get_channel(channel_id)
        embed = Embed(title="Reputation Points Reset",
                      color=Colour.from_rgb(177, 252, 129))
        embed.add_field(name="Member", value="**EVERYONE**")
        embed.add_field(name="Staff", value=str(ctx.author))
        embed.set_footer(
            text=self.bot.correct_time().strftime(self.bot.ts_format))
        await channel.send(embed=embed)
Beispiel #21
0
    async def submit(self, ctx, *args):
        '''Submit a QOTD'''
        qotd = ' '.join(args)
        if len(qotd) > 255:
            await ctx.send('Question over **255** characters, please **shorten** before trying the command again.')
            return
        if not args:
            await ctx.send('```-qotd submit <question>```')
            return
        member = ctx.author.id

        today = datetime.datetime.utcnow().date()
        today_date = datetime.datetime(today.year, today.month, today.day)
        async with self.bot.pool.acquire() as connection:
            submitted_today = await connection.fetch('SELECT * FROM qotd WHERE submitted_by = ($1) AND submitted_at > ($2)', str(member), today_date)
            if len(submitted_today) >= 2 and member not in SPAMPING_PERMS and not self.staff(member): #adam bypass
                await ctx.send('You can only submit 2 QOTD per day - this is to stop bot abuse.')
            else:
                await connection.execute('INSERT INTO qotd (question, submitted_by) VALUES ($1, $2)', qotd, str(member))
                id = await connection.fetchval("SELECT MAX(id) FROM qotd")
                await ctx.send(f':thumbsup: Thank you for submitting your QOTD. Your QOTD ID is **{id}**.')
            
                embed = Embed(title='QOTD Submitted', color=Colour.from_rgb(177,252,129))
                embed.add_field(name='ID', value=id)
                embed.add_field(name='Author', value=ctx.author)
                embed.add_field(name='Question', value=qotd, inline=True)
                embed.set_footer(text=(datetime.datetime.utcnow()-datetime.timedelta(hours=1)).strftime('%x'))
                await get(ctx.guild.text_channels, name='adambot-logs').send(embed=embed)
Beispiel #22
0
    async def trivia_end_leaderboard(self,
                                     member: discord.Member = None,
                                     reset=True):
        result = self.reload_trivias()
        if not result:
            await ctx.send(
                "Issue when reloading trivias - ping Adam for a fix.")
        if not member:
            color = Colour.from_rgb(177, 252, 129)
        else:
            color = member.color

        embed = Embed(title='Trivia results' if reset else 'Trivia scores',
                      color=color)
        total_score = sum([self.score[indv] for indv in self.score])
        for indv in self.score:
            embed.add_field(
                name=indv,
                value=
                f'{round(self.score[indv]*100/total_score,4)}% ({self.score[indv]})',
                inline=True)
        if reset:
            embed.set_footer(
                text=
                f'This trivia took {(datetime.utcnow()-self.started_at).seconds} seconds to complete.'
            )
            await self.trivia_channel.send('Trivia stopped.')
            self.reset()
        await self.trivia_channel.send(embed=embed)
Beispiel #23
0
    async def award(self, ctx, user: discord.Member, change=1):
        '''Gives the member a rep, mods can do `-rep award @Member <change>` where change is the number of reps to be awarded'''
        if ctx.author != user:  #check to not rep yourself
            try:
                change = int(change)
            except ValueError:
                await ctx.send('Please choose a valid number!')
                return
            if 'Moderator' in [y.name for y in ctx.author.roles]:
                reps = await self.modify_rep(user, change)
            else:
                reps = await self.modify_rep(user, 1)
            await ctx.send(f'{user.mention} now has {reps} reputation points!')

            embed = Embed(title='Reputation Points',
                          color=Colour.from_rgb(177, 252, 129))
            embed.add_field(name='From',
                            value=f'{str(ctx.author)} ({ctx.author.id})')
            embed.add_field(name='To', value=f'{str(user)} ({user.id})')
            embed.add_field(name='New Rep', value=reps)
            embed.set_footer(text=(datetime.datetime.utcnow() -
                                   datetime.timedelta(hours=1)).strftime('%x'))
            await get(ctx.guild.text_channels,
                      name='adambot-logs').send(embed=embed)
        else:
            await ctx.send('You cannot rep yourself, cheating bugger.')
Beispiel #24
0
    async def handle_unban(self,
                           data: dict,
                           reason: str = "",
                           author: str = "",
                           ctx: commands.Context = None) -> None:
        try:
            user = self.bot.get_user(data["member_id"])
            if not user and ctx:
                user, in_guild = await self.get_member_obj(
                    ctx, data["member_id"])
                if not user:
                    return
            guild = self.bot.get_guild(data["guild_id"])
            await guild.unban(user, reason=reason)
            channel_id = await self.bot.get_config_key(ctx, "log_channel")
            if channel_id is None:
                return
            channel = self.bot.get_channel(channel_id)

            embed = Embed(title="Unban", color=Colour.from_rgb(76, 176, 80))
            embed.add_field(name="User", value=f"{user.mention} ({user.id})")
            embed.add_field(name="Moderator",
                            value=str(self.bot.user if not author else author))
            embed.add_field(name="Reason", value=reason)
            embed.set_thumbnail(url=get_user_avatar_url(user)[0])
            embed.set_footer(
                text=self.bot.correct_time().strftime(self.bot.ts_format))
            await channel.send(embed=embed)
        except Exception as e:
            print(e)
            pass  # go away!
Beispiel #25
0
    async def pick(self, ctx, question_id):
        async with self.bot.pool.acquire() as connection:
            questions = []
            if question_id.lower() == 'random':
                questions = await connection.fetch('SELECT * FROM qotd')
            else:
                questions = await connection.fetch('SELECT * FROM qotd WHERE id = $1', int(question_id))
            if not questions:
                await ctx.send(f'Question with ID {question_id} not found. Please try again.')
                return
            else:
                question_data = choice(questions)

            question = question_data[1]
            member = await self.bot.fetch_user(question_data[2])
            message = f"**QOTD**\n{question} - Credit to {member.mention}"

            await connection.execute('DELETE FROM qotd WHERE id = ($1)', int(question_id))

        await ctx.send(':ok_hand:')
        await get(ctx.author.guild.text_channels, name='question-of-the-day').send(message)
        
        embed = Embed(title='QOTD Picked', color=Colour.from_rgb(177,252,129))
        embed.add_field(name='ID', value=question_data[0])
        embed.add_field(name='Author', value=str(member))
        embed.add_field(name='Question', value=question, inline=True)
        embed.add_field(name='Staff', value=str(ctx.author))
        embed.set_footer(text=(datetime.datetime.utcnow()-datetime.timedelta(hours=1)).strftime('%x'))
        
        await get(ctx.author.guild.text_channels, name='adambot-logs').send(embed=embed)
Beispiel #26
0
    async def remove(self,
                     connection: SupportConnection,
                     staff: discord.User = None) -> None:
        """
        Method that removes the support connection from the database and logs in support-logs. This method assumes
        that the connection DOES exist. If staff is not None then staff closed the ticket, otherwise it was member.
        """

        async with self.bot.pool.acquire() as db_connection:
            await db_connection.execute("DELETE FROM support WHERE id = $1",
                                        connection.id)

        channel_id = await self.bot.get_config_key(
            self.bot.get_guild(connection.guild_id), "support_log_channel")
        if channel_id is not None:
            channel = self.bot.get_channel(channel_id)
            if channel is None:
                return
            embed = Embed(title="Ticket Ended",
                          color=Colour.from_rgb(255, 0, 0))
            embed.add_field(name="ID", value=connection.id, inline=True)
            if staff is not None:
                embed.add_field(name="Initiator",
                                value=f"Staff: {staff.display_name}",
                                inline=True)
            else:
                embed.add_field(name="Initiator", value="Member", inline=True)

            await channel.send(embed=embed)
Beispiel #27
0
    async def get_mythicplus_affix(self, ctx):
        """
        Get the Mythic+ affixes of this week.
        """
        guild_server = GuildServer.objects.filter(guild_id=ctx.guild.id, default=True).first()
        region = "us"
        if guild_server:
            region = guild_server.get_region_display()
        params = {
            "namespace": f"dynamic-{region}",
            "locale": "en-US"
        }
        r = battlenet_util.execute_battlenet_request(f"https://{region}.api.blizzard.com/data/wow/mythic-challenge-mode/", params=params)
        json_mythicplus = r.json()
        embed = Embed()
        embed.set_thumbnail(url="http://wow.zamimg.com/images/wow/icons/large/inv_relics_hourglass.jpg")
        current_difficulty = 0
        embed, current_difficulty = affixEmbed(embed, current_difficulty, json_mythicplus['current_keystone_affixes'][0])
        embed, current_difficulty = affixEmbed(embed, current_difficulty, json_mythicplus['current_keystone_affixes'][1])
        embed, current_difficulty = affixEmbed(embed, current_difficulty, json_mythicplus['current_keystone_affixes'][2])
        embed, current_difficulty = affixEmbed(embed, current_difficulty, json_mythicplus['current_keystone_affixes'][3])

        if current_difficulty <= 3:
            embed.colour = Colour.green()
        elif current_difficulty == 4:
            embed.colour = Colour.from_rgb(255, 255, 0)
        else:
            embed.colour = Colour.red()
        await ctx.send(embed=embed)
Beispiel #28
0
async def fromDict(rmDict : dict) -> ReactionPollMenu:
    """Reconstruct a ReactionPollMenu object from its dictionary-serialized representation - the opposite of ReactionPollMenu.toDict

    :param dict rmDict: A dictionary containing all information needed to recreate the desired ReactionPollMenu
    :return: A new ReactionPollMenu object as described in rmDict
    :rtype: ReactionPollMenu
    """
    options = {}
    for emojiName in rmDict["options"]:
        emoji = bbUtil.dumbEmojiFromStr(emojiName)
        options[emoji] = ReactionMenu.DummyReactionMenuOption(rmDict["options"][emojiName], emoji)

    msg = await bbGlobals.client.get_guild(rmDict["guild"]).get_channel(rmDict["channel"]).fetch_message(rmDict["msg"])

    timeoutTT = None
    if "timeout" in rmDict:
        expiryTime = datetime.utcfromtimestamp(rmDict["timeout"])
        bbGlobals.reactionMenusTTDB.scheduleTask(TimedTask.TimedTask(expiryTime=expiryTime, expiryFunction=printAndExpirePollResults, expiryFunctionArgs=msg.id))

    return ReactionPollMenu(msg, options, timeoutTT, multipleChoice=rmDict["multipleChoice"] if "multipleChoice" in rmDict else False,
                                titleTxt=rmDict["titleTxt"] if "titleTxt" in rmDict else "",
                                desc=rmDict["desc"] if "desc" in rmDict else "",
                                col=Colour.from_rgb(rmDict["col"][0], rmDict["col"][1], rmDict["col"][2]) if "col" in rmDict else Colour.default(),
                                footerTxt=rmDict["footerTxt"] if "footerTxt" in rmDict else "",
                                img=rmDict["img"] if "img" in rmDict else "",
                                thumb=rmDict["thumb"] if "thumb" in rmDict else "",
                                icon=rmDict["icon"] if "icon" in rmDict else "",
                                authorName=rmDict["authorName"] if "authorName" in rmDict else "",
                                targetMember=msg.guild.get_member(rmDict["targetMember"]) if "targetMember" in rmDict else None,
                                targetRole=msg.guild.get_role(rmDict["targetRole"]) if "targetRole" in rmDict else None,
                                owningBBUser=bbGlobals.usersDB.getUser(rmDict["owningBBUser"]) if "owningBBUser" in rmDict and bbGlobals.usersDB.userIDExists(rmDict["owningBBUser"]) else None)
Beispiel #29
0
    async def log_message(self, msg_type: MessageOrigin,
                          message: discord.Message) -> None:
        """
        Method that should be executed when a new message is sent through a support ticket. `message`
        refers to the actual message object sent and `msg_type` should be of the MessageOrigin type.
        """

        channel_id = await self.bot.get_config_key(self.guild,
                                                   "support_log_channel")
        if channel_id is not None:
            channel = self.bot.get_channel(channel_id)
            if channel is None:
                return

            embed = Embed(title="Message Sent",
                          color=Colour.from_rgb(177, 252, 129))
            embed.add_field(name="ID", value=f"{self.id}", inline=True)
            if msg_type == MessageOrigin.MEMBER:
                embed.add_field(name="Author", value=f"Member", inline=True)
            elif msg_type == MessageOrigin.STAFF:
                embed.add_field(name="Author",
                                value=f"Staff: {message.author.display_name}")

            embed.add_field(name="Content",
                            value=f"{message.content}",
                            inline=False)
            await channel.send(embed=embed)
Beispiel #30
0
    async def _warnlist_member(self,
                               ctx: commands.Context,
                               member: discord.Member,
                               page_num: int = 1) -> None:
        """
        Handles getting the warns for a specific member
        """

        async with self.bot.pool.acquire() as connection:
            warns = await connection.fetch(
                "SELECT * FROM warn WHERE member_id = ($1) AND guild_id = $2 ORDER BY id;",
                member.id, ctx.guild.id)

        if len(warns) > 0:
            embed = self.bot.EmbedPages(
                self.bot.PageTypes.WARN,
                warns,
                f"{member.display_name}'s warnings",
                Colour.from_rgb(177, 252, 129),
                self.bot,
                ctx.author,
                ctx.channel,
                thumbnail_url=get_guild_icon_url(ctx.guild),
                icon_url=get_user_avatar_url(ctx.author, mode=1)[0],
                footer=
                f"Requested by: {ctx.author.display_name} ({ctx.author})\n" +
                self.bot.correct_time().strftime(self.bot.ts_format))

            await embed.set_page(int(page_num))
            await embed.send()
        else:
            await ctx.send("No warnings recorded!")
Beispiel #31
0
	def _getStatusEmbed(self, servicesInfo):
		embed = discord.Embed(title="Server Statuses")

		successCount = 0
		totalCount = 9

		for service in servicesInfo:
			embed.add_field(name=service["name"], value=upperFirst(service["statusClass"]))
			if service["statusClass"] == "good" or service["statusClass"] == "success":
				successCount += 1

		failCount = totalCount - successCount

		# Switch between green and red depending on number of failed services
		redPercent = (failCount / totalCount) * 255
		greenPercent = (successCount / totalCount) * 255

		embed.colour = Colour.from_rgb(int(redPercent), int(greenPercent), 0)

		if failCount > 0:
			string = "are {0} services".format(failCount)
			if failCount == 1:
				string = "is 1 service"
			embed.add_field(name="Overall Status", value="There may be some latency issues because there {0} not operating at full capacity.".format(string))
		else:
			embed.add_field(name="Overall Status", value="All services running at full capacity.")

		embed.timestamp = dt.utcnow()
		embed.set_footer(text="SteamAPI from http://steamstat.us/ .")
		return embed