Exemple #1
0
    async def give(self, ctx, mentioned_user: discord.Member = discord.Member, amount=0):
        """Give a user money [Format: %give (@user) (amount)]"""
        try:
            userid = ctx.author.id
            if await check_in_game(userid):
                await register_user(userid)
                if mentioned_user.id != userid:
                    current_amount = await get_balance(userid)
                    if amount == 0:
                        await ctx.send("> **Please specify an amount [Format: %give (@user) (amount)]**", delete_after=60)
                    if amount > 0:
                        if amount > current_amount:
                            await ctx.send("> **You do not have enough money to give!**", delete_after=60)
                        if amount <= current_amount:
                            mentioned_money = await get_balance(mentioned_user.id)
                            new_amount = mentioned_money + amount
                            subtracted_amount = current_amount - amount
                            await update_balance(mentioned_user.id, str(new_amount))
                            await update_balance(userid, str(subtracted_amount))
                            await ctx.send("> **Your money has been transferred.**")
                elif mentioned_user.id == userid:
                    await ctx.send("> **You can not give money to yourself!**")

            else:
                await ctx.send("> **Please type %endgame. You cannot use this command when you're in a game.**")
        except Exception as e:
            log.console(e)
Exemple #2
0
 async def give(self, ctx, mentioned_user: discord.Member = discord.Member, amount="0"):
     """Give a user money [Format: %give (@user) (amount)]"""
     try:
         amount = ex.remove_commas(amount)
         check = True
     except Exception as e:
         await ctx.send(f"> **{amount} is not a proper value.**")
         check = False
     try:
         if check:
             user_id = ctx.author.id
             if not await ex.check_in_game(user_id, ctx):
                 await ex.register_user(user_id)
                 if mentioned_user.id != user_id:
                     current_amount = await ex.get_balance(user_id)
                     if amount == 0:
                         await ctx.send("> **Please specify an amount [Format: %give (@user) (amount)]**", delete_after=60)
                     if amount > 0:
                         if amount > current_amount:
                             await ctx.send("> **You do not have enough money to give!**", delete_after=60)
                         if amount <= current_amount:
                             mentioned_money = await ex.get_balance(mentioned_user.id)
                             new_amount = mentioned_money + amount
                             subtracted_amount = current_amount - amount
                             await ex.update_balance(mentioned_user.id, str(new_amount))
                             await ex.update_balance(user_id, str(subtracted_amount))
                             await ctx.send("> **Your money has been transferred.**")
                 elif mentioned_user.id == user_id:
                     await ctx.send("> **You can not give money to yourself!**")
     except Exception as e:
         log.console(e)
Exemple #3
0
 async def count(self, ctx, *, name=None):
     """Shows howmany times an idol has been called. [Format: %count (idol's name/all)]"""
     try:
         if name == 'all' or not name:
             idol_called = 0
             for member in ex.cache.idols:
                 idol_called += member.called
             return await ctx.send(
                 f"> **All Idols have been called a total of {idol_called} times.**"
             )
         server_id = await ex.get_server_id(ctx)
         members = await ex.u_group_members.get_idol_where_member_matches_name(
             name, server_id=server_id)
         if not members:
             return await ctx.send(f"> **{name} could not be found.**")
         for member in members:
             if not member.called:
                 await ctx.send(
                     f"> **{member.full_name} ({member.stage_name}) has not been called by a user yet.**"
                 )
             else:
                 rank_list = await ex.conn.fetch(
                     "SELECT memberid FROM groupmembers.count ORDER BY Count DESC"
                 )
                 for count, rank_row in enumerate(rank_list):
                     mem_id = rank_row[0]
                     if mem_id == member.id:
                         final_rank = count + 1
                         await ctx.send(
                             f"> **{member.full_name} ({member.stage_name}) has been called {member.called} times at rank {final_rank}.**"
                         )
     except Exception as e:
         await ctx.send(f"> **ERROR: {e}**")
         log.console(e)
Exemple #4
0
    async def announce(self, ctx, *, new_message):
        """Sends a bot message to certain text channels"""
        desc = f"{new_message}"
        embed = discord.Embed(
            title=f"Announcement from {ctx.author} ({ctx.author.id})",
            description=desc,
            color=0xff00f6)
        embed.set_author(
            name="Irene",
            url='https://www.youtube.com/watch?v=dQw4w9WgXcQ',
            icon_url=
            'https://cdn.discordapp.com/emojis/693392862611767336.gif?v=1')
        embed.set_footer(
            text="Type %support for an invite to Irene's discord server.",
            icon_url=
            'https://cdn.discordapp.com/emojis/683932986818822174.gif?v=1')
        # embed.add_field(name=f"{ctx.author.name} ({ctx.author.id})", value=desc)

        guilds = self.client.guilds
        for guild in guilds:
            try:
                await guild.system_channel.send(embed=embed)
            except Exception as e:
                log.console(e)
                pass
Exemple #5
0
 async def check_voice_clients(self):
     if not ex.client.loop.is_running():
         return
     try:
         for voice_client in ex.client.voice_clients:
             # members in vc must be equal to 1 to stop playing (includes the bot)
             if voice_client.is_connected(
             ) and voice_client.channel.members == 1:
                 if voice_client.is_playing():
                     try:
                         songs_queued = queued[voice_client.guild.id]
                         if songs_queued:
                             channel = songs_queued[0][1]
                             msg = f"> **There are no users in this voice channel. Resetting queue and leaving.**"
                             await channel.send(msg)
                     except:
                         pass
                     self.reset_queue_for_guild(voice_client.guild.id)
                     voice_client.stop()
                 await voice_client.disconnect()
         keep_files = []
         for key in queued:
             file_name = (queued[key][0][2])
             keep_files.append(file_name)
         for song_file_name in os.listdir("music"):
             file_location = f"music/{song_file_name}"
             if file_location in keep_files and file_location == "music":
                 continue
             try:
                 os.remove(file_location)
             except:
                 pass
     except Exception as e:
         log.console(e)
Exemple #6
0
    async def create_new_question(self):
        """Create a new question and send it to the channel."""
        # noinspection PyBroadException
        try:
            if self.idol_post_msg:
                try:
                    await self.idol_post_msg.delete()
                except:
                    # message does not exist.
                    pass
            if self.rounds >= self.max_rounds:
                if not self.force_ended:
                    await self.end_game()
                return True  # will properly end the game.
            self.idol = await ex.u_group_members.get_random_idol()
            if not self.gender_forced:
                self.gender = random.choice(['m', 'f'])

            while self.idol.gender != self.gender or ex.cache.difficulty_aliases[self.idol.difficulty] > self.difficulty:
                # will result in an infinite loop if there are no idols on easy mode and difficulty is easy mode.
                self.idol = await ex.u_group_members.get_random_idol()

            self.group_names = [(await ex.u_group_members.get_group(group_id)).name for group_id in self.idol.groups]
            self.correct_answers = []
            for alias in self.idol.aliases:
                self.correct_answers.append(alias.lower())
            self.correct_answers.append(self.idol.full_name.lower())
            self.correct_answers.append(self.idol.stage_name.lower())
            log.console(f'{", ".join(self.correct_answers)} - {self.channel.id}')
            self.idol_post_msg, self.photo_link = await ex.u_group_members.idol_post(self.channel, self.idol, user_id=self.host, guessing_game=True, scores=self.players)
            await self.check_message()
        except:
            pass
Exemple #7
0
 async def deletealias(self, ctx, alias, mem_id: int, mode="idol"):
     """Remove alias from an idol/group (Underscores are spaces)[Format: %deletealias (alias) (ID of idol/group) ("idol" or "group")]"""
     alias = alias.replace("_", " ")
     if mode.lower() == "idol":
         mode = "member"
         param = "id"
         is_group = False
     elif mode.lower() == "group":
         mode = "groups"
         param = "groupid"
         is_group = True
     else:
         return await ctx.send("> **Please specify 'idol' or 'group'**.")
     try:
         id_exists = ex.first_result(await ex.conn.fetchrow(
             f"SELECT COUNT(*) FROM groupmembers.{mode} WHERE {param} = $1",
             mem_id))
         if id_exists == 0:
             return await ctx.send("> **That ID does not exist.**")
         else:
             # check if the alias exists, if it does delete it.
             aliases = await ex.get_aliases(object_id=mem_id,
                                            group=is_group)
             if alias in aliases:
                 await ex.conn.execute(
                     "DELETE FROM groupmembers.aliases WHERE objectid = $1 AND alias = $2 AND isgroup = $3",
                     mem_id, alias.lower(), int(is_group))
                 return await ctx.send(
                     f"> **Alias: {alias} was removed from {mem_id}.**")
             else:
                 return await ctx.send(
                     f"> **Could not find alias: {alias}**")
     except Exception as e:
         await ctx.send(e)
         log.console(e)
Exemple #8
0
 async def on_ready():
     global first_run
     if first_run:
         await client.change_presence(status=discord.Status.online,
                                      activity=discord.Game("%help"))
     log.console('Irene is online')
     first_run = False
Exemple #9
0
    async def updates(self, ctx, community_name, role: discord.Role = None):
        """Receive Weverse Updates of a specific Weverse community in the current text channel. Use again to disable for a specific community.
        Available Communities ->
        [TXT, BTS, GFRIEND, SEVENTEEN, ENHYPEN, NU'EST, CL, P1Harmony, Weeekly, SUNMI, HENRY, Dreamcatcher]
        [Format: %updates <community name> [role to notify]]
        """
        try:
            if not ex.weverse_client.cache_loaded:
                return await ctx.send(f"> {ctx.author.display_name}, Weverse cache is being updated. Please try again in a minute or two.")

            channel_id = ctx.channel.id
            community_name = community_name.lower()
            if await ex.u_weverse.check_weverse_channel(channel_id, community_name):
                if not role:
                    await ex.u_weverse.delete_weverse_channel(channel_id, community_name)
                    return await ctx.send(f"> {ctx.author.display_name}, You will no longer receive updates for {community_name}.")
            for community in ex.weverse_client.communities:
                if community.name.lower() == community_name:
                    # delete any existing before adding a new one.
                    await ex.u_weverse.delete_weverse_channel(channel_id, community_name)
                    await ex.u_weverse.add_weverse_channel(channel_id, community_name)
                    # add role to weverse subscription after channel is added to db.
                    if role:
                        await ex.u_weverse.add_weverse_role(channel_id, community_name, role.id)
                    return await ctx.send(f"> {ctx.author.display_name}, You will now receive weverse updates for {community.name} in this channel.")
            return await ctx.send(f"> {ctx.author.display_name},I could not find {community_name}. Available choices are:\n{self.available_choices}")
        except Exception as e:
            msg = "An error has occurred trying to subscribe to a weverse community."
            log.console(f"{msg} - {e}")
            return await ctx.send(msg)
Exemple #10
0
 async def on_guild_remove(guild):
     try:
         await ex.conn.execute("INSERT INTO stats.leftguild (id, name, region, ownerid, membercount) VALUES($1, "
                               "$2, $3, $4, $5)", guild.id, guild.name,
                               str(guild.region), guild.owner_id, guild.member_count)
     except Exception as e:
         log.console(f"{guild.name} ({guild.id})has already kicked Irene before. - {e}")
Exemple #11
0
 async def on_guild_join(guild):
     try:
         if guild.system_channel:
             await guild.system_channel.send(f">>> Hello!\nMy prefix for this server is set to {await ex.get_server_prefix(guild.id)}.\nIf you have any questions or concerns, you may join the support server ({await ex.get_server_prefix(guild.id)}support).")
     except:
         pass
     log.console(f"{guild.name} ({guild.id}) has invited Irene.")
Exemple #12
0
    async def on_message_user_notifications(message):
        # user phrase notifications
        try:
            if message.author.bot:
                return

            message_split = message.content.lower().split(" ")
            for guild_id, user_id, phrase in ex.cache.user_notifications:
                if phrase not in message_split or guild_id != message.guild.id:
                    continue
                if message.author.id == user_id or user_id not in [member.id for member in message.channel.members]:
                    continue

                log.console(f"message_notifications 1 - {phrase} to {user_id}")
                dm_channel = await ex.get_dm_channel(user_id)
                log.console(f"message_notifications 2 - {phrase} to {user_id}")
                start_loc = (message.content.lower()).find(phrase)
                end_loc = start_loc + len(phrase)
                new_message_content = f"{message.content[0:start_loc]}`{message.content[start_loc:end_loc]}`" \
                    f"{message.content[end_loc:len(message.content)]}"
                title_desc = f"""
Phrase: {phrase}
Message Author: {message.author}

**Message:** {new_message_content}
[Click to go to the Message]({message.jump_url})
"""
                embed = await ex.create_embed(title="Phrase Found", color=ex.get_random_color(), title_desc=title_desc)
                await dm_channel.send(embed=embed)
        except:
            pass
Exemple #13
0
 async def unmute(self, ctx, user: discord.Member = None):
     """Unmute a user that is already muted.
     Format: [%unmute @user (reason)]"""
     try:
         if user is None:
             return await ctx.send(
                 f"> **<@{ctx.author.id}>, Please specify a user to unmute.**"
             )
         if user.id == ctx.author.id:
             return await ctx.send(
                 f"> **<@{ctx.author.id}>, You cannot unmute yourself.**")
         mute_role = await self.get_mute_role(ctx)
         muted = await self.check_if_muted(user.id, mute_role)
         if mute_role is None:
             return await ctx.send(
                 ">**This user was not muted by me as the mute role could not be found. In order for me to create a custom mute role, I need to mute someone first.**"
             )
         if muted:
             await user.remove_roles(
                 mute_role,
                 reason=
                 f"UnMuting User - Requested by {ctx.author.display_name} ({user.id})"
             )
             return await ctx.send(f"> **<@{user.id}> has been unmuted.**")
         else:
             return await ctx.send(f"> **<@{user.id}> is not muted.**")
     except Exception as e:
         log.console(e)
         return await ctx.send(
             f"> **I am missing permissions to unmute {user.display_name}. {e}**"
         )
Exemple #14
0
    async def listcommands(self, ctx):
        """List all the custom commands for this server. [Format: %listcommands]"""
        try:
            async def get_new_embed(desc):
                return await ex.create_embed(f"Custom Commands for {ctx.guild.name} ({ctx.guild.id})", color=ex.get_random_color(),
                                             title_desc=desc)
            custom_commands = ex.cache.custom_commands.get(ctx.guild.id)
            embed_list = []
            embed_message = ""

            if not custom_commands:
                return await ctx.send("> There are no custom commands for your server.")

            for command in custom_commands:
                added_to_list = False
                message = f"**{command}** -> {custom_commands.get(command)}\n"
                if len(message) > 1000:
                    embed_list.append(await get_new_embed(message))
                    added_to_list = True

                if not added_to_list:
                    embed_message += message
                    if len(embed_message) >= 950:
                        embed_list.append(await get_new_embed(embed_message))
                        embed_message = ""
            if embed_message:
                embed_list.append(await get_new_embed(embed_message))
            if embed_list:
                msg = await ctx.send(embed=embed_list[0])
                if len(embed_list) > 1:
                    await ex.check_left_or_right_reaction_embed(msg, embed_list)

        except Exception as e:
            await ctx.send(f"> An unexpected error occurred -> {e}. Please {await ex.get_server_prefix_by_context(ctx)}report it.")
            log.console(e)
Exemple #15
0
        async def change_page(c_page):
            """Waits for the user's reaction and then changes the page based on their reaction."""
            try:
                reaction, user = await self.client.wait_for('reaction_add', check=reaction_check)
                if reaction.emoji == '➡':
                    c_page += 1
                    if c_page >= len(embed_lists):
                        c_page = 0  # start from the beginning of the list
                    await msg.edit(embed=embed_lists[c_page])

                elif reaction.emoji == '⬅':
                    c_page -= 1
                    if c_page < 0:
                        c_page = len(embed_lists) - 1  # going to the end of the list
                    await msg.edit(embed=embed_lists[c_page])

                # await msg.clear_reactions()
                # await msg.add_reaction(reaction1)
                # await msg.add_reaction(reaction2)
                # only remove user's reaction instead of all reactions
                try:
                    await reaction.remove(user)
                except:
                    pass
                await change_page(c_page)
            except Exception as e:
                log.console(f"check_left_or_right_reaction_embed - {e}")
                await change_page(c_page)
 async def new_task4(self):
     try:
         if ex.client.loop.is_running():
             if self.first_run == 1:
                 await asyncio.sleep(
                     10)  # sleeping to stabilize connection to DB
             self.count_loop += 1
             if self.first_run == 1:
                 number = ex.first_result(await ex.conn.fetchrow(
                     "SELECT PostID FROM dreamcatcher.DCPost"))
                 self.first_run = 0
                 self.number = number
                 self.post_list.append(number)
             if self.error_status == 1:
                 if 5 > self.tries >= 2:
                     self.number += 1
                 if self.tries >= 5:
                     count_list = (len(self.post_list))
                     self.number = self.post_list[count_list - 1]
                     self.tries = 0
             if self.error_status == 0:
                 self.tries = 0
                 self.number += 1
                 pass
             await self.check_dc_post(self.number)
     except Exception as e:
         log.console(e)
Exemple #17
0
    async def ggleaderboard(self, ctx, difficulty="medium", mode="server"):
        """Shows global leaderboards for guessing game
        [Format: %ggleaderboard (easy/medium/hard) (server/global)]"""
        if difficulty.lower() not in ['easy', 'medium', 'hard']:
            difficulty = "medium"

        try:
            if mode.lower() not in ["server", "global"]:
                mode = "server"
            if mode == "server":
                server_id = await ex.get_server_id(ctx)
                if not server_id:
                    return await ctx.send("> You should not use this command in DMs.")
                members = f"({', '.join([str(member.id) for member in ex.client.get_guild(server_id).members])})"
                top_user_scores = await ex.u_guessinggame.get_guessing_game_top_ten(difficulty, members=members)

            else:
                top_user_scores = await ex.u_guessinggame.get_guessing_game_top_ten(difficulty)

            user_position = 0
            lb_string = ""
            for user_id, score in top_user_scores:
                user_position += 1
                score = await ex.u_guessinggame.get_user_score(difficulty.lower(), user_id)
                lb_string += f"**{user_position})** <@{user_id}> - {score}\n"
            m_embed = await ex.create_embed(title=f"Guessing Game Leaderboard ({difficulty.lower()}) ({mode})",
                                            title_desc=lb_string)
            await ctx.send(embed=m_embed)
        except Exception as e:
            log.console(e)
            return await ctx.send(f"> You may not understand this error. Please report it -> {e}")
Exemple #18
0
    async def download_url(self, url, drive_id, channel_id):
        try:
            async with ex.session.get(url) as r:
                check = False
                if r.status == 200:
                    unique_id = randint(0, 1000000000000)
                    unique_id2 = randint(0, 1000)
                    unique_id3 = randint(0, 500)
                    src = url[len(url) - 4:len(url)]
                    checkerx = url.find(":large")
                    if checkerx != -1:
                        src = url[len(url) - 10:len(url) - 6]
                        url = f"{url[0:checkerx-1]}:orig"

                    src2 = url.find('?format=')
                    if src2 != -1:
                        check = True
                        src = f".{url[src2+8:src2+11]}"
                        url = f"{url[0:src2-1]}{src}:orig"
                    if src == ".jpg" or src == ".gif" or src == '.png' or check:
                        file_name = f"1_{unique_id}_{unique_id2}_{unique_id3}{src}"
                        fd = await aiofiles.open('Photos/{}'.format(file_name),
                                                 mode='wb')
                        await fd.write(await r.read())
                        await fd.close()
                        await ex.conn.execute(
                            "INSERT INTO archive.ArchivedChannels VALUES($1,$2,$3,$4)",
                            file_name, src, drive_id, channel_id)
                    # quickstart.Drive.checker()
        except Exception as e:
            log.console(e)
Exemple #19
0
 async def addalias(self, ctx, alias, mem_id: int, mode="idol"):
     """Add alias to an idol/group (Underscores are spaces)[Format: %addalias (alias) (ID of idol/group) ("idol" or "group"]"""
     alias = alias.replace("_", " ")
     if mode.lower() == "idol":
         mode = "member"
         param = "id"
         is_group = False
     elif mode.lower() == "group":
         mode = "groups"
         param = "groupid"
         is_group = True
     else:
         return await ctx.send("> **Please specify 'idol' or 'group'**.")
     try:
         id_exists = ex.first_result(await ex.conn.fetchrow(
             f"SELECT COUNT(*) FROM groupmembers.{mode} WHERE {param} = $1",
             mem_id))
         if id_exists == 0:
             return await ctx.send(
                 f"> **That ID ({mem_id}) does not exist.**")
         else:
             # check if the alias already exists, if not, add it
             aliases = await ex.get_aliases(object_id=mem_id,
                                            group=is_group)
             if alias not in aliases:
                 await ex.conn.execute(
                     "INSERT INTO groupmembers.aliases(objectid, alias, isgroup) VALUES ($1, $2, $3)",
                     mem_id, alias.lower(), int(is_group))
                 await ctx.send(f"> **Added Alias: {alias} to {mem_id}**")
             else:
                 return await ctx.send(
                     f"> **{alias} already exists with {mem_id}.**")
     except Exception as e:
         await ctx.send(e)
         log.console(e)
Exemple #20
0
        async def history(guild_id, drive_id):
            try:
                async for message in ctx.channel.history(limit=None,
                                                         after=after):
                    if len(message.attachments) > 0:
                        for file in message.attachments:
                            url = file.url
                            if "%27%3E" in url:
                                pos = url.find("%27%3E")
                                url = url[0:pos - 1]
                            if ":large" in url:
                                pos = url.find(":large")
                                url = url[0:pos - 1]
                            await self.download_url(url, drive_id,
                                                    ctx.channel.id)

                    if len(message.embeds) > 0:
                        for embed in message.embeds:
                            if str(embed.url) == "Embed.Empty":
                                pass
                            else:
                                url = embed.url
                                if "%27%3E" in url:
                                    pos = url.find("%27%3E")
                                    url = url[0:pos - 1]
                                if ":large" in url:
                                    pos = url.find(":large")
                                    url = url[0:pos - 1]
                                await self.download_url(
                                    url, drive_id, ctx.channel.id)

                    pass
            except Exception as e:
                log.console(e)
                pass
Exemple #21
0
 async def closedm(self, ctx, user: discord.User = None):
     """Closes a DM either by the User ID or by the current channel.
     [Format: %closedm <user id>] """
     try:
         if user is not None:
             user_id = user.id
         else:
             user_id = ex.first_result(await ex.conn.fetchrow(
                 "SELECT userid FROM general.modmail WHERE channelid = $1",
                 ctx.channel.id))
         dm_channel = await ex.get_dm_channel(user_id)
         if dm_channel is None:
             return await ctx.send(
                 "> **There are no DMs set up in this channel.**")
         ex.cache.mod_mail.pop(user_id, None)
         await ex.conn.execute(
             "DELETE FROM general.modmail WHERE userid = $1 and channelid = $2",
             user_id, ctx.channel.id)
         await ctx.send(f"> The DM has been deleted successfully.")
         await dm_channel.send(
             f"> {ctx.author.display_name} ({ctx.author.id}) has closed the DM with you. Your messages will no longer be sent to them."
         )
     except Exception as e:
         await ctx.send(f"ERROR - {e}")
         log.console(e)
Exemple #22
0
    async def mod_mail_on_message(message):
        # mod mail
        try:
            message_sender = message.author
            message_channel = message.channel
            message_content = message.content
            if message_sender.id == keys.bot_id:
                return
            if 'closedm' in message_content or 'createdm' in message_content:
                return

            for user_id in ex.cache.mod_mail:
                try:
                    channel_id = ex.cache.mod_mail.get(user_id)
                    mod_channel = await ex.client.fetch_channel(channel_id)
                    if user_id == message_sender.id:
                        dm_channel = await ex.get_dm_channel(message_sender.id)
                        if message_channel.id == dm_channel:
                            await mod_channel.send(
                                f">>> FROM: {message_sender.display_name} ({message_sender.id}) - {message_content}"
                            )
                    if mod_channel == message_channel:
                        dm_channel = await ex.get_dm_channel(user_id)
                        await dm_channel.send(
                            f">>> FROM: {message_sender.display_name} ({message_sender.id}) - {message_content}"
                        )
                except Exception as e:
                    log.console(
                        f"{e} - Iteration Error in BotMod.mod_mail_on_message")
                    # change in dictionary size should break the loop.
                    break

        except Exception as e:
            log.console(f"{e} - BotMod.mod_mail_on_message")
Exemple #23
0
 async def play(self, ctx, *, url=None):
     """Plays audio to a voice channel. [Format: %play (title/url)]"""
     if not url:
         if not ctx.voice_client.is_paused:
             return await ctx.send(
                 "> The player is not paused. Please enter a title or link to play audio."
             )
         ctx.voice_client.resume()
         return await ctx.send(f"> **The video player is now resumed**")
     try:
         if not self.check_user_in_vc(ctx):
             return await ctx.send(
                 f"> **{ctx.author}, we are not in the same voice channel.**"
             )
         async with ctx.typing():
             msg = await ctx.send(
                 f"> **Gathering information about the video/playlist, this may take a few minutes if it is a long playlist.**"
             )
             videos, first_video_live = await YTDLSource.from_url(
                 url,
                 loop=ex.client.loop,
                 stream=False,
                 guild_id=ctx.guild.id,
                 channel=ctx.channel,
                 author_id=ctx.author.id)
             if not ctx.voice_client.is_playing():
                 if not first_video_live:
                     player = await download_video(videos[0])
                     video_title = videos[0].get('title')
                 else:
                     player = videos[0]
                     video_title = player.title
                 try:
                     ctx.voice_client.play(player,
                                           after=self.start_next_song)
                     # THIS IS VERY IMPORTANT
                     # This makes the front of the queue always a player.
                     # This is useful so that no code is changed for going to the next song (music rework)
                     queued[ctx.guild.id][0][0] = player
                 except:  # Already Playing Audio
                     return await ctx.send(
                         f"> **Added {video_title} to the queue.**")
                 await ctx.send(f'> **Now playing: {video_title}**',
                                delete_after=240)  # deletes after 4min
             else:
                 # grabbing the latest player
                 if len(videos) == 1:  # do not shorten code
                     if not first_video_live:
                         title = videos[0].get('title')
                     else:
                         title = videos[0].title
                     await ctx.send(f"> **Added {title} to the queue.**")
                 else:
                     await ctx.send(
                         f"> **Added {len(videos)} songs to the queue.**")
             await msg.delete()
     except IndexError:
         pass
     except Exception as e:
         log.console(e)
Exemple #24
0
 async def topalbums(self,
                     ctx,
                     user: typing.Union[discord.User, str] = None,
                     time_period: typing.Union[discord.User, str] = None):
     """See the top albums of a Last FM Account by a discord user or a Last FM username
     [Format: %topalbums (username) (time period)]
     Time period options are ``overall | week | month | 3month | 6month | year``.
     Time period defaults to overall."""
     try:
         user, time_period = await self.set_user(
             ctx, user, time_period), self.set_period(user, time_period)
         response = await ex.get_fm_response('user.getTopAlbums',
                                             user,
                                             limit=10,
                                             time_period=time_period)
         list_of_albums = response['topalbums']['album']
         counter = 0
         tracks_and_titles = []
         for album in list_of_albums:
             counter += 1
             title = f"**#{counter} ({album['playcount']} plays)**"
             artist_name = f"**[{album['name']} by {album['artist']['name']}]({album['url']})**"
             tracks_and_titles.append([title, artist_name])
         await ctx.send(embed=await self.create_fm_embed(
             f"{user} **Top Albums ({time_period})**", tracks_and_titles))
     except KeyError:
         await events.Events.error(ctx, self.user_not_found)
     except Exception as e:
         log.console(e)
         await ctx.send(
             f"> **Something went wrong.. Please {await ex.get_server_prefix_by_context(ctx)}report it.**"
         )
Exemple #25
0
    async def stand(self, ctx):
        """Keep Your Cards/Stand [Format: %stand]"""
        try:
            check = False
            user_id = ctx.author.id
            game_id = await ex.u_blackjack.get_game_by_player(user_id)
            if game_id is None:
                await ctx.send(f"> **{ctx.author}, you are not in a game.**")
            else:
                if await ex.u_blackjack.compare_channels(user_id, ctx.channel):
                    # Do not inform other users that the player already stood by busting.
                    # Instead, just send the same message that they are standing every time this command is called.
                    await ex.u_blackjack.set_player_stand(user_id)
                    game = await ex.u_blackjack.get_game(game_id)

                    if ex.u_blackjack.check_if_bot(game[2]):
                        check = True
                        await ex.u_blackjack.finish_game(game_id, ctx.channel)

                    if not check:
                        total_score = str(
                            await ex.u_blackjack.get_player_total(user_id))
                        if len(total_score) == 1:
                            total_score = '0' + total_score  # this is to prevent being able to detect the number of digits by the spoiler
                        if not ex.u_blackjack.check_if_bot(game[2]):
                            await ctx.send(
                                f"> **{ctx.author} finalized their deck with ||{total_score}|| points.**"
                            )
                        if await ex.u_blackjack.check_game_over(game_id):
                            await ex.u_blackjack.finish_game(
                                game_id, ctx.channel)
        except Exception as e:
            log.console(e)
Exemple #26
0
 async def scrape_videos():
     links = await ex.conn.fetch("SELECT link, channelid FROM youtube.links"
                                 )
     for url, channel_id in links:
         try:
             link_id = ex.first_result(await ex.conn.fetchrow(
                 "SELECT id FROM youtube.links WHERE link = $1", url))
             async with ex.session.get(url) as r:
                 if r.status != 200:
                     continue
                 page_html = await r.text()
                 start_pos = page_html.find("viewCount") + 12
                 end_loc = start_pos
                 while page_html[end_loc] != '"':
                     end_loc += 1
                 raw_view_count = page_html[start_pos:end_loc]
                 view_count = f"{int(raw_view_count):,} views"
                 current_date = datetime.now()
                 await ex.conn.execute(
                     "INSERT INTO youtube.views(linkid, views, date) VALUES ($1,$2,$3)",
                     link_id, view_count, str(current_date))
                 await YoutubeLoop.send_channel(
                     channel_id,
                     f"> **UPDATE FOR <{url}>: {view_count} -- {current_date}**"
                 )
         except Exception as e:
             log.console(e)
     log.console("Updated Video Views Tracker")
Exemple #27
0
    async def aliases(self, ctx, mode="member", page_number=1):
        """Lists the aliases of idols or groups that have one. Underscores are spaces and commas are to split idol or group names
[Format: %aliases (names of idols/groups) (page number)]"""
        try:
            mode = mode.replace("_", " ")
            mode = mode.replace(",", " ")
            server_id = await ex.get_server_id(ctx)
            embed_list = await ex.u_group_members.set_embed_with_aliases(
                mode, server_id=server_id)
            if not embed_list:
                if 'member' in mode.lower():
                    embed_list = await ex.u_group_members.set_embed_with_all_aliases(
                        "Idol", server_id=server_id)
                elif 'group' in mode.lower():
                    embed_list = await ex.u_group_members.set_embed_with_all_aliases(
                        "Group", server_id=server_id)
                else:
                    return await ctx.send(
                        f">>> **No results were found. Please specify whether you want member or group aliases, or enter a name of an idol/group.\n`{await ex.get_server_prefix_by_context(ctx)}help aliases`**"
                    )
            if len(embed_list) < page_number or page_number < 1:
                page_number = 1
            msg = await ctx.send(embed=embed_list[page_number - 1])
            if len(embed_list) > 1:
                await ex.check_left_or_right_reaction_embed(
                    msg, embed_list, page_number - 1)
        except Exception as e:
            log.console(e)
            await ctx.send(f"> **Error - {e}**")
Exemple #28
0
 async def check_voice_clients(self):
     if ex.client.loop.is_running():
         try:
             voice_clients = client.voice_clients
             for voice_client in voice_clients:
                 if voice_client.is_connected():
                     if len(voice_client.channel.members) == 1:
                         if voice_client.is_playing():
                             try:
                                 songs_queued = queued[voice_client.guild.id]
                                 if len(songs_queued) > 0:
                                     channel = songs_queued[0][1]
                                     msg = f"> **There are no users in this voice channel. Resetting queue and leaving.**"
                                     await channel.send(msg)
                             except Exception as e:
                                 pass
                             self.reset_queue_for_guild(voice_client.guild.id)
                             voice_client.stop()
                         await voice_client.disconnect()
             keep_files = []
             for key in queued:
                 file_name = (queued[key][0][2])
                 keep_files.append(file_name)
             all_music = os.listdir("music")
             for song_file_name in all_music:
                 file_location = f"music/{song_file_name}"
                 if file_location not in keep_files:
                     if file_location != "music":
                         try:
                             os.remove(file_location)
                         except Exception as e:
                             pass
         except Exception as e:
             log.console(e)
Exemple #29
0
    async def movelinks(self, ctx):
        """Add DC LINKS to main link table."""
        c.execute("SELECT link, member FROM currency.dchdlinks")
        hd_links = fetch_all()
        count = 0
        for link in hd_links:
            url = link[0]
            member_name = link[1]
            member_id = None
            if member_name == "Gahyeon":
                member_id = 163
            elif member_name == "Siyeon":
                member_id = 159
            elif member_name == "Yoohyeon":
                member_id = 161
            elif member_name == "JIU":
                member_id = 157
            elif member_name == "SUA":
                member_id = 158
            elif member_name == "Dami":
                member_id = 162
            elif member_name == "Handong":
                member_id = 160
            else:
                pass

            try:
                c.execute("INSERT INTO groupmembers.imagelinks VALUES (%s,%s)", (url, member_id))
                DBconn.commit()
                count += 1
            except Exception as e:
                log.console(e)
                pass
        await ctx.send(f"> **Added {count} links.**")
Exemple #30
0
 async def interact_with_user(ctx,
                              user,
                              interaction,
                              interaction_type,
                              self_interaction=False):
     await ex.u_patreon.reset_patreon_cooldown(ctx)
     try:
         if user == discord.Member:
             user = ctx.author
         list_of_links = await ex.conn.fetch(
             "SELECT url FROM general.interactions WHERE interaction = $1",
             interaction_type)
         if not self_interaction:
             if ctx.author.id == user.id:
                 ctx.command.reset_cooldown(ctx)
                 return await ctx.send(
                     f"> **{ctx.author.display_name}, you cannot perform this interaction on yourself.**"
                 )
         link = random.choice(list_of_links)
         embed = discord.Embed(
             title=
             f"**{ctx.author.display_name}** {interaction} **{user.display_name}**",
             color=ex.get_random_color())
         if not await ex.u_patreon.check_if_patreon(ctx.author.id):
             embed.set_footer(
                 text=
                 f"Become a {await ex.get_server_prefix_by_context(ctx)}patreon to get rid of interaction cooldowns!"
             )
         embed.set_image(url=link[0])
         return await ctx.send(embed=embed)
     except Exception as e:
         log.console(e)
         return await ctx.send(
             f"> **{ctx.author.display_name}, there are no links saved for this interaction yet.**"
         )