# Discord.py | LFG/Event Bot # ################ Imports ######################## import asyncio import discord import discord.guild import discord.reaction import discord.user import discord.utils import discord_slash import pytz import pendulum import validators from discord.ext import commands from discord_slash.utils.manage_commands import create_option, create_choice, create_permission from discord_slash.utils.manage_components import create_select, create_select_option, create_button, create_actionrow from discord_slash import SlashCommand, SlashContext, ComponentContext from discord_slash.model import SlashCommandPermissionType, ButtonStyle import mysql.connector import logging import sys import datetime from datetime import timedelta from pytz import timezone import random import os import re import statistics from statistics import mean from statistics import mode # ################ Globals ######################## # Global Essentials from pip._vendor import requests asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) prefix = '/' client = commands.Bot(command_prefix=prefix, case_insensitive=True, intents=discord.Intents.all()) slash = SlashCommand(client, sync_commands=True) # Global MySQl Connection database = mysql.connector.connect( host=os.environ['SQL_HOST'], port=3306, user=os.environ['SQL_USER'], password=os.environ['SQL_PASS'], database=os.environ['SQL_DB'] ) sql_connect = database.cursor(dictionary=True, buffered=True) # Important URLs url_discord = 'https://discord.gg/Gm5FSXxxR3' url_website = 'https://valkyrin.github.io/LFG-Event-Bot-Website/' # Image URLs # Best AOE Gif https://cdn.discordapp.com/attachments/860960452074536982/873036668788178984/AOE2_Logo-GIF.gif img_tip = 'https://cdn.discordapp.com/attachments/860960452074536982/860960473980862505/tip.png' img_logo = 'https://cdn.discordapp.com/attachments/860960452074536982/873043699423125534/LFGEvent_Logo_-_Gif_-_Without_Text_-_Upscale.gif' img_logo_banner = 'https://cdn.discordapp.com/attachments/860960452074536982/873037013840982026/LFGEvent_Logo_-_Gif_-_Banner.gif' img_error = 'https://cdn0.iconfinder.com/data/icons/shift-free/32/Error-512.png' img_unknown = 'https://media3.giphy.com/media/eTVG7eVNnud8Y/giphy.gif?cid=ecf05e47w0ufpij8y4o8u7kyco0f3y37xa84f00rzn72ps89&rid=giphy.gif&ct=g' img_games = [ {'value': 'aoe2', 'img_url': 'https://media4.giphy.com/media/f3v2DFsPXgggFDQn9x/giphy.gif?cid=ecf05e47m1n8a1acsn869iimqwjl4ozyyv6aptfqxznttneo&rid=giphy.gif&ct=g', 'color': 0xC82621}, {'value': 'aoe3', 'img_url': 'https://static.ageofempires.com/aoe/wp-content/uploads/2020/10/aoe3de_AvailableNow_LogoOnly.jpg', 'color': 0xD19E60}, {'value': 'apex', 'img_url': 'https://c.tenor.com/-xpCOQ_0HXYAAAAC/apex-legends-intro.gif', 'color': 0xD42A2A}, {'value': 'arma3', 'img_url': 'https://media1.tenor.com/images/c2b7e5842a5b34a428eacfff447e4d40/tenor.gif?itemid=22604375', 'color': 0xffffff}, {'value': 'bf', 'img_url': 'https://c4.wallpaperflare.com/wallpaper/866/362/554/battlefield-battlefield-6-hd-wallpaper-preview.jpg', 'color': 0x35FCDE}, {'value': 'bl', 'img_url': 'https://4.bp.blogspot.com/-CGU7JQIZDqc/XRk2yy__fDI/AAAAAAAAH5o/96yu9mF_kUEl-EMVnhraVJeHCNqIzXALACKgBGAs/w4096-h2304-c/borderlands-3-uhdpaper.com-4K-42.jpg', 'color': 0xC76F0E}, {'value': 'codw', 'img_url': 'https://mp1st.com/wp-content/uploads/2020/03/call-of-duty-warzone.jpg', 'color': 0xffffff}, {'value': 'dayz', 'img_url': 'https://c.tenor.com/tpgqqTFcbtIAAAAC/day-z.gif', 'color': 0xD7D7D7}, {'value': 'd2', 'img_url': 'https://i.ytimg.com/vi/UzRkqOmi3j8/maxresdefault.jpg', 'color': 0x0F1521}, {'value': 'dota', 'img_url': 'https://thumbs.gfycat.com/ActualGleefulCoral-size_restricted.gif', 'color': 0x981D0E}, {'value': 'tark', 'img_url': 'https://cdn.vox-cdn.com/thumbor/ufVpeRQTU8eJ6Y96EgTDYieDmN8=/0x0:1521x647/1200x800/filters:focal(599x199:841x441)/cdn.vox-cdn.com/uploads/chorus_image/image/62696342/Escape_from_Tarkov_logo.0.png', 'color': 0x89826F}, {'value': 'fort', 'img_url': 'https://besthqwallpapers.com/Uploads/15-6-2018/55808/thumb2-fortnite-battle-royale-logo-2018-games-poster-fortnite.jpg', 'color': 0xF6D00F}, {'value': 'gtav', 'img_url': 'https://c.tenor.com/htFVFkpa_SQAAAAC/gta-v-grand-theft-auto.gif', 'color': 0x4F8700}, {'value': 'mc', 'img_url': 'https://media1.tenor.com/images/a07e60b2f11bbd495b448ae51962fc09/tenor.gif?itemid=22604396', 'color': 0x66A33B}, {'value': 'nms', 'img_url': 'https://i.ytimg.com/vi/RRpDn5qPp3s/maxresdefault.jpg', 'color': 0xD2302E}, {'value': 'over', 'img_url': 'https://thumbs.gfycat.com/CourteousReliableHalcyon-size_restricted.gif', 'color': 0xFFA200}, {'value': 'rust', 'img_url': 'https://c.tenor.com/-GjGhS7sVaMAAAAC/rust-west.gif', 'color': 0xD63F2B}, {'value': 'sins', 'img_url': 'https://cdn.cloudflare.steamstatic.com/steamcommunity/public/images/clans/3625261/b58712696ef9d6732f0c73d842674bae889d3329.png', 'color': 0x6A93A5}, {'value': 'star', 'img_url': 'https://www.stellaris.com/social-image.jpg', 'color': 0x202E29}, {'value': 'squad', 'img_url': 'https://cdn-ext.fanatical.com/production/product/1280x720/97ae216e-f277-4027-b7d6-869d94541e2f.jpeg', 'color': 0xFFC40B}, {'value': 'eso', 'img_url': 'https://i.pinimg.com/originals/f6/90/22/f69022daf0e98df0b3a25151cc04c93a.jpg', 'color': 0xFFECC1}, {'value': 'vh', 'img_url': 'https://www.allkeyshop.com/blog/wp-content/uploads/valheim.jpg', 'color': 0x15232C}, {'value': 'val', 'img_url': 'https://i.redd.it/w2k5s8br47i51.gif', 'color': 0xFF4654}, {'value': 'ww3', 'img_url': 'https://cdn.discordapp.com/attachments/860960452074536982/889234261469720649/WW3_GIF.gif', 'color': 0xEC1C24}, {'value': 'other', 'img_url': 'https://media1.tenor.com/images/e8ceda99343f91cd9a33687e276ed94c/tenor.gif?itemid=22604447', 'color': 0x808080} ] # Embed Colors clr_error = 15158332 # Embed Text txt_footer = 'Running into issues or have a question?\nClick the message title to join our Discord!' txt_interact = '❕┃**Interaction Completed**' # Bot Tips tip_host = '\n\n**Team Organizer Options**:\n• `🔒 Close` will remove your post and inform Team or Event Members it is time to start.\n• `🛑 Disband` will remove your post and inform Team or Event Members you intend to no longer play.' tip_member = '\n\n**Team Member Options**:\n• `✔️ Join` will add you to the Team\'s or Event\'s Members, if an LFG Post then the Team Organizer will be informed.\n• `❌ Leave` will remove you from the Team\'s or Event\'s Members, if an LFG Post then the Team Organizer will be informed.' # LFG Post Buttons post_buttons = [create_actionrow( create_button(style=ButtonStyle.blurple, label="Join", emoji='✔️', custom_id='post_join'), create_button(style=ButtonStyle.danger, label="Leave", emoji='❌', custom_id='post_leave'), create_button(style=ButtonStyle.secondary, label="Close", emoji='🔒', custom_id='post_close'), create_button(style=ButtonStyle.secondary, label="Disband", emoji='🛑', custom_id='post_disband'), )] # Thread Button thread_button = [create_actionrow( create_button(style=ButtonStyle.secondary, label="Close Thread", emoji='🔒', custom_id='thread_close'), )] # Slash Dropdowns setup_option = create_select( custom_id='setup_option', options=[ create_select_option(label="Setup Guide", description='Guide on initializing LFG/Event Features', value="guide", emoji="❓"), create_select_option(label="LFG/Event Initialization", description='Create Channels, choose LFG & Event Game Formats.', value="bot-init", emoji="📝"), ], placeholder="Choose to provide a guide or to initialize!", min_values=1, max_values=1, ) setup_global_search_option_yes = create_select( custom_id='setup_global_search_option', options=[ create_select_option(label="Opt-In", description='Server\'s LFG & Events visible on Global Network', value="global-search_yes", emoji="✔️"), create_select_option(label="Stay Opt-Out", description='Server removed from Global LFG & Event Network', value="global-search_stayno", emoji="❌") ], placeholder="Choose to Opt-In or Out of our Global LFG & Event Network!", min_values=1, max_values=1, ) setup_global_search_option_no = create_select( custom_id='setup_global_search_option', options=[ create_select_option(label="Stay Opt-In", description='Server\'s LFG & Events visible on Global Network', value="global-search_stayyes", emoji="✔️"), create_select_option(label="Opt-Out", description='Server removed from Global LFG & Event Network', value="global-search_no", emoji="❌") ], placeholder="Choose to Opt-In or Out of our Global LFG & Event Network!", min_values=1, max_values=1, ) setup_event_perms_option_unrestrict = create_select( custom_id='setup_global_search_option', options=[ create_select_option(label="Restrict Events", description='Users with Moderation permissions can only host', value="event-perms-restrict", emoji="🔒"), create_select_option(label="Remain Un-Restricting", description='Everyone can host Events', value="event-perms-stayunrestrict", emoji="🔓") ], placeholder="Choose to Restrict or Unrestrict the posting of events!", min_values=1, max_values=1, ) setup_event_perms_option_restrict = create_select( custom_id='setup_global_search_option', options=[ create_select_option(label="Remain Restricting", description='Users with Moderation permissions can only host', value="event-perms-stayrestrict", emoji="🔒"), create_select_option(label="Un-Restrict Events", description='Everyone can host Events', value="event-perms-unrestrict", emoji="🔓") ], placeholder="Choose to Restrict or Unrestrict the posting of events!", min_values=1, max_values=1, ) lfg_format_option_init = create_select( custom_id='lfg_format_option_init', options=[ create_select_option(label="Add LFG Formats", description='Add to your server\'s supported LFG/Event Formats!', value="lfg_format_add", emoji="✔️"), ], placeholder="Choose your first LFG/Event game formats for users to advertise for!", min_values=1, max_values=1, ) lfg_format_option_both = create_select( custom_id='lfg_format_option_both', options=[ create_select_option(label="Add LFG Formats", description='Add to your server\'s supported LFG/Event Formats!', value="lfg_format_add", emoji="✔️"), create_select_option(label="Remove LFG Formats", description='Remove LFG/Event Formats your server supports!', value="lfg_format_remove", emoji="❌"), ], placeholder="Choose or remove LFG/Event Game Formats for users to advertise for!", min_values=1, max_values=1, ) lfg_games_add = create_select( custom_id='lfg_games_add', options=[ create_select_option(label="Age of Empires 2", description='Medieval RTS, CO-OP & Mass-Multiplayer Capable', value="aoe2", emoji="⚔️"), create_select_option(label="Age of Empires 3", description='Colonial Era RTS, CO-OP & Mass-Multiplayer Capable', value="aoe3", emoji="⚓"), create_select_option(label="Apex Legends", description='Mass-Multiplayer, TitanFall Themed Battle Royale', value="apex", emoji="💪"), create_select_option(label="Arma 3", description='Modern Tactical FPS, Mass-Multiplayer Capable', value="arma3", emoji="🔫"), create_select_option(label="Battlefield Series", description='Vehicle & Infantry Focused, First Person Shooter', value="bf", emoji="🗡️"), create_select_option(label="Borderlands Series", description='Open World, Sci-Fi Gritty First-Person Looter & Shooter', value="bl", emoji="🪐"), create_select_option(label="Call of Duty Warzone", description='Modern Fast-Paced First Persion, Battle Royale', value="codw", emoji="🎮"), create_select_option(label="DayZ", description='Mass-Multiplayer Zombie Survival Game', value="dayz", emoji="🧟"), create_select_option(label="Destiny 2", description='Sci-Fi Mass-Multiplayer Online Game, First-Person Shooter', value="d2", emoji="🧙"), create_select_option(label="Dota 2", description='Fantasy Multiplayer Online Battle Arena', value="dota", emoji="👹"), create_select_option(label="Escape From Tarkov", description='Survival Realistic, Mass-Multiplayer Online-Game', value="tark", emoji="🥽"), create_select_option(label="Fortnite Battle Royale", description='Battle Royale, Third Person Shooter, Mass-Multiplayer Capable', value="fort", emoji="🏰"), create_select_option(label="Grand Theft Auto V", description='Open World, Modern Action-Adventure Simulator', value="gtav", emoji="🚓"), create_select_option(label="Minecraft", description='Block-Building Sandbox, Mass-Multiplayer Capable', value="mc", emoji="🌎"), create_select_option(label="No Mans Sky", description='Sci-Fi Mass-Multiplayer Capable, Survival Sandbox Game', value="nms", emoji="🚀"), create_select_option(label="Overwatch", description='Team-Based Multiplayer First Person Hero Shooter', value="over", emoji="🦸"), create_select_option(label="Rust", description='Multiplayer-Only Realistic Survival Sandbox Game', value="rust", emoji="🌲"), create_select_option(label="Sins of a Solar Empire: Rebellion", description='Sci-Fi 4X Grand Strategy, Competitive RTS', value="sins", emoji="🌍"), create_select_option(label="Stellaris", description='4X Grand Strategy, Space Exploration RTS', value="star", emoji="🌌"), create_select_option(label="Squad", description='Modern Realistic FPS, Mass-Multiplayer Capable', value="squad", emoji="🔧"), create_select_option(label="The Elder Scrolls: Online", description='Fantasy & Medieval Focused Open World MMORPG', value="eso", emoji="🐎"), create_select_option(label="Valheim", description='Medieval Survival, Indie, Role-Playing, & Adventure Game', value="vh", emoji="🪓"), create_select_option(label="Valorant", description='Free-To-Play, Competitive First Person Hero Shooter', value="val", emoji="🎖️"), create_select_option(label="World War 3", description='Modern FPS, Combined Arms Mass-Multiplayer Capable', value="ww3", emoji="💥"), create_select_option(label="Other", description='Select to allow LFG for games not listed above', value="other", emoji="❔"), ], placeholder="Choose accepted LFG/Event Game Formats for users to advertise for!", min_values=1, max_values=25, ) lfg_games_remove = create_select( custom_id='lfg_games_remove', options=lfg_games_add['options'], placeholder=lfg_games_add['placeholder'], min_values=lfg_games_add['min_values'], max_values=lfg_games_add['max_values'], ) lfg_games_values = [] for x in lfg_games_add['options']: lfg_games_values.append([x.get(keys) for keys in ["value", "label"]]) # Slash LFG Draft host_options = [ create_option( name="type", description="❔ Select type of post to submit:", option_type=3, required=True, choices=[ create_choice( name="LFG Post", value="type_lfg" ), create_choice( name="Event Post", value="type_event" )]), create_option( name="platform", description="🕹️ Select platform of game to LFG for:", option_type=3, required=True, choices=[ create_choice( name="PC: Other", value="plat_pc_other" ), create_choice( name="PC: Steam", value="plat_pc_steam" ), create_choice( name="PC: Origin", value="plat_pc_origin" ), create_choice( name="PC: Blizzard.net", value="plat_pc_blizzard" ), create_choice( name="Playstation: 4", value="plat_ps_4" ), create_choice( name="Playstation: 5", value="plat_ps_5" ), create_choice( name="Xbox: One", value="plat_xbox_one" ), create_choice( name="Xbox: Series X/S", value="plat_xbox_series" ), create_choice( name="Nintendo Switch", value="plat_switch" ), create_choice( name="Other", value="plat_other" )]), create_option( name="game", description="🎮 Select game to LFG for:", option_type=3, required=True, choices=[ create_choice( name=lfg_games_add['options'][0]['label'], value=lfg_games_add['options'][0]['value'] ), create_choice( name=lfg_games_add['options'][1]['label'], value=lfg_games_add['options'][1]['value'] ), create_choice( name=lfg_games_add['options'][2]['label'], value=lfg_games_add['options'][2]['value'] ), create_choice( name=lfg_games_add['options'][3]['label'], value=lfg_games_add['options'][3]['value'] ), create_choice( name=lfg_games_add['options'][4]['label'], value=lfg_games_add['options'][4]['value'] ), create_choice( name=lfg_games_add['options'][5]['label'], value=lfg_games_add['options'][5]['value'] ), create_choice( name=lfg_games_add['options'][6]['label'], value=lfg_games_add['options'][6]['value'] ), create_choice( name=lfg_games_add['options'][7]['label'], value=lfg_games_add['options'][7]['value'] ), create_choice( name=lfg_games_add['options'][8]['label'], value=lfg_games_add['options'][8]['value'] ), create_choice( name=lfg_games_add['options'][9]['label'], value=lfg_games_add['options'][9]['value'] ), create_choice( name=lfg_games_add['options'][10]['label'], value=lfg_games_add['options'][10]['value'] ), create_choice( name=lfg_games_add['options'][11]['label'], value=lfg_games_add['options'][11]['value'] ), create_choice( name=lfg_games_add['options'][12]['label'], value=lfg_games_add['options'][12]['value'] ), create_choice( name=lfg_games_add['options'][13]['label'], value=lfg_games_add['options'][13]['value'] ), create_choice( name=lfg_games_add['options'][14]['label'], value=lfg_games_add['options'][14]['value'] ), create_choice( name=lfg_games_add['options'][15]['label'], value=lfg_games_add['options'][15]['value'] ), create_choice( name=lfg_games_add['options'][16]['label'], value=lfg_games_add['options'][16]['value'] ), create_choice( name=lfg_games_add['options'][17]['label'], value=lfg_games_add['options'][17]['value'] ), create_choice( name=lfg_games_add['options'][18]['label'], value=lfg_games_add['options'][18]['value'] ), create_choice( name=lfg_games_add['options'][19]['label'], value=lfg_games_add['options'][19]['value'] ), create_choice( name=lfg_games_add['options'][20]['label'], value=lfg_games_add['options'][20]['value'] ), create_choice( name=lfg_games_add['options'][21]['label'], value=lfg_games_add['options'][21]['value'] ), create_choice( name=lfg_games_add['options'][22]['label'], value=lfg_games_add['options'][22]['value'] ), create_choice( name=lfg_games_add['options'][23]['label'], value=lfg_games_add['options'][23]['value'] ), create_choice( name=lfg_games_add['options'][24]['label'], value=lfg_games_add['options'][24]['value'] )]), create_option( name="activity", description="⚽ What gamemode you intend to play:", option_type=3, required=True), create_option( name="description", description="💬 Brief overview of your plans:", option_type=3, required=True), create_option( name="size", description="#️⃣ Define the number of players you are looking for: (Digits Only)", option_type=4, required=True), create_option( name="username", description="📛 Host Username/ID so players may add you in-game: (Friend Code, Invite Link, In-Game Name, etc.)", option_type=3, required=True), create_option( name="experience", description="💼 Desired experience of players who join: (ELO, (Novice/Veteran), Rank, Etc.)", option_type=3, required=False), create_option( name="server", description="🖥️ Server IP, Lobby/Game ID, Etc. for players to direct join:", option_type=3, required=False), create_option( name="date", description="🕐 Date, Time, & Timezone Code to start the `Event` Post (YYYY-MM-DD HH:MM ZONE) - shorturl.at/mrA47:", option_type=3, required=False), create_option( name="banner", description="🖼️ A link to an image for your `Event` Post's banner:", option_type=3, required=False)] # Slash Global LFG & Event Network # create_option( # name="members", # description="🧑 List of people in event (WARNING: `DEBUG OPTION`)", # option_type=3, # required=False), post_modify = [ create_option( name="post_id", description="💬 Provide a Message ID, numbers ONLY (Options or right-click the desired message, select `Copy Id`):", option_type=3, required=True), create_option( name=host_options[1]['name'], description=host_options[1]['description'], option_type=3, required=False, choices=host_options[1]['choices']), create_option( name=host_options[2]['name'], description=host_options[2]['description'], option_type=3, required=False, choices=host_options[2]['choices']), create_option( name=host_options[3]['name'], description=host_options[3]['description'], option_type=3, required=False), create_option( name=host_options[4]['name'], description=host_options[4]['description'], option_type=3, required=False), create_option( name=host_options[5]['name'], description=host_options[5]['description'], option_type=3, required=False), create_option( name=host_options[6]['name'], description=host_options[6]['description'], option_type=3, required=False), create_option( name=host_options[7]['name'], description=host_options[7]['description'], option_type=3, required=False), create_option( name=host_options[8]['name'], description=host_options[8]['description'], option_type=3, required=False), create_option( name=host_options[9]['name'], description=host_options[9]['description'], option_type=3, required=False), create_option( name=host_options[10]['name'], description=host_options[10]['description'], option_type=3, required=False)] # Slash Global LFG & Event Network global_search = [ create_option( name="choice", description="🌎 Select network to search:", option_type=3, required=True, choices=[ create_choice( name="Event Posts", value="type_events" ), create_choice( name="LFG Posts", value="type_lfg" )]), create_option( name=host_options[2]['name'], description=host_options[2]['description'], option_type=3, required=host_options[2]['required'], choices=host_options[2]['choices']), create_option( name=host_options[1]['name'], description=host_options[1]['description'], option_type=3, required=False, choices=host_options[1]['choices'])] # Notify Me System notify_chocies = [ create_option( name="choice", description="🌎 Select post type to be notified for:", option_type=3, required=True, choices=[ create_choice( name="Event Posts", value="type_events" ), create_choice( name="LFG Posts", value="type_lfg" )]), create_option( name=host_options[2]['name'], description='🎮 Select game to be notified for:', option_type=3, required=host_options[2]['required'], choices=host_options[2]['choices']), create_option( name=host_options[1]['name'], description='🕹️ Select platform of game to be notified for:', option_type=3, required=False, choices=host_options[1]['choices'])] # Logging # logger = logging.getLogger('discord') # logger.setLevel(logging.DEBUG) # handler = logging.FileHandler(filename='./logs/' + str(datetime.datetime.now().strftime('%Y.%m.%d_%H.%M.%S')) + '.log', encoding='utf-8', mode='w') # handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')) # logger.addHandler(handler) # ################# MySQL Commit Database ################### @client.event async def mysql_commit(sql, val): global database global sql_connect # Refresh MySQl connection database = mysql.connector.connect( host=os.environ['SQL_HOST'], port=3306, user=os.environ['SQL_USER'], password=os.environ['SQL_PASS'], database=os.environ['SQL_DB'] ) sql_connect = database.cursor(dictionary=True, buffered=True) sql_connect.execute(sql, val) database.commit() # ################# MySQL Update Guilds ################### @client.event async def sql_update_guilds(): print('Updating Guilds Table: ' + str(datetime.datetime.now())) for guild in client.guilds: sql = "SELECT guild_id FROM guilds WHERE guild_id = %s" val = (guild.id,) sql_connect.execute(sql, val) sql_fetch = sql_connect.fetchone() if sql_fetch is None: print('New guild found: ' + str(guild.name)) sql = "INSERT INTO guilds (guild_id, guild_owner_id) VALUES (%s, %s)" val = (guild.id, guild.owner.id) await mysql_commit(sql=sql, val=val) # ################# MySQL Purge posts ################### @client.event async def sql_purge_posts(exceptions): if exceptions: sql_connect.execute("SELECT * FROM posts") posts = sql_connect.fetchall() for idx, post in enumerate(posts): if posts[idx]['post_id'] not in exceptions: sql = "DELETE FROM posts WHERE post_id = %s" val = (posts[idx]['post_id'],) await mysql_commit(sql=sql, val=val) else: sql_connect.execute("TRUNCATE TABLE posts") database.commit() # ################ On Ready ######################## @client.event async def on_ready(): print(f'{client.user.name} has connected to Discord: ' + str(datetime.datetime.now())) await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name='ℹ️ - `/setup` for help ')) await sql_update_guilds() saved_events = [] for guild in client.guilds: sql = "SELECT global_search_invite, channel_lfgPosts_id, global_search FROM guilds WHERE global_search = %s AND guild_id = %s" val = ('yes', str(guild.id)) await mysql_commit(sql=sql, val=val) invite_lfg = sql_connect.fetchall() if invite_lfg: if invite_lfg[0]['global_search'] == 'yes': try: await client.fetch_invite(invite_lfg[0]['global_search_invite']) except: if (client.get_channel(int(invite_lfg[0]['channel_lfgPosts_id']))) is not None: lfg_posts_channel = client.get_channel(int(invite_lfg[0]['channel_lfgPosts_id'])) globalinvite = await lfg_posts_channel.create_invite(max_uses=0, max_age=0, unique=True) sql = "UPDATE guilds SET global_search_invite = %s WHERE guild_id = %s" val = (str(globalinvite), guild.id) await mysql_commit(sql=sql, val=val) else: sql = "UPDATE guilds SET global_search_invite = %s WHERE guild_id = %s" val = ('', str(guild.id)) await mysql_commit(sql=sql, val=val) pass if (client.get_channel(int(invite_lfg[0]['channel_lfgPosts_id']))) is not None: await silent_expired_posts(client.get_channel(int(invite_lfg[0]['channel_lfgPosts_id'])), type='type_lfg') # Mark - LFG Posts Removals PT1 elif not invite_lfg: sql = "SELECT channel_lfgPosts_id FROM guilds WHERE guild_id = %s" val = (str(guild.id),) await mysql_commit(sql=sql, val=val) sql_query = sql_connect.fetchall() if (client.get_channel(int(sql_query[0]['channel_lfgPosts_id']))) is not None: await silent_expired_posts(client.get_channel(int(sql_query[0]['channel_lfgPosts_id'])), type='type_lfg') sql = "SELECT channel_events_id FROM guilds WHERE guild_id = %s" val = (guild.id,) await mysql_commit(sql=sql, val=val) channels = sql_connect.fetchall() if (client.get_channel(int(channels[0]['channel_events_id']))) is not None: await silent_expired_posts(client.get_channel(int(channels[0]['channel_events_id'])), type='type_event') if client.get_channel(int(channels[0]['channel_events_id'])) is not None: events_channel = client.get_channel(int(channels[0]['channel_events_id'])) async for msg in events_channel.history(): try: if (msg.embeds[0].title == 'Event Organizer:') & (msg.author.id == client.user.id): if not ('Event Now Starting' in msg.content): fmt = "%Y-%m-%d %H:%M" event_time = msg.embeds[0].fields[-1].value.replace('[', '').replace(']', '').partition('(') event_time = datetime.datetime.utcfromtimestamp(int(event_time[0].replace('<t:', '').replace(':F>', ''))) event_time = datetime.datetime.strptime(event_time.strftime(fmt), '%Y-%m-%d %H:%M') time_now = datetime.datetime.now(timezone('UTC')) time_now = datetime.datetime.strptime(time_now.strftime(fmt), '%Y-%m-%d %H:%M') starttime = (event_time - time_now).total_seconds() if not (time_now >= event_time): # Repost and Update Log new_msg = await events_channel.send(embed=msg.embeds[0], components=post_buttons, delete_after=starttime) sql = "UPDATE posts SET post_id = %s WHERE post_id = %s" val = (new_msg.id, msg.id) await mysql_commit(sql=sql, val=val) saved_events.append(str(new_msg.id)) await msg.delete() except (AttributeError, IndexError): pass await sql_purge_posts(saved_events) @client.event async def on_guild_join(guild): sql = "SELECT guild_id, channel_lfgPosts_id, channel_events_id FROM guilds WHERE guild_id = %s" val = (guild.id,) await mysql_commit(sql=sql, val=val) sql_query = sql_connect.fetchall() if sql_query: embed_message = discord.Embed(title='☑️┃Server Re-Joined', description='Thank you for re-inviting `' + client.user.name + '` to `' + guild.name + '`.', color=random.randint(0, 0xffffff)) else: embed_message = discord.Embed(title='☑️┃Server New-Join', description='Thank you for inviting `' + client.user.name + '` to `' + guild.name + '`.', color=random.randint(0, 0xffffff)) embed_message.add_field(name='▬▬▬▬ COMMANDS OVERVIEW ▬▬▬▬', value='`' + client.user.name + '` provides LFG & Event services of which are configured and accessible through slash commands. Type `/` in your server to use them if the bot is online.\n• `/host` - Used to submit an LFG or Event Post for this server\'s supported games!\n• `/notify` - Used to setup Notifications for LFG or Events of specific Games & Platforms!\n• `/search` - Used to browse the Global LFG & Event Network of Posts from other Servers!\n• `/setup` - Used to provide a guide on and initialize LFG/Event features!\n• `/support` - Used to provide a guide on supported games for this server\'s LFG & Event features!', inline=False) embed_message.add_field(name='▬▬▬▬ SETUP GUIDE PT.1 ▬▬▬▬', value='In order to use LFG or Event services, appropriate channels and server settings must first be configured using `/setup`. The server settings are re-configurable at anytime by rerunning `/setup`.\n• **Step 1:** To begin type `/setup` in any channel. Upon prompt choose `LFG/Event Initialization` from the dropdown menu.\n• **Step 2:** You will be offered to restrict the posting of events to Admins/Moderators only. Restricting means only those with a role providing a special permission related to message or channel modification will be able to post an event.\n• **Step 3:** You will be given the option to Opt-Into the Global LFG & Event Network. If you Opt-In to the Network this bot will be authorized to maintain a Invite link to your server. All posted LFG Teams & Events will then appear upon using `/search` or `/notify` for users in any server.', inline=False) embed_message.add_field(name='▬▬▬▬ SETUP GUIDE PT.2 ▬▬▬▬', value='• **Step 4:** Upon choosing a Network option, the bot will create two channels `📑┃lfg-posts` and `📅┃events` to list submitted posts from users using `/host`.\n• **Step 5:** Add or remove LFG Formats to control what games LFG Teams and Events can list for.\n• **Step 6:** Upon choosing formats setup is now complete! Use `/host` in nay channel to create a new LFG Team or Post. Submitted posts are translated into an embed which appear in the created channels. Feel free to modify the channel names or move them to a category, users without Moderator/Admin permissions cannot talk in said channels.', inline=False) status_lfg = '\n• 📑 **LFG Posts Channel**: **❌ No Channel Exists, run `/setup` to create.**' if sql_query: if discord.utils.get(guild.channels, id=int(sql_query[0]['channel_lfgPosts_id'])) is not None: lfg_channel = discord.utils.get(guild.channels, id=int(sql_query[0]['channel_lfgPosts_id'])) status_lfg = '\n• 📑 **LFG Posts Channel**: Active - <#' + str(lfg_channel.id) + '>' status_event = '\n• 📅 **Event Posts Channel**: **❌ No Channel Exists, run `/setup` to create.**' if sql_query: if discord.utils.get(guild.channels, id=int(sql_query[0]['channel_events_id'])) is not None: event_channel = discord.utils.get(guild.channels, id=int(sql_query[0]['channel_events_id'])) status_event = '\n• 📅 **Event Posts Channel**: Active - <#' + str(event_channel.id) + '>' embed_message.add_field(name='▬▬▬▬ CHANNEL STATUSES ▬▬▬▬', value='See below the status of the channels responsible for LFG & Event posts. Running `/setup` will initialize said channels if they do not currently exist.' + status_lfg + status_event, inline=False) embed_message.add_field(name='▬▬▬▬ HELPFUL TIPS ▬▬▬▬', value='• If a `/` command is not working, ensure the bot is online, then attempt to use your `Enter` or `Arrow` keys instead of your mouse to select the command from the list.\n• Attempt to remove then re-invite the bot to your server if issues with commands persist as a sort of refresh.\n• If the bot is removed from your server, it will retain selected server settings and channels upon re-join preventing the need to re-run `/setup`.\n• Maintenance for the bot will be conducted weekly Sundays 20:00 EDT at which time the bot will restart to apply new features and bug fixes.\n• Support or Suggestions for the bot can be directed to our [Support Server](' + url_discord + ') or to the Primary Developer <@224349699061186570>.\n• Important announcements from the Developers will be funneled through the bot via DM to server owners, please keep your inbox settings open.\n• The bot is able to leave servers on its own whilst informing server owners, this can happen due to important updates requriring re-join.', inline=False) embed_message.add_field(name='▬▬▬▬ WHERE TO FIND US ▬▬▬▬', value='If you would like further information regarding our service consider joining our support server or our offical homepage.\n• [**Official Homepage**](https://valkyrin.github.io/LFG-Event-Bot-Website/)\n• [**Support Server**](https://discord.gg/Gm5FSXxxR3)\n• [**Invitation Link**](https://discord.com/oauth2/authorize?client_id=860300499177832458&scope=bot%20applications.commands&permissions=260654497393)\n• [**Privacy Policy**](https://valkyrin.github.io/LFG-Event-Bot-Website/privacy)', inline=False) embed_message.set_image(url=img_logo_banner) try: embed_message.set_author(name=guild.name, url=url_discord, icon_url=guild.icon.url) except (AttributeError, IndexError): embed_message.set_author(name=guild.name, url=url_discord, icon_url=img_unknown) pass embed_message.timestamp = datetime.datetime.now() embed_message.set_footer(text=txt_footer + str(embed_message.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) try: await guild.owner.send(embed=embed_message) except: pass try: await guild.system_channel.send(embed=embed_message) except: print(f'❗┃Possibly no System Channel? {guild.name} @ ' + str(datetime.datetime.now())) pass print(f'{client.user.name} has joined Guild: ' + str(guild.name) + ' @ ' + str(datetime.datetime.now())) sql = "INSERT INTO connection_log (guild_action, guild_id, guild_name, datetime) VALUES (%s, %s, %s, %s)" val = ('join', guild.id, guild.name, datetime.datetime.now()) await mysql_commit(sql=sql, val=val) await sql_update_guilds() @client.event async def on_guild_remove(guild): print(f'{client.user.name} was removed from Guild: ' + str(guild.name) + ' @ ' + str(datetime.datetime.now())) sql = "DELETE FROM posts WHERE guild_id = %s" val = (guild.id,) await mysql_commit(sql=sql, val=val) sql = "INSERT INTO connection_log (guild_action, guild_id, guild_name, datetime) VALUES (%s, %s, %s, %s)" val = ('remove', guild.id, guild.name, datetime.datetime.now()) await mysql_commit(sql=sql, val=val) @client.event async def on_member_remove(member): # Check if in LFG or Event posts if so remove or cancel sql = "SELECT channel_lfgPosts_id FROM guilds WHERE guild_id = %s" val = (member.guild.id,) await mysql_commit(sql=sql, val=val) sql_query = sql_connect.fetchall() if client.get_channel(int(sql_query[0]['channel_lfgPosts_id'])) is not None: lfg_posts_channel = client.get_channel(int(sql_query[0]['channel_lfgPosts_id'])) async for msg in lfg_posts_channel.history(): try: if msg.embeds[0].title == 'Team Organizer:': # Host Work if str(member.id) in msg.embeds[0].description: # No Members to Inform if msg.embeds[0].fields[0].name != 'Team Members:': sql = "SELECT * FROM posts WHERE post_id = %s" val = (msg.id,) await mysql_commit(sql=sql, val=val) sql_query = sql_connect.fetchall() if sql_query is not None: if sql_query[0]['thread_id'] != '': thread_id = sql_query[0]['thread_id'] if msg.channel.get_thread(int(thread_id)): message_thread = msg.channel.get_thread(int(thread_id)) await message_thread.delete() sql = "DELETE FROM posts WHERE post_id = %s" val = (msg.id,) await mysql_commit(sql=sql, val=val) await msg.delete() # Members to Inform if msg.embeds[0].fields[0].name == 'Team Members:': sql = "SELECT * FROM posts WHERE post_id = %s" val = (msg.id,) await mysql_commit(sql=sql, val=val) sql_query = sql_connect.fetchall() if sql_query is not None: members = sql_query[0]['post_members'] member_ids = members.replace('<@', '').replace('>', '') members_list = member_ids.split() for user_id in members_list: try: await member.guild.get_member(int(user_id)).send(content='🛑┃**Team Disbanded**:\n• Team Organizer has left the server thus their team has been disbanded and will cease playing.\n• You do not need to contact them, feel free to instead join a new Team anytime.', embed=msg.embeds[0]) except: pass if sql_query[0]['thread_id'] != '': thread_id = sql_query[0]['thread_id'] if msg.channel.get_thread(int(thread_id)): message_thread = msg.channel.get_thread(int(thread_id)) await message_thread.delete() sql = "DELETE FROM posts WHERE post_id = %s" val = (msg.id,) await mysql_commit(sql=sql, val=val) await msg.delete() # Participant Work if (str(member.id) not in msg.embeds[0].description) & (str(member.id) in msg.embeds[0].fields[0].value): sql = "SELECT * FROM posts WHERE post_id = %s" val = (msg.id,) await mysql_commit(sql=sql, val=val) sql_query = sql_connect.fetchall() if sql_query is not None: organizer_id = sql_query[0]['post_organizer'] organizer_id = organizer_id.replace('<@', '').replace('>', '') organizer = client.get_user(int(organizer_id)) members = sql_query[0]['post_members'] member_ids = members.replace('<@', '').replace('>', '') members_list = member_ids.split() members_list.remove(str(member.id)) members_list_len = len(members_list) button_origin_msg = [create_actionrow(create_button(style=ButtonStyle.URL, label='Origin Post', emoji='📑', url=str(msg.jump_url)))] try: await organizer.send(content='❌┃**Team Member Left**:\n• Team Member <@' + str(member.id) + '> has been removed from your team due to leaving the server, you do not need to contact them. You will be alerted if a new user joins your team.' + tip_host, embed=msg.embeds[0], components=button_origin_msg) except: pass member_field = '' member_field_sql = '' # If nobody remains if members_list_len == 0: msg.embeds[0].remove_field(0) member_field_sql = member_field # If less than 40 if (members_list_len <= 40) & (members_list_len > 0): for idx, member in enumerate(members_list): if idx == 0: member_field = '<@' + member + '>' elif idx > 0: member_field = ' <@' + member + '>' msg.embeds[0].set_field_at(0, name="Team Members:", value=member_field, inline=False) member_field_sql = member_field # If more than 40 elif members_list_len > 40: for idx, member in enumerate(members_list): if idx == 0: member_field = member_field + '<@' + member + '>' elif (idx > 0) & (idx <= 40): member_field = member_field + ' <@' + member + '>' elif idx > 40: if idx == 41: member_field_sql = member_field member_field_sql = member_field_sql + ' <@' + member + '>' member_field = member_field + ' Plus ' + str(int(members_list_len - 40)) + ' More...' msg.embeds[0].set_field_at(0, name="Team Members:", value=member_field, inline=False) for idx, field in enumerate(msg.embeds[0].fields): if field.name == 'Available Slots:': size = sql_query[0]['slots'] size = int(size.replace('*', '')) + 1 size = '**' + str(size) + '**' msg.embeds[0].set_field_at(idx, name="Available Slots:", value=size, inline=True) break await msg.edit(embed=msg.embeds[0]) sql = "UPDATE posts SET post_members = %s, slots = %s WHERE post_id = %s" val = (member_field_sql, size, msg.id) await mysql_commit(sql=sql, val=val) except (AttributeError, IndexError): pass sql = "SELECT channel_events_id FROM guilds WHERE guild_id = %s" val = (member.guild.id,) await mysql_commit(sql=sql, val=val) sql_query = sql_connect.fetchall() if client.get_channel(int(sql_query[0]['channel_events_id'])) is not None: events_channel = client.get_channel(int(sql_query[0]['channel_events_id'])) async for msg in events_channel.history(): try: if msg.embeds[0].title == 'Event Organizer:': # Host Work if str(member.id) in msg.embeds[0].description: # No Members to Inform if msg.embeds[0].fields[0].name != 'Participants:': sql = "DELETE FROM posts WHERE post_id = %s" val = (msg.id,) await mysql_commit(sql=sql, val=val) await msg.delete() # Members to Inform if (msg.embeds[0].fields[0].name == 'Participants:') & ('📅┃**Event Now Starting**' not in msg.content): sql = "SELECT * FROM posts WHERE post_id = %s" val = (msg.id,) await mysql_commit(sql=sql, val=val) sql_query = sql_connect.fetchall() if sql_query is not None: members = msg.embeds[0].fields[0].value member_ids = members.replace('<@', '').replace('>', '') members_list = member_ids.split() for user_id in members_list: try: await member.guild.get_member(int(user_id)).send(content='🛑┃**Event Disbanded**:\n• Event Organizer has left the server thus their event has been disbanded and will cease hosting.\n• You do not need to contact them, feel free to instead join a new Event anytime.', embed=msg.embeds[0]) except: pass sql = "DELETE FROM posts WHERE post_id = %s" val = (msg.id,) await mysql_commit(sql=sql, val=val) await msg.delete() # Participant Work if (str(member.id) not in msg.embeds[0].description) & (str(member.id) in msg.embeds[0].fields[0].value) & ('📅┃**Event Now Starting**' not in msg.content): sql = "SELECT * FROM posts WHERE post_id = %s" val = (msg.id,) await mysql_commit(sql=sql, val=val) sql_query = sql_connect.fetchall() if sql_query is not None: members = sql_query[0]['post_members'] member_ids = members.replace('<@', '').replace('>', '') members_list = member_ids.split() members_list.remove(str(member.id)) members_list_len = len(members_list) member_field = '' member_field_sql = '' # If nobody remains if members_list_len == 0: msg.embeds[0].remove_field(0) member_field_sql = member_field # If less than 40 if (members_list_len <= 40) & (members_list_len > 0): for idx, member in enumerate(members_list): if idx == 0: member_field = '<@' + member + '>' elif idx > 0: member_field = ' <@' + member + '>' msg.embeds[0].set_field_at(0, name="Participants:", value=member_field, inline=False) member_field_sql = member_field # If more than 40 elif members_list_len > 40: for idx, member in enumerate(members_list): if idx == 0: member_field = member_field + '<@' + member + '>' elif (idx > 0) & (idx <= 40): member_field = member_field + ' <@' + member + '>' elif idx > 40: if idx == 41: member_field_sql = member_field member_field_sql = member_field_sql + ' <@' + member + '>' member_field = member_field + ' Plus ' + str(int(members_list_len - 40)) + ' More...' msg.embeds[0].set_field_at(0, name="Participants:", value=member_field, inline=False) for idx, field in enumerate(msg.embeds[0].fields): if field.name == 'Available Slots:': size = sql_query[0]['slots'] size = int(size.replace('*', '')) + 1 size = '**' + str(size) + '**' msg.embeds[0].set_field_at(idx, name="Available Slots:", value=size, inline=True) break await msg.edit(embed=msg.embeds[0]) sql = "UPDATE posts SET post_members = %s, slots = %s WHERE post_id = %s" val = (member_field_sql, size, msg.id) await mysql_commit(sql=sql, val=val) except (AttributeError, IndexError): pass # ################ Setup Commands ######################## @slash.slash(name="setup", description="Used to provide a guide on and initialize LFG/Event features!") async def setup(ctx: ComponentContext): if bool([item for item in ctx.author.guild_permissions if (item[0] == 'administrator') & (item[1] is True)]): embed_message = discord.Embed(title=client.user.display_name + ' - Setup Options', description='Thank you for using the LFG/Event Bot!\nChoose from below options for initializing bot functions.', color=random.randint(0, 0xffffff)) try: embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass embed_message.timestamp = datetime.datetime.now() embed_message.set_footer(text=txt_footer + str(embed_message.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message.set_thumbnail(url=img_logo) await ctx.send(embed=embed_message, components=[create_actionrow(setup_option)], hidden=True) else: await ctx.send(content='❗┃**Interaction Failed**:\n• Command restricted to Administrators only.', hidden=True) # ################ Setup Commands ######################## @slash.slash(name="support", description="Used to provide a guide on supported games for this server\'s LFG & Event features!") async def support(ctx): sql = "SELECT channel_lfgPosts_id, channel_events_id, lfg_formats FROM guilds WHERE guild_id = %s" val = (ctx.author.guild.id,) await mysql_commit(sql=sql, val=val) sql_query = sql_connect.fetchall() game_titles = [] if (sql_query[0]['lfg_formats'] is not None) & (sql_query[0]['lfg_formats'] != ''): for values in lfg_games_values: if values[0] in sql_query[0]['lfg_formats']: game_titles.append(values[1]) game_titles = '\n• '.join(game_titles) else: game_titles = 'Please contact your server admin to have them re-run the `/setup` command to define LFG formats.' embed_message_error = discord.Embed(title=client.user.display_name + ' - Supported Games', description='Thank you for your inquiry. See below this server\'s supported games you may create LFG Teams or Events for. Ask your server admins to add more supported games if interested!', color=0xffffff) embed_message_error.add_field(name="Supported LFG & Event Games:", value='• ' + game_titles, inline=False) if client.get_channel(int(sql_query[0]['channel_lfgPosts_id'])) is not None: embed_message_error.add_field(name="Where to post LFG Teams:", value='• <#' + sql_query[0]['channel_lfgPosts_id'] + '>', inline=False) else: embed_message_error.add_field(name="Where to post LFG Teams:", value='• Please contact your server admin to have them re-run the `/setup` command to create a channel for LFG Teams.', inline=False) if client.get_channel(int(sql_query[0]['channel_events_id'])) is not None: embed_message_error.add_field(name="Where to post Events:", value='• <#' + sql_query[0]['channel_events_id'] + '>', inline=False) else: embed_message_error.add_field(name="Where to post Events:", value='• Please contact your server admin to have them re-run the `/setup` command to create a channel for Events.', inline=False) try: embed_message_error.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message_error.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass embed_message_error.timestamp = datetime.datetime.now() embed_message_error.set_footer(text=txt_footer + str(embed_message_error.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_error.set_thumbnail(url=img_tip) await ctx.send(embed=embed_message_error, hidden=True) @client.event async def on_component(ctx: ComponentContext): await ctx.defer(hidden=True) if (ctx.selected_options is not None) & (ctx.channel.type is not discord.ChannelType.private): if ctx.selected_options[0] == 'guide': embed_message = discord.Embed(title=client.user.display_name + ' - Setup Guide', description='Thank you for using the LFG/Event Bot!\nSee below a breakdown for initializing bot functions.', color=random.randint(0, 0xffffff)) embed_message.add_field(name='▬▬▬▬ LFG FUNCTIONS ▬▬▬▬', value='Looking For Game (LFG) is utlilized by players to publish their intention to form a team in realtime for playing a videogame.\nDuring the following process we will establish two primary channels pictured below.', inline=False) embed_message.add_field(name='• 📑┃lfg-posts - What to expect here?', value='Users may browse here, LFG posts are created using the `/host` command and then vetted into an embed. Authors and fellow users can react through buttons below the embeds in order to join/leave/disband teams.', inline=False) embed_message.add_field(name='▬▬▬▬ EVENT FUNCTIONS ▬▬▬▬', value='Events, similar to LFG, are used to publish the intention to form a team at a later date for playing a videogame.', inline=False) embed_message.add_field(name='• 📅┃events - What to expect here?', value='Similar to the LFG posting process, events follow a format which is translated into an embed. The posts are vetted and then sent to the created events channel.', inline=False) embed_message.add_field(name='▬▬▬▬ BEGIN SETUP ▬▬▬▬', value='• To begin Setup re-type: `/setup` and then select the Initialization option.', inline=False) try: embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass embed_message.timestamp = datetime.datetime.now() embed_message.set_footer(text=txt_footer + str(embed_message.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message.set_thumbnail(url=img_logo) await ctx.send(embed=embed_message, hidden=True) elif ctx.selected_options[0] == 'bot-init': sql = "SELECT event_perms FROM guilds WHERE guild_id = %s" val = (ctx.author.guild.id,) await mysql_commit(sql=sql, val=val) opt_event = sql_connect.fetchall() if opt_event[0]['event_perms'] == 'restrict': embed_message = discord.Embed(title=client.user.display_name + ' - Event Permissions', description='', color=random.randint(0, 0xffffff)) embed_message.add_field(name='▬▬▬▬ Event Posting Permissions ▬▬▬▬', value='Choose if would you like to restrict Event posts creation to Moderators & Administrators.', inline=False) embed_message.add_field(name='• `🔓 Un-Restrict Events`', value='Anyone who uses `/lfg` to post an Event will have their post vetted and translated into an Embed for others to participate in.', inline=False) try: embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass embed_message.timestamp = datetime.datetime.now() embed_message.set_footer(text=txt_footer + str(embed_message.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message.set_thumbnail(url=img_logo) await ctx.send(embed=embed_message, components=[create_actionrow(setup_event_perms_option_restrict)], hidden=True) elif opt_event[0]['event_perms'] == 'unrestrict': embed_message = discord.Embed(title=client.user.display_name + ' - Event Permissions', description='', color=random.randint(0, 0xffffff)) embed_message.add_field(name='▬▬▬▬ Event Posting Permissions ▬▬▬▬', value='Choose if would you like to allow Event posts to be created by everyone.', inline=False) embed_message.add_field(name='• `🔒 Restrict Events`', value='Those who use `/lfg` to draft an Event without any Moderatation permissions will be denied.', inline=False) try: embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass embed_message.timestamp = datetime.datetime.now() embed_message.set_footer(text=txt_footer + str(embed_message.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message.set_thumbnail(url=img_logo) await ctx.send(embed=embed_message, components=[create_actionrow(setup_event_perms_option_unrestrict)], hidden=True) elif (ctx.selected_options[0] == 'event-perms-restrict') | (ctx.selected_options[0] == 'event-perms-unrestrict') | (ctx.selected_options[0] == 'event-perms-stayrestrict') | (ctx.selected_options[0] == 'event-perms-stayunrestrict'): if (ctx.selected_options[0] == 'event-perms-restrict') | (ctx.selected_options[0] == 'event-perms-stayrestrict'): sql = "UPDATE guilds SET event_perms = %s WHERE guild_id = %s" val = ('restrict', ctx.author.guild.id) await mysql_commit(sql=sql, val=val) elif (ctx.selected_options[0] == 'event-perms-unrestrict') | (ctx.selected_options[0] == 'event-perms-stayunrestrict'): sql = "UPDATE guilds SET event_perms = %s WHERE guild_id = %s" val = ('unrestrict', ctx.author.guild.id) await mysql_commit(sql=sql, val=val) sql = "SELECT global_search FROM guilds WHERE guild_id = %s" val = (ctx.author.guild.id,) await mysql_commit(sql=sql, val=val) opt_lfg = sql_connect.fetchall() if opt_lfg[0]['global_search'] == 'yes': embed_message = discord.Embed(title=client.user.display_name + ' - Opt-Out Global LFG & Event Network', description='', color=random.randint(0, 0xffffff)) embed_message.add_field(name='▬▬▬▬ Global LFG & Event Network ▬▬▬▬', value='Choose if would you like to Opt-Out your server to our Global LFG & Event Network.', inline=False) embed_message.add_field(name='• `❌ Opt-Out`', value='Leaving the network will no longer authorize `' + client.user.display_name + '` to maintain an active invite link to your server. All of your server\'s submitted LFG Groups & Events will remain private unable to be seen by users outside of your server.', inline=False) try: embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass embed_message.timestamp = datetime.datetime.now() embed_message.set_footer(text=txt_footer + str(embed_message.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message.set_thumbnail(url=img_logo) await ctx.send(embed=embed_message, components=[create_actionrow(setup_global_search_option_no)], hidden=True) elif opt_lfg[0]['global_search'] == 'no': embed_message = discord.Embed(title=client.user.display_name + ' - Opt-In Global LFG & Event Network', description='', color=random.randint(0, 0xffffff)) embed_message.add_field(name='▬▬▬▬ Global LFG & Event Network ▬▬▬▬', value='Choose if would you like to Opt-In your server to our Global LFG & Event Network.', inline=False) embed_message.add_field(name='• `✔️ Opt-In`', value='Joining the network will authorize `' + client.user.display_name + '` to maintain an active invite link to your server. All of your server\'s submitted LFG Groups & EVents will be listed to users outside this server using the `/search` command. An option to join your server in order to become a member of said Group or Event will be provided to users. Servers are by default Opt-Out of the network.', inline=False) try: embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass embed_message.timestamp = datetime.datetime.now() embed_message.set_footer(text=txt_footer + str(embed_message.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message.set_thumbnail(url=img_logo) await ctx.send(embed=embed_message, components=[create_actionrow(setup_global_search_option_yes)], hidden=True) elif (ctx.selected_options[0] == 'global-search_yes') | (ctx.selected_options[0] == 'global-search_no') | (ctx.selected_options[0] == 'global-search_stayyes') | (ctx.selected_options[0] == 'global-search_stayno'): sql = "SELECT channel_lfgPosts_id, channel_events_id FROM guilds WHERE guild_id = %s" val = (ctx.author.guild.id,) await mysql_commit(sql=sql, val=val) ids = sql_connect.fetchall() # Create LFG Posts if (discord.utils.get(ctx.author.guild.channels, id=int(ids[0]['channel_lfgPosts_id'])) is None) & (discord.utils.get(ctx.author.guild.channels, id=int(ids[0]['channel_events_id'])) is not None): channel_lfgPosts = await ctx.guild.create_text_channel(name='📑┃lfg-posts', topic='Use `/host LFG Posts` in order to post here. Or use this to browse available posts.') await channel_lfgPosts.set_permissions(ctx.guild.default_role, add_reactions=False, attach_files=False, send_tts_messages=False) sql = "UPDATE guilds SET channel_lfgPosts_id = %s WHERE guild_id = %s" val = (channel_lfgPosts.id, ctx.author.guild.id) await mysql_commit(sql=sql, val=val) embed_message = discord.Embed(title=client.user.display_name + ' - LFG Channels Initialization', description='Operation successful, the below LFG channels were created!', color=random.randint(0, 0xffffff)) embed_message.add_field(name='What was Created?', value='• LFG Posts Channel: <#' + str(channel_lfgPosts.id) + '>', inline=False) embed_message.add_field(name='What Channel Exists?', value='• Events Channel: <#' + str(ids[0]['channel_events_id']) + '>', inline=False) try: embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass embed_message.timestamp = datetime.datetime.now() embed_message.set_footer(text=txt_footer + str(embed_message.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message.set_thumbnail(url=img_logo) await ctx.send(embed=embed_message, hidden=True) await check_channel_embeds(ctx, str(channel_lfgPosts.id)) # Create Events elif (discord.utils.get(ctx.author.guild.channels, id=int(ids[0]['channel_lfgPosts_id'])) is not None) & (discord.utils.get(ctx.author.guild.channels, id=int(ids[0]['channel_events_id'])) is None): channel_events = await ctx.guild.create_text_channel(name='📅┃events', topic='Use `/host Event Posts` in order to post here. Or use this to browse available posts.') await channel_events.set_permissions(ctx.guild.default_role, add_reactions=False, attach_files=False, send_tts_messages=False) sql = "UPDATE guilds SET channel_events_id = %s WHERE guild_id = %s" val = (channel_events.id, ctx.author.guild.id) await mysql_commit(sql=sql, val=val) embed_message = discord.Embed(title=client.user.display_name + ' - LFG Channels Initialization', description='Operation successful, the below Event channels were created!', color=random.randint(0, 0xffffff)) embed_message.add_field(name='What was Created?', value='• Events Channel: <#' + str(channel_events.id) + '>', inline=False) embed_message.add_field(name='What Channel Exists?', value='• LFG Posts Channel: <#' + str(ids[0]['channel_lfgPosts_id']) + '>', inline=False) try: embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass embed_message.timestamp = datetime.datetime.now() embed_message.set_footer(text=txt_footer + str(embed_message.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message.set_thumbnail(url=img_logo) await ctx.send(embed=embed_message, hidden=True) await check_channel_embeds(ctx, str(channel_events.id)) # Create Both elif (discord.utils.get(ctx.author.guild.channels, id=int(ids[0]['channel_lfgPosts_id'])) is None) & (discord.utils.get(ctx.author.guild.channels, id=int(ids[0]['channel_events_id'])) is None): channel_lfgPosts = await ctx.guild.create_text_channel(name='📑┃lfg-posts', topic='Use `/host LFG Posts` in order to post here. Or use this to browse available posts.') await channel_lfgPosts.set_permissions(ctx.guild.default_role, add_reactions=False, attach_files=False, send_tts_messages=False) channel_events = await ctx.guild.create_text_channel(name='📅┃events', topic='Use `/host Event Posts` in order to post here. Or use this to browse available posts.') await channel_events.set_permissions(ctx.guild.default_role, add_reactions=False, attach_files=False, send_tts_messages=False) sql = "UPDATE guilds SET channel_lfgPosts_id = %s, channel_events_id = %s WHERE guild_id = %s" val = (channel_lfgPosts.id, channel_events.id, ctx.author.guild.id) await mysql_commit(sql=sql, val=val) embed_message = discord.Embed(title=client.user.display_name + ' - LFG Channel Initialization', description='Setup required, creating both channels!', color=random.randint(0, 0xffffff)) embed_message.add_field(name='What was Created?', value='• LFG Posts Channel: <#' + str(channel_lfgPosts.id) + '>\n• Events Channel: <#' + str(channel_events.id) + '>', inline=False) try: embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass embed_message.timestamp = datetime.datetime.now() embed_message.set_footer(text=txt_footer + str(embed_message.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message.set_thumbnail(url=img_logo) await ctx.send(embed=embed_message, hidden=True) await check_channel_embeds(ctx, str(channel_lfgPosts.id), str(channel_events.id)) # Display Both Exist elif (discord.utils.get(ctx.author.guild.channels, id=int(ids[0]['channel_lfgPosts_id'])) is not None) & (discord.utils.get(ctx.author.guild.channels, id=int(ids[0]['channel_events_id'])) is not None): embed_message = discord.Embed(title=client.user.display_name + ' - LFG Channel Initialization', description='Setup not required, both channels already exists!', color=random.randint(0, 0xffffff)) embed_message.add_field(name='What Channel Exists?', value='• LFG Posts Channel: <#' + str(ids[0]['channel_lfgPosts_id']) + '>\n• Events Channel: <#' + str(ids[0]['channel_events_id']) + '>', inline=False) try: embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass embed_message.timestamp = datetime.datetime.now() embed_message.set_footer(text=txt_footer + str(embed_message.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message.set_thumbnail(url=img_logo) await ctx.send(embed=embed_message, hidden=True) await check_channel_embeds(ctx, ids[0]['channel_lfgPosts_id'], ids[0]['channel_events_id']) if (ctx.selected_options[0] == 'global-search_yes') | (ctx.selected_options[0] == 'global-search_stayyes'): sql = "UPDATE guilds SET global_search = %s WHERE guild_id = %s" val = ('yes', ctx.author.guild.id) await mysql_commit(sql=sql, val=val) sql = "SELECT global_search, channel_lfgPosts_id, global_search_invite FROM guilds WHERE guild_id = %s" val = (ctx.author.guild.id,) await mysql_commit(sql=sql, val=val) opt_lfg = sql_connect.fetchall() if ([item for item in await ctx.author.guild.invites() if item.url == str(opt_lfg[0]['global_search_invite'])] is False) | (str(opt_lfg[0]['global_search_invite']) == '0'): globalinvite = '' if client.get_channel(int(opt_lfg[0]['channel_lfgPosts_id'])) is not None: lfg_posts_channel = client.get_channel(int(opt_lfg[0]['channel_lfgPosts_id'])) globalinvite = await lfg_posts_channel.create_invite(max_uses=0, max_age=0, unique=True) else: text_channel = random.choice(ctx.author.guild.text_channels) globalinvite = await text_channel.create_invite(max_uses=0, max_age=0, unique=True) sql = "UPDATE guilds SET global_search_invite = %s WHERE guild_id = %s" val = (str(globalinvite), ctx.author.guild.id) await mysql_commit(sql=sql, val=val) elif (ctx.selected_options[0] == 'global-search_no') | (ctx.selected_options[0] == 'global-search_stayno'): sql = "UPDATE guilds SET global_search = %s WHERE guild_id = %s" val = ('no', ctx.author.guild.id) await mysql_commit(sql=sql, val=val) sql = "SELECT global_search_invite FROM guilds WHERE guild_id = %s" val = (ctx.author.guild.id,) await mysql_commit(sql=sql, val=val) opt_lfg = sql_connect.fetchall() try: invite = await client.fetch_invite(str(opt_lfg[0]['global_search_invite'])) await invite.delete() except: pass sql = "UPDATE guilds SET global_search_invite = %s WHERE guild_id = %s" val = ('0', ctx.author.guild.id) await mysql_commit(sql=sql, val=val) sql = "SELECT lfg_formats FROM guilds WHERE guild_id = %s" val = (ctx.author.guild.id,) await mysql_commit(sql=sql, val=val) sql_fetch = sql_connect.fetchone() formats = '' if sql_fetch is not None: formats = sql_fetch['lfg_formats'] if not formats: embed_message = discord.Embed(title=client.user.display_name + ' - LFG Format Setup', description='Add your server\'s first supported LFG Formats!\nRe-run the LFG Setup in order to choose or remove more games in the future!', color=random.randint(0, 0xffffff)) try: embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass embed_message.timestamp = datetime.datetime.now() embed_message.set_footer(text=txt_footer + str(embed_message.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message.set_thumbnail(url=img_logo) await ctx.send(embed=embed_message, components=[create_actionrow(lfg_format_option_init)], hidden=True) else: embed_message = discord.Embed(title=client.user.display_name + ' - LFG Format Setup', description='Add or Remove your server\'s supported LFG Formats!\nRe-run the LFG Setup in order to choose or remove more games in the future!', color=random.randint(0, 0xffffff)) try: embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass embed_message.timestamp = datetime.datetime.now() embed_message.set_footer(text=txt_footer + str(embed_message.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message.set_thumbnail(url=img_logo) await ctx.send(embed=embed_message, components=[create_actionrow(lfg_format_option_both)], hidden=True) elif (ctx.selected_options[0] == 'lfg_format_add') | (ctx.selected_options[0] == 'lfg_format_remove'): sql = "SELECT lfg_formats FROM guilds WHERE guild_id = %s" val = (ctx.author.guild.id,) await mysql_commit(sql=sql, val=val) sql_fetch = sql_connect.fetchone() formats = '' if sql_fetch is not None: formats = sql_fetch['lfg_formats'] game_titles = [] if formats: formats = formats.split(" ") for values in lfg_games_values: if values[0] in formats: game_titles.append(values[1]) game_titles = '\n• '.join(game_titles) else: game_titles = 'No LFG Formats currently supported!' if ctx.selected_options[0] == 'lfg_format_add': embed_message = discord.Embed(title=client.user.display_name + ' - LFG Format Selection ✅', description='Add to your server\'s supported LFG Formats that users may advertise for!\nRe-run the LFG Setup in order to choose or remove more games in the future!', color=random.randint(0, 0xffffff)) embed_message.add_field(name='Current Server Supported LFG Formats:', value='• ' + game_titles, inline=False) try: embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass embed_message.timestamp = datetime.datetime.now() embed_message.set_footer(text=txt_footer + str(embed_message.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message.set_thumbnail(url=img_logo) await ctx.send(embed=embed_message, components=[create_actionrow(lfg_games_add)], hidden=True) elif ctx.selected_options[0] == 'lfg_format_remove': embed_message = discord.Embed(title=client.user.display_name + ' - LFG Format Selection ❌', description='Remove LFG Formats from your server that users are actively avdertising for!\nRe-run the LFG Setup in order to choose or remove more games in the future!', color=random.randint(0, 0xffffff)) embed_message.add_field(name='Current Server Supported LFG Formats:', value='• ' + game_titles, inline=False) try: embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass embed_message.timestamp = datetime.datetime.now() embed_message.set_footer(text=txt_footer + str(embed_message.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message.set_thumbnail(url=img_logo) await ctx.send(embed=embed_message, components=[create_actionrow(lfg_games_remove)], hidden=True) elif set(ctx.selected_options).issubset(set([value[0] for value in lfg_games_values])): if ctx.custom_id == 'lfg_games_add': formats = ' '.join(ctx.selected_options) formats_db_list = [] game_titles_current_compare = [] sql = "SELECT lfg_formats FROM guilds WHERE guild_id = %s" val = (ctx.author.guild.id,) await mysql_commit(sql=sql, val=val) sql_fetch = sql_connect.fetchone() formats_db = '' if sql_fetch is not None: formats_db = sql_fetch['lfg_formats'] game_titles_current = [] if (formats_db is not None) & (formats_db != ''): formats_db_list = formats_db.split(" ") for values in lfg_games_values: if values[0] in formats_db_list: game_titles_current.append(values[1]) game_titles_current_compare = game_titles_current game_titles_current = '\n• '.join(game_titles_current) else: game_titles_current = 'No LFG Formats were supported before now!' game_titles = [] formats_list = formats.split(" ") for values in lfg_games_values: if values[0] in formats_list: game_titles.append(values[1]) game_titles = [title for title in game_titles if title not in game_titles_current_compare] if game_titles: game_titles = '\n• '.join(game_titles) else: game_titles = 'No new LFG Formats added!' formats_update = formats_db_list formats_update.extend(value for value in formats_list if value not in formats_update) formats_update = ' '.join(formats_update) sql = "UPDATE guilds SET lfg_formats = %s WHERE guild_id = %s" val = (formats_update, ctx.author.guild.id) await mysql_commit(sql=sql, val=val) embed_message = discord.Embed(title=client.user.display_name + ' - LFG Format Selection ✅', description='Success, the below LFG Formats have been added to your server!\nRe-run the LFG Setup in order to choose or remove more games in the future!', color=random.randint(0, 0xffffff)) embed_message.add_field(name='Just Added LFG Formats:', value='• ' + game_titles, inline=False) embed_message.add_field(name='Current Server Supported LFG Formats:', value='• ' + game_titles_current, inline=False) try: embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass embed_message.timestamp = datetime.datetime.now() embed_message.set_footer(text=txt_footer + str(embed_message.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message.set_thumbnail(url=img_logo) await ctx.send(embed=embed_message, hidden=True) elif ctx.custom_id == 'lfg_games_remove': sql = "SELECT lfg_formats FROM guilds WHERE guild_id = %s" val = (ctx.author.guild.id,) await mysql_commit(sql=sql, val=val) sql_fetch = sql_connect.fetchone() formats_db = '' if sql_fetch is not None: formats_db = sql_fetch['lfg_formats'] formats_list = formats_db.split(" ") formats_update = [title for title in ctx.selected_options if title in formats_list] formats_update_removing = formats_update formats_update = [title for title in formats_list if title not in formats_update] formats_update_remaining = formats_update formats_update = ' '.join(formats_update) if formats_update is not None: sql = "UPDATE guilds SET lfg_formats = %s WHERE guild_id = %s" val = (formats_update, ctx.author.guild.id) await mysql_commit(sql=sql, val=val) game_titles_removing = [] for values in lfg_games_values: if values[0] in formats_update_removing: game_titles_removing.append(values[1]) game_titles_removing = '\n• '.join(game_titles_removing) if not game_titles_removing: game_titles_removing = 'No exisiting employed LFG Formats to be removed!' game_titles_remaining = [] for values in lfg_games_values: if values[0] in formats_update_remaining: game_titles_remaining.append(values[1]) game_titles_remaining = '\n• '.join(game_titles_remaining) if not game_titles_remaining: game_titles_remaining = 'No LFG Formats now employed, consider re-running Setup to add more!' embed_message = discord.Embed(title=client.user.display_name + ' - LFG Format Removal ❌', description='Success, the below LFG Formats were removed from your server!\nRe-run the LFG Setup in order to choose or remove more games in the future!', color=random.randint(0, 0xffffff)) embed_message.add_field(name='Removed Existing LFG Formats:', value='• ' + game_titles_removing, inline=False) embed_message.add_field(name='Updated Server Supported LFG Formats:', value='• ' + game_titles_remaining, inline=False) try: embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass embed_message.timestamp = datetime.datetime.now() embed_message.set_footer(text=txt_footer + str(embed_message.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message.set_thumbnail(url=img_logo) await ctx.send(embed=embed_message, hidden=True) elif ctx.custom_id is not None: if ctx.custom_id == 'thread_close': type_message = '' type_channel = '' if ctx.origin_message.embeds[0].title == 'Team Organizer:': type_message = 'Team' type_channel = 'LFG Posts' elif ctx.origin_message.embeds[0].title == 'Event Organizer:': type_message = 'Event' type_channel = 'Events' if (str(ctx.author.id) == str(ctx.origin_message.embeds[0].description).replace('<@!', '').replace('<@', '').replace('>', '')) | bool([item for item in ctx.author.guild_permissions if (item[0] == 'manage_channels') & (item[1] is True)]) | bool([item for item in ctx.author.guild_permissions if (item[0] == 'manage_messages') & (item[1] is True)]) | bool([item for item in ctx.author.guild_permissions if (item[0] == 'administrator') & (item[1] is True)]): if str(ctx.author.id) == str(ctx.origin_message.embeds[0].description).replace('<@!', '').replace('<@', '').replace('>', ''): try: await ctx.author.send(content=f'🔒┃**Thread Closed - {type_message} Organizer Deletion**:\n• The below {type_message}\'s Thread you were Organizer of has been removed per your request.\n• If you plan to continue playing please reach out to your {type_message} Members or return to the {type_channel} channel and disband your {type_message}.', embed=ctx.origin_message.embeds[0]) except: pass for member_id in ctx.origin_message.channel._members: if str(member_id) != str(ctx.author.id): usr = await client.fetch_user(int(member_id)) try: await usr.send(content=f'🔒┃**Thread Closed - {type_message} Organizer Deletion**:\n• The below {type_message}\'s Thread you were a Member of has been removed by your {type_message} Organizer.\n• This is due to the Organizer wishing to simply not use the thread as a means of communication.\n• Please reach out to your {type_message} Organizer, <@{ctx.author.id}>, to continue organizing plans for your {type_message}, enjoy!', embed=ctx.origin_message.embeds[0]) except: pass await ctx.origin_message.channel.delete() elif bool([item for item in ctx.author.guild_permissions if (item[0] == 'manage_channels') & (item[1] is True)]) | bool([item for item in ctx.author.guild_permissions if (item[0] == 'manage_messages') & (item[1] is True)]) | bool([item for item in ctx.author.guild_permissions if (item[0] == 'administrator') & (item[1] is True)]): try: await ctx.author.send(content=f'🔒┃**Thread Closed - Administrator Deletion**:\n• The below {type_message}\'s Thread has been removed per your request as an Administrator/Moderator.\n• If this is an offending {type_message} please return to the {type_channel} channel and disband their corresponding {type_message} as well.', embed=ctx.origin_message.embeds[0]) except: pass for member_id in ctx.origin_message.channel._members: if str(member_id) != str(ctx.author.id): usr = await client.fetch_user(int(member_id)) try: await usr.send(content=f'🔒┃**Thread Closed - Administrator Deletion**:\n• The below {type_message}\'s Thread you were a Member of has been removed by an Administrator/Moderator.\n• This is either due to the channel being currently unused/archived or due to the channel containing offending content.\n• If you were currently playing please reach out to your {type_message} Organizer, <@{ctx.author.id}>, to re-organize plans or return to the {type_channel} channel and join a new {type_message}.', embed=ctx.origin_message.embeds[0]) except: pass await ctx.origin_message.channel.delete() sql = "UPDATE posts SET thread_id = %s WHERE thread_id = %s" val = ('', str(ctx.origin_message.channel.id)) await mysql_commit(sql=sql, val=val) else: await ctx.send(content=f'❌┃**Thread Not Closed - Not {type_message} Organizer**:\n• The below {type_message}\'s Thread you attempted to remove failed due to not being the {type_message}\'s Organizer.\n• Please refrain from removing Threads you are not owner of, all threads expire one hour after inactivity.', embed=ctx.origin_message.embeds[0], hidden=True) elif (ctx.custom_id == 'notify_remove_lfg') | (ctx.custom_id == 'notify_remove_event'): choice = '' post_type = '' if ctx.custom_id == 'notify_remove_lfg': choice = 'type_lfg' post_type = 'LFG Post' elif ctx.custom_id == 'notify_remove_event': choice = 'type_events' post_type = 'Event' sql = "SELECT * FROM notify WHERE user_id = %s AND choice = %s" val = (ctx.author.id, choice) await mysql_commit(sql=sql, val=val) member_notify = sql_connect.fetchall() if member_notify: embed_message = discord.Embed(title=client.user.display_name + ' - Notifications Disabled', description=f'You will no longer be notified of any new {post_type} added to the Global Network for the below.', color=0xffffff) embed_message.add_field(name='Game:', value=member_notify[0]['game'], inline=False) if member_notify[0]['platform']: platform_title = '' for element in host_options[1]['choices']: if element['value'] == member_notify[0]['platform']: platform_title = element['name'] embed_message.add_field(name='Platform:', value=platform_title, inline=False) else: embed_message.add_field(name='Platform:', value='No Specific Platform Selected', inline=False) embed_message.add_field(name='Helpful Tips:', value=f'\n• Stop {post_type} notifications simply by joining any {post_type} or using the `🛑 Stop {post_type} Notifications` button attached to any notification.\n• You can be subscribed for notifications of Events & LFG posts at the same time!', inline=False) embed_message.timestamp = datetime.datetime.now() embed_message.set_footer(text=txt_footer + str(embed_message.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message.set_thumbnail(url=img_logo) await ctx.send(embed=embed_message, hidden=True) else: embed_message = discord.Embed(title=client.user.display_name + ' - Notifications Not Enabled', description=f'You are currently not being notified of any new {post_type} added to the Global Network.', color=0xffffff) embed_message.add_field(name='Helpful Tips:', value=f'\n• Re-Enable {post_type} notifications simply by typing `/notify` and choosing your desired post type, game, and platform.\n• You can be subscribed for notifications of Events & LFG posts at the same time!', inline=False) embed_message.timestamp = datetime.datetime.now() embed_message.set_footer( text=txt_footer + str(embed_message.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message.set_thumbnail(url=img_logo) await ctx.send(embed=embed_message, hidden=True) sql = "DELETE FROM notify WHERE user_id = %s AND choice = %s" val = (ctx.author.id, choice) await mysql_commit(sql=sql, val=val) elif (ctx.custom_id == 'post_join') | (ctx.custom_id == 'post_leave') | (ctx.custom_id == 'post_close') | (ctx.custom_id == 'post_disband') | (ctx.custom_id == 'lfg_info'): if (ctx.custom_id == 'post_join') | (ctx.custom_id == 'post_leave') | (ctx.custom_id == 'post_close') | (ctx.custom_id == 'post_disband'): post_organizer_id = str(ctx.origin_message.embeds[0].description).replace('<@!', '').replace('<@', '').replace('>', '') post_organizer = ctx.guild.get_member(int(post_organizer_id)) button_origin_msg = [create_actionrow(create_button(style=ButtonStyle.URL, label='Origin Post', emoji='📑', url=str(ctx.origin_message.jump_url)))] members_field = False members_value = '' members_amount = 0 members_list_len = 0 members_list = [] if (ctx.origin_message.embeds[0].fields[0].name == 'Team Members:') | (ctx.origin_message.embeds[0].fields[0].name == 'Participants:'): members_field = True members_value = str(ctx.origin_message.embeds[0].fields[0].value) if ctx.origin_message.embeds[0].fields[2].name == 'Available Slots:': members_amount = int(ctx.origin_message.embeds[0].fields[2].value.replace('*', '')) elif ctx.origin_message.embeds[0].fields[3].name == 'Available Slots:': members_amount = int(ctx.origin_message.embeds[0].fields[3].value.replace('*', '')) if members_field is True: if 'Plus' in members_value: sql = "SELECT post_members FROM posts WHERE post_id = %s" val = (ctx.origin_message.id, ) await mysql_commit(sql=sql, val=val) sql_query_members = sql_connect.fetchall() if sql_query_members: members_value = sql_query_members[0]['post_members'] members_ids = sql_query_members[0]['post_members'].replace('<@!', '').replace('<@', '').replace('>', '') members_list = members_ids.split(' ') members_list_len = len(members_list) else: members_overflow = re.search('Plus (.*) More', members_value) members_overflow = int(members_overflow.group(1)) members_value.partition(' Plus') members_ids = members_value.replace('<@!', '').replace('<@', '').replace('>', '') members_list = members_ids.split(' ') members_list_len = len(members_list) + members_overflow else: members_ids = members_value.replace('<@!', '').replace('<@', '').replace('>', '') members_list = members_ids.split(' ') members_list_len = len(members_list) if (ctx.custom_id == 'post_join') | (ctx.custom_id == 'post_leave'): if int(post_organizer_id) != ctx.author.id: if ctx.custom_id == 'post_join': if members_field is False: choice = '' game = '' if ctx.origin_message.embeds[0].title == 'Team Organizer:': choice = 'type_events' elif ctx.origin_message.embeds[0].title == 'Event Organizer:': choice = 'type_lfg' for element in host_options[2]['choices']: if element['name'] == ctx.origin_message.embeds[0].fields[1].value: game = element['value'] sql = "DELETE FROM notify WHERE user_id = %s AND choice = %s AND game = %s" val = (ctx.author.id, choice, game) await mysql_commit(sql=sql, val=val) prior_join_check = await check_joined_posts(ctx) if not prior_join_check: members_amount = members_amount - 1 if ctx.origin_message.embeds[0].title == 'Team Organizer:': ctx.origin_message.embeds[0].insert_field_at(0, name="Team Members:", value='<@' + str(ctx.author.id) + '>', inline=False) ctx.origin_message.embeds[0].set_field_at(3, name="Available Slots:", value='**' + str(members_amount) + '**', inline=True) elif ctx.origin_message.embeds[0].title == 'Event Organizer:': ctx.origin_message.embeds[0].insert_field_at(0, name="Participants:", value='<@' + str(ctx.author.id) + '>', inline=False) ctx.origin_message.embeds[0].set_field_at(3, name="Available Slots:", value='**' + str(members_amount) + '**', inline=True) await ctx.origin_message.edit(embed=ctx.origin_message.embeds[0]) if ctx.origin_message.embeds[0].title == 'Team Organizer:': await ctx.send(content='☑️┃**Joined Team**:\n• Please visit the Team\'s assigned thread and contact Team Organizer <@' + str(post_organizer_id) + '> to arrange friend requests and in-game plans. You may leave the team at anytime and they will be informed, have fun!' + tip_member, embed=ctx.origin_message.embeds[0], components=button_origin_msg, hidden=True) try: await post_organizer.send(content='☑️┃**Team Member Joined**:\n• Please visit the Team\'s assigned thread and contact Team Member <@' + str(ctx.author.id) + '> to arrange friend requests and in-game plans. You will be alerted if a user leaves your team, have fun!' + tip_host, embed=ctx.origin_message.embeds[0], components=button_origin_msg) except: pass sql = "SELECT thread_id FROM posts WHERE post_id = %s" val = (ctx.origin_message.id,) await mysql_commit(sql=sql, val=val) query = sql_connect.fetchall() if query: if query[0]['thread_id'] != '': thread_id = query[0]['thread_id'] if ctx.origin_message.channel.get_thread(int(thread_id)): message_thread = ctx.origin_message.channel.get_thread(int(thread_id)) try: await message_thread.add_user(ctx.author) except: pass await ctx.send(content=f'❕┃**Team Thread Joined**:\n• Please visit the following Thread to discuss the joined LFG Team: <#{thread_id}>', hidden=True) elif ctx.origin_message.embeds[0].title == 'Event Organizer:': await ctx.send(content='☑️┃**Joined Event**:\n• You will be directly informed once the Event Start Time is reached. Please return to the Events channel after the Event starts and visit the Event\'s created thread for instructions from Event Organizer <@' + str(post_organizer_id) + '> on arranging friend requests and in-game plans. You may leave the event at anytime, have fun!' + tip_member, embed=ctx.origin_message.embeds[0], components=button_origin_msg, hidden=True) sql = "UPDATE posts SET post_members = %s, slots = %s WHERE post_id = %s" val = ('<@' + str(ctx.author.id) + '>', '**' + str(members_amount) + '**', ctx.origin_message_id) await mysql_commit(sql=sql, val=val) elif (members_field is True) & (str(ctx.author.id) not in members_list): choice = '' game = '' if ctx.origin_message.embeds[0].title == 'Team Organizer:': choice = 'type_events' elif ctx.origin_message.embeds[0].title == 'Event Organizer:': choice = 'type_lfg' for element in host_options[2]['choices']: if element['name'] == ctx.origin_message.embeds[0].fields[2].value: game = element['value'] sql = "DELETE FROM notify WHERE user_id = %s AND choice = %s AND game = %s" val = (ctx.author.id, choice, game) await mysql_commit(sql=sql, val=val) prior_join_check = await check_joined_posts(ctx) if not prior_join_check: members_amount = members_amount - 1 members_list.append(str(ctx.author.id)) members_list_len = members_list_len + 1 if ctx.origin_message.embeds[0].title == 'Team Organizer:': if members_list_len <= 40: ctx.origin_message.embeds[0].set_field_at(0, name="Team Members:", value=members_value + ' <@' + str(ctx.author.id) + '>', inline=False) elif members_list_len > 40: ctx.origin_message.embeds[0].set_field_at(0, name="Team Members:", value=' '.join(members_value.split(" ")[:40]) + ' Plus ' + str(int(members_list_len - 40)) + ' More...', inline=False) ctx.origin_message.embeds[0].set_field_at(3, name="Available Slots:", value='**' + str(members_amount) + '**', inline=True) elif ctx.origin_message.embeds[0].title == 'Event Organizer:': if members_list_len <= 40: ctx.origin_message.embeds[0].set_field_at(0, name="Participants:", value=members_value + ' <@' + str(ctx.author.id) + '>', inline=False) elif members_list_len > 40: ctx.origin_message.embeds[0].set_field_at(0, name="Participants:", value=' '.join(members_value.split(" ")[:40]) + ' Plus ' + str(int(members_list_len - 40)) + ' More...', inline=False) ctx.origin_message.embeds[0].set_field_at(3, name="Available Slots:", value='**' + str(members_amount) + '**', inline=True) await ctx.origin_message.edit(embed=ctx.origin_message.embeds[0]) if ctx.origin_message.embeds[0].title == 'Team Organizer:': await ctx.send(content='☑️┃**Joined Team**:\n• Please visit the Team\'s assigned thread and contact Team Organizer <@' + str(post_organizer_id) + '> to arrange friend requests and in-game plans. You may leave the team at anytime and they will be informed, have fun!' + tip_member, embed=ctx.origin_message.embeds[0], components=button_origin_msg, hidden=True) try: await post_organizer.send(content='☑️┃**Team Member Joined**:\n• Please visit the Team\'s assigned thread and contact Team Member <@' + str(ctx.author.id) + '> to arrange friend requests and in-game plans. You will be alerted if a user leaves your team, have fun!' + tip_host, embed=ctx.origin_message.embeds[0], components=button_origin_msg) except: pass sql = "SELECT thread_id FROM posts WHERE post_id = %s" val = (ctx.origin_message.id,) await mysql_commit(sql=sql, val=val) query = sql_connect.fetchall() if query: if query[0]['thread_id'] != '': thread_id = query[0]['thread_id'] if ctx.origin_message.channel.get_thread(int(thread_id)): message_thread = ctx.origin_message.channel.get_thread(int(thread_id)) try: await message_thread.add_user(ctx.author) except: pass await ctx.send(content=f'❕┃**Team Thread Joined**:\n• Please visit the following Thread to discuss the joined LFG Team: <#{thread_id}>', hidden=True) elif ctx.origin_message.embeds[0].title == 'Event Organizer:': await ctx.send(content='☑️┃**Joined Event**:\n• You will be directly informed once the Event Start Time is reached. Please return to the Events channel after the Event starts and visit the Event\'s created thread for instructions from Event Organizer <@' + str(post_organizer_id) + '> on arranging friend requests and in-game plans. You may leave the event at anytime, have fun!' + tip_member, embed=ctx.origin_message.embeds[0], components=button_origin_msg, hidden=True) sql = "UPDATE posts SET post_members = %s, slots = %s WHERE post_id = %s" val = (members_value + ' <@' + str(ctx.author.id) + '>', '**' + str(members_amount) + '**', ctx.origin_message_id) await mysql_commit(sql=sql, val=val) else: if ctx.origin_message.embeds[0].title == 'Team Organizer:': await ctx.send(content='❗┃**Team Already Joined**:\n' + tip_member, embed=ctx.origin_message.embeds[0], components=button_origin_msg, hidden=True) elif ctx.origin_message.embeds[0].title == 'Event Organizer:': await ctx.send(content='❗┃**Event Already Joined**:\n' + tip_member, embed=ctx.origin_message.embeds[0], components=button_origin_msg, hidden=True) if ctx.origin_message.embeds[0].title == 'Team Organizer:': if members_amount == 0: sql = "SELECT post_members FROM posts WHERE post_id = %s" val = (ctx.origin_message.id,) await mysql_commit(sql=sql, val=val) members_query = sql_connect.fetchall() members_ids = members_query[0]['post_members'].replace('<@!', '').replace('<@', '').replace('>', '') members_list = members_ids.split(' ') for member in members_list: try: await ctx.guild.get_member(int(member)).send(content='☑️┃**Team Filled**:\n• All available slots have been filled on the Team you joined, your Team is now ready to play.\n• Please visit the Team\'s assigned thread and contact Team Organizer <@' + str(post_organizer_id) + '> to arrange friend requests and in-game plans, have fun!', embed=ctx.origin_message.embeds[0]) except: pass if members_list_len <= 40: try: await post_organizer.send(content='☑️┃**Team Filled**:\n• All available slots have been filled, your Team Post has been removed and all Team Members informed.\n• Please visit the Team\'s assigned thread and arrange friend requests and in-game plans with the below said Team Members, have fun!', embed=ctx.origin_message.embeds[0]) except: pass elif members_list_len > 40: try: await post_organizer.send(content='☑️┃**Team Filled**:\n• All available slots have been filled, your Team Post has been removed and all Team Members informed.\n• Please visit the Team\'s assigned thread and arrange friend requests and in-game plans with the below said Team Members, have fun!', embed=ctx.origin_message.embeds[0]) await post_organizer.send(content='❗┃**Full Members List**:\n• Your post contained more than 50 members, see below all of their names!\n\n' + members_query[0]['post_members']) except: pass await ctx.origin_message.delete() elif (members_field is True) & (ctx.custom_id == 'post_leave'): if str(ctx.author.id) in members_list: members_amount = members_amount + 1 members_value_more = '' members_value = members_value.replace(' <@' + str(ctx.author.id) + '>', '').replace('<@' + str(ctx.author.id) + '>', '').replace(' <@!' + str(ctx.author.id) + '>', '').replace('<@!' + str(ctx.author.id) + '>', '') if members_list_len <= 40: members_value.partition(' Plus') elif members_list_len > 40: members_value_more = ' '.join(members_value.split(" ")[:40]) + ' Plus ' + str(int((members_list_len - 1) - 40)) + ' More...' ctx.origin_message.embeds[0].set_field_at(3, name="Available Slots:", value='**' + str(members_amount) + '**', inline=True) if (not members_value) | (members_value.isspace()): ctx.origin_message.embeds[0].remove_field(0) await ctx.origin_message.edit(embed=ctx.origin_message.embeds[0]) else: if ctx.origin_message.embeds[0].title == 'Team Organizer:': if members_list_len <= 40: ctx.origin_message.embeds[0].set_field_at(0, name="Team Members:", value=members_value, inline=False) elif members_list_len > 40: ctx.origin_message.embeds[0].set_field_at(0, name="Team Members:", value=members_value_more, inline=False) elif ctx.origin_message.embeds[0].title == 'Event Organizer:': if members_list_len <= 40: ctx.origin_message.embeds[0].set_field_at(0, name="Participants:", value=members_value, inline=False) elif members_list_len > 40: ctx.origin_message.embeds[0].set_field_at(0, name="Participants:", value=members_value_more, inline=False) await ctx.origin_message.edit(embed=ctx.origin_message.embeds[0]) sql = "UPDATE posts SET post_members = %s, slots = %s WHERE post_id = %s" val = (members_value, '**' + str(members_amount) + '**', ctx.origin_message_id) await mysql_commit(sql=sql, val=val) if ctx.origin_message.embeds[0].title == 'Team Organizer:': await ctx.send(content='❌┃**Left Team**:\n• Team Organizer has been informed of your leave, you do not need to contact them. Feel free to join another team anytime.' + tip_member, embed=ctx.origin_message.embeds[0], components=button_origin_msg, hidden=True) try: await post_organizer.send(content='❌┃**Team Member Left**:\n• Team Member <@' + str(ctx.author.id) + '> has left your team, you do not need to contact them. You will be alerted if a new user joins your team.' + tip_host, embed=ctx.origin_message.embeds[0], components=button_origin_msg) except: pass sql = "SELECT thread_id FROM posts WHERE post_id = %s" val = (ctx.origin_message.id,) await mysql_commit(sql=sql, val=val) query = sql_connect.fetchall() if query: if query[0]['thread_id'] != '': thread_id = query[0]['thread_id'] if ctx.origin_message.channel.get_thread(int(thread_id)): message_thread = ctx.origin_message.channel.get_thread(int(thread_id)) await message_thread.remove_user(ctx.author) await ctx.send(content=f'❕┃**Team Thread Left**:\n• You have been removed from the following Thread due to leaving said Team: <#{thread_id}>', hidden=True) elif ctx.origin_message.embeds[0].title == 'Event Organizer:': await ctx.send(content='❌┃**Left Event**:\n• You have been removed as a Participant. Feel free to join another Event anytime.' + tip_member, embed=ctx.origin_message.embeds[0], components=button_origin_msg, hidden=True) else: if ctx.origin_message.embeds[0].title == 'Team Organizer:': await ctx.send(content='❗┃**Unable to Leave, not a Team Member**:' + tip_member, embed=ctx.origin_message.embeds[0], components=button_origin_msg, hidden=True) elif ctx.origin_message.embeds[0].title == 'Event Organizer:': await ctx.send(content='❗┃**Unable to Leave, not a Participant**:' + tip_member, embed=ctx.origin_message.embeds[0], components=button_origin_msg, hidden=True) else: if ctx.origin_message.embeds[0].title == 'Team Organizer:': await ctx.send(content='❗┃**Unable to Leave, No Current Team Members**:' + tip_member, embed=ctx.origin_message.embeds[0], components=button_origin_msg, hidden=True) elif ctx.origin_message.embeds[0].title == 'Event Organizer:': await ctx.send(content='❗┃**Unable to Leave, No Current Participants**:' + tip_member, embed=ctx.origin_message.embeds[0], components=button_origin_msg, hidden=True) else: if (ctx.custom_id == 'post_join') & (ctx.origin_message.embeds[0].title == 'Team Organizer:'): await ctx.send(content='❗┃**Unable to Join Own Team**:' + tip_host, embed=ctx.origin_message.embeds[0], components=button_origin_msg, hidden=True) elif (ctx.custom_id == 'post_join') & (ctx.origin_message.embeds[0].title == 'Event Organizer:'): await ctx.send(content='❗┃**Unable to Join Own Event**:' + tip_host, embed=ctx.origin_message.embeds[0], components=button_origin_msg, hidden=True) elif (ctx.custom_id == 'post_leave') & (ctx.origin_message.embeds[0].title == 'Team Organizer:'): await ctx.send(content='❗┃**Unable to Leave Own Team**:' + tip_host, embed=ctx.origin_message.embeds[0], components=button_origin_msg, hidden=True) elif (ctx.custom_id == 'post_leave') & (ctx.origin_message.embeds[0].title == 'Event Organizer:'): await ctx.send(content='❗┃**Unable to Leave Own Event**:' + tip_host, embed=ctx.origin_message.embeds[0], components=button_origin_msg, hidden=True) elif (ctx.custom_id == 'post_close') | (ctx.custom_id == 'post_disband'): if (ctx.custom_id == 'post_close') & (int(post_organizer_id) == ctx.author.id): if members_field is True: if ctx.origin_message.embeds[0].title == 'Team Organizer:': for member in members_list: try: await ctx.guild.get_member(int(member)).send(content='🔒┃**Team Closed**:\n• Team Organizer has decided to start early before all available slots filled.\n• Please visit the Team\'s assigned thread and contact Team Organizer <@' + str(post_organizer_id) + '> to coordinate friend requests and in-game plans, have fun!', embed=ctx.origin_message.embeds[0]) except: pass await ctx.send(content='🔒┃**Team Closed**:\n• All Team Members have been informed of the Team starting early and your contact info.\n• Please visit the Team\'s assigned thread and contact the below listed Team Members to coordinate friend requests and in-game plans, have fun!', embed=ctx.origin_message.embeds[0], hidden=True) elif ctx.origin_message.embeds[0].title == 'Event Organizer:': for member in members_list: try: await ctx.guild.get_member(int(member)).send(content='🔒┃**Event Starting Early**:\n• Event Organizer has decided to start early before the designated Start Time.\n• Please return to Events channel and visit the Event\'s created thread for instructions from Event Organizer <@' + str(post_organizer_id) + '> on arranging friend requests and in-game plans, have fun!', embed=ctx.origin_message.embeds[0]) except: pass await ctx.send(content='🔒┃**Event Starting Early**:\n• All Participants have been informed of the Event starting early and your contact info.\n• Please return to Events channel and visit the Event\'s created thread to contact the below listed Participants so you can coordinate friend requests and in-game plans, have fun!', embed=ctx.origin_message.embeds[0], hidden=True) if members_list_len > 40: sql = "SELECT post_members FROM posts WHERE post_id = %s" val = (ctx.origin_message.id,) await mysql_commit(sql=sql, val=val) members_query = sql_connect.fetchall() try: await post_organizer.send(content='❗┃**Full Members List**:\n• Your post contained more than 50 members, see below all of their names!\n\n' + members_query[0]['post_members']) except: pass event_msg = await ctx.channel.send(content='📅┃**Event Now Starting**:\n• The below Event is now live, please visit the Event\'s created thread for further instructions or DM the Event Organizer!', embed=ctx.origin_message.embeds[0], delete_after=900) event_thread = '' if str(event_msg.embeds[0].fields[1].name) == 'Event Game:': event_thread = await event_msg.start_thread(name='Event - ' + ctx.author.display_name + ' | ' + str(event_msg.embeds[0].fields[1].value), auto_archive_duration=60) elif str(ctx.origin_message.embeds[0].fields[2].name) == 'Event Game:': event_thread = await event_msg.start_thread(name='Event - ' + ctx.author.display_name + ' | ' + str(event_msg.embeds[0].fields[2].value), auto_archive_duration=60) info_msg = await event_thread.send(content='📅┃**Event Information**:\n• Please use this thread to coordinate friend requests and in-game plans for the below Event.', embed=event_msg.embeds[0], components=thread_button) await info_msg.pin() try: await event_thread.add_user(ctx.author) except: pass if str(event_msg.embeds[0].fields[0].name) == 'Participants:': for member_id in members_list: if ctx.author.guild.get_member(int(member_id)) is not None: usr = await client.fetch_user(int(member_id)) try: await event_thread.add_user(usr) except: pass try: await usr.send(content=f'❕┃**Event Thread Created**:\n• Please visit the following Thread to discuss the started Event: <#{str(event_thread.id)}>') except: pass sql = "DELETE FROM posts WHERE post_id = %s" val = (ctx.origin_message_id,) await mysql_commit(sql=sql, val=val) await ctx.origin_message.delete() else: if ctx.origin_message.embeds[0].title == 'Team Organizer:': await ctx.send(content='❗┃**Unable to Close Team**:\n• Your team currently contains no Team Members.\n• Please use the `🛑 Disband` option when removing empty teams.', embed=ctx.origin_message.embeds[0], components=button_origin_msg, hidden=True) elif ctx.origin_message.embeds[0].title == 'Event Organizer:': await ctx.send(content='❗┃**Unable to Start Event Early**:\n• Your event currently contains no Participants.\n• Please use the `🛑 Disband` option when removing empty events.', embed=ctx.origin_message.embeds[0], components=button_origin_msg, hidden=True) elif ((ctx.custom_id == 'post_disband') & (int(post_organizer_id) == ctx.author.id)) | ((ctx.custom_id == 'post_disband') & bool([item for item in ctx.author.guild_permissions if (item[0] == 'administrator') & (item[1] is True)]) & (not(int(post_organizer_id) == ctx.author.id))) | ((ctx.custom_id == 'post_disband') & bool([item for item in ctx.author.guild_permissions if (item[0] == 'manage_messages') & (item[1] is True)]) & (not(int(post_organizer_id) == ctx.author.id))) | ((ctx.custom_id == 'post_disband') & bool([item for item in ctx.author.guild_permissions if (item[0] == 'manage_channels') & (item[1] is True)]) & (not(int(post_organizer_id) == ctx.author.id))): if int(post_organizer_id) == ctx.author.id: if (ctx.origin_message.embeds[0].title == 'Team Organizer:') & (members_list_len > 0): if members_field is True: for member in members_list: try: await ctx.guild.get_member(int(member)).send(content='🛑┃**Team Disbanded**:\n• Team Organizer has decided to remove their team and cease playing.\n• You do not need to contact them, feel free to instead join a new Team anytime.', embed=ctx.origin_message.embeds[0]) except: pass await ctx.send(content='🛑┃**Team Disbanded**:\n• All Team Members have been informed of your intention to no longer play.\n• You do not need to contact them, feel free to post a new Team anytime.', embed=ctx.origin_message.embeds[0], hidden=True) elif (ctx.origin_message.embeds[0].title == 'Event Organizer:') & (members_list_len > 0): if members_field is True: for member in members_list: try: await ctx.guild.get_member(int(member)).send(content='🛑┃**Event Canceled**:\n• Event Organizer has decided to cancel the Event and cease plans.\n• You do not need to contact them, feel free to instead join a new Event anytime.', embed=ctx.origin_message.embeds[0]) except: pass await ctx.send(content='🛑┃**Event Canceled**:\n• All Participants have been informed of your intention to no longer play.\n• You do not need to contact them, feel free to post a new Event anytime.', embed=ctx.origin_message.embeds[0], hidden=True) else: if ctx.origin_message.embeds[0].title == 'Team Organizer:': await ctx.send(content='🛑┃**Team Disbanded**:\n• No Team Members at time of Disband.\n• You do not need to contact anyone, feel free to post a new Team anytime.', embed=ctx.origin_message.embeds[0], hidden=True) elif ctx.origin_message.embeds[0].title == 'Event Organizer:': await ctx.send(content='🛑┃**Event Canceled**:\n• No Participants at time of Disband.\n• You do not need to contact anyone, feel free to post a new Event anytime.', embed=ctx.origin_message.embeds[0], hidden=True) else: if (ctx.origin_message.embeds[0].title == 'Team Organizer:') & (members_list_len > 0): if members_field is True: await ctx.send(content='🛑┃**Team Disbanded - Administrator Deletion**:\n• The below Team has been removed per your request as an Administrator/Moderator.', embed=ctx.origin_message.embeds[0], hidden=True) for member in members_list: try: await ctx.guild.get_member(int(member)).send(content='🛑┃**Team Disbanded - Administrator Deletion**:\n• The below Team you were a Team Member of has been removed by an Administrator.\n• You do not need to contact the Team Organizer, feel free to instead join a new Team anytime.', embed=ctx.origin_message.embeds[0]) except: pass try: await post_organizer.send(content='🛑┃**Team Disbanded - Administrator Deletion**:\n• The below Team you were Team Organizer of has been removed by an Administrator, ensure you are following all Server rules when posting.\n• You do not need to contact the Team Members, feel free to instead post a new Team anytime.', embed=ctx.origin_message.embeds[0]) except: pass elif (ctx.origin_message.embeds[0].title == 'Event Organizer:') & (members_list_len > 0): if members_field is True: await ctx.send(content='🛑┃**Event Disbanded - Administrator Deletion**:\n• The below Event has been removed per your request as an Administrator/Moderator.', embed=ctx.origin_message.embeds[0], hidden=True) for member in members_list: try: await ctx.guild.get_member(int(member)).send(content='🛑┃**Event Disbanded - Administrator Deletion**:\n• The below Event you were a Participant of has been removed by an Administrator.\n• You do not need to contact the Event Organizer, feel free to instead join a new Event anytime.', embed=ctx.origin_message.embeds[0]) except: pass try: await post_organizer.send(content='🛑┃**Event Disbanded - Administrator Deletion**:\n• The below Event you were Organizer of has been removed by an Administrator, ensure you are following all Server rules when posting.\n• You do not need to contact the Participants, feel free to instead post a new Event anytime.', embed=ctx.origin_message.embeds[0]) except: pass else: if ctx.origin_message.embeds[0].title == 'Team Organizer:': await ctx.send(content='🛑┃**Team Disbanded - Administrator Deletion**:\n• The below Team has been removed per your request as an Administrator/Moderator.', embed=ctx.origin_message.embeds[0], hidden=True) try: await post_organizer.send(content='🛑┃**Team Disbanded - Administrator Deletion**:\n• The below Team you were Organizer of has been removed by an Administrator, ensure you are following all Server rules when posting.\n• You did not have any Team Members at the time of removal, feel free to instead post a new Team anytime.', embed=ctx.origin_message.embeds[0]) except: pass elif ctx.origin_message.embeds[0].title == 'Event Organizer:': await ctx.send(content='🛑┃**Event Disbanded - Administrator Deletion**:\n• The below Event has been removed per your request as an Administrator/Moderator.', embed=ctx.origin_message.embeds[0], hidden=True) try: await post_organizer.send(content='🛑┃**Event Disbanded - Administrator Deletion**:\n• The below Team you were Organizer of has been removed by an Administrator, ensure you are following all Server rules when posting.\n• You did not have any Participants at the time of removal, feel free to instead post a new Event anytime.', embed=ctx.origin_message.embeds[0]) except: pass if ctx.origin_message.embeds[0].title == 'Team Organizer:': sql = "SELECT thread_id FROM posts WHERE post_id = %s" val = (ctx.origin_message.id,) await mysql_commit(sql=sql, val=val) query = sql_connect.fetchall() if query: if query[0]['thread_id'] != '': thread_id = query[0]['thread_id'] if ctx.origin_message.channel.get_thread(int(thread_id)): message_thread = ctx.origin_message.channel.get_thread(int(thread_id)) await message_thread.delete() await ctx.origin_message.delete() sql = "DELETE FROM posts WHERE post_id = %s" val = (ctx.origin_message_id,) await mysql_commit(sql=sql, val=val) else: if ctx.origin_message.embeds[0].title == 'Team Organizer:': err_tip = '\n\n**Team Organizer Options**:\n• `🔒 Close` will remove your post and inform Team Members it is time to start.\n• `🛑 Disband` will remove your post and inform Team Members you intend to no longer play.' await ctx.send(content='❗┃**Error, you are NOT the Team Organizer**:\n\n**Team Member Options**:\n• `✔️ Join` will add you to the Team\'s Members, the Team Organizer will be informed.\n• `❌ Leave` will remove you from the Team\'s Members, the Team Organizer will be informed.' + err_tip, embed=ctx.origin_message.embeds[0], components=button_origin_msg, hidden=True) elif ctx.origin_message.embeds[0].title == 'Event Organizer:': err_tip = '\n\n**Event Organizer Options**:\n• `🔒 Close` will remove your post and inform Participants it is time to start early.\n• `🛑 Disband` will cancel your Event and inform Participants you intend to no longer play.' await ctx.send(content='❗┃**Error, you are NOT the Event Organizer**:\n\n**Participant Options**:\n• `✔️ Join` will add you to the Event\'s Participants, you will be informed once the Event starts.\n• `❌ Leave` will remove you from the Event\'s Participants.' + err_tip, embed=ctx.origin_message.embeds[0], components=button_origin_msg, hidden=True) elif ctx.custom_id == 'lfg_info': sql = "SELECT channel_lfgPosts_id, channel_events_id, lfg_formats FROM guilds WHERE guild_id = %s" val = (ctx.author.guild.id,) await mysql_commit(sql=sql, val=val) sql_query = sql_connect.fetchall() game_titles = [] if (sql_query[0]['lfg_formats'] is not None) & (sql_query[0]['lfg_formats'] != ''): for values in lfg_games_values: if values[0] in sql_query[0]['lfg_formats']: game_titles.append(values[1]) game_titles = '\n• '.join(game_titles) else: game_titles = 'Please contact your server admin to have them re-run the `/setup` command to define LFG formats.' embed_message_error = discord.Embed(title=client.user.display_name + ' - Supported Games', description='Thank you for your inquiry. See below this server\'s supported games you may create LFG Teams or Events for. Ask your server admins to add more supported games if interested!', color=0xffffff) embed_message_error.add_field(name="Supported LFG & Event Games:", value='• ' + game_titles, inline=False) if client.get_channel(int(sql_query[0]['channel_lfgPosts_id'])) is not None: embed_message_error.add_field(name="Where to post LFG Teams:", value='• <#' + sql_query[0]['channel_lfgPosts_id'] + '>', inline=False) else: embed_message_error.add_field(name="Where to post LFG Teams:", value='• Please contact your server admin to have them re-run the `/setup` command to create a channel for LFG Teams.', inline=False) if client.get_channel(int(sql_query[0]['channel_events_id'])) is not None: embed_message_error.add_field(name="Where to post Events:", value='• <#' + sql_query[0]['channel_events_id'] + '>', inline=False) else: embed_message_error.add_field(name="Where to post Events:", value='• Please contact your server admin to have them re-run the `/setup` command to create a channel for Events.', inline=False) try: embed_message_error.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message_error.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass embed_message_error.timestamp = datetime.datetime.now() embed_message_error.set_footer(text=txt_footer + str(embed_message_error.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_error.set_thumbnail(url=img_tip) await ctx.send(embed=embed_message_error, hidden=True) # ################ LFG Commands ######################## @slash.slash(name='host', description='Used to submit an LFG or Event Post for this server\'s supported games!', options=host_options) async def host(ctx, type: str, platform: str, game: str, activity: str, description: str, size: int, username: str, experience: str = '', server: str = '', date: str = '', banner: str = ''): sql = "SELECT channel_lfgPosts_id, channel_events_id, event_perms FROM guilds WHERE guild_id = %s" val = (ctx.author.guild.id,) await mysql_commit(sql=sql, val=val) ids = sql_connect.fetchall() sql = "SELECT lfg_formats FROM guilds WHERE guild_id = %s" val = (ctx.author.guild.id,) await mysql_commit(sql=sql, val=val) sql_fetch = sql_connect.fetchone() formats_db = '' if sql_fetch is not None: formats_db = sql_fetch['lfg_formats'] formats_db_list = [] formats_correct = False if (formats_db is not None) & (formats_db != ''): formats_db_list = formats_db.split(" ") for element in formats_db_list: if element == game: formats_correct = True break game_titles = [] if ((formats_db is not None) & (formats_db != '')) & (formats_correct is False): for values in lfg_games_values: if values[0] in formats_db: game_titles.append(values[1]) game_titles = '\n• '.join(game_titles) else: game_titles = '• Please contact your server admin to have them re-run the `/setup` command to define LFG formats.' for element in host_options[1]['choices']: if element['value'] == platform: platform = element['name'] thumbnail_url = '' for element in img_games: if element['value'] == game: thumbnail_url = element['img_url'] clr_game = 0 for element in img_games: if element['value'] == game: clr_game = element['color'] for element in host_options[2]['choices']: if element['value'] == game: game = element['name'] timezones = {} for tz in pendulum.timezones: if (not (any(i.isdigit() for i in str(timezone(tz).tzname(datetime.datetime.now()))))) & ('+' not in str(timezone(tz).tzname(datetime.datetime.now()))) & ('-' not in str(timezone(tz).tzname(datetime.datetime.now()))): if timezone(tz).tzname(datetime.datetime.now()) not in timezones: timezones[f'{timezone(tz).tzname(datetime.datetime.now())}'] = tz error_date_expiring = False error_date_timezone = False error_date_valid = False error_date_length = False starttime = '' fmt = "%Y-%m-%d %H:%M" if (type == 'type_event') & bool(date): start_time_array = date.split(' ') if len(date.split(' ')) >= 3: start_time_array = start_time_array[0:3] start_time = start_time_array[0] + ' ' + start_time_array[1] if start_time_array[2] in timezones: start_timezone = timezones[start_time_array[2]] try: formatted_date = datetime.datetime.strptime(start_time, fmt) formatted_date = formatted_date.replace(tzinfo=pendulum.timezone(start_timezone)) converted_date = pendulum.timezone('UTC').convert(formatted_date) converted_date = datetime.datetime.strptime(converted_date.strftime(fmt), '%Y-%m-%d %H:%M') converted_date_utc = datetime.datetime.timestamp(formatted_date) converted_date_utc = str(str(converted_date_utc).partition('.')[0]) date_link = '[<t:' + converted_date_utc + ':F>](https://www.epochconverter.com/timezones?q=' + converted_date_utc + ')' # date_link = '[' + str(converted_date) + '](https://www.timeanddate.com/worldclock/converter.html?iso=' + str(converted_date.strftime('%Y%m%d')) + 'T' + str(converted_date.strftime('%H%M%S')) + '&p1=tz_utc)' time_now = datetime.datetime.utcnow() time_now = datetime.datetime.strptime(time_now.strftime(fmt), '%Y-%m-%d %H:%M') if converted_date >= time_now + timedelta(seconds=1200): starttime = (converted_date - time_now).total_seconds() else: error_date_valid = True error_date_expiring = True except: error_date_valid = True pass else: error_date_timezone = True else: error_date_length = True expected_permissions = ['manage_nicknames', 'kick_members', 'ban_members', 'mute_members', 'deafen_members', 'move_members', 'administrator', 'manage_roles', 'manage_messages', 'manage_channels'] has_permission = False if (type == 'type_event') & (ids[0]['event_perms'] == 'restrict'): for permission in ctx.author.guild_permissions: if (permission[0] in expected_permissions) & (permission[1] is True): has_permission = True break else: has_permission = True if ((has_permission is True) & (formats_correct is True)) & (((type == 'type_lfg') & (discord.utils.get(ctx.author.guild.channels, id=int(ids[0]['channel_lfgPosts_id'])) is not None)) | ((type == 'type_event') & (discord.utils.get(ctx.author.guild.channels, id=int(ids[0]['channel_events_id'])) is not None)) & (formats_correct is True) & (bool(date)) & ((error_date_expiring is False) & (error_date_valid is False) & (error_date_length is False) & (error_date_timezone is False))): # Build post to Submit if size <= 0: size = 1 elif size > 10000: size = 10000 embed_message_post = '' organizer = '<@' + str(ctx.author.id) + '>' if type == 'type_lfg': embed_message_post = discord.Embed(title="Team Organizer:", description=organizer, color=clr_game) embed_message_post.add_field(name="Platform:", value=platform, inline=True) embed_message_post.add_field(name="Game:", value=game, inline=True) embed_message_post.add_field(name="Available Slots:", value='**' + str(size) + '**', inline=True) embed_message_post.add_field(name="In-Game Name:", value=username, inline=True) elif type == 'type_event': embed_message_post = discord.Embed(title="Event Organizer:", description=organizer, color=clr_game) embed_message_post.add_field(name="Event Platform:", value=platform, inline=True) embed_message_post.add_field(name="Event Game:", value=game, inline=True) embed_message_post.add_field(name="Available Slots:", value='**' + str(size) + '**', inline=True) embed_message_post.add_field(name="In-Game Name:", value=username, inline=True) if type == 'type_lfg': embed_message_post.add_field(name="Activity:", value=activity, inline=False) embed_message_post.add_field(name="Description:", value=description, inline=False) if type == 'type_event': embed_message_post.add_field(name="Event Title:", value=activity, inline=False) embed_message_post.add_field(name="Event Details:", value=description, inline=False) if experience: embed_message_post.add_field(name="Desired Skillset:", value=experience, inline=True) if server: if ('aoe2de://0/' in server) & (game == 'Age of Empires 2'): if 'aoe2de://0/' in server: second = server.split('aoe2de://0/')[1][0:9] if second.isdigit(): server = '[Join Game](https://aoe2.net/j/' + second + ')' embed_message_post.add_field(name="Server/Lobby ID:", value=server, inline=True) if type == 'type_event': if date: embed_message_post.add_field(name="Start Time:", value=date_link, inline=False) if bool(banner) & (len(banner) < 2048): if validators.url(banner): embed_message_post.set_image(url=banner) embed_message_post.timestamp = datetime.datetime.now() embed_message_post.set_footer(text="Join or Leave this by interacting below!\nPosted" + str(embed_message_post.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_post.set_thumbnail(url=thumbnail_url) # Submit post to correct channel lfg_msg = '' lfg_thread = '' if type == 'type_lfg': lfg_posts_channel = client.get_channel(int(ids[0]['channel_lfgPosts_id'])) await silent_expired_posts(channel=lfg_posts_channel, type='type_lfg') lfg_msg = await lfg_posts_channel.send(embed=embed_message_post, components=post_buttons, delete_after=900) lfg_thread = await lfg_msg.start_thread(name='Team - ' + ctx.author.display_name + ' | ' + game, auto_archive_duration=60) info_msg = await lfg_thread.send(content='📑┃**LFG Team Information**:\n• Please use this thread to coordinate friend requests and in-game plans for the below Team.', embed=embed_message_post, components=thread_button) await info_msg.pin() try: await lfg_thread.add_user(ctx.author) except: pass sql = "INSERT INTO posts (guild_id, post_id, thread_id, type, post_organizer, platform, slots, game, game_clr, game_img, activity, description, username, experience, server, posttime) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)" val = (ctx.author.guild.id, lfg_msg.id, lfg_thread.id, type, organizer, platform, '**' + str(size) + '**', game, clr_game, thumbnail_url, activity, description, username, experience, server, str(embed_message_post.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f'))) await mysql_commit(sql=sql, val=val) elif type == 'type_event': events_channel = client.get_channel(int(ids[0]['channel_events_id'])) await silent_expired_posts(channel=events_channel, type='type_event') lfg_msg = await events_channel.send(embed=embed_message_post, components=post_buttons, delete_after=starttime) sql = "INSERT INTO posts (guild_id, post_id, type, post_organizer, platform, slots, game, game_clr, game_img, activity, description, username, experience, server, posttime, date, banner) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)" val = (ctx.author.guild.id, lfg_msg.id, type, organizer, platform, '**' + str(size) + '**', game, clr_game, thumbnail_url, activity, description, username, experience, server, str(embed_message_post.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')), converted_date, banner) await mysql_commit(sql=sql, val=val) # Submit Hidden Confirmation of Accepted Post button_lfg_post = [create_actionrow(create_button(style=ButtonStyle.URL, label="LFG Post", emoji='📑', url=str(lfg_msg.jump_url)))] button_event_post = [create_actionrow(create_button(style=ButtonStyle.URL, label="Event Post", emoji='📅', url=str(lfg_msg.jump_url)))] embed_message_success = '' if type == 'type_lfg': embed_message_success = discord.Embed(title='📝 | LFG Draft - Submitted', description='Your LFG Post is now visible and availble for interactions:\n• All LFG Posts expire 15 minutes after initial posting.', color=clr_game) elif type == 'type_event': embed_message_success = discord.Embed(title='📝 | Event Draft - Submitted', description='Your Event is now visible and availble for interactions:\n• All Event Posts are removed 15 minutes after designated start time.', color=clr_game) embed_message_success.add_field(name="Platform:", value=platform, inline=True) embed_message_success.add_field(name="Game:", value=game, inline=True) embed_message_success.add_field(name="Available Slots:", value='**' + str(size) + '**', inline=True) embed_message_success.add_field(name="In-Game Name:", value=username, inline=True) embed_message_success.add_field(name="Activity:", value=activity, inline=False) embed_message_success.add_field(name="Description:", value=description, inline=False) if experience: embed_message_success.add_field(name="Experience:", value=experience, inline=True) if server: if ('aoe2de://0/' in server) & (game == 'Age of Empires 2'): if 'aoe2de://0/' in server: second = server.split('aoe2de://0/')[1][0:9] if second.isdigit(): server = '[Join Game](https://aoe2.net/j/' + second + ')' embed_message_success.add_field(name="Server/Lobby ID:", value=server, inline=True) if type == 'type_event': if date: embed_message_success.add_field(name="Start Time:", value=date_link, inline=False) if bool(banner) & (len(banner) < 2048): if validators.url(banner): embed_message_success.set_image(url=banner) try: embed_message_success.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message_success.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass embed_message_success.timestamp = datetime.datetime.now() embed_message_success.set_footer(text=txt_footer + str(embed_message_success.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_success.set_thumbnail(url=thumbnail_url) if type == 'type_lfg': await ctx.send(embed=embed_message_success, hidden=True, components=button_lfg_post) await check_submitted_posts(ctx, lfg_msg) await check_joined_posts(ctx) elif type == 'type_event': await ctx.send(embed=embed_message_success, hidden=True, components=button_event_post) sql = "SELECT global_search, global_search_invite FROM guilds WHERE guild_id = %s" val = (ctx.guild.id,) await mysql_commit(sql=sql, val=val) guild_info = sql_connect.fetchall() if guild_info[0]['global_search'] == 'yes': choice = '' game_value = '' platform_value = '' button_post_join = '' button_notify_remove = '' if type == 'type_lfg': choice = 'type_lfg' button_post_join = [create_actionrow(create_button(style=ButtonStyle.URL, label="Join Team", emoji='📑', url=str(guild_info[0]['global_search_invite'])))] button_notify_remove = [create_actionrow(create_button(style=ButtonStyle.danger, label="Stop LFG Post Notifications", emoji='🛑', custom_id='notify_remove_lfg'))] elif type == 'type_event': choice = 'type_events' button_post_join = [create_actionrow(create_button(style=ButtonStyle.URL, label="Join Event", emoji='📅', url=str(guild_info[0]['global_search_invite'])))] button_notify_remove = [create_actionrow(create_button(style=ButtonStyle.danger, label="Stop Event Notifications", emoji='🛑', custom_id='notify_remove_event'))] for element in host_options[2]['choices']: if element['name'] == game: game_value = element['value'] for element in host_options[1]['choices']: if element['name'] == platform: platform_value = element['value'] sql = "SELECT * FROM notify WHERE choice = %s AND game = %s" val = (choice, game_value) await mysql_commit(sql=sql, val=val) notify_members = sql_connect.fetchall() for member in notify_members: if member['user_id'] != str(ctx.author.id): usr = await client.fetch_user(int(member['user_id'])) if choice == 'type_lfg': post_type = 'LFG Post' elif choice == 'type_events': post_type = 'Event' embed_message = discord.Embed(title=client.user.display_name + ' - Notification Alert', description=f'See below a notitication of a new {post_type} added to the Global Network which meets your notification criteria.', color=0xffffff) embed_message.add_field(name='Preferred Game:', value=game, inline=False) if member['platform']: platform_title = '' for element in host_options[1]['choices']: if element['value'] == member['platform']: platform_title = element['name'] embed_message.add_field(name='Preferred Platform:', value=platform_title, inline=False) else: embed_message.add_field(name='Preferred Platform:', value='No Specific Platform Selected', inline=False) embed_message.add_field(name='Helpful Tips:', value=f'\n• Stop {post_type} notifications simply by joining any {post_type} or using the `🛑 Stop {post_type} Notifications` button attached to any notification.\n• You can be subscribed for notifications of Events & LFG posts at the same time!', inline=False) try: embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass embed_message.timestamp = datetime.datetime.now() embed_message.set_footer(text=txt_footer + str(embed_message.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message.set_thumbnail(url=img_logo) if member['platform']: if (member['game'] == game_value) & (member['platform'] == platform_value): try: await usr.send(embed=embed_message, components=button_notify_remove) await usr.send(content='🕹️┃**Discord Server**: ' + ctx.guild.name, embed=embed_message_post, components=button_post_join) except: pass else: if member['game'] == game_value: try: await usr.send(embed=embed_message, components=button_notify_remove) await usr.send(content='🕹️┃**Discord Server**: ' + ctx.guild.name, embed=embed_message_post, components=button_post_join) except: pass else: embed_message_error = discord.Embed(title='📝 | Draft Post Error', description='Please see below a list of errors encountered upon posting.', color=clr_error) if has_permission is False: embed_message_error.add_field(name="Error - Missing Permissions:", value='• Please note Event creation is currently restricted to those with moderation or administration permissions only thus your post has been rejected, feel free however to join any other Event!.', inline=False) else: if (type == 'type_lfg') & (discord.utils.get(ctx.author.guild.channels, id=int(ids[0]['channel_lfgPosts_id'])) is None): embed_message_error.add_field(name="Error - Missing LFG Channel:", value='• Your submitted LFG Draft is unable to be processed at this time due to this server not having a channel assigned to LFG Posts.\nPlease contact your server admin to have them re-run the `/setup` command.', inline=False) elif (type == 'type_event') & (discord.utils.get(ctx.author.guild.channels, id=int(ids[0]['channel_events_id'])) is None): embed_message_error.add_field(name="Error - Missing Event Channel:", value='• Your submitted Event Draft is unable to be processed at this time due to this server not having a channel assigned to Event Posts.\nPlease contact your server admin to have them re-run the `/setup` command.', inline=False) else: if formats_correct is False: embed_message_error.add_field(name="Error - Unsupported Game:", value='• The Game you specified to host for is not supported by the server at this time.', inline=False) embed_message_error.add_field(name="Currently Supported Games:", value=f'• {game_titles}', inline=False) if bool(not date): embed_message_error.add_field(name="Error - Missing `Date` Parameter:", value='• Please re-submit your `/host` request with use of the `Date` option, in order to set a Start Time for your Event', inline=False) embed_message_error.add_field(name="Helpful Tip:", value='• Remember when specifying a Start Time to build it like so - Date, Time, Timezone Code (Ex: YYYY-MM-DD HH:MM ZONE)', inline=False) else: if error_date_valid is False: embed_message_error.add_field(name="Helpful Tip:", value='• Remember when specifying a Start Time to build it like so - Date, Time, Timezone Code (Ex: YYYY-MM-DD HH:MM ZONE)', inline=False) if error_date_expiring is True: embed_message_error.add_field(name="Error - Expiring Soon:", value='• The Start Time you provided was less than 20 minutes in the future.', inline=False) if (error_date_valid is True) | (error_date_length is True): embed_message_error.add_field(name="Error - Invalid Date Format:", value='• The Start Time you provided was not following the proper format, please ensure to provide - Date, Time, Timezone Code (Ex: 2022-12-30 12:00 PST || YYYY-MM-DD HH:MM ZONE).', inline=False) if len(date.split(' ')) == 2: if (date.split(' ')[0] not in timezones) & (date.split(' ')[1] not in timezones): embed_message_error.add_field(name="Error - Missing Timezone:", value='• No Timezone Code was provided for your Start Time, see the following code sources.\n• [Table of Timezone Codes](https://en.wikipedia.org/wiki/List_of_time_zone_abbreviations)\n• [Interactive TimeZone Map W/ Codes](https://www.timeanddate.com/time/map/)', inline=False) if error_date_timezone is True: embed_message_error.add_field(name="Error - Invalid Timezone:", value='• The Timezone Code you provided is not a valid code, see the following code sources.\n• [Table of Timezone Codes](https://en.wikipedia.org/wiki/List_of_time_zone_abbreviations)\n• [Interactive TimeZone Map W/ Codes](https://www.timeanddate.com/time/map/)', inline=False) # Re-construction of submission embed_message_error.add_field(name="Post Draft Parameters:", value='See below your submitted parameters.', inline=False) embed_message_error.add_field(name="Platform:", value=platform, inline=True) embed_message_error.add_field(name="Game:", value=game, inline=True) embed_message_error.add_field(name="Available Slots:", value='**' + str(size) + '**', inline=True) embed_message_error.add_field(name="In-Game Name:", value=username, inline=True) embed_message_error.add_field(name="Activity:", value=activity, inline=False) embed_message_error.add_field(name="Description:", value=description, inline=False) if experience: embed_message_error.add_field(name="Experience:", value=experience, inline=True) if server: if ('aoe2de://0/' in server) & (game == 'Age of Empires 2'): if 'aoe2de://0/' in server: second = server.split('aoe2de://0/')[1][0:9] if second.isdigit(): server = '[Join Game](https://aoe2.net/j/' + second + ')' embed_message_error.add_field(name="Server:", value=server, inline=True) if type == 'type_event': if date: embed_message_error.add_field(name="Start Date:", value=date, inline=False) if bool(banner) & (len(banner) < 2048): if validators.url(banner): embed_message_error.set_image(url=banner) try: embed_message_error.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message_error.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass embed_message_error.timestamp = datetime.datetime.now() embed_message_error.set_footer(text=txt_footer + str(embed_message_error.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_error.set_thumbnail(url=img_error) await ctx.send(embed=embed_message_error, hidden=True) @slash.slash(name='modify', description='Used to modify the parameters of an already active LFG or Event Post!', options=post_modify) async def search(ctx, post_id: str = '', platform: str = '', game: str = '', activity: str = '', description: str = '', size: int = None, username: str = '', experience: str = '', server: str = '', date: str = '', banner: str = ''): sql = "SELECT channel_lfgPosts_id, channel_events_id, lfg_formats FROM guilds WHERE guild_id = %s" val = (ctx.author.guild.id,) await mysql_commit(sql=sql, val=val) channels = sql_connect.fetchall() lfg_posts_channel = None events_channel = None post = None tips = '• Ensure you are providing a valid Post ID by simply right-clicking or viewing the options of any post you are Organizer of AND is listed as posted by <@' + str(client.user.id) + '>, then choosing `Copy ID`' expected_permissions = ['manage_nicknames', 'kick_members', 'ban_members', 'mute_members', 'deafen_members', 'move_members', 'administrator', 'manage_roles', 'manage_messages', 'manage_channels'] timezones = {} for tz in pendulum.timezones: if (not (any(i.isdigit() for i in str(timezone(tz).tzname(datetime.datetime.now()))))) & ('+' not in str(timezone(tz).tzname(datetime.datetime.now()))) & ('-' not in str(timezone(tz).tzname(datetime.datetime.now()))): if timezone(tz).tzname(datetime.datetime.now()) not in timezones: timezones[f'{timezone(tz).tzname(datetime.datetime.now())}'] = tz error_date_expiring = False error_date_timezone = False error_date_valid = False error_date_length = False starttime = '' fmt = "%Y-%m-%d %H:%M" # Build Parameters confirmation message embed_message_parameters = discord.Embed(title=client.user.display_name + ' - Provided Parameters', description='Below is a re-hash of the parameters you provided upon use of `/modify`', color=0xffffff) # if members != '': # embed_message_parameters.add_field(name="Members:", value=members, inline=False) if post_id != '': if post_id.replace(" ", "").isdigit(): post_id = int(post_id.replace(" ", "")) embed_message_parameters.add_field(name="Post ID:", value=post_id, inline=False) else: embed_message_parameters.add_field(name="Post ID:", value=post_id + ' - Incorrect, please only provide numbers!', inline=False) if platform != '': for element in host_options[1]['choices']: if element['value'] == platform: platform = element['name'] embed_message_parameters.add_field(name="Platform:", value=platform, inline=False) if game != '': for element in host_options[2]['choices']: if element['value'] == game: game_name = element['name'] embed_message_parameters.add_field(name="Game:", value=game_name, inline=False) if activity != '': embed_message_parameters.add_field(name="Activity:", value=activity, inline=False) if description != '': embed_message_parameters.add_field(name="Description:", value=description, inline=False) if size is not None: if int(size) <= 0: size = 1 embed_message_parameters.add_field(name="Size:", value='**' + str(size) + '** - Size must be 1 or higher.', inline=False) elif int(size) > 10000: size = 10000 embed_message_parameters.add_field(name="Size:", value='**' + str(size) + '** - Size must be 10000 or lower.', inline=False) else: embed_message_parameters.add_field(name="Size:", value='**' + str(size) + '**', inline=False) if username != '': embed_message_parameters.add_field(name="Username:", value=username, inline=False) if experience != '': embed_message_parameters.add_field(name="Experience:", value=experience, inline=False) if server != '': embed_message_parameters.add_field(name="Server:", value=server, inline=False) if date != '': start_time_array = date.split(' ') if len(date.split(' ')) >= 3: start_time_array = start_time_array[0:3] start_time = start_time_array[0] + ' ' + start_time_array[1] if start_time_array[2] in timezones: start_timezone = timezones[start_time_array[2]] try: formatted_date = datetime.datetime.strptime(start_time, fmt) formatted_date = formatted_date.replace(tzinfo=pendulum.timezone(start_timezone)) converted_date = pendulum.timezone('UTC').convert(formatted_date) converted_date = datetime.datetime.strptime(converted_date.strftime(fmt), '%Y-%m-%d %H:%M') converted_date_utc = datetime.datetime.timestamp(formatted_date) converted_date_utc = str(str(converted_date_utc).partition('.')[0]) date_link = '[<t:' + converted_date_utc + ':F>](https://www.epochconverter.com/timezones?q=' + converted_date_utc + ')' time_now = datetime.datetime.utcnow() time_now = datetime.datetime.strptime(time_now.strftime(fmt), '%Y-%m-%d %H:%M') if converted_date >= time_now + timedelta(seconds=1200): starttime = (converted_date - time_now).total_seconds() else: error_date_valid = True error_date_expiring = True except: error_date_valid = True pass else: error_date_timezone = True else: error_date_length = True embed_message_parameters.add_field(name="Date:", value=date, inline=False) if banner != '': if not validators.url(banner): embed_message_parameters.add_field(name="Banner:", value='Invalid Banner URL provided, the text you provided is not a valid url!', inline=False) elif len(banner) > 2048: embed_message_parameters.add_field(name="Banner:", value='Overlength Banner URL provided, as it is longer than 2048 characters!', inline=False) else: embed_message_parameters.add_field(name="Banner:", value=banner, inline=False) # Post Search game_titles = [] if (channels[0]['lfg_formats'] is not None) & (channels[0]['lfg_formats'] != ''): for values in lfg_games_values: if values[0] in channels[0]['lfg_formats']: game_titles.append(values[1]) game_titles = '\n• '.join(game_titles) else: game_titles = 'Please contact your server admin to have them re-run the `/setup` command to define LFG formats.' if str(post_id).isdigit(): if client.get_channel(int(channels[0]['channel_lfgPosts_id'])) is not None: lfg_posts_channel = client.get_channel(int(channels[0]['channel_lfgPosts_id'])) async for msg in lfg_posts_channel.history(): if msg.id == post_id: post = msg break if client.get_channel(int(channels[0]['channel_events_id'])) is not None: events_channel = client.get_channel(int(channels[0]['channel_events_id'])) async for msg in events_channel.history(): if msg.id == post_id: post = msg break embed_message_parameters.timestamp = datetime.datetime.now() embed_message_parameters.set_footer(text=txt_footer + str(embed_message_parameters.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_parameters.set_thumbnail(url=img_tip) # Error Handling if not str(post_id).isdigit(): embed_message_error = discord.Embed(title=client.user.display_name + ' - Post ID Contains Non-Numbers', description='We are unable to process your modify request due to you providing a Post ID which contained letters or symbols. Please **only** provide numbers for all Post IDs.', color=clr_error) embed_message_error.timestamp = datetime.datetime.now() embed_message_error.set_footer(text=txt_footer + str(embed_message_error.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_error.set_thumbnail(url=img_error) await ctx.send(content='❌┃**Post Modification Un-Succesful!**', embed=embed_message_parameters, hidden=True) await ctx.send(embed=embed_message_error, hidden=True) elif (error_date_timezone is True) | (error_date_length is True) | (error_date_valid is True) | (error_date_expiring is True): await ctx.send(content='❌┃**Post Modification Un-Succesful!**', embed=embed_message_parameters, hidden=True) if error_date_timezone is True: embed_message_error = discord.Embed(title=client.user.display_name + ' - Invalid Timezone', description='We are unable to process your modify request due to the Timezone Code you provided not being a valid code, see the following code sources.\n• [Table of Timezone Codes](https://en.wikipedia.org/wiki/List_of_time_zone_abbreviations)\n• [Interactive TimeZone Map W/ Codes](https://www.timeanddate.com/time/map/)', color=clr_error) embed_message_error.timestamp = datetime.datetime.now() embed_message_error.set_footer(text=txt_footer + str(embed_message_error.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_error.set_thumbnail(url=img_error) await ctx.send(embed=embed_message_error, hidden=True) if error_date_expiring is True: embed_message_error = discord.Embed(title=client.user.display_name + ' - Expiring Soon', description='We are unable to process your modify request due to the Start Time you provided being less than 20 minutes in the future.', color=clr_error) embed_message_error.timestamp = datetime.datetime.now() embed_message_error.set_footer(text=txt_footer + str(embed_message_error.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_error.set_thumbnail(url=img_error) await ctx.send(embed=embed_message_error, hidden=True) elif (error_date_valid is True) | (error_date_length is True): embed_message_error = discord.Embed(title=client.user.display_name + ' - Invalid Date Format', description='We are unable to process your modify request due to the Start Time you provided not following the proper format, please ensure to provide - Date, Time, Timezone Code (Ex: 2022-12-30 12:00 PST || YYYY-MM-DD HH:MM ZONE).', color=clr_error) embed_message_error.timestamp = datetime.datetime.now() embed_message_error.set_footer(text=txt_footer + str(embed_message_error.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_error.set_thumbnail(url=img_error) await ctx.send(embed=embed_message_error, hidden=True) elif (lfg_posts_channel is None) & (events_channel is None): embed_message_error = discord.Embed(title=client.user.display_name + ' - Missing Channels', description='We are unable to process your modify request due to the required LFG Posts & Events channels not yet being setup. Please contact your server admin to have them re-run the `/setup` command to create a channel for LFG Teams & Events.', color=clr_error) embed_message_error.add_field(name="Supported LFG & Event Games:", value='• ' + game_titles, inline=False) try: embed_message_error.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message_error.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass embed_message_error.timestamp = datetime.datetime.now() embed_message_error.set_footer(text=txt_footer + str(embed_message_error.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_error.set_thumbnail(url=img_error) await ctx.send(content='❌┃**Post Modification Un-Succesful!**', embed=embed_message_parameters, hidden=True) await ctx.send(embed=embed_message_error, hidden=True) elif post is None: if lfg_posts_channel is not None: tips = tips + '\n• In order to modify a LFG Team post, navigate to <#' + str(lfg_posts_channel.id) + '> and provide your submitted Post\'s ID.' if events_channel is not None: tips = tips + '\n• In order to modify a Event post, navigate to <#' + str(events_channel.id) + '> and provide your submitted Post\'s ID.' embed_message_error = discord.Embed(title=client.user.display_name + ' - Invalid Post ID', description='We are unable to process your modify request due to being unable to fetch your requested Post.', color=clr_error) embed_message_error.add_field(name="Common Troubleshooting Tips:", value=tips, inline=False) try: embed_message_error.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message_error.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass embed_message_error.timestamp = datetime.datetime.now() embed_message_error.set_footer(text=txt_footer + str(embed_message_error.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_error.set_thumbnail(url=img_error) await ctx.send(content='❌┃**Post Modification Un-Succesful!**', embed=embed_message_parameters, hidden=True) await ctx.send(embed=embed_message_error, hidden=True) elif (post is not None) & ('📅┃**Event Now Starting**:' in post.content): await ctx.send(content='❌┃**Post Modification Un-Succesful!**', embed=embed_message_parameters, hidden=True) embed_message_error = discord.Embed(title=client.user.display_name + ' - Already Started Event', description='We are unable to process your modify request due to the post being an Event which has already started!', color=clr_error) embed_message_error.timestamp = datetime.datetime.now() embed_message_error.set_footer(text=txt_footer + str(embed_message_error.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_error.set_thumbnail(url=img_error) await ctx.send(embed=embed_message_error, hidden=True) # elif (post.embeds[0].fields[0].name != 'Participants:') & (post.embeds[0].fields[0].name != 'Team Members:'): # await ctx.send(content='❌┃**Post Modification Un-Succesful!**', embed=embed_message_parameters, hidden=True) # embed_message_error = discord.Embed(title=client.user.display_name + ' - No Post Members', description='We are unable to process your modify request due to the post currently having no members!', color=clr_error) # embed_message_error.timestamp = datetime.datetime.now() # embed_message_error.set_footer(text=txt_footer + str(embed_message_error.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) # embed_message_error.set_thumbnail(url=img_error) # await ctx.send(embed=embed_message_error, hidden=True) elif (post.embeds[0].title != 'Event Organizer:') & ((date != '') | (banner != '')): await ctx.send(content='❌┃**Post Modification Un-Succesful!**', embed=embed_message_parameters, hidden=True) if date != '': embed_message_error = discord.Embed(title=client.user.display_name + ' - No Dates for LFG Posts', description='We are unable to process your modify request due to you providing a Date for a LFG Post. Only Events require Dates thus please re-modify without said parameter.', color=clr_error) embed_message_error.timestamp = datetime.datetime.now() embed_message_error.set_footer(text=txt_footer + str(embed_message_error.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_error.set_thumbnail(url=img_error) await ctx.send(embed=embed_message_error, hidden=True) if banner != '': embed_message_error = discord.Embed(title=client.user.display_name + ' - No Banners for LFG Posts', description='We are unable to process your modify request due to you providing a Banner for a LFG Post. Only Events may use Banners thus please re-modify without said parameter.', color=clr_error) embed_message_error.timestamp = datetime.datetime.now() embed_message_error.set_footer(text=txt_footer + str(embed_message_error.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_error.set_thumbnail(url=img_error) await ctx.send(embed=embed_message_error, hidden=True) elif post.author != client.user: if lfg_posts_channel is not None: tips = tips + '\n• In order to modify a LFG Team post, navigate to <#' + str(lfg_posts_channel.id) + '> and provide your submitted Post\'s ID.' if events_channel is not None: tips = tips + '\n• In order to modify a Event post, navigate to <#' + str(events_channel.id) + '> and provide your submitted Post\'s ID.' embed_message_error = discord.Embed(title=client.user.display_name + ' - Invalid Post Author', description='We are unable to process your modify request due to you providing the ID of a Post, who\'s author is not <@' + str(client.user.id) + '>', color=clr_error) embed_message_error.add_field(name="Common Troubleshooting Tips:", value=tips, inline=False) embed_message_error.timestamp = datetime.datetime.now() embed_message_error.set_footer(text=txt_footer + str(embed_message_error.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_error.set_thumbnail(url=img_error) await ctx.send(content='❌┃**Post Modification Un-Succesful!**', embed=embed_message_parameters, hidden=True) await ctx.send(embed=embed_message_error, hidden=True) elif (post.author == client.user) & ((post.embeds[0].title != 'Event Organizer:') & (post.embeds[0].title != 'Team Organizer:')): tips = tips + '\n• Only submit the ID of a post who\'s title is either `Event Organizer` or `Team Organizer` and has you listed as stated Organizer.' if lfg_posts_channel is not None: tips = tips + '\n• In order to modify a LFG Team post, navigate to <#' + str(lfg_posts_channel.id) + '> and provide your submitted Post\'s ID.' if events_channel is not None: tips = tips + '\n• In order to modify a Event post, navigate to <#' + str(events_channel.id) + '> and provide your submitted Post\'s ID.' embed_message_error = discord.Embed(title=client.user.display_name + ' - Not a Valid Post Type', description='We are unable to process your modify request due to you providing the ID of a Post which is neither an actual LFG Team or Event.', color=clr_error) embed_message_error.add_field(name="Common Troubleshooting Tips:", value=tips, inline=False) embed_message_error.timestamp = datetime.datetime.now() embed_message_error.set_footer(text=txt_footer + str(embed_message_error.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_error.set_thumbnail(url=img_error) await ctx.send(content='❌┃**Post Modification Un-Succesful!**', embed=embed_message_parameters, hidden=True) await ctx.send(embed=embed_message_error, hidden=True) elif (post.author == client.user) & ((post.embeds[0].title == 'Event Organizer:') | (post.embeds[0].title == 'Team Organizer:')) & ((post.embeds[0].description != '<@' + str(ctx.author.id) + '>') & ((post.embeds[0].description != '<@' + str(ctx.author.id) + '>') & (not bool([item for item in ctx.author.guild_permissions if ((item[0] in expected_permissions) & (item[1] is True))])))): tips = tips + '\n• Only submit the ID of a post who\'s title is either `Event Organizer` or `Team Organizer` and has you listed as stated Organizer.' if lfg_posts_channel is not None: tips = tips + '\n• In order to modify a LFG Team post, navigate to <#' + str(lfg_posts_channel.id) + '> and provide your submitted Post\'s ID.' if events_channel is not None: tips = tips + '\n• In order to modify a Event post, navigate to <#' + str(events_channel.id) + '> and provide your submitted Post\'s ID.' embed_message_error = discord.Embed(title=client.user.display_name + ' - Not Organizer of Post', description='We are unable to process your modify request due to you providing the ID of a Post which does not have you listed as the Organizer.', color=clr_error) embed_message_error.add_field(name="Common Troubleshooting Tips:", value=tips, inline=False) embed_message_error.timestamp = datetime.datetime.now() embed_message_error.set_footer(text=txt_footer + str(embed_message_error.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_error.set_thumbnail(url=img_error) await ctx.send(content='❌┃**Post Modification Un-Succesful!**', embed=embed_message_parameters, hidden=True) await ctx.send(embed=embed_message_error, hidden=True) elif (post_id == '') & (platform == '') & (game == '') & (activity == '') & (description == '') & (size is None) & (username == '') & (experience == '') & (server == '') & (date == '') & (banner == ''): embed_message_error = discord.Embed(title=client.user.display_name + ' - No Parameters Provided', description='We are unable to process your modify request due to you not providing any parameter to modify for a post. Please include a value for one of the optional parameters to process a edit.', color=clr_error) embed_message_error.timestamp = datetime.datetime.now() embed_message_error.set_footer(text=txt_footer + str(embed_message_error.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_error.set_thumbnail(url=img_error) await ctx.send(content='❌┃**Post Modification Un-Succesful!**', embed=embed_message_parameters, hidden=True) await ctx.send(embed=embed_message_error, hidden=True) else: # if members != '': # members_list_len = 0 # members_value = '' # if '<@' in members: # members_value = members.replace('><', '> <') # members_ids = members_value.replace('<@!', '').replace('<@', '').replace('>', '') # members_list = members_ids.split(' ') # members_list_len = len(members_list) # # if members_list_len > 40: # members_value_more = ' '.join(members_value.split(" ")[:40]) + ' Plus ' + str(int(members_list_len - 40)) + ' More...' # # if post.embeds[0].title == 'Team Organizer:': # for idx, field in enumerate(post.embeds[0].fields): # if (field.name == 'Team Members:') & (members_list_len <= 40): # post.embeds[0].set_field_at(idx, name="Team Members:", value=members_value, inline=False) # break # elif (field.name == 'Team Members:') & (members_list_len > 40): # post.embeds[0].set_field_at(idx, name="Team Members:", value=members_value_more, inline=False) # # elif post.embeds[0].title == 'Event Organizer:': # for idx, field in enumerate(post.embeds[0].fields): # if (field.name == 'Participants:') & (members_list_len <= 40): # post.embeds[0].set_field_at(idx, name="Participants:", value=members_value, inline=False) # break # elif (field.name == 'Participants:') & (members_list_len > 40): # post.embeds[0].set_field_at(idx, name="Participants:", value=members_value_more, inline=False) # if '<@' in members: # await post.edit(embed=post.embeds[0]) # sql = "UPDATE posts SET post_members = %s WHERE post_id = %s" # val = (members_value.replace('!', ''), post.id) # await mysql_commit(sql=sql, val=val) # else: # await post.edit(embed=post.embeds[0]) # sql = "UPDATE posts SET post_members = %s WHERE post_id = %s" # val = (members, post.id) # await mysql_commit(sql=sql, val=val) if platform != '': if post.embeds[0].title == 'Team Organizer:': for idx, field in enumerate(post.embeds[0].fields): if field.name == 'Platform:': post.embeds[0].set_field_at(idx, name="Platform:", value=platform, inline=True) break elif post.embeds[0].title == 'Event Organizer:': for idx, field in enumerate(post.embeds[0].fields): if field.name == 'Event Platform:': post.embeds[0].set_field_at(idx, name="Event Platform:", value=platform, inline=True) break await post.edit(embed=post.embeds[0]) sql = "UPDATE posts SET platform = %s WHERE post_id = %s" val = (platform, post.id) await mysql_commit(sql=sql, val=val) if activity != '': if post.embeds[0].title == 'Team Organizer:': for idx, field in enumerate(post.embeds[0].fields): if field.name == 'Activity:': post.embeds[0].set_field_at(idx, name="Activity:", value=activity, inline=False) break elif post.embeds[0].title == 'Event Organizer:': for idx, field in enumerate(post.embeds[0].fields): if field.name == 'Event Title:': post.embeds[0].set_field_at(idx, name="Event Title:", value=activity, inline=False) break await post.edit(embed=post.embeds[0]) sql = "UPDATE posts SET activity = %s WHERE post_id = %s" val = (activity, post.id) await mysql_commit(sql=sql, val=val) if description != '': if post.embeds[0].title == 'Team Organizer:': for idx, field in enumerate(post.embeds[0].fields): if field.name == 'Description:': post.embeds[0].set_field_at(idx, name="Description:", value=description, inline=False) break elif post.embeds[0].title == 'Event Organizer:': for idx, field in enumerate(post.embeds[0].fields): if field.name == 'Event Details:': post.embeds[0].set_field_at(idx, name="Event Details:", value=description, inline=False) break await post.edit(embed=post.embeds[0]) sql = "UPDATE posts SET description = %s WHERE post_id = %s" val = (description, post.id) await mysql_commit(sql=sql, val=val) if size is not None: for idx, field in enumerate(post.embeds[0].fields): if field.name == 'Available Slots:': post.embeds[0].set_field_at(idx, name="Available Slots:", value='**' + str(size) + '**', inline=True) break await post.edit(embed=post.embeds[0]) sql = "UPDATE posts SET slots = %s WHERE post_id = %s" val = (size, post.id) await mysql_commit(sql=sql, val=val) if username != '': for idx, field in enumerate(post.embeds[0].fields): if field.name == 'In-Game Name:': post.embeds[0].set_field_at(idx, name="In-Game Name:", value=username, inline=False) break await post.edit(embed=post.embeds[0]) sql = "UPDATE posts SET username = %s WHERE post_id = %s" val = (username, post.id) await mysql_commit(sql=sql, val=val) if experience != '': if bool([item for item in post.embeds[0].fields if item.name == 'Desired Skillset:']): for idx, field in enumerate(post.embeds[0].fields): if field.name == 'Desired Skillset:': post.embeds[0].set_field_at(idx, name="Desired Skillset:", value=experience, inline=True) break elif not bool([item for item in post.embeds[0].fields if item.name == 'Desired Skillset:']): if (post.embeds[0].fields[0] == 'Team Members:') | (post.embeds[0].fields[0] == 'Participants:'): post.embeds[0].insert_field_at(7, name="Desired Skillset:", value=experience, inline=True) elif (post.embeds[0].fields[0] != 'Team Members:') | (post.embeds[0].fields[0] != 'Participants:'): post.embeds[0].insert_field_at(6, name="Desired Skillset:", value=experience, inline=True) await post.edit(embed=post.embeds[0]) sql = "UPDATE posts SET experience = %s WHERE post_id = %s" val = (experience, post.id) await mysql_commit(sql=sql, val=val) if game != '': thumbnail_url = '' for element in img_games: if element['value'] == game: thumbnail_url = element['img_url'] clr_game = 0 for element in img_games: if element['value'] == game: clr_game = element['color'] if post.embeds[0].title == 'Team Organizer:': for idx, field in enumerate(post.embeds[0].fields): if field.name == 'Game:': post.embeds[0].set_field_at(idx, name="Game:", value=game_name, inline=True) break elif post.embeds[0].title == 'Event Organizer:': for idx, field in enumerate(post.embeds[0].fields): if field.name == 'Event Game:': post.embeds[0].set_field_at(idx, name="Event Game:", value=game_name, inline=True) break new_embed = discord.Embed(title=post.embeds[0].title, description=post.embeds[0].description, color=clr_game) for field in post.embeds[0].fields: new_embed.add_field(name=field.name, value=field.value, inline=field.inline) new_embed.timestamp = datetime.datetime.now() new_embed.set_footer(text=txt_footer + str(new_embed.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) new_embed.set_thumbnail(url=thumbnail_url) if post.embeds[0].image.url is not None: new_embed.set_image(url=post.embeds[0].image.url) await post.edit(embed=new_embed) sql = "UPDATE posts SET game = %s, game_clr = %s, game_img = %s WHERE post_id = %s" val = (game_name, clr_game, thumbnail_url, post.id) await mysql_commit(sql=sql, val=val) if server != '': if ('aoe2de://0/' in server) & ((post.embeds[0].fields[2].value == 'Age of Empires 2') | (post.embeds[0].fields[1].value == 'Age of Empires 2')): if 'aoe2de://0/' in server: second = server.split('aoe2de://0/')[1][0:9] if second.isdigit(): server = '[Join Game](https://aoe2.net/j/' + second + ')' if bool([item for item in post.embeds[0].fields if item.name == 'Server/Lobby ID:']): for idx, field in enumerate(post.embeds[0].fields): if field.name == 'Server/Lobby ID:': post.embeds[0].set_field_at(idx, name="Server/Lobby ID:", value=server, inline=True) break elif not bool([item for item in post.embeds[0].fields if item.name == 'Server/Lobby ID:']): if (post.embeds[0].fields[0] == 'Team Members:') | (post.embeds[0].fields[0] == 'Participants:'): post.embeds[0].insert_field_at(8, name="Server/Lobby ID:", value=server, inline=True) elif (post.embeds[0].fields[0] != 'Team Members:') | (post.embeds[0].fields[0] != 'Participants:'): post.embeds[0].insert_field_at(7, name="Server/Lobby ID:", value=server, inline=True) await post.edit(embed=post.embeds[0]) sql = "UPDATE posts SET server = %s WHERE post_id = %s" val = (server, post.id) await mysql_commit(sql=sql, val=val) if banner != '': if post.embeds[0].title == 'Event Organizer:': if len(banner) < 2048: if validators.url(banner): post.embeds[0].set_image(url=banner) await post.edit(embed=post.embeds[0]) sql = "UPDATE posts SET banner = %s WHERE post_id = %s" val = (banner, post.id) await mysql_commit(sql=sql, val=val) if date != '': if post.embeds[0].title == 'Event Organizer:': if (error_date_timezone is False) & (error_date_length is False) & (error_date_valid is False) & (error_date_expiring is False): for idx, field in enumerate(post.embeds[0].fields): if field.name == 'Start Time:': post.embeds[0].set_field_at(idx, name="Start Time:", value=date_link, inline=False) break await post.edit(embed=post.embeds[0]) modified_post = await events_channel.send(embed=post.embeds[0], components=post_buttons, delete_after=starttime) sql = "UPDATE posts SET post_id = %s, date = %s WHERE post_id = %s" val = (modified_post.id, date_link, post.id) await mysql_commit(sql=sql, val=val) await post.delete() await ctx.send(content='☑️┃**Post Modification Succesful!**', embed=embed_message_parameters, hidden=True) @slash.slash(name='search', description='Used to browse the Global LFG & Event Network of Posts from other Servers!', options=global_search) async def search(ctx, choice: str, game: str, platform: str = ''): for element in host_options[2]['choices']: if element['value'] == game: game = element['name'] for element in host_options[1]['choices']: if element['value'] == platform: platform = element['name'] if choice == 'type_lfg': embed_message = discord.Embed(title=client.user.display_name + ' - Global LFG Network 🌎', description='See below a list of LFG Posts from across particpating servers in our Global LFG Network!', color=random.randint(0, 0xffffff)) embed_message.add_field(name='LFG Post Options:', value='• LFG Posts listed below provide a Join button which will re-direct to the post\'s server\'s `📑┃lfg-posts` channel\n• If you join a LFG Post the Team Organizer will be informed of your interest to become a Team Member', inline=False) embed_message.add_field(name='Useful Tips:', value='• It is suggested to message the Team Organizer or server\'s admins to coordinate permissions in the event the `📑┃lfg-posts` channel is not accessible on join\n• Re-run the `/search` command in order to refresh currently available LFG Posts', inline=False) if platform == '': embed_message.add_field(name='Selected Posts:', value='• Game: **' + game + '**\n• Platform: **None Selected**', inline=False) else: embed_message.add_field(name='Selected Posts:', value='• Game: **' + game + '**\n• Platform: **' + platform + '**', inline=False) try: embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass embed_message.timestamp = datetime.datetime.now() embed_message.set_footer(text=txt_footer + str(embed_message.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message.set_thumbnail(url=img_logo) await ctx.send(embed=embed_message, hidden=True) elif choice == 'type_events': embed_message = discord.Embed(title=client.user.display_name + ' - Global Event Network 🌎', description='See below a list of Events from across particpating servers in our Global Network!', color=random.randint(0, 0xffffff)) embed_message.add_field(name='Event Options:', value='• Events listed below provide a Join button which will re-direct to the post\'s server\n• Joining an Event will put you on a distro of users to be informed once the event starts.', inline=False) embed_message.add_field(name='Useful Tips:', value='• Be certain to re-check the channel in which the Event is posted in, in case of updates on the acitivty instructions\n• Re-run the `/search` command in order to refresh currently available Events', inline=False) if platform == '': embed_message.add_field(name='Selected Events:', value='• Game: **' + game + '**\n• Platform: **None Selected**', inline=False) else: embed_message.add_field(name='Selected Events:', value='• Game: **' + game + '**\n• Platform: **' + platform + '**', inline=False) try: embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass embed_message.timestamp = datetime.datetime.now() embed_message.set_footer(text=txt_footer + str(embed_message.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message.set_thumbnail(url=img_logo) await ctx.send(embed=embed_message, hidden=True) search_choice = '' if choice == 'type_events': search_choice = 'type_event' elif choice == 'type_lfg': search_choice = 'type_lfg' if platform == '': sql = "SELECT guild_id, post_organizer, type, post_members, platform, slots, game, game_clr, game_img, activity, description, username, experience, server, posttime, date, banner FROM posts WHERE game = %s AND type = %s" val = (game, search_choice) else: sql = "SELECT guild_id, post_organizer, type, post_members, platform, slots, game, game_clr, game_img, activity, description, username, experience, server, posttime, date, banner FROM posts WHERE game = %s AND platform = %s AND type = %s" val = (game, platform, search_choice) await mysql_commit(sql=sql, val=val) posts = sql_connect.fetchall() if platform == '': for post in posts: sql = "SELECT global_search FROM guilds WHERE guild_id = %s" val = (post['guild_id'],) await mysql_commit(sql=sql, val=val) search_option = sql_connect.fetchall() if (post['game'] == game) & (search_option[0]['global_search'] == 'yes'): await create_global_search(ctx, post, choice) else: for post in posts: sql = "SELECT global_search FROM guilds WHERE guild_id = %s" val = (post['guild_id'],) await mysql_commit(sql=sql, val=val) search_option = sql_connect.fetchall() if ((post['game'] == game) & (post['platform'] == platform)) & (search_option[0]['global_search'] == 'yes'): await create_global_search(ctx, post, choice) @slash.slash(name='notify', description='Used to setup Notifications for LFG or Events of specific Games & Platforms!', options=global_search) async def search(ctx, choice: str, game: str, platform: str = ''): for element in host_options[2]['choices']: if element['value'] == game: game_title = element['name'] for element in host_options[1]['choices']: if element['value'] == platform: platform_title = element['name'] sql = "SELECT * FROM notify WHERE user_id = %s AND choice = %s" val = (ctx.author.id, choice) await mysql_commit(sql=sql, val=val) select_query = sql_connect.fetchall() if select_query: sql = "UPDATE notify SET game = %s, platform = %s WHERE user_id = %s AND choice = %s" val = (game, platform, ctx.author.id, choice) await mysql_commit(sql=sql, val=val) else: sql = "INSERT INTO notify (user_id, choice, game, platform) VALUES (%s, %s, %s, %s)" val = (ctx.author.id, choice, game, platform) await mysql_commit(sql=sql, val=val) if choice == 'type_lfg': post_type = 'LFG Posts' elif choice == 'type_events': post_type = 'Event' embed_message = discord.Embed(title=client.user.display_name + ' - Notifications Enabled', description=f'You will now be notified of any new {post_type} added to the Global Network for the below.', color=0xffffff) embed_message.add_field(name='Game:', value=game_title, inline=False) if platform: embed_message.add_field(name='Platform:', value=platform_title, inline=False) else: embed_message.add_field(name='Platform:', value='No Specific Platform Selected', inline=False) embed_message.add_field(name='Helpful Tips:', value=f'\n• Stop {post_type} notifications simply by joining any {post_type} or using the `🛑 Stop {post_type} Notifications` button attached to any notification.\n• You can be subscribed for notifications of Events & LFG posts at the same time!', inline=False) if ctx.author.guild is not None: try: embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass else: embed_message.set_author(name="Unable to fetch Server Name", url=url_discord, icon_url=img_unknown) embed_message.timestamp = datetime.datetime.now() embed_message.set_footer(text=txt_footer + str(embed_message.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message.set_thumbnail(url=img_logo) await ctx.send(embed=embed_message, hidden=True) @client.event async def create_global_search(ctx, post, choice): sql = "SELECT global_search_invite FROM guilds WHERE guild_id = %s" val = (post['guild_id'],) await mysql_commit(sql=sql, val=val) guild_invite = sql_connect.fetchall() if choice == 'type_lfg': embed_message_post = discord.Embed(title="Team Organizer:", description=post['post_organizer'], color=int(post['game_clr'])) if post['post_members']: embed_message_post.add_field(name="Team Members:", value=post['post_members'], inline=False) embed_message_post.add_field(name="Platform:", value=post['platform'], inline=True) embed_message_post.add_field(name="Game:", value=post['game'], inline=True) embed_message_post.add_field(name="Available Slots:", value=post['slots'], inline=True) embed_message_post.add_field(name="In-Game Name:", value=post['username'], inline=True) embed_message_post.add_field(name="Activity:", value=post['activity'], inline=False) embed_message_post.add_field(name="Description:", value=post['description'], inline=False) if post['experience']: embed_message_post.add_field(name="Experience:", value=post['experience'], inline=True) if post['server']: embed_message_post.add_field(name="Server/Lobby ID:", value=post['server'], inline=True) embed_message_post.set_footer(text="Join or Leave this by interacting below!\nPosted" + post['posttime'], icon_url=img_tip) embed_message_post.set_thumbnail(url=post['game_img']) elif choice == 'type_events': embed_message_post = discord.Embed(title="Event Organizer:", description=post['post_organizer'], color=int(post['game_clr'])) if post['post_members']: embed_message_post.add_field(name="Participants:", value=post['post_members'], inline=False) embed_message_post.add_field(name="Event Platform:", value=post['platform'], inline=True) embed_message_post.add_field(name="Event Game:", value=post['game'], inline=True) embed_message_post.add_field(name="Available Slots:", value=post['slots'], inline=True) embed_message_post.add_field(name="In-Game Name:", value=post['username'], inline=True) embed_message_post.add_field(name="Event Title:", value=post['activity'], inline=False) embed_message_post.add_field(name="Event Details:", value=post['description'], inline=False) if post['experience']: embed_message_post.add_field(name="Desired Skillset:", value=post['experience'], inline=True) if post['server']: embed_message_post.add_field(name="Server/Lobby ID:", value=post['server'], inline=True) if post['date']: fmt = "%Y-%m-%d %H:%M:%S" formatted_date = datetime.datetime.strptime(post['date'], fmt) formatted_date = formatted_date.replace(tzinfo=pendulum.timezone('UTC')) converted_date_utc = datetime.datetime.timestamp(formatted_date) converted_date_utc = str(str(converted_date_utc).partition('.')[0]) date_link = '[<t:' + converted_date_utc + ':F>](https://www.epochconverter.com/timezones?q=' + converted_date_utc + ')' embed_message_post.add_field(name="Start Time:", value=date_link, inline=False) if bool(post['banner']) & (len(post['banner']) < 2048): if validators.url(post['banner']): embed_message_post.set_image(url=post['banner']) embed_message_post.set_footer(text="Join or Leave this by interacting below!\nPosted" + post['posttime'], icon_url=img_tip) embed_message_post.set_thumbnail(url=post['game_img']) guild = client.get_guild(int(post['guild_id'])) button_post_join = '' if choice == 'type_lfg': button_post_join = [create_actionrow(create_button(style=ButtonStyle.URL, label="Join Team", emoji='📑', url=str(guild_invite[0]['global_search_invite'])))] elif choice == 'type_events': button_post_join = [create_actionrow(create_button(style=ButtonStyle.URL, label="Join Event", emoji='📅', url=str(guild_invite[0]['global_search_invite'])))] await ctx.send(content='🕹️┃**Discord Server**: ' + guild.name, embed=embed_message_post, components=button_post_join, hidden=True) # @client.event # async def on_slash_command_error(ctx, ex): # await ctx.send(content='❗┃**Interaction Failed**:\n• Apologies. an error has occured. You may be providing an invalid format or the bot needs more time to initialize, please remove said message and try again later.', hidden=True) # # # @client.event # async def on_component_callback_error(ctx, ex): # await ctx.send(content='❗┃**Interaction Failed**:\n• Apologies. an error has occured. You may be using an old message or the bot needs more time to initialize, please remove said message and try again later.', hidden=True) @client.event async def on_guild_channel_delete(channel): sql = "SELECT channel_lfgPosts_id, channel_events_id FROM guilds WHERE guild_id = %s" val = (channel.guild.id,) await mysql_commit(sql=sql, val=val) channels = sql_connect.fetchall() if channel.id == int(channels[0]['channel_lfgPosts_id']): sql = "SELECT guild_id, type, post_organizer, post_members, platform, slots, game, game_clr, game_img, activity, description, username, experience, server, posttime, date, banner FROM posts WHERE guild_id = %s AND type = %s" val = (channel.guild.id, 'type_lfg') await mysql_commit(sql=sql, val=val) post = sql_connect.fetchall() for idx, msg in enumerate(post): embed_message_post = discord.Embed(title="Team Organizer:", description=post[idx]['post_organizer'], color=int(post[idx]['game_clr'])) if post[idx]['post_members']: embed_message_post.add_field(name="Team Members:", value=post[idx]['post_members'], inline=False) embed_message_post.add_field(name="Platform:", value=post[idx]['platform'], inline=True) embed_message_post.add_field(name="Game:", value=post[idx]['game'], inline=True) embed_message_post.add_field(name="Available Slots:", value=post[idx]['slots'], inline=True) embed_message_post.add_field(name="In-Game Name:", value=post[idx]['username'], inline=True) embed_message_post.add_field(name="Activity:", value=post[idx]['activity'], inline=False) embed_message_post.add_field(name="Description:", value=post[idx]['description'], inline=False) if post[idx]['experience']: embed_message_post.add_field(name="Experience:", value=post[idx]['experience'], inline=True) if post[idx]['server']: embed_message_post.add_field(name="Server/Lobby ID:", value=post[idx]['server'], inline=True) embed_message_post.set_footer(text="Join or Leave this by interacting below!\nPosted" + post[idx]['posttime'], icon_url=img_tip) embed_message_post.set_thumbnail(url=post[idx]['game_img']) if post[idx]['post_members'] is not None: members_ids = post[idx]['post_members'].replace('<@!', '').replace('<@', '').replace('>', '') members_list = members_ids.split(' ') for member in members_list: try: await channel.guild.get_member(int(member)).send(content='🛑┃**Team Disbanded**:\n• Your below joined team has been Disbanded due to Administrator removal of the LFG Posts channel.\n• You do not need to contact anyone, feel free to instead join a new Team once a new channel is created.', embed=embed_message_post) except: pass try: await channel.guild.get_member(int(post[idx]['post_organizer'].replace('<@!', '').replace('<@', '').replace('>', ''))).send(content='🛑┃**Team Disbanded**:\n• Your below team has been Disbanded due to Administrator removal of the LFG Posts channel.\n• You do not need to contact anyone, feel free to instead post a new Team once a new channel is created.', embed=embed_message_post) except: error_usr = channel.guild.get_member(int(post[idx]['post_organizer'].replace('<@!', '').replace('<@', '').replace('>', ''))) pass sql = "DELETE FROM posts WHERE guild_id = %s AND type = %s" val = (channel.guild.id, 'type_lfg') await mysql_commit(sql=sql, val=val) sql = "UPDATE guilds SET channel_lfgPosts_id = %s WHERE guild_id = %s" val = ('0', channel.guild.id) await mysql_commit(sql=sql, val=val) try: await channel.guild.owner.send(content='❗┃**Channel Removal - LFG Posts**:\nPlease be aware the required channel for `' + client.user.display_name + '\'s` LFG services has been removed. Please consider re-running our `/setup` command to restore functionality.') except: pass elif channel.id == int(channels[0]['channel_events_id']): sql = "SELECT guild_id, type, post_organizer, post_members, platform, slots, game, game_clr, game_img, activity, description, username, experience, server, posttime, date, banner FROM posts WHERE guild_id = %s AND type = %s" val = (channel.guild.id, 'type_event') await mysql_commit(sql=sql, val=val) post = sql_connect.fetchall() for idx, msg in enumerate(post): embed_message_post = discord.Embed(title="Event Organizer:", description=post[idx]['post_organizer'], color=int(post[idx]['game_clr'])) if post[idx]['post_members']: embed_message_post.add_field(name="Participants:", value=post[idx]['post_members'], inline=False) embed_message_post.add_field(name="Event Platform:", value=post[idx]['platform'], inline=True) embed_message_post.add_field(name="Event Game:", value=post[idx]['game'], inline=True) embed_message_post.add_field(name="Available Slots:", value=post[idx]['slots'], inline=True) embed_message_post.add_field(name="In-Game Name:", value=post[idx]['username'], inline=True) embed_message_post.add_field(name="Event Title:", value=post[idx]['activity'], inline=False) embed_message_post.add_field(name="Event Details:", value=post[idx]['description'], inline=False) if post[idx]['experience']: embed_message_post.add_field(name="Experience:", value=post[idx]['experience'], inline=True) if post[idx]['server']: embed_message_post.add_field(name="Server/Lobby ID:", value=post[idx]['server'], inline=True) embed_message_post.add_field(name="Start Time:", value=post[idx]['date'], inline=False) if post[idx]['banner']: image_formats = ("image/png", "image/jpeg", "image/jpg") r = requests.head(post[idx]['banner']) if r.headers["content-type"] in image_formats: embed_message_post.set_image(url=post[idx]['banner']) embed_message_post.set_footer(text="Join or Leave this event by interacting below!\nPosted" + post[idx]['posttime'], icon_url=img_tip) embed_message_post.set_thumbnail(url=post[idx]['game_img']) if post[idx]['post_members'] is not None: members_ids = post[idx]['post_members'].replace('<@!', '').replace('<@', '').replace('>', '') members_list = members_ids.split(' ') for member in members_list: try: await channel.guild.get_member(int(member)).send(content='🛑┃**Event Disbanded**:\n• Your below joined Event has been Disbanded due to Administrator removal of the Events channel.\n• You do not need to contact anyone, feel free to instead join a new Event once a new channel is created.', embed=embed_message_post) except: pass try: await channel.guild.get_member(int(post[idx]['post_organizer'].replace('<@!', '').replace('<@', '').replace('>', ''))).send(content='🛑┃**Event Disbanded**:\n• Your below Event has been Disbanded due to Administrator removal of the Events channel.\n• You do not need to contact anyone, feel free to instead post a new Event once a new channel is created.', embed=embed_message_post) except: error_usr = channel.guild.get_member(int(post[idx]['post_organizer'].replace('<@!', '').replace('<@', '').replace('>', ''))) pass sql = "DELETE FROM posts WHERE guild_id = %s AND type = %s" val = (channel.guild.id, 'type_event') await mysql_commit(sql=sql, val=val) sql = "UPDATE guilds SET channel_events_id = %s WHERE guild_id = %s" val = ('0', channel.guild.id) await mysql_commit(sql=sql, val=val) try: await channel.guild.owner.send(content='❗┃**Channel Removal - Events**:\nPlease be aware the required channel for `' + client.user.display_name + '\'s` Event services has been removed. Please consider re-running our `/setup` command to restore functionality.') except: pass @client.event async def on_message_delete(ctx): if str(ctx.type) != 'MessageType.pins_add': if ctx.guild is not None: try: if (not ((str(ctx.embeds[0].fields[1].name) == 'Available Slots:') & (str(ctx.embeds[0].fields[1].value) == '0'))) & (not ((str(ctx.embeds[0].fields[2].name) == 'Available Slots:') & (str(ctx.embeds[0].fields[2].value) == '0'))): if ctx.embeds[0].title == 'Team Organizer:': fmt = "%Y-%m-%d %H:%M:%S" current_time = pytz.utc.localize(datetime.datetime.utcnow()) current_time = datetime.datetime.strptime(current_time.strftime(fmt), '%Y-%m-%d %H:%M:%S') message_time = ctx.created_at.astimezone(pytz.utc) message_time = datetime.datetime.strptime(message_time.strftime(fmt), '%Y-%m-%d %H:%M:%S') if (current_time >= (message_time + timedelta(seconds=900))) & (current_time < (message_time + timedelta(seconds=1200))): post_organizer_id = str(ctx.embeds[0].description).replace('<@!', '').replace('<@', '').replace('>', '') if ctx.author.guild.get_member(int(post_organizer_id)) is not None: post_organizer = await client.fetch_user(int(post_organizer_id)) if str(ctx.embeds[0].fields[0].name) == 'Team Members:': members_value = str(ctx.embeds[0].fields[0].value) members_ids = members_value.replace('<@!', '').replace('<@', '').replace('>', '') members_list = members_ids.split(' ') for member_id in members_list: if ctx.author.guild.get_member(int(member_id)) is not None: usr = await client.fetch_user(int(member_id)) try: await usr.send(content='🔒┃**Team Closed - Expired**:\n• The below Team you joined has been active for more than 15 minutes and thus has been closed for new Team Members.\n• Please return to the LFG Posts channel and visit the Teams\'s assigned thread and contact Team Organizer <@' + str(post_organizer_id) + '> to arrange friend requests and in-game plans, have fun!', embed=ctx.embeds[0]) except: pass try: await post_organizer.send(content='🔒┃**Team Closed - Expired**:\n• The below Team you posted has been active for more than 15 minutes and thus has been closed for new Team Members.\n• Please return to the LFG Posts channel and visit the Teams\'s assigned thread and contact the below listed Team Members to coordinate friend requests and in-game plans, have fun!', embed=ctx.embeds[0]) except: pass else: try: await post_organizer.send(content='🔒┃**Team Closed - Expired**:\n• The below Team you posted has been active for more than 15 minutes and thus has been closed for new Team Members.\n• No Team Members at time of closure so you do not need to contact anyone, feel free to post a new Team anytime.', embed=ctx.embeds[0]) except: pass if ctx.embeds[0].title == 'Team Organizer:': sql = "SELECT thread_id FROM posts WHERE post_id = %s" val = (ctx.id,) await mysql_commit(sql=sql, val=val) query = sql_connect.fetchall() if query: if query[0]['thread_id'] != '': thread_id = query[0]['thread_id'] if ctx.channel.get_thread(int(thread_id)): message_thread = ctx.channel.get_thread(int(thread_id)) await message_thread.delete() elif ctx.embeds[0].title == 'Event Organizer:': fmt = "%Y-%m-%d %H:%M:%S" current_time = pytz.utc.localize(datetime.datetime.utcnow()) current_time = datetime.datetime.strptime(current_time.strftime(fmt), '%Y-%m-%d %H:%M:%S') event_time = ctx.embeds[0].fields[-1].value.replace('[', '').replace(']', '').partition('(') event_time = datetime.datetime.utcfromtimestamp(int(event_time[0].replace('<t:', '').replace(':F>', ''))) event_time = datetime.datetime.strptime(event_time.strftime(fmt), '%Y-%m-%d %H:%M:%S') if (current_time >= event_time) & (current_time < (event_time + timedelta(seconds=300))): post_organizer_id = str(ctx.embeds[0].description).replace('<@!', '').replace('<@', '').replace('>', '') if ctx.author.guild.get_member(int(post_organizer_id)) is not None: post_organizer = await client.fetch_user(int(post_organizer_id)) if str(ctx.embeds[0].fields[0].name) == 'Participants:': members_value = str(ctx.embeds[0].fields[0].value) if 'Plus' in members_value: sql = "SELECT post_members FROM posts WHERE post_id = %s" val = (ctx.origin_message.id,) await mysql_commit(sql=sql, val=val) sql_query_members = sql_connect.fetchall() if sql_query_members: members_value = sql_query_members[0]['post_members'] members_ids = sql_query_members[0]['post_members'].replace('<@', '').replace('>', '') members_list = members_ids.split(' ') members_list_len = len(members_list) else: members_overflow = re.search('Plus (.*) More', members_value) members_overflow = int(members_overflow.group(1)) members_value.partition(' Plus') members_ids = members_value.replace('<@!', '').replace('<@', '').replace('>', '') members_list = members_ids.split(' ') members_list_len = len(members_list) + members_overflow else: members_ids = members_value.replace('<@!', '').replace('<@', '').replace('>', '') members_list = members_ids.split(' ') members_list_len = len(members_list) for member_id in members_list: if ctx.author.guild.get_member(int(member_id)) is not None: usr = await client.fetch_user(int(member_id)) try: await usr.send(content='📅┃**Event Now Starting**:\n• The below Event you joined has has now reached it\'s start time.\n• Please return to Events channel and visit the Event\'s created thread for instructions from the Event Organizer <@' + str(post_organizer_id) + '> to arrange friend requests and in-game plans, have fun!', embed=ctx.embeds[0]) except: pass if members_list_len > 40: try: await post_organizer.send(content='📅┃**Event Now Starting**:\n• The below Event you posted has now reached it\'s start time.\n• Please return to Events channel and visit the Event\'s created thread to provide instructions or coordinate with your Participants via DM, have fun!', embed=ctx.embeds[0]) await post_organizer.send(content='❗┃**Full Members List**:\n• Your post contained more than 50 members, see below all of their names!\n\n' + members_value) except: pass else: try: await post_organizer.send(content='📅┃**Event Now Starting**:\n• The below Event you posted has now reached it\'s start time.\n• Please return to Events channel and visit the Event\'s created thread to provide instructions or coordinate with your Participants via DM, have fun!', embed=ctx.embeds[0]) except: pass else: try: await post_organizer.send(content='📅┃**Event Now Starting**:\n• The below Event you posted has now reached it\'s start time, please return to the Events channel and visit the Event\'s created thread to provide instructions or coordinate with future Participants via DM.\n• No Participants at time of start so you do not need to contact anyone, feel free to post a new Event anytime or continue recruiting!', embed=ctx.embeds[0]) except: pass event_msg = await ctx.channel.send(content='📅┃**Event Now Starting**:\n• The below Event is now live, please visit the Event\'s created thread for further instructions or DM the Event Organizer!', embed=ctx.embeds[0], delete_after=900) event_thread = '' if str(ctx.embeds[0].fields[1].name) == 'Event Game:': event_thread = await event_msg.start_thread(name='Event - ' + post_organizer.display_name + ' | ' + str(ctx.embeds[0].fields[1].value), auto_archive_duration=60) elif str(ctx.embeds[0].fields[2].name) == 'Event Game:': event_thread = await event_msg.start_thread(name='Event - ' + post_organizer.display_name + ' | ' + str(ctx.embeds[0].fields[2].value), auto_archive_duration=60) info_msg = await event_thread.send(content='📅┃**Event Information**:\n• Please use this thread to coordinate friend requests and in-game plans for the below Event.', embed=ctx.embeds[0], components=thread_button) await info_msg.pin() try: await event_thread.add_user(post_organizer) except: pass if str(ctx.embeds[0].fields[0].name) == 'Participants:': members_value = str(ctx.embeds[0].fields[0].value) members_ids = members_value.replace('<@!', '').replace('<@', '').replace('>', '') members_list = members_ids.split(' ') for member_id in members_list: if ctx.author.guild.get_member(int(member_id)) is not None: usr = await client.fetch_user(int(member_id)) try: await event_thread.add_user(usr) except: pass try: await usr.send(content=f'❕┃**Event Thread Created**:\n• Please visit the following Thread to discuss the started Event: <#{str(event_thread.id)}>') except: pass sql = "DELETE FROM posts WHERE post_id = %s" val = (ctx.id,) await mysql_commit(sql=sql, val=val) except (AttributeError, IndexError): pass @client.event async def on_message(ctx): if ctx.webhook_id is None: if not (ctx.channel.type is discord.ChannelType.private): sql = "SELECT channel_lfgPosts_id, channel_events_id FROM guilds WHERE guild_id = %s" val = (ctx.guild.id,) await mysql_commit(sql=sql, val=val) channels = sql_connect.fetchall() expected_permissions = ['manage_nicknames', 'kick_members', 'ban_members', 'mute_members', 'deafen_members', 'move_members', 'administrator', 'manage_roles', 'manage_messages', 'manage_channels'] if channels: if (ctx.channel.id == int(channels[0]['channel_lfgPosts_id'])) | (ctx.channel.id == int(channels[0]['channel_events_id'])): if not ((ctx.author == client.user) | bool([item for item in ctx.author.guild_permissions if ((item[0] in expected_permissions) & (item[1] is True))]) | (ctx.author.id == 224349699061186570)): # try: # await ctx.author.send(content='❗┃**Unable to Post Here**:\n• This channel is restricted to <@' + str(client.user.id) + '> and users with Administrator permissions.') # except: # pass await ctx.delete() elif (ctx.channel.type is discord.ChannelType.private) & (ctx.author.id == 224349699061186570) & ('!help' in ctx.content): embed_message_help = discord.Embed(title=client.user.display_name + ' - Hidden Commands', description='See below a list of hidden commands restricted to user <@224349699061186570>.', color=0xffffff) embed_message_help.add_field(name="Server Owner Announcement:", value='Usage: `!announce optional(int(guild_id)) message`', inline=False) embed_message_help.add_field(name="Leave Joined Servers:", value='Usage: `!leave int(guild_id) silent/inform`', inline=False) embed_message_help.add_field(name="List Joined Servers:", value='Usage: `!servers`', inline=False) embed_message_help.add_field(name="Fetch Guild:", value='Usage: `!guild int(id)`', inline=False) embed_message_help.add_field(name="Fetch User:", value='Usage: `!user int(id)`', inline=False) embed_message_help.timestamp = datetime.datetime.now() embed_message_help.set_footer(text=txt_footer + str(embed_message_help.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_help.set_thumbnail(url=img_tip) embed_message_help.set_image(url=img_logo_banner) await ctx.channel.send(embed=embed_message_help, delete_after=30) elif (ctx.channel.type is discord.ChannelType.private) & (ctx.author.id == 224349699061186570) & ('!servers' in ctx.content): embed_message_help = discord.Embed(title=client.user.display_name + ' - Joined Servers List', description='See below a list of all servers <@' + str(client.user.id) + '> is currently a member of.', color=0xffffff) embed_message_help.timestamp = datetime.datetime.now() embed_message_help.set_footer(text=txt_footer + str(embed_message_help.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_help.set_thumbnail(url=img_tip) await ctx.channel.send(embed=embed_message_help, delete_after=120) all_regions = '' serviced_guilds = 0 serviced_users = 0 total_tiers = 0 total_subs = 0 guild_members = [] guild_regions = [] guild_verifications = [] guild_tiers = [] guild_subs = [] for guild in client.guilds: if guild.description is not None: description_text = guild.description else: description_text = 'No server description provided...' embed_message_servers = discord.Embed(title=str(guild.name), description=description_text, color=random.randint(0, 0xffffff)) embed_message_servers.add_field(name="Server ID:", value=str(guild.id), inline=False) embed_message_servers.add_field(name="Server Member Count:", value=str(guild.member_count), inline=False) if guild.premium_tier is not None: embed_message_servers.add_field(name="Server Boost Tier:", value=str(guild.premium_tier), inline=False) if guild.premium_subscription_count is not None: embed_message_servers.add_field(name="Server Boosters Count:", value=str(guild.premium_subscription_count), inline=False) if guild.region is not None: embed_message_servers.add_field(name="Server Region:", value=str(guild.region), inline=False) if guild.verification_level is not None: embed_message_servers.add_field(name="Server Verification Level:", value=str(guild.verification_level), inline=False) embed_message_servers.add_field(name="Owner ID:", value=str(guild.owner.id), inline=False) embed_message_servers.add_field(name="Owner Name:", value="<@" + str(guild.owner.id) + '> - ' + str(guild.owner.name), inline=False) embed_message_servers.add_field(name="Owner Discriminator:", value=str(guild.owner.discriminator), inline=False) try: embed_message_servers.add_field(name="Owner Avatar:", value=str(guild.owner.avatar), inline=False) except: embed_message_servers.add_field(name="Owner Avatar:", value='No Avatar set...', inline=False) embed_message_servers.timestamp = datetime.datetime.now() embed_message_servers.set_footer(text=txt_footer + str(embed_message_servers.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_servers.set_thumbnail(url=img_tip) try: embed_message_servers.set_thumbnail(url=guild.icon.url) except (AttributeError, IndexError): embed_message_servers.set_thumbnail(url=img_unknown) pass try: if guild.banner is not None: embed_message_servers.set_image(url=guild.banner.url) except (AttributeError, IndexError): pass await ctx.channel.send(embed=embed_message_servers, delete_after=120) serviced_guilds = serviced_guilds + 1 serviced_users = serviced_users + guild.member_count total_tiers = total_tiers + guild.premium_tier total_subs = total_subs + guild.premium_subscription_count guild_members.append(guild.member_count) guild_regions.append(guild.region) guild_verifications.append(guild.verification_level) guild_tiers.append(guild.premium_tier) guild_subs.append(guild.premium_subscription_count) set_guild_regions = set(guild_regions) list_guild_regions = (list(set_guild_regions)) for idx, region in enumerate(list_guild_regions): if idx == 0: all_regions = all_regions + str(region) elif idx > 0: all_regions = all_regions + ', ' + str(region) if client.guilds is None: await ctx.channel.send(content='❗┃**Joined Servers List - Error**:\nThe bot is currently not apart of any servers, thus no data can be queried!', delete_after=120) else: embed_message_stats = discord.Embed(title=client.user.display_name + ' - Joined Servers Statistics', description='See below a list of server statistics gathered from all servers <@' + str(client.user.id) + '> is currently a member of.', color=0xffffff) embed_message_stats.add_field(name="Total Serviced Guilds:", value=str(serviced_guilds), inline=False) embed_message_stats.add_field(name="Total Serviced Users:", value=str(serviced_users), inline=False) embed_message_stats.add_field(name="Total Guild Tiers:", value=str(total_tiers), inline=False) embed_message_stats.add_field(name="Total Guild Subs:", value=str(total_subs), inline=False) embed_message_stats.add_field(name="Total Serviced Regions:", value=str(len(set(guild_regions))), inline=False) embed_message_stats.add_field(name="Guild Serviced Regions:", value=str(all_regions), inline=False) embed_message_stats.add_field(name="Average Guild Users:", value=str(mean(guild_members)), inline=False) embed_message_stats.add_field(name="Average Guild Tiers:", value=str(mean(guild_tiers)), inline=False) embed_message_stats.add_field(name="Average Guild Subs:", value=str(mean(guild_subs)), inline=False) embed_message_stats.add_field(name="Most Common Guild Tier:", value=str(mode(guild_tiers)), inline=False) embed_message_stats.add_field(name="Most Common Guild Subs:", value=str(mode(guild_subs)), inline=False) embed_message_stats.add_field(name="Most Common Guild Region:", value=str(mode(guild_regions)), inline=False) embed_message_stats.add_field(name="Most Common Verification Level:", value=str(mode(guild_verifications)), inline=False) embed_message_stats.timestamp = datetime.datetime.now() embed_message_stats.set_footer(text=txt_footer + str(embed_message_stats.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_stats.set_thumbnail(url=img_logo) await ctx.channel.send(embed=embed_message_stats, delete_after=120) elif (ctx.channel.type is discord.ChannelType.private) & (ctx.author.id == 224349699061186570) & ('!user' in ctx.content): cmd_list = ctx.content.split() if len(cmd_list) == 2: if cmd_list[1].replace(" ", "").isdigit(): user_id = int(cmd_list[1].replace(" ", "")) if client.get_user(user_id) is not None: user_query = client.get_user(user_id) embed_message_query = discord.Embed(title=client.user.display_name + ' - Queried User', description='See below information pertaining to the queried user.', color=0xffffff) embed_message_query.add_field(name="User ID:", value=str(user_query.id), inline=False) embed_message_query.add_field(name="User Name:", value=str(user_query.name), inline=False) embed_message_query.add_field(name="User Discriminator:", value=str(user_query.discriminator), inline=False) embed_message_query.add_field(name="User Mutual Guilds:", value=str(user_query.mutual_guilds), inline=False) embed_message_query.add_field(name="User System:", value=str(user_query.system), inline=False) embed_message_query.add_field(name="Is User a Bot?", value=str(user_query.bot), inline=False) embed_message_query.timestamp = datetime.datetime.now() embed_message_query.set_footer(text=txt_footer + str(embed_message_query.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) if user_query.avatar is not None: embed_message_query.set_thumbnail(url=user_query.avatar) if user_query.banner is not None: embed_message_query.set_image(url=user_query.banner.url) await ctx.channel.send(embed=embed_message_query, delete_after=60) else: await ctx.channel.send(content='❗┃**Fetch User - Error**:\nPlease provide a ID of a valid user the bot shares a server with, correct format `!user int(id)`', delete_after=180) elif not cmd_list[1].replace(" ", "").isdigit(): await ctx.channel.send(content='❗┃**Fetch User - Error**:\nPlease provide numbers only and no letters or symbols, correct format `!user int(id)`', delete_after=180) elif len(cmd_list) > 2: await ctx.channel.send(content='❗┃**Fetch User - Error**:\nPlease provide only one ID at a time, correct format `!user int(id)`', delete_after=180) elif len(cmd_list) < 2: await ctx.channel.send(content='❗┃**Fetch User - Error**:\nPlease provide one ID, correct format `!user int(id)`', delete_after=180) elif (ctx.channel.type is discord.ChannelType.private) & (ctx.author.id == 224349699061186570) & ('!guild' in ctx.content): cmd_list = ctx.content.split() if len(cmd_list) == 2: if cmd_list[1].replace(" ", "").isdigit(): guild_id = int(cmd_list[1].replace(" ", "")) if client.get_guild(guild_id) is not None: guild_query = client.get_guild(guild_id) embed_message_query = discord.Embed(title=client.user.display_name + ' - Queried Server', description='See below information pertaining to the queried server.', color=0xffffff) embed_message_query.add_field(name="Server ID:", value=str(guild_query.id), inline=False) embed_message_query.add_field(name="Server Name:", value=str(guild_query.name), inline=False) if guild_query.description is not None: embed_message_query.add_field(name="Server Description:", value=str(guild_query.description), inline=False) embed_message_query.add_field(name="Server Member Count:", value=str(guild_query.member_count), inline=False) if guild_query.premium_tier is not None: embed_message_query.add_field(name="Server Boost Tier:", value=str(guild_query.premium_tier), inline=False) if guild_query.premium_subscription_count is not None: embed_message_query.add_field(name="Server Boosters Count:", value=str(guild_query.premium_subscription_count), inline=False) if guild_query.region is not None: embed_message_query.add_field(name="Server Region:", value=str(guild_query.region), inline=False) if guild_query.verification_level is not None: embed_message_query.add_field(name="Server Verification Level:", value=str(guild_query.verification_level), inline=False) embed_message_query.add_field(name="Owner ID:", value=str(guild_query.owner.id), inline=False) embed_message_query.add_field(name="Owner Name:", value=str(guild_query.owner.name), inline=False) embed_message_query.add_field(name="Owner Discriminator:", value=str(guild_query.owner.discriminator), inline=False) try: embed_message_query.add_field(name="Owner Avatar:", value=str(guild_query.owner.avatar), inline=False) except: embed_message_query.add_field(name="Owner Avatar:", value='No Avatar set...', inline=False) embed_message_query.timestamp = datetime.datetime.now() embed_message_query.set_footer(text=txt_footer + str(embed_message_query.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) try: embed_message_query.set_thumbnail(url=guild_query.icon.url) except (AttributeError, IndexError): embed_message_query.set_thumbnail(url=img_unknown) pass try: if guild_query.banner is not None: embed_message_query.set_image(url=guild_query.banner.url) except: pass await ctx.channel.send(embed=embed_message_query, delete_after=60) else: await ctx.channel.send(content='❗┃**Fetch Guild - Error**:\nPlease provide a ID of a valid server the bot is a member of, correct format `!guild int(id)`', delete_after=180) elif not cmd_list[1].replace(" ", "").isdigit(): await ctx.channel.send(content='❗┃**Fetch Guild - Error**:\nPlease provide numbers only and no letters or symbols, correct format `!guild int(id)`', delete_after=180) elif len(cmd_list) > 2: await ctx.channel.send(content='❗┃**Fetch Guild - Error**:\nPlease provide only one ID at a time, correct format `!guild int(id)`', delete_after=180) elif len(cmd_list) < 2: await ctx.channel.send(content='❗┃**Fetch Guild - Error**:\nPlease provide one ID, correct format `!guild int(id)`', delete_after=180) elif (ctx.channel.type is discord.ChannelType.private) & (ctx.author.id == 224349699061186570) & ('!leave' in ctx.content): cmd_list = ctx.content.split() if len(cmd_list) == 3: if (len(cmd_list) == 3) & ((cmd_list[1].isnumeric()) | (cmd_list[1] == '*')) & ((cmd_list[2] == 'silent') | (cmd_list[2] == 'inform')): guilds = [] guild_id = 0 if cmd_list[1].isnumeric(): guild_id = int(cmd_list[1]) sql = "SELECT guild_id FROM guilds WHERE guild_id = %s" val = (str(guild_id),) await mysql_commit(sql=sql, val=val) guilds = sql_connect.fetchall() elif cmd_list[1] == '*': sql_connect.execute('SELECT guild_id FROM guilds') guilds = sql_connect.fetchall() if guilds: if guilds[0]['guild_id'] == str(guild_id): guild = discord.utils.get(client.guilds, id=guild_id) if cmd_list[2] == 'silent': embed_message_garrus = discord.Embed(title='❗┃Server Removal Notice', description='• Please be aware Bot `' + client.user.name + '` has left Server `' + guild.name + '` per your request.\n• Guild Owners have has been informed to re-invite the bot as soon as they are able.', color=0xffffff) embed_message_garrus.set_author(name=client.user.name, url=url_discord, icon_url=client.user.avatar.url) embed_message_garrus.timestamp = datetime.datetime.now() embed_message_garrus.set_footer(text=txt_footer + str(embed_message_garrus.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_garrus.set_thumbnail(url=img_tip) await ctx.channel.send(embed=embed_message_garrus) print(f'{client.user.name} has left Guild per silent request: ' + str(guild.name) + ' @ ' + str(datetime.datetime.now())) await guild.leave() sql = "DELETE FROM guilds WHERE guild_id = %s" val = (str(guild_id),) await mysql_commit(sql=sql, val=val) elif cmd_list[2] == 'inform': sql_connect.execute("SELECT * FROM guilds_announcement_blacklist") blacklisted_guilds = sql_connect.fetchall() if not bool([item for item in blacklisted_guilds if (item['guild_id'] == str(guild.id))]): button_invite = [create_actionrow(create_button(style=ButtonStyle.URL, label='Re-Invite Bot', emoji='🤖', url=os.environ['INVITE_LINK']))] embed_message_owner = discord.Embed(title='❗┃Server Removal Notice', description='• Please be aware Bot `' + client.user.name + '` has left your Server `' + guild.name + '`\n• These leaves occur when our Bot has recieved a substantial update requiring it to leave in order for said features to become available.\n• Please re-invite the Bot back to your server using the below link as soon as possible.', color=clr_error) try: embed_message_owner.set_author(name=guild.name, url=url_discord, icon_url=guild.icon.url) except (AttributeError, IndexError): embed_message_owner.set_author(name=guild.name, url=url_discord, icon_url=img_unknown) pass embed_message_owner.timestamp = datetime.datetime.now() embed_message_owner.set_footer(text=txt_footer + str(embed_message_owner.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_owner.set_thumbnail(url=img_error) try: await guild.owner.send(embed=embed_message_owner, components=button_invite) except: pass elif bool([item for item in blacklisted_guilds if (item['guild_id'] == str(guild.id))]): print(f'{client.user.name} skipped informing blacklisted guild \'' + str(guild.name) + '\' @ ' + str(datetime.datetime.now())) embed_message_garrus = discord.Embed(title='❗┃Server Removal Notice', description='• Please be aware Bot `' + client.user.name + '` has left Server `' + guild.name + '` per your request.\n• Guild Owner <@' + str(guild.owner.id) + '> has been informed to re-invite the bot as soon as they are able.', color=0xffffff) try: embed_message_garrus.set_author(name=guild.name, url=url_discord, icon_url=guild.icon.url) except (AttributeError, IndexError): embed_message_garrus.set_author(name=guild.name, url=url_discord, icon_url=img_unknown) pass embed_message_garrus.timestamp = datetime.datetime.now() embed_message_garrus.set_footer(text=txt_footer + str(embed_message_garrus.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_garrus.set_thumbnail(url=img_tip) await ctx.channel.send(embed=embed_message_garrus) print(f'{client.user.name} has left Guild per inform request: ' + str(guild.name) + ' @ ' + str(datetime.datetime.now())) await guild.leave() sql = "DELETE FROM guilds WHERE guild_id = %s" val = (str(guild_id),) await mysql_commit(sql=sql, val=val) elif guild_id == '*': embed_message_garrus = discord.Embed(title='❗┃Server Removal Notice', description='• Please be aware Bot `' + client.user.name + '` has left all Servers per your request.\n• Guild Owners have has been informed to re-invite the bot as soon as they are able.', color=0xffffff) embed_message_garrus.set_author(name=client.user.name, url=url_discord, icon_url=client.user.avatar.url) embed_message_garrus.timestamp = datetime.datetime.now() embed_message_garrus.set_footer(text=txt_footer + str(embed_message_garrus.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_garrus.set_thumbnail(url=img_tip) await ctx.channel.send(embed=embed_message_garrus) for guild in client.guilds: if cmd_list[2] == 'silent': print(f'{client.user.name} has left Guild per silent request: ' + str(guild.name) + ' @ ' + str(datetime.datetime.now())) sql = "DELETE FROM guilds WHERE guild_id = %s" val = (str(guild.id),) await mysql_commit(sql=sql, val=val) await guild.leave() elif cmd_list[2] == 'inform': button_invite = [create_actionrow(create_button(style=ButtonStyle.URL, label='Re-Invite Bot', emoji='🤖', url=os.environ['INVITE_LINK']))] embed_message_owner = discord.Embed(title='❗┃Server Removal Notice', description='• Please be aware Bot `' + client.user.name + '` has left your Server `' + guild.name + '`\n• These leaves occur when our Bot has recieved a substantial update requiring it to leave in order for said features to become available.\n• Please re-invite the Bot back to your server using the below link as soon as possible.', color=clr_error) try: embed_message_owner.set_author(name=guild.name, url=url_discord, icon_url=guild.icon.url) except (AttributeError, IndexError): embed_message_owner.set_author(name=guild.name, url=url_discord, icon_url=img_unknown) pass embed_message_owner.timestamp = datetime.datetime.now() embed_message_owner.set_footer(text=txt_footer + str(embed_message_owner.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_owner.set_thumbnail(url=img_error) try: await guild.owner.send(embed=embed_message_owner, components=button_invite) except: pass print(f'{client.user.name} has left Guild per inform request: ' + str(guild.name) + ' @ ' + str(datetime.datetime.now())) sql = "DELETE FROM guilds WHERE guild_id = %s" val = (str(guild.id),) await mysql_commit(sql=sql, val=val) await guild.leave() else: await ctx.channel.send(content='❗┃**Guild Remove - Error**:\nGuild ID provided not of any guild `' + client.user.name + '` is apart of, correct format `!leave int(guild_id) silent/inform`', delete_after=180) elif (len(cmd_list) == 3) & (not((cmd_list[1].isnumeric()) | (cmd_list[1] == '*'))) & ((cmd_list[2] == 'silent') | (cmd_list[2] == 'inform')): await ctx.channel.send(content='❗┃**Guild Remove - Error**:\nSecond Arguement provided invalid format, not numeric, correct format `!leave int(guild_id) silent/inform`', delete_after=180) elif (len(cmd_list) == 3) & ((cmd_list[1].isnumeric()) | (cmd_list[1] == '*')) & (not ((cmd_list[2] == 'silent') | (cmd_list[2] == 'inform'))): await ctx.channel.send(content='❗┃**Guild Remove - Error**:\nThird Arguement provided invalid format, not `silent` or `inform`, correct format `!leave int(guild_id) silent/inform`', delete_after=180) elif (len(cmd_list) == 3) & (not((cmd_list[1].isnumeric()) | (cmd_list[1] == '*'))) & (not ((cmd_list[2] == 'silent') | (cmd_list[2] == 'inform'))): await ctx.channel.send(content='❗┃**Guild Remove - Error**:\nSecond Arguement provided invalid format, not numeric\nThird Arguement provided invalid format, not `silent` or `inform`\nCorrect format `!leave int(guild_id) silent/inform`', delete_after=180) elif len(cmd_list) > 3: await ctx.channel.send(content='❗┃**Guild Remove - Error**:\nMore than 3 arguements provided, correct format `!leave int(guild_id) silent/inform`', delete_after=180) elif len(cmd_list) < 3: await ctx.channel.send(content='❗┃**Guild Remove - Error**:\nLess than 3 arguements provided, correct format `!leave int(guild_id) silent/inform`', delete_after=180) elif (isinstance(ctx.channel, discord.channel.DMChannel)) & (ctx.author.id == 224349699061186570) & ('!announce' in ctx.content): button_invite = [create_actionrow(create_button(style=ButtonStyle.URL, label='Support Server', emoji='🔧', url=url_discord), create_button(style=ButtonStyle.URL, label='Bot Invite Link', emoji='🤖', url=os.environ['INVITE_LINK']), create_button(style=ButtonStyle.URL, label='Website', emoji='🌐', url=url_website))] cmd_list = ctx.content.split() special_announcement = False if len(cmd_list) >= 2: if len(cmd_list) >= 3: if cmd_list[1].isnumeric(): announcement = ctx.content.replace('!announce', '').replace(str(cmd_list[1]) + ' ', '') if client.get_guild(int(cmd_list[1])) in client.guilds: special_announcement = True specific_guild = client.get_guild(int(cmd_list[1])) embed_message_owner = discord.Embed(title='❕┃Developer Announcement', description='Please be aware Bot `' + client.user.name + '` has delivered an Announcement from it\'s Developer `Garrus Valkyrin` below to you personally:', color=0xffffff) embed_message_owner.add_field(name="Announcement:", value=announcement, inline=False) embed_message_owner.add_field(name="Looking to get more engaged?", value='Do you have a innovative or even a quality of life change you\'d like to see implemented? Join our Support Server today to provide us with any and all feedback in time for the next update!\n- **Rock On** :wink: - `Developer, Garrus Valkyrin#9816`', inline=False) try: embed_message_owner.set_author(name=specific_guild.name, url=url_discord, icon_url=specific_guild.icon.url) except (AttributeError, IndexError): embed_message_owner.set_author(name=specific_guild.name, url=url_discord, icon_url=img_unknown) pass embed_message_owner.timestamp = datetime.datetime.now() embed_message_owner.set_footer(text=txt_footer + str(embed_message_owner.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_owner.set_thumbnail(url=img_tip) try: await specific_guild.owner.send(embed=embed_message_owner, components=button_invite) except: pass if not special_announcement: announcement = ctx.content.replace('!announce', '') database.commit() sql_connect.execute("SELECT * FROM guilds_announcement_blacklist") blacklisted_guilds = sql_connect.fetchall() for guild in client.guilds: if not bool([item for item in blacklisted_guilds if (item['guild_id'] == str(guild.id))]): embed_message_owner = discord.Embed(title='❕┃Developer Announcement', description='Please be aware Bot `' + client.user.name + '` has delivered an Announcement from it\'s Developer `Garrus Valkyrin` below:', color=0xffffff) embed_message_owner.add_field(name="Announcement:", value=announcement, inline=False) embed_message_owner.add_field(name="How to update?", value='Nothing, updates roll out automatically! In order for the detailed new features to take place please give the bot a few minutes to process all servers, some features such as new slash commands may require a few extra minutes to finish implementing.', inline=False) embed_message_owner.add_field(name="Looking to get more engaged?", value='Do you have a innovative or even a quality of life change you\'d like to see implemented? Join our Support Server today to provide us with any and all feedback in time for the next update!\n- **Rock On** :wink: - `Developer, Garrus Valkyrin#9816`', inline=False) try: embed_message_owner.set_author(name=guild.name, url=url_discord, icon_url=guild.icon.url) except (AttributeError, IndexError): embed_message_owner.set_author(name=guild.name, url=url_discord, icon_url=img_unknown) pass embed_message_owner.timestamp = datetime.datetime.now() embed_message_owner.set_footer(text=txt_footer + str(embed_message_owner.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_owner.set_thumbnail(url=img_tip) try: await guild.owner.send(embed=embed_message_owner, components=button_invite) except: pass elif bool([item for item in blacklisted_guilds if (item['guild_id'] == str(guild.id))]): print(f'{client.user.name} skipped blacklisted guild \'' + str(guild.name) + '\' @ ' + str(datetime.datetime.now())) embed_message_garrus = discord.Embed(title='❕┃Developer Announcement Delivered', description='Please be aware Bot `' + client.user.name + '` has delivered the requested Announcement to all Guild Owners:', color=0xffffff) embed_message_garrus.add_field(name="Announcement:", value=announcement, inline=False) embed_message_garrus.set_author(name=client.user.name, url=url_discord, icon_url=client.user.avatar.url) embed_message_garrus.timestamp = datetime.datetime.now() embed_message_garrus.set_footer(text=txt_footer + str(embed_message_garrus.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message_garrus.set_thumbnail(url=img_tip) await ctx.channel.send(embed=embed_message_garrus) print(f'{client.user.name} has dispersed requested announcement to Guild Owners ' + ' @ ' + str(datetime.datetime.now())) elif len(cmd_list) < 2: await ctx.channel.send(content='❗┃**Announcement - Error**:\nPlease provide a statement to announce!', delete_after=180) @client.event async def on_invite_delete(invite): sql = "SELECT global_search, channel_lfgPosts_id, global_search_invite FROM guilds WHERE guild_id = %s" val = (invite.guild.id,) await mysql_commit(sql=sql, val=val) opt_lfg = sql_connect.fetchall() if opt_lfg[0]['global_search'] == 'yes': if invite.url == str(opt_lfg[0]['global_search_invite']): globalinvite = '' if client.get_channel(int(opt_lfg[0]['channel_lfgPosts_id'])) is not None: lfg_posts_channel = client.get_channel(int(opt_lfg[0]['channel_lfgPosts_id'])) globalinvite = await lfg_posts_channel.create_invite(max_uses=0, max_age=0, unique=True) else: text_channel = await random.choice(invite.guild.text_channels) globalinvite = await text_channel.create_invite(max_uses=0, max_age=0, unique=True) sql = "UPDATE guilds SET global_search_invite = %s WHERE guild_id = %s" val = (str(globalinvite), invite.guild.id) await mysql_commit(sql=sql, val=val) @client.event async def silent_expired_posts(channel, type): if type == 'type_lfg': async for msg in channel.history(): try: if (msg.embeds[0].title == 'Team Organizer:') & (msg.author.id == client.user.id): sql = "SELECT * FROM posts WHERE post_id = %s" val = (msg.id,) await mysql_commit(sql=sql, val=val) sql_query = sql_connect.fetchall() if sql_query is not None: # Mark - LFG Posts Removals PT2 if sql_query[0]['thread_id'] != '': thread_id = sql_query[0]['thread_id'] if msg.channel.get_thread(int(thread_id)): message_thread = msg.channel.get_thread(int(thread_id)) await message_thread.delete() await msg.delete() elif datetime.datetime.utcnow() >= msg.created_at.utcnow() + timedelta(seconds=1200): await msg.delete() sql = "DELETE FROM posts WHERE post_id = %s" val = (msg.id,) await mysql_commit(sql=sql, val=val) except (AttributeError, IndexError): pass elif type == 'type_event': async for msg in channel.history(): try: if (msg.embeds[0].title == 'Event Organizer:') & (msg.author.id == client.user.id): sql = "SELECT * FROM posts WHERE post_id = %s" val = (msg.id,) await mysql_commit(sql=sql, val=val) sql_query = sql_connect.fetchall() fmt = "%Y-%m-%d %H:%M" submitted_time = msg.embeds[0].fields[-1].value.replace('[', '').replace(']', '').partition('(') event_time = datetime.datetime.utcfromtimestamp(int(submitted_time[0].replace('<t:', '').replace(':F>', ''))) event_time = datetime.datetime.strptime(event_time.strftime(fmt), '%Y-%m-%d %H:%M') time_now = datetime.datetime.now(timezone('UTC')) time_now = datetime.datetime.strptime(time_now.strftime(fmt), '%Y-%m-%d %H:%M') if time_now >= event_time + timedelta(seconds=1200): await msg.delete() sql = "DELETE FROM posts WHERE post_id = %s" val = (msg.id,) await mysql_commit(sql=sql, val=val) elif (time_now <= event_time + timedelta(seconds=1200)) & (not bool(sql_query)): await msg.delete() except (AttributeError, IndexError): pass @client.event async def check_channel_embeds(ctx, lfg_posts_id='', events_id=''): if lfg_posts_id != '': lfg_posts_channel = client.get_channel(int(lfg_posts_id)) lfg_posts_channel_messages = await lfg_posts_channel.history().flatten() found_lfg_posts_author = False for msg in lfg_posts_channel_messages: try: if (msg.author.id == 860300499177832458) & (msg.embeds[0].title == client.user.display_name + ' - LFG Posts Channel'): found_lfg_posts_author = True break except (AttributeError, IndexError): pass if found_lfg_posts_author is False: button_lfg_info = [create_actionrow(create_button(style=ButtonStyle.secondary, label="Supported Games", emoji='❔', custom_id='lfg_info'))] embed_message = discord.Embed(title=client.user.display_name + ' - LFG Posts Channel', description='Find below an area to review and join open LFG Posts for this server\'s supported games.', color=0xffffff) embed_message.add_field(name='Where to find us?', value='If you would like further information regarding our service consider joining our support server or our offical homepage.\n• [**Official Homepage**](https://valkyrin.github.io/LFG-Event-Bot-Website/)\n• [**Support Server**](https://discord.gg/Gm5FSXxxR3)\n• [**Bot Invite Link**](https://discord.com/oauth2/authorize?client_id=860300499177832458&scope=bot%20applications.commands&permissions=260654497393)', inline=False) embed_message.add_field(name='What to expect here?', value='\n• Find in <#' + str(lfg_posts_id) + '> an area to review the submitted LFG Posts from both others and yourself for the games this server supports.', inline=False) embed_message.add_field(name='How to create your own Team?', value='\n• To post here, use the `/host` command to build a LFG Team.\n• Posts will be displayed here in embed format for others to join.\n• Each post expires 15 minutes after initial post.', inline=False) embed_message.add_field(name='Team Organizer Options:', value='• `🔒 Close` will remove your post and inform Team Members it is time to start.\n• `🛑 Disband` will remove your post and inform Team Members you intend to no longer play.', inline=False) embed_message.add_field(name='Team Member Options:', value='• `✔️ Join` will add you to the Team\'s Members, the Team Organizer will be informed.\n• `❌ Leave` will remove you from the Team\'s Members, the Team Organizer will be informed.', inline=False) try: embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass embed_message.timestamp = datetime.datetime.now() embed_message.set_footer(text=txt_footer + str(embed_message.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message.set_image(url=img_logo_banner) msg = await lfg_posts_channel.send(embed=embed_message, components=button_lfg_info) await msg.pin() for msg in await lfg_posts_channel.history().flatten(): await msg.delete() break if events_id != '': events_channel = client.get_channel(int(events_id)) events_channel_messages = await events_channel.history().flatten() found_events_author = False for msg in events_channel_messages: try: if (msg.author.id == 860300499177832458) & (msg.embeds[0].title == client.user.display_name + ' - Events Channel'): found_events_author = True break except (AttributeError, IndexError): pass if found_events_author is False: button_lfg_info = [create_actionrow(create_button(style=ButtonStyle.secondary, label="Supported Games", emoji='❔', custom_id='lfg_info'))] embed_message = discord.Embed(title=client.user.display_name + ' - Events Channel', description='Find below an area to review and join open Events for this server\'s supported games.', color=0xffffff) embed_message.add_field(name='Where to find us?', value='If you would like further information regarding our service consider joining our support server or our offical homepage.\n• [**Official Homepage**](https://valkyrin.github.io/LFG-Event-Bot-Website/)\n• [**Support Server**](https://discord.gg/Gm5FSXxxR3)\n• [**Bot Invite Link**](https://discord.com/oauth2/authorize?client_id=860300499177832458&scope=bot%20applications.commands&permissions=260654497393)', inline=False) embed_message.add_field(name='What to expect here?', value='\n• Find in <#' + str(events_id) + '> an area to review the upcoming Events from both others and yourself for the games this server supports.', inline=False) embed_message.add_field(name='How to create your own Event?', value='\n• To post here, use the `/host` command to build a Event.\n• When using `/host` specify your type as Event, include a required date, and even an optional banner url.\n• Posts will be displayed here in embed format for others to join.\n• Each post expires 15 minutes after specified start time.', inline=False) embed_message.add_field(name='Event Organizer Options:', value='• `🔒 Close` will remove your post and inform Participants it is time to start early.\n• `🛑 Disband` will remove your Event and inform Participants you intend to no longer host.', inline=False) embed_message.add_field(name='Event Participant Options:', value='• `✔️ Join` will add you to the Event\'s Participants, you will be informed once the Event starts.\n• `❌ Leave` will remove you from the Event\'s Participants.', inline=False) try: embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=ctx.author.guild.icon.url) except (AttributeError, IndexError): embed_message.set_author(name=ctx.author.guild.name, url=url_discord, icon_url=img_unknown) pass embed_message.timestamp = datetime.datetime.now() embed_message.set_footer(text=txt_footer + str(embed_message.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[0:0]), icon_url=img_tip) embed_message.set_image(url=img_logo_banner) msg = await events_channel.send(embed=embed_message, components=button_lfg_info) await msg.pin() for msg in await events_channel.history().flatten(): await msg.delete() break @client.event async def check_joined_posts(ctx): slash_context = False try: lfg_posts_channel_messages = await ctx.origin_message.channel.history().flatten() except (AttributeError, IndexError): sql = "SELECT channel_lfgPosts_id FROM guilds WHERE guild_id = %s" val = (ctx.author.guild.id,) await mysql_commit(sql=sql, val=val) ids = sql_connect.fetchall() lfg_posts_channel = client.get_channel(int(ids[0]['channel_lfgPosts_id'])) lfg_posts_channel_messages = await lfg_posts_channel.history().flatten() slash_context = True for msg in lfg_posts_channel_messages: if msg.author == client.user: try: if msg.embeds[0].title == 'Team Organizer:': post_organizer_id = str(msg.embeds[0].description).replace('<@!', '').replace('<@', '').replace('>', '') if (post_organizer_id == str(ctx.author.id)) & (not slash_context): button_origin_msg = [create_actionrow(create_button(style=ButtonStyle.URL, label='Origin Post', emoji='📑', url=str(msg.jump_url)))] await ctx.send(content='🛑┃**Team Join Forbidden - Already Hosting**:\n• Whilst currently hosting an LFG Team of your own, you are unable to join other teams.\n• Please disband or close your current team in order to begin joining new teams.', embed=msg.embeds[0], components=button_origin_msg, hidden=True) return True elif msg.embeds[0].fields[0].name == 'Team Members:': members_value = str(msg.embeds[0].fields[0].value) if 'Plus' in members_value: sql = "SELECT post_members FROM posts WHERE post_id = %s" val = (ctx.origin_message.id,) await mysql_commit(sql=sql, val=val) sql_query_members = sql_connect.fetchall() if sql_query_members: members_value = sql_query_members[0]['post_members'] members_ids = sql_query_members[0]['post_members'].replace('<@!', '').replace('<@', '').replace('>', '') members_list = members_ids.split(' ') members_list_len = len(members_list) else: members_overflow = re.search('Plus (.*) More', members_value) members_overflow = int(members_overflow.group(1)) members_value.partition(' Plus') members_ids = members_value.replace('<@!', '').replace('<@', '').replace('>', '') members_list = members_ids.split(' ') members_list_len = len(members_list) + members_overflow else: members_ids = members_value.replace('<@!', '').replace('<@', '').replace('>', '') members_list = members_ids.split(' ') members_list_len = len(members_list) available_slots = int(msg.embeds[0].fields[3].value.replace('*', '')) for member_ids in members_list: if member_ids == str(ctx.author.id): msg.embeds[0].set_field_at(3, name="Available Slots:", value='**' + str(available_slots + 1) + '**', inline=True) if members_list_len - 1 <= 0: msg.embeds[0].remove_field(0) elif members_list_len - 1 > 0: members_list.remove(str(ctx.author.id)) members_field = '' for member in members_list: members_field += '<@' + member + '>' if member != members_list[-1]: members_field += ' ' msg.embeds[0].set_field_at(0, name="Team Members:", value=members_field, inline=True) await msg.edit(embed=msg.embeds[0]) post_organizer = await client.fetch_user(int(post_organizer_id)) button_origin_msg = [create_actionrow(create_button(style=ButtonStyle.URL, label='Origin Post', emoji='📑', url=str(msg.jump_url)))] try: await post_organizer.send(content='❌┃**Team Member Left**:\n• Team Member <@' + str(ctx.author.id) + '> has left your team, you do not need to contact them. You will be alerted if a new user joins your team.' + tip_host, embed=msg.embeds[0], components=button_origin_msg) except: pass if not slash_context: await ctx.send(content='❌┃**Left Prior Team**:\n• You have joined a new Team whilst already being a Member of another team.\n• Your prior Team Organizer has been informed of your leave, you do not need to contact them. Enjoy your new team!' + tip_member, embed=msg.embeds[0], components=button_origin_msg, hidden=True) elif slash_context: await ctx.send(content='❌┃**Left Prior Team**:\n• You have started hosting a new Team whilst already being a Member of another team.\n• Your prior Team Organizer has been informed of your leave, you do not need to contact them. Enjoy your new team!' + tip_member, embed=msg.embeds[0], components=button_origin_msg, hidden=True) return False except (AttributeError, IndexError): pass return False @client.event async def check_submitted_posts(ctx, lfg_msg): sql = "SELECT channel_lfgPosts_id FROM guilds WHERE guild_id = %s" val = (ctx.author.guild.id,) await mysql_commit(sql=sql, val=val) ids = sql_connect.fetchall() lfg_posts_channel = client.get_channel(int(ids[0]['channel_lfgPosts_id'])) lfg_posts_channel_messages = await lfg_posts_channel.history().flatten() for msg in lfg_posts_channel_messages: if msg != lfg_msg: if msg.embeds[0].title == 'Team Organizer:': post_organizer_id = str(msg.embeds[0].description).replace('<@!', '').replace('<@', '').replace('>', '') if post_organizer_id == str(ctx.author.id): if msg.embeds[0].fields[0].name == 'Team Members:': members_value = str(msg.embeds[0].fields[0].value) members_ids = members_value.replace('<@!', '').replace('<@', '').replace('>', '') members_list = members_ids.split(' ') for member_ids in members_list: try: await ctx.guild.get_member(int(member_ids)).send(content='🛑┃**Team Disbanded - New Team**:\n• Team Organizer has decided to remove their team and post a new Team.\n• You do not need to contact them, feel free to instead join a different Team or their new team.', embed=msg.embeds[0]) except: pass await ctx.send(content='🛑┃**Team Disbanded - New Team**:\n• Due to only allowing one LFG post at a time, your prior active Team has been removed and your new team is now active.\n• All Team Members have been informed so you do not need to contact them, feel free to post a new Team anytime.', embed=msg.embeds[0], hidden=True) else: await ctx.send(content='🛑┃**Team Disbanded - New Team**:\n• Due to only allowing one LFG post at a time, your prior active Team has been removed and your new team is now active.\n• You did not have any Team Members at the time of removal, feel free to post a new Team anytime.', embed=msg.embeds[0], hidden=True) sql = "SELECT thread_id FROM posts WHERE post_id = %s" val = (msg.id,) await mysql_commit(sql=sql, val=val) query = sql_connect.fetchall() if query: if query[0]['thread_id'] != '': thread_id = query[0]['thread_id'] message_thread = msg.channel.get_thread(int(thread_id)) sql = "UPDATE posts SET thread_id = %s WHERE thread_id = %s" val = ('', str(message_thread.id)) await mysql_commit(sql=sql, val=val) await message_thread.delete() await msg.delete() # ################ Client Run ######################## client.run(os.environ['AEGIS'])