def generate_permissions(): permissions_per_guild = {} for guild in config.bot.guilds: for guild_role in guild.roles: if guild_role.permissions.manage_roles: permissions_per_guild[guild.id] = create_permission( guild_role.id, 1, True)
def build_permissions(): print("Contruindo permissões") global allowed_guilds global default_permissions doc = mongo_collection.find_one({"_name": "allowed_guilds"}) allowed_guilds = doc["allowed_guilds"] default_permissions = [ create_permission( id=867858666525949972, id_type=1, permission=True ), create_permission( id=744991248284254278, id_type=1, permission=False ) ]
def generate_admin_permissions() -> Dict: """Generate the admin permissions from the config. Note that this is a bit hacky and the config cog has to be loaded first. Unfortunately we can't use the bot object in the annotation, so we can't access the config like this directly. """ permissions = {} for guild in config["Discord"]["guilds"]: permissions[guild["id"]] = [ create_permission(role_id, SlashCommandPermissionType.ROLE, True) for role_id in guild["mod_roles"] ] print(permissions) return permissions
async def add_permissions_to_commands(self, sync=False): perms_data = {} for guild in self.guilds: perms_data[guild.id] = [] guild_data = await self.get_guild_data(guild.id) self.slash.perms_cache[guild.id] = guild_data.moderation_roles for role_id in guild_data.moderation_roles: perms_data[guild.id].append(manage_commands.create_permission(role_id, 1, True)) _temp = copy.copy(self.slash.commands) for command in _temp.keys(): if not self.slash.commands[command].default_permission: self.slash.commands[command].permissions = perms_data else: self.slash.commands[command].permissions = [] if sync: await self.slash.sync_all_commands()
@client.event async def on_ready(): print("Let them trains roll!") # Initializing the Slash Commands # Commands without DB use @slash.slash( name="DevSet", description="Give someone the Dev-Role... Spooky", guild_ids=guild_id, default_permission=False, permissions={ girc_guild_id: [ create_permission(head_dev_role_id, SlashCommandPermissionType.ROLE, True), ] }, options=[ create_option( name="person", description="The Person you wanna give power to.", option_type=6, required=True ), create_option( name="language", description="The language of the person.", option_type=3, required=True, choices=[
required=False), create_option( name="limite_superieure", description="Le nombre le plus haut que le dé peux donner.", option_type=4, required=False) ]) async def lancer(ctx, tricher, limite_inferieure=1, limite_superieure=6): await ctx.send("Je lance le dé...") num = random.randint(limite_inferieure, limite_superieure) if tricher == "y": num = 4 await ctx.send(f"**{num}** 🎲!") @slash.slash(name="bonjour", guild_ids=[871456214016458772], description="Cette commande dis bonjour !") @slash.permission(guild_id=871456214016458772, permissions=[ create_permission(871456214016458772, SlashCommandPermissionType.ROLE, False), create_permission(871463050409050112, SlashCommandPermissionType.ROLE, True), ]) async def bonjour(ctx): await ctx.send(ctx.author.display_name + " dis bonjour !") bot.run("ODcxNDU1MzkwODAwNDI0OTkw.YQbkFA.tf3b3iiA9uCYen5GNjlCGMia55M")
# Whitelist @cog_ext.cog_slash( name="addserver", description="Adds a server into the whitelist.", options=[ create_option(name="server_id", description="The ID of the server to whitelist.", option_type=3, required=True), ] #, guild_ids=TEST_GUILDS , default_permission=False, permissions={ TEST_GUILDS[0]: [ create_permission(647452832852869120, SlashCommandPermissionType.USER, True) ] }) async def insert_server(self, interaction, server_id: str) -> None: member = interaction.author if not server_id.isdigit(): return await interaction.send( f"**Please, inform a server ID, {member.mention}!**", hidden=True) server_id = int(server_id) try: await self._insert_server(server_id) await interaction.send(
from messages import commands server_ids, role_id, bot_token = get_env_vars( ) # Get Variables from Environmental Variables client = discord.Client(intents=discord.Intents.default()) slash = SlashCommand( client, sync_commands=True) # Declares slash commands through the client. quest_roles = [] for server in server_ids: quest_roles += [ create_permission( role_id, SlashCommandPermissionType.ROLE, True), # Lumenaut | Custom Role with Permissions from env var create_permission(server, SlashCommandPermissionType.ROLE, False), # Everyone | everyone role ID = Server ID ] @client.event async def on_ready(): print("Ready!") for command in commands: function_name = f"_{command}" @slash.slash(name=command,
import discord import discord_slash from discord_slash import SlashCommand from discord_slash.utils.manage_commands import create_permission from discord_slash.model import SlashCommandPermissionType import os from messages import commands client = discord.Client(intents=discord.Intents.default()) slash = SlashCommand(client, sync_commands=True) # Declares slash commands through the client. guild_ids = [703325111209427015, 763798356484161566] # Test Server, Stellar Quest Server quest_roles = [ create_permission(766768688342499390, SlashCommandPermissionType.ROLE, True), # Lumenaut create_permission(763798356484161566, SlashCommandPermissionType.ROLE, False), # Everyone ] @client.event async def on_ready(): print("Ready!") @slash.slash(name="ping", guild_ids=guild_ids) @slash.permission(guild_id=763798356484161566,permissions=quest_roles) async def _ping(ctx): # Defines a new "context" (ctx) command called "ping." await ctx.send(f"Pong! ({client.latency*1000}ms)") for command in commands: function_name = f"_{command}" @slash.slash(name=command, guild_ids=guild_ids, description=f"{commands[command][:97]}...") async def function_name(ctx):
}, { "State": "Wyoming", "Abbrev": "Wyo.", "Code": "WY" }, { "State": "Puerto Rico", "Code": "PR" }, ] # Slash command permissions admin_mod_perms = { GUILD_PROD: [ create_permission(ROLE_ADMIN_PROD, SlashCommandPermissionType.ROLE, True), create_permission(ROLE_MOD_PROD, SlashCommandPermissionType.ROLE, True), create_permission(ROLE_EVERYONE_PROD, SlashCommandPermissionType.ROLE, False), ] } admin_perms = { GUILD_PROD: [ create_permission(ROLE_ADMIN_PROD, SlashCommandPermissionType.ROLE, True), create_permission(ROLE_EVERYONE_PROD, SlashCommandPermissionType.ROLE, False), ] }
import os from discord_slash.utils.manage_commands import create_permission, SlashCommandPermissionType perms = { os.environ.get('SERVER_ID'): [ create_permission(int(os.environ.get('MODERATOR_ROLE_ID')), SlashCommandPermissionType.ROLE, True), create_permission(int(os.environ.get('SERVER_ID')), SlashCommandPermissionType.ROLE, False) ] # Если хотите отключить обычным пользователям использовать /команду, в аргументах команды укажите # default_permission = False. Такой костыль не обязателен. }
class Unloading(commands.Cog): def __init__(self): """ This class is a collection functionality for tracking a booze cruise unload operations """ @cog_ext.cog_slash( name="Wine_Helper_Market_Open", guild_ids=[bot_guild_id()], description="Creates a new unloading helper operation in this channel.", permissions={ bot_guild_id(): [ create_permission(server_admin_role_id(), SlashCommandPermissionType.ROLE, True), create_permission(server_wine_carrier_role_id(), SlashCommandPermissionType.ROLE, True), create_permission(server_sommelier_role_id(), SlashCommandPermissionType.ROLE, True), create_permission(server_mod_role_id(), SlashCommandPermissionType.ROLE, True), create_permission(bot_guild_id(), SlashCommandPermissionType.ROLE, False), ] }, ) async def booze_unload_market(self, ctx: SlashContext): """ Command to set a booze cruise market unload. Generates a default message in the channel that it ran in. :param SlashContext ctx: The discord slash context. :returns: A discord embed with some emoji's """ print( f'User {ctx.author} requested a new booze unload in channel: {ctx.channel}.' ) embed = discord.Embed(title='Avast Ye!') embed.add_field( name= 'If you are INTENDING TO BUY, please react with: :airplane_arriving:.\n' f'Once you are DOCKED react with: <:Assassin:{str(get_custom_assassin_id())}>\n' f'Once you PURCHASE WINE, react with: :wine_glass:', value= 'Market will be opened once we have aligned the number of commanders.', inline=True) embed.set_footer( text= 'All 3 emoji counts should match by the end or Pirate Steve will be unhappy. 🏴☠' ) message = await ctx.send(embed=embed) await message.add_reaction('🛬') await message.add_reaction( f'<:Assassin:{str(get_custom_assassin_id())}>') await message.add_reaction('🍷') @cog_ext.cog_slash( name="Wine_Helper_Market_Closed", guild_ids=[bot_guild_id()], description= "Sends a message to indicate you have closed your market. Command sent in active channel.", permissions={ bot_guild_id(): [ create_permission(server_admin_role_id(), SlashCommandPermissionType.ROLE, True), create_permission(server_wine_carrier_role_id(), SlashCommandPermissionType.ROLE, True), create_permission(server_sommelier_role_id(), SlashCommandPermissionType.ROLE, True), create_permission(server_mod_role_id(), SlashCommandPermissionType.ROLE, True), create_permission(bot_guild_id(), SlashCommandPermissionType.ROLE, False), ] }, ) async def booze_market_closed(self, ctx: SlashContext): print( f'User {ctx.author} requested a to close the market in channel: {ctx.channel}.' ) embed = discord.Embed( title='Batten Down The Hatches! This sale is currently done!') embed.add_field( name='Go fight the sidewinder for the landing pad.', value='Hopefully you got some booty, now go get your doubloons!') embed.set_footer( text='Notified by your friendly neighbourhood pirate bot.') message = await ctx.send(embed=embed) await message.add_reaction('🏴☠️') @cog_ext.cog_slash( name='Wine_Unload', guild_ids=[bot_guild_id()], description= 'Posts a new wine unloading notification for a specific carrier. Admin/Sommelier role required.', permissions={ bot_guild_id(): [ create_permission(server_admin_role_id(), SlashCommandPermissionType.ROLE, True), create_permission(server_sommelier_role_id(), SlashCommandPermissionType.ROLE, True), create_permission(server_mod_role_id(), SlashCommandPermissionType.ROLE, True), create_permission(bot_guild_id(), SlashCommandPermissionType.ROLE, False), ] }, options=[ create_option(name='carrier_id', description='The XXX-XXX ID string for the carrier', option_type=3, required=True), create_option( name='planetary_body', description= 'A string representing the location of the carrier, ie Star, P1, P2', option_type=3, required=True, choices=[ create_choice(name="Star", value="Star"), create_choice(name="Planet 1", value="Planet 1"), create_choice(name="Planet 2", value="Planet 2"), create_choice(name="Planet 3", value="Planet 3"), create_choice(name="Planet 4", value="Planet 4"), create_choice(name="Planet 5", value="Planet 5"), create_choice(name="Planet 6", value="Planet 6") ]), create_option(name='market_type', description='The market conditions for the carrier', option_type=3, required=True, choices=[ create_choice(name="TimedMarkets", value="Timed"), create_choice(name="SquadronOnly", value="Squadron"), create_choice(name="Squadron-And-Friends", value="SquadronFriends"), create_choice(name="Open", value="Open") ]), create_option( name='unload_channel', description= 'The discord channel #xxx which the carrier will run timed unloads in', option_type=3, required=False), ]) async def wine_carrier_unload(self, ctx: SlashContext, carrier_id: str, planetary_body: str, market_type: str, unload_channel=None): """ Posts a wine unload request to the unloading channel. :param SlashContext ctx: The discord slash context. :param str carrier_id: The carrier ID string :param str planetary_body: Where is the carrier? Star, P1 etc? :param str market_type: The market conditions for the opening. Timed, Squadron or Open :param str unload_channel: The discord unload channel. Required if using timed market openings so we can point the user where to go. This is an optional value. :returns: A message to the user :rtype: Union[discord.Message, dict] """ print( f'User {ctx.author} has requested a new wine unload operation for carrier: {carrier_id} around the ' f'body: {planetary_body} using unload channel: {unload_channel} using market type: {market_type}.' ) # Cast this to upper case just in case carrier_id = carrier_id.upper() # Check the carrier ID regex if not re.match(r"\w{3}-\w{3}", carrier_id): print( f'{ctx.author}, the carrier ID was invalid, XXX-XXX expected received, {carrier_id}.' ) return await ctx.channel.send( f'{ctx.author}, the carrier ID was invalid, XXX-XXX expected received, ' f'{carrier_id}.') if market_type == 'Timed' and not unload_channel: print( f'Sorry, to run a timed market we need an unload channel, you provided: {unload_channel}.' ) return await ctx.channel.send( f'Sorry, to run a timed market we need an unload channel, you ' f'provided: {unload_channel}.') pirate_steve_lock.acquire() pirate_steve_db.execute( "SELECT * FROM boozecarriers WHERE carrierid LIKE (?)", (f'%{carrier_id}%', )) # We will only get a single entry back here as the carrierid is a unique field. carrier_data = BoozeCarrier(pirate_steve_db.fetchone()) pirate_steve_lock.release() if not carrier_data: print( f'We failed to find the carrier: {carrier_id} in the database.' ) return await ctx.send( f'Sorry, during unload we could not find a carrier for the data: {carrier_id}.' ) wine_alert_channel = bot.get_channel( get_discord_booze_unload_channel()) unloading_channel_id = None if unload_channel: unloading_channel_id = bot.get_channel( int( unload_channel.replace('#', '').replace('<', '').replace('>', ''))) if carrier_data.discord_unload_notification: print( f'Sorry, carrier {carrier_data.carrier_identifier} is already on a wine unload.' ) return await ctx.send( f'Carrier: {carrier_data.carrier_name} ({carrier_data.carrier_identifier}) is ' f'already unloading wine. Check the notification in {unload_channel}.' ) print( f'Starting to post un-load operation for carrier: {carrier_data}') message_send = await ctx.channel.send("**Sending to Discord...**") market_conditions = 'Timed Openings' if market_type == 'Squadron': market_conditions = f'{carrier_data.platform} Squadron' elif market_type == 'SquadronFriends': market_conditions = f'{carrier_data.platform} Squadron and Friends' elif market_type == 'Open': market_conditions = 'Open for all.' # Only in the case of timed openings does a channel make sense. unload_tracking = f' Tracked in {unload_channel}.' if market_type == 'Timed' else '' wine_load_embed = discord.Embed( title='Wine unload notification.', description= f'Carrier {carrier_data.carrier_name} (**{carrier_data.carrier_identifier}**) is currently ' f'unloading **{carrier_data.wine_total // carrier_data.run_count}** tonnes of wine from *' f'*{planetary_body}**.' f'\n Market Conditions: **{market_conditions}**.{unload_tracking}') fc_complete = bot.get_emoji(get_fc_complete_id()) wine_load_embed.set_footer( text=f'Please react with this emoji once completed.', icon_url= f'https://cdn.discordapp.com/emojis/{get_fc_complete_id()}.png?v=1' ) wine_unload_alert = await wine_alert_channel.send(embed=wine_load_embed ) await message_send.delete() # Get the discord alert ID and drop it into the database discord_alert_id = wine_unload_alert.id print( f'Posted the wine unload alert for {carrier_data.carrier_name} ({carrier_data.carrier_identifier})' ) try: pirate_steve_lock.acquire() data = (discord_alert_id, f'%{carrier_id}%') pirate_steve_db.execute( ''' UPDATE boozecarriers SET discord_unload_in_progress=?, totalunloads=totalunloads+1 WHERE carrierid LIKE (?) ''', data) pirate_steve_conn.commit() finally: pirate_steve_lock.release() print( f'Discord alert ID written to database for {carrier_data.carrier_identifier}' ) if unload_channel: embed = discord.Embed(title='Wine unloading starting shortly') # If we have an unload channel ID, go write a message there also. embed.add_field( name= f'Carrier {carrier_data.carrier_name} ({carrier_data.carrier_identifier}).\n' f'Unloading {carrier_data.wine_total // carrier_data.run_count} tonnes of wine with timed ' f'openings.\nLocation: {planetary_body}', value='Market unloads will begin shortly.', inline=True) embed.set_footer( text= 'C/O: Try the commands /wine_helper_market_open and /wine_helper_market_closed.' ) await unloading_channel_id.send(embed=embed) # Also post a note into the primary channel to go read the announcements. booze_cruise_chat = bot.get_channel( get_primary_booze_discussions_channel()) await booze_cruise_chat.send( f"A new wine unload is in progress. See <#{wine_unload_alert.channel.id}>" ) return await ctx.send( f'Wine unload requested by {ctx.author} for **{carrier_data.carrier_name}** ({carrier_id}) ' f'processed successfully. Market: **{market_conditions}**.{unload_tracking}' ) @cog_ext.cog_slash( name='Wine_Unload_Complete', guild_ids=[bot_guild_id()], description= 'Removes any trade channel notification for unloading wine. Admin/Sommelier role required.', options=[ create_option(name='carrier_id', description='The XXX-XXX ID string for the carrier', option_type=3, required=True) ], permissions={ bot_guild_id(): [ create_permission(server_admin_role_id(), SlashCommandPermissionType.ROLE, True), create_permission(server_sommelier_role_id(), SlashCommandPermissionType.ROLE, True), create_permission(server_mod_role_id(), SlashCommandPermissionType.ROLE, True), create_permission(bot_guild_id(), SlashCommandPermissionType.ROLE, False), ] }, ) async def wine_unloading_complete(self, ctx: SlashContext, carrier_id): print( f'Wine unloading complete for {carrier_id} flagged by {ctx.author}.' ) # Cast this to upper case just in case carrier_id = carrier_id.upper() # Check the carrier ID regex if not re.match(r"\w{3}-\w{3}", carrier_id): print( f'{ctx.author}, the carrier ID was invalid, XXX-XXX expected received, {carrier_id}.' ) return await ctx.channel.send( f'{ctx.author}, the carrier ID was invalid, XXX-XXX expected received, ' f'{carrier_id}.') pirate_steve_db.execute( "SELECT * FROM boozecarriers WHERE carrierid LIKE (?)", (f'%{carrier_id}%', )) # We will only get a single entry back here as the carrierid is a unique field. carrier_data = BoozeCarrier(pirate_steve_db.fetchone()) if not carrier_data: print(f'No carrier found while searching the DB for: {carrier_id}') return await ctx.send( f'Sorry, could not find a carrier for the ID data in DB: {carrier_id}.' ) if carrier_data.discord_unload_notification and carrier_data.discord_unload_notification != 'NULL': # If we have a notification, remove it. print( f'Deleting the wine carrier unload notification for: {carrier_id}.' ) wine_alert_channel = bot.get_channel( get_discord_booze_unload_channel()) msg = await wine_alert_channel.fetch_message( carrier_data.discord_unload_notification) # Now delete it in the database try: pirate_steve_lock.acquire() data = (f'%{carrier_id}%', ) pirate_steve_db.execute( ''' UPDATE boozecarriers SET discord_unload_in_progress=NULL WHERE carrierid LIKE (?) ''', data) pirate_steve_conn.commit() finally: pirate_steve_lock.release() await msg.delete() response = f'Removed the unload notification for {carrier_data.carrier_name} ({carrier_id})' print( f'Deleted the carrier discord notification for carrier: {carrier_id}' ) else: response = f'Sorry {ctx.author}, we have no carrier unload notification found in the database for ' \ f'{carrier_id}.' print( f'No discord alert found for carrier, {carrier_id}. It likely ran an untracked market.' ) return await ctx.send(content=response) @cog_ext.cog_slash( name='Make_Wine_Carrier', guild_ids=[bot_guild_id()], description= 'Toggle user\'s Wine Carrier role. Admin/Sommelier role required.', options=[ create_option( name='user', description= 'An @ mention of the Discord user to receive/remove the role.', option_type=6, # user required=True) ], permissions={ bot_guild_id(): [ create_permission(server_admin_role_id(), SlashCommandPermissionType.ROLE, True), create_permission(server_sommelier_role_id(), SlashCommandPermissionType.ROLE, True), create_permission(server_mod_role_id(), SlashCommandPermissionType.ROLE, True), create_permission(bot_guild_id(), SlashCommandPermissionType.ROLE, False), ] }, ) async def make_user_wine_carrier(self, ctx: SlashContext, user: discord.Member): print( f"make_wine_carrier called by {ctx.author} in {ctx.channel} for {user}" ) # set the target role print(f"Wine Carrier role ID is {server_wine_carrier_role_id()}") role = discord.utils.get(ctx.guild.roles, id=server_wine_carrier_role_id()) print(f"Wine Carrier role name is {role.name}") if role in user.roles: # toggle off print(f"{user} is a Wine Carrier, removing the role.") try: await user.remove_roles(role) response = f"{user.display_name} no longer has the Wine Carrier role." return await ctx.send(content=response) except Exception as e: print(e) await ctx.send(f"Failed removing role from {user}: {e}") else: # toggle on print(f"{user} is not a Wine Carrier, adding the role.") try: await user.add_roles(role) print(f"Added Wine Hauler role to {user}") response = f"{user.display_name} now has the Wine Carrier role." return await ctx.send(content=response) except Exception as e: print(e) await ctx.send(f"Failed adding role to {user}: {e}")
class MimicSteve(commands.Cog): """ This class implements functionality for a user to send commands as PirateSteve """ @cog_ext.cog_slash( name='Steve_Says', guild_ids=[bot_guild_id()], description='Send a message as PirateSteve.', options=[ create_option(name='message', description='The message to send', option_type=3, required=True), create_option(name='send_channel', description='The channel to send the message in', option_type=3, required=True) ], permissions={ bot_guild_id(): [ create_permission(server_admin_role_id(), SlashCommandPermissionType.ROLE, True), create_permission(server_sommelier_role_id(), SlashCommandPermissionType.ROLE, True), create_permission(server_mod_role_id(), SlashCommandPermissionType.ROLE, True), create_permission(bot_guild_id(), SlashCommandPermissionType.ROLE, False), ] }, ) async def impersonate_steve(self, ctx: SlashContext, message: str, send_channel: str): """ Sends the provided message as Pirate Steve in the provided channel. :param SlashContext ctx: The discord context :param str message: The message to send :param str send_channel: The discord channel to send the message in. :returns: A message of pass/fail :rtype: SlashMessage """ print( f'User {ctx.author} has requested to send the message {message} as PirateSteve in: {send_channel}.' ) # Check we are in the designated mission channel, if not go no farther. restricted_channel = bot.get_channel( get_sommelier_notification_channel()) if ctx.channel != restricted_channel: # problem, wrong channel, no progress print( f'Error, the command can only be ran out of: {restricted_channel}. You are in: {ctx.channel}.' ) return await ctx.send( f'Sorry, you can only run this command out of: {restricted_channel}.', hidden=True) channel = bot.get_channel( int( send_channel.replace('#', '').replace('<', '').replace('>', ''))) print( f'Channel resolved into: {channel}. Checking for any potential use names to be resolved.' ) possible_id = None # Try to resolve any @<int> to a user for word in message.split(): if word.startswith('@'): try: print(f'Potential user id found: {word}.') # this might be a user ID, int convert it possible_id = int(re.search(r'\d+', word).group()) # Ok this was in fact an int, try to see if it resolves to a discord user member = await bot.fetch_user(possible_id) print(f'Member determined as: {member}') message = message.replace(word, f'<@{member.id}>') print(f'New message is: {message}') except discord.errors.NotFound as ex: print( f'Potential user string "{possible_id if possible_id else word}" is invalid: {ex}. Continuing ' f'on as-is') except ValueError as ex: # Ok continue on anyway and send it as-is print(f'Error converting the word: {word}. {ex}') response = f'{message}' msg = await channel.send(content=response) if msg: print('Message was impersonated successfully.') return await ctx.send( f'Pirate Steve said: {message} in: {send_channel} successfully' ) # Error case print(f'Error sending message in {message} channel: {send_channel}') return await ctx.send( f'Pirate Steve failed to say: {message} in: {send_channel}.')
owo = owo.replace('RR', '🇷 🇷') owo = owo.replace('r', 'w') owo = owo.replace('R', 'W') owo = owo.replace('🇷', 'rr') owo = owo.replace('🇷 🇷', 'RR') owo = owo.replace('ll', 'w') owo = owo.replace('LL', 'W') if random.randrange(0, 100) in range(50): owo += '~' await ctx.send(owo, hidden=hidden) @slash.slash(default_permission=False, permissions={ 766848554899079218: [ create_permission(312292633978339329, SlashCommandPermissionType.USER, True) ] }) async def purge(ctx, messageid, hidden: bool = False): messageid = int(messageid) purge = None async for x in ctx.channel.history(): try: if x.id == messageid: purge = x except AttributeError: embed = discord.Embed(title="you need to give a message id", colour=discord.Colour.red()) await ctx.send(embed=embed, hidden=hidden) return