async def scrape_videos(check=True): try: links = await ex.conn.fetch( "SELECT link, channelid FROM youtube.links") check = True except Exception as e: pass if check: try: for link in links: link_id = ex.first_result(await ex.conn.fetchrow( "SELECT id FROM youtube.links WHERE link = $1", link[0])) async with ex.session.get(link[0]) as r: if r.status == 200: page_html = await r.text() start_pos = page_html.find("viewCount") + 14 end_loc = start_pos while page_html[end_loc] != '\\': end_loc += 1 view_count = f"{int(page_html[start_pos:end_loc]):,} 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( link[1], f"> **UPDATE FOR <{link[0]}>: {view_count} -- {current_date}**" ) log.console("Updated Video Views Tracker") except Exception as e: log.console(e)
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)
async def addnoti(self, ctx, *, phrase): """Receive a DM whenever a phrase or word is said in the current server. [Format: %addnoti (phrase/word)]""" try: check_exists = ex.first_result(await ex.conn.fetchrow( "SELECT COUNT(*) FROM general.notifications WHERE guildid = $1 AND userid = $2 AND phrase = $3", ctx.guild.id, ctx.author.id, phrase.lower())) if check_exists: raise Exception await ex.conn.execute( "INSERT INTO general.notifications(guildid,userid,phrase) VALUES($1, $2, $3)", ctx.guild.id, ctx.author.id, phrase.lower()) ex.cache.user_notifications.append( [ctx.guild.id, ctx.author.id, phrase.lower()]) await ctx.send( f"> **{ctx.author.display_name}, I added `{phrase}` to your notifications.**" ) except AttributeError: return await ctx.send( f"> **{ctx.author.display_name}, You are not allowed to use this command in DMs.**" ) except: await ctx.send( f"> **{ctx.author.display_name}, You are already receiving notifications for `{phrase}`**" )
async def logadd(self, ctx, text_channel: discord.TextChannel = None): """Start logging a text channel. [Format: %logadd #text-channel]""" if not text_channel: text_channel = ctx.channel if not await ex.u_logging.check_if_logged(server_id=ctx.guild.id): return await ctx.send( f"> **The server must be logged in order to log a channel. ({await ex.get_server_prefix_by_context(ctx)}startlogging)**" ) if await ex.u_logging.check_if_logged(channel_id=text_channel.id): return await ctx.send( f"> **{text_channel.name} is already being logged.**") is_logging_channel = ex.first_result(await ex.conn.fetchrow( "SELECT COUNT(*) FROM logging.servers WHERE channelid = $1", text_channel.id)) if is_logging_channel: return await ctx.send( f"> **{text_channel.name} can not be logged since log messages are sent here.**" ) logging_id = await ex.u_logging.get_logging_id(ctx.guild.id) await ex.conn.execute( "INSERT INTO logging.channels (channelid, server) VALUES($1, $2)", text_channel.id, logging_id) ex.cache.list_of_logged_channels.append(text_channel.id) await ctx.send(f"> **{text_channel.name} is now being logged.**")
async def update_user_wins(self): if self.bracket_winner: wins = ex.first_result(await ex.conn.fetchrow("SELECT wins FROM biasgame.winners WHERE userid = $1 AND idolid = $2", self.host, self.bracket_winner.id)) if wins: await ex.conn.execute("UPDATE biasgame.winners SET wins = $1 WHERE userid = $2 AND idolid = $3", wins + 1, self.host, self.bracket_winner.id) else: await ex.conn.execute("INSERT INTO biasgame.winners(idolid, userid, wins) VALUES ($1, $2, $3)", self.bracket_winner.id, self.host, 1)
async def leaderboard(self, ctx, mode="server"): """Shows Top 10 Users server/global wide [Format: %leaderboard (global/server)][Aliases: leaderboards, lb]""" counter = ex.first_result(await ex.conn.fetchrow("SELECT count(UserID) FROM currency.Currency")) embed = discord.Embed(title=f"Currency Leaderboard ({mode.lower()})", color=0xffb6c1) embed.set_author(name="Irene", url=bot_website, icon_url='https://cdn.discordapp.com/emojis/693392862611767336.gif?v=1') embed.set_footer(text="Type %bal (user) to view their balance.", icon_url='https://cdn.discordapp.com/emojis/683932986818822174.gif?v=1') if counter == 0: await ctx.send("> **There are no users to display.**", delete_after=60) if counter > 0: amount = await ex.conn.fetch("Select UserID,Money FROM currency.Currency") sort_money = [] for sort in amount: if sort[0] in [member.id for member in ctx.guild.members] or mode == "global": new_user = [sort[0], int(sort[1])] sort_money.append(new_user) sort_money.sort(key=lambda x: x[1], reverse=True) count = 0 for a in sort_money: count += 1 user_id = a[0] money = a[1] user_name = ex.client.get_user(user_id) if count <= 10: embed.add_field(name=f"{count}) {user_name} ({user_id})", value=await ex.u_currency.shorten_balance(str(money)), inline=True) await ctx.send(embed=embed)
async def get_aces_used(user_id): """Get the aces that were changed from 11 to 1.""" aces_used = ex.first_result(await ex.conn.fetchrow( "SELECT acesused FROM blackjack.currentstatus WHERE userid = $1", user_id)) if aces_used is None: return [] return aces_used.split(',')
async def get_current_cards(user_id): """Get the current cards of a user.""" in_hand = ex.first_result(await ex.conn.fetchrow( "SELECT inhand FROM blackjack.currentstatus WHERE userid = $1", user_id)) if in_hand is None: return [] return in_hand.split(',')
async def get_balance(self, user_id): """Get current balance of a user.""" if not (await self.register_user(user_id)): money = await ex.conn.fetchrow( "SELECT money FROM currency.currency WHERE userid = $1", user_id) return int(ex.first_result(money)) else: return 100
async def register_user(user_id): """Register a user to the database if they are not already registered.""" count = ex.first_result(await ex.conn.fetchrow( "SELECT COUNT(*) FROM currency.Currency WHERE UserID = $1", user_id)) if not count: await ex.conn.execute( "INSERT INTO currency.Currency (UserID, Money) VALUES ($1, $2)", user_id, "100") return True
async def get_db_members_in_group(group_name=None, group_id=None): """Get the members in a specific group from database.""" if group_id is None: group_id = ex.first_result(await ex.conn.fetchrow( f"SELECT groupid FROM groupmembers.groups WHERE groupname = $1", group_name)) members = await ex.conn.fetch( "SELECT idolid FROM groupmembers.idoltogroup WHERE groupid = $1", group_id) return [member[0] for member in members]
async def get_if_user_voted(user_id): time_stamp = ex.first_result(await ex.conn.fetchrow( "SELECT votetimestamp FROM general.lastvoted WHERE userid = $1", user_id)) if time_stamp: tz_info = time_stamp.tzinfo current_time = datetime.datetime.now(tz_info) check = current_time - time_stamp if check.seconds <= 43200: return True return False
async def get_if_user_voted(user_id): time_stamp = ex.first_result(await ex.conn.fetchrow( "SELECT votetimestamp FROM general.lastvoted WHERE userid = $1", user_id)) if time_stamp: tz_info = time_stamp.tzinfo current_time = datetime.datetime.now(tz_info) check = current_time - time_stamp log.console( f"It has been {check.seconds} seconds since {user_id} voted.") return check.seconds <= 86400 log.console(f"{user_id} has not voted in the past 24 hours.")
async def update_command_counter(self): """Updates Cache for command counter and sessions""" ex.cache.command_counter = {} session_id = await self.get_session_id() all_commands = await ex.conn.fetch( "SELECT commandname, count FROM stats.commands WHERE sessionid = $1", session_id) for command_name, count in all_commands: ex.cache.command_counter[command_name] = count ex.cache.current_session = ex.first_result(await ex.conn.fetchrow( "SELECT session FROM stats.sessions WHERE date = $1", datetime.date.today()))
async def check_in_game( user_id, ctx ): # this is meant for when it is accessed by commands outside of BlackJack. """Check if a user is in a game.""" check = ex.first_result(await ex.conn.fetchrow( "SELECT COUNT(*) From blackjack.games WHERE player1 = $1 OR player2 = $1", user_id)) if check: await ctx.send( f"> **{ctx.author}, you are already in a pending/active game. Please type {await ex.get_server_prefix_by_context(ctx)}endgame.**" ) return True
async def set_reminder(remind_reason, remind_time, user_id): """Add reminder date to cache and db.""" await ex.conn.execute("INSERT INTO reminders.reminders(userid, reason, timestamp) VALUES ($1, $2, $3)", user_id, remind_reason, remind_time) remind_id = ex.first_result(await ex.conn.fetchrow( "SELECT id FROM reminders.reminders WHERE userid=$1 AND reason=$2 AND timestamp=$3 ORDER BY id DESC", user_id, remind_reason, remind_time)) user_reminders = ex.cache.reminders.get(user_id) remind_info = [remind_id, remind_reason, remind_time] if user_reminders: user_reminders.append(remind_info) else: ex.cache.reminders[user_id] = [remind_info]
async def get_google_drive_link(api_url): """Get the google drive link based on the api's image url.""" # commenting this out because now the file ids are in the api urls. # return ex.first_result( # await ex.conn.fetchrow("SELECT driveurl FROM groupmembers.apiurl WHERE apiurl = $1", str(api_url))) beginning_position = api_url.find("/idol/") + 6 ending_position = api_url.find("image.") if ending_position == -1: ending_position = api_url.find("video.") api_url_id = int(api_url[beginning_position:ending_position] ) # the file id hidden in the url return ex.first_result(await ex.conn.fetchrow( "SELECT link FROM groupmembers.imagelinks WHERE id = $1", api_url_id))
async def moveto(self, ctx, idol_id, link): """Moves a link to another idol. (Cannot be used for adding new links)[Format: %moveto (idol id) (link)]""" try: drive_link = ex.first_result(await ex.conn.fetchrow( "SELECT driveurl FROM groupmembers.apiurl WHERE apiurl = $1", link)) if not drive_link: return await ctx.send( f"> **{link} does not have a connection to a google drive link.**" ) await ex.conn.execute( "UPDATE groupmembers.imagelinks SET memberid = $1 WHERE link = $2", int(idol_id), drive_link) await ctx.send(f"> **Moved {link} to {idol_id} if it existed.**") except Exception as e: log.console(e) await ctx.send(f"> **{e}**")
async def set_level(user_id, level, command): """Set the level of a user for a specific command.""" async def update_level(): """Updates a user's level.""" await ex.conn.execute( f"UPDATE currency.Levels SET {command} = $1 WHERE UserID = $2", level, user_id) count = ex.first_result(await ex.conn.fetchrow( f"SELECT COUNT(*) FROM currency.Levels WHERE UserID = $1", user_id)) if not count: await ex.conn.execute( "INSERT INTO currency.Levels VALUES($1, NULL, NULL, NULL, NULL, 1)", user_id) await update_level() else: await update_level()
async def deletechannel(self, ctx): """Stop the current channel from being archived [Format: %deletechannel]""" try: count = ex.first_result(await ex.conn.fetchrow( "SELECT COUNT(*) FROM archive.ChannelList WHERE ChannelID = $1", ctx.channel.id)) if count == 0: await ctx.send( "> **This channel is not currently being archived.**") else: await ex.conn.execute( "DELETE FROM archive.ChannelList WHERE ChannelID = $1", ctx.channel.id) await ctx.send("> **This channel is no longer being archived**" ) except Exception as e: log.console(e) await ctx.send("> **There was an error.**")
async def scandrive(self, ctx, name="NULL", member_id=0): """Scan DriveIDs Table and update other tables.""" try: all_links = await ex.conn.fetch( "SELECT id, linkid, name FROM archive.DriveIDs") for pic in all_links: try: ID = pic[0] Link_ID = pic[1] Link_Name = pic[2] new_link = f"https://drive.google.com/uc?export=view&id={Link_ID}" all_names = await ex.conn.fetch( "SELECT Name FROM archive.ChannelList") if name == "NULL" and member_id == 0: for idol_name in all_names: idol_name = idol_name[0] if idol_name == Link_Name and ( idol_name != "Group" or idol_name != "MDG Group"): member_id1 = ex.first_result( await ex.conn.fetchrow( "SELECT ID FROM groupmembers.Member WHERE StageName = $1", idol_name)) await ex.conn.execute( "INSERT INTO groupmembers.uploadimagelinks VALUES($1,$2)", new_link, member_id1) await ex.conn.execute( "DELETE FROM archive.DriveIDs WHERE ID = $1", ID) elif Link_Name.lower() == name.lower(): await ex.conn.execute( "DELETE FROM archive.DriveIDs WHERE ID = $1", ID) await ex.conn.execute( "INSERT INTO groupmembers.uploadimagelinks VALUES($1,$2)", new_link, member_id) except Exception as e: log.console(e) await ctx.send(f"> **Completed Scan**") except Exception as e: log.console(e)
async def modify_channel_role(channel_id, server_id): """Add or Change a server's self-assignable role channel.""" def update_cache(): cache_info = ex.cache.assignable_roles.get(server_id) if not cache_info: ex.cache.assignable_roles[server_id] = { 'channel_id': channel_id } else: cache_info['channel_id'] = channel_id amount_of_results = ex.first_result(await ex.conn.fetchrow( "SELECT COUNT(*) FROM selfassignroles.channels WHERE serverid = $1", server_id)) if amount_of_results: update_cache() return await ex.conn.execute( "UPDATE selfassignroles.channels SET channelid = $1 WHERE serverid = $2", channel_id, server_id) await ex.conn.execute( "INSERT INTO selfassignroles.channels(channelid, serverid) VALUES($1, $2)", channel_id, server_id) update_cache()
async def get_db_idol_called(member_id): """Get the amount of times an idol has been called from the database.""" return ex.first_result(await ex.conn.fetchrow( "SELECT Count FROM groupmembers.Count WHERE MemberID = $1", member_id))
async def get_all_images_count(): """Get the amount of images the bot has.""" return ex.first_result( await ex.conn.fetchrow("SELECT COUNT(*) FROM groupmembers.imagelinks"))
async def addgroup(self, ctx, *, group_json): """Adds a group using the syntax from https://irenebot.com/addgroup.html [Format: %addgroup (json)]""" try: # load string to json group_json = json.loads(group_json) # set empty strings to NoneType for key in group_json: if not group_json.get(key): group_json[key] = None # create variables for values used more than once or that need to be adjusted. debut_date = group_json.get("Debut Date") disband_date = group_json.get("Disband Date") if debut_date: debut_date = (datetime.datetime.strptime( debut_date, "%Y-%m-%d")).date() if disband_date: disband_date = (datetime.datetime.strptime( disband_date, "%Y-%m-%d")).date() group_name = group_json.get("Group Name") # for security purposes, do not simplify the structure. await ex.conn.execute( "INSERT INTO groupmembers.unregisteredgroups(groupname, debutdate, disbanddate, " "description, twitter, youtube, melon, instagram, vlive, spotify, fancafe, " "facebook, tiktok, fandom, company, website, thumbnail, banner, gender, tags, " "notes) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, " "$16, $17, $18, $19, $20, $21)", group_name, debut_date, disband_date, group_json.get("Description"), group_json.get("Twitter"), group_json.get("Youtube"), group_json.get("Melon"), group_json.get("Instagram"), group_json.get("VLive"), group_json.get("Spotify"), group_json.get("Fancafe"), group_json.get("Facebook"), group_json.get("TikTok"), group_json.get("Fandom"), group_json.get("Company"), group_json.get("Website"), group_json.get("Avatar"), group_json.get("Banner"), group_json.get("Gender"), group_json.get("Tags"), group_json.get("Approver Notes")) # get the id of the data that was just added to db. query_id = ex.first_result(await ex.conn.fetchrow( "SELECT id FROM groupmembers.unregisteredgroups WHERE groupname = $1 ORDER BY id DESC", group_name)) # get the channel to send idol information to. channel = client.get_channel(keys.add_group_channel_id) # fetch if discord.py cache is not loaded. if not channel: channel = await ex.client.fetch_channel( keys.add_group_channel_id) title_description = f""" ================== Query ID: {query_id} Requester: {ctx.author.display_name} ({ctx.author.id}) ================== """ # Add all the key values to the title description for key in group_json: title_description += f"\n{key}: {group_json.get(key)}" # send embed to approval/deny channel embed = await ex.create_embed(title="New Unregistered Group", title_desc=title_description) msg = await channel.send(embed=embed) await msg.add_reaction(keys.check_emoji) await msg.add_reaction(keys.trash_emoji) await ctx.send( f"{ctx.author.display_name}, your request for adding this Group has been successfully sent." f" The Group's query ID is {query_id}.") except Exception as e: log.console(e) await ctx.send( f"Something Went Wrong. You may not understand the following error. Please report it.-> {e}" )
async def addidol(self, ctx, *, idol_json): """Adds an idol using the syntax from https://irenebot.com/addidol.html [Format: %addidol (json)]""" try: # load string to json idol_json = json.loads(idol_json) # set empty strings to NoneType for key in idol_json: if not idol_json.get(key): idol_json[key] = None # create variables for values used more than once or that need to be adjusted. birth_date = idol_json.get("Birth Date") if birth_date: birth_date = (datetime.datetime.strptime( birth_date, "%Y-%m-%d")).date() height = idol_json.get("Height") full_name = idol_json.get("Full Name") stage_name = idol_json.get("Stage Name") if height: height = int(height) # for security purposes, do not simplify the structure. await ex.conn.execute( "INSERT INTO groupmembers.unregisteredmembers(fullname, stagename, formerfullname, " "formerstagename, birthdate, birthcountry, birthcity, gender, description, height, " "twitter, youtube, melon, instagram, vlive, spotify, fancafe, facebook, tiktok, zodiac," " thumbnail, banner, bloodtype, tags, groupids, notes) VALUES ($1, $2, $3, $4, $5, $6, " "$7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, " "$25, $26)", full_name, stage_name, idol_json.get("Former Full Name"), idol_json.get("Former Stage Name"), birth_date, idol_json.get("Birth Country"), idol_json.get("Birth City"), idol_json.get("Gender"), idol_json.get("Description"), height, idol_json.get("Twitter"), idol_json.get("Youtube"), idol_json.get("Melon"), idol_json.get("Instagram"), idol_json.get("VLive"), idol_json.get("Spotify"), idol_json.get("Fancafe"), idol_json.get("Facebook"), idol_json.get("TikTok"), idol_json.get("Zodiac"), idol_json.get("Avatar"), idol_json.get("Banner"), idol_json.get("BloodType"), idol_json.get("Tags"), idol_json.get("Group IDs"), idol_json.get("Approver Notes")) # get the id of the data that was just added to db. query_id = ex.first_result(await ex.conn.fetchrow( "SELECT id FROM groupmembers.unregisteredmembers WHERE fullname = $1 AND stagename = $2 ORDER BY id DESC", full_name, stage_name)) # get the channel to send idol information to. channel = client.get_channel(keys.add_idol_channel_id) # fetch if discord.py cache is not loaded. if not channel: channel = await ex.client.fetch_channel( keys.add_idol_channel_id) title_description = f""" ================== Query ID: {query_id} Requester: {ctx.author.display_name} ({ctx.author.id}) ================== """ # Add all the key values to the title description for key in idol_json: title_description += f"\n{key}: {idol_json.get(key)}" # send embed to approval/deny channel embed = await ex.create_embed(title="New Unregistered Idol", title_desc=title_description) msg = await channel.send(embed=embed) await msg.add_reaction(keys.check_emoji) await msg.add_reaction(keys.trash_emoji) await ctx.send( f"{ctx.author.display_name}, your request for adding this Idol has been successfully sent." f"The Idol's query ID is {query_id}.") except Exception as e: log.console(e) await ctx.send( f"Something Went Wrong. You may not understand the following error. Please report it.-> {e}" )
async def check_player_standing(user_id): """Check if a player is standing.""" return ex.first_result(await ex.conn.fetchrow( "SELECT stand FROM blackjack.currentstatus WHERE userid = $1", user_id)) == 1
async def get_game_by_player(player_id): """Get the current game of a player.""" return ex.first_result(await ex.conn.fetchrow( "SELECT gameid FROM blackjack.games WHERE player1 = $1 OR player2 = $1", player_id))
async def get_card_name(card_id): """Get the name of a card.""" return ex.first_result(await ex.conn.fetchrow( "SELECT name FROM blackjack.cards WHERE id = $1", card_id))
async def get_player_total(user_id): """Get a player's total score.""" return ex.first_result(await ex.conn.fetchrow( "SELECT total FROM blackjack.currentstatus WHERE userid = $1", user_id))