예제 #1
0
    def __init__(self):
        # Environment variables
        # If the bot isn't running on Replit, load the env files from the .env file
        if isfile('.env'):
            # Import the .env library
            from dotenv import load_dotenv
            load_dotenv()

        # Set up the intents (What the bot can access)
        intents = discord.Intents.default()
        intents.members = True
        intents.message_content = True

        # Set up the bot
        super().__init__(intents=intents)

        # Set up the Twitter API
        # In order, the tokens are: Access token, access secret, API key, API secret
        self.twitter = twitterApi(access_token_key=getenv('ATOKEN'),
                                  access_token_secret=getenv('ASECRET'),
                                  consumer_key=getenv('CKEY'),
                                  consumer_secret=getenv('CSEC'))

        # The command tree
        self.commands = app_commands.CommandTree(self)

        # Import the other commands
        for module in modules:
            module.setup(self)

        # On ready
        @self.event
        async def on_ready():
            # The loaded bot commands
            loadedCommands = self.commands.get_commands()
            # Show that the bot is logged in
            print(
                f"------\n|-Logged in as: {self.user.name}\n------\n|-Commands loaded: "
            )
            for command in loadedCommands:
                print(f"  |-{command.name}")
            print('------')

        # Command to sync the bot commands
        @self.event
        async def on_message(message) -> None:
            if message.author == self.user:
                return

            if message.content.startswith('brightbot-update'):
                try:
                    await self.commands.sync(guild=message.guild)
                    await message.channel.send('Commands updated.')
                except discord.errors.Forbidden:
                    await message.channel.send('There was an error syncing. :('
                                               )
예제 #2
0
    def __init__(self) -> None:
        # Just default intents and a `discord.Client` instance
        # We don't need a `commands.Bot` instance because we are not
        # creating text-based commands.
        intents = discord.Intents.default()
        super().__init__(intents=intents)

        # We need an `discord.app_commands.CommandTree` instance
        # to register application commands (slash commands in this case)
        self.tree = app_commands.CommandTree(self)
예제 #3
0
 def __init__(self, *, intents: discord.Intents):
     super().__init__(intents=intents)
     # A CommandTree is a special type that holds all the application command
     # state required to make it work. This is a separate class because it
     # allows all the extra state to be opt-in.
     # Whenever you want to work with application commands, your tree is used
     # to store and work with them.
     # Note: When using commands.Bot instead of discord.Client, the bot will
     # maintain its own tree instead.
     self.tree = app_commands.CommandTree(self)
예제 #4
0
    def __init__(
        self,
        command_prefix: PrefixType[BotT],
        help_command: Optional[HelpCommand[Any]] = _default,
        description: Optional[str] = None,
        **options: Any,
    ) -> None:
        super().__init__(**options)
        self.command_prefix: PrefixType[BotT] = command_prefix
        self.extra_events: Dict[str, List[CoroFunc]] = {}
        # Self doesn't have the ClientT bound, but since this is a mixin it technically does
        self.__tree: app_commands.CommandTree[Self] = app_commands.CommandTree(
            self)  # type: ignore
        self.__cogs: Dict[str, Cog] = {}
        self.__extensions: Dict[str, types.ModuleType] = {}
        self._checks: List[Check] = []
        self._check_once: List[Check] = []
        self._before_invoke: Optional[CoroFunc] = None
        self._after_invoke: Optional[CoroFunc] = None
        self._help_command: Optional[HelpCommand[Any]] = None
        self.description: str = inspect.cleandoc(
            description) if description else ''
        self.owner_id: Optional[int] = options.get('owner_id')
        self.owner_ids: Optional[Collection[int]] = options.get(
            'owner_ids', set())
        self.strip_after_prefix: bool = options.get('strip_after_prefix',
                                                    False)

        if self.owner_id and self.owner_ids:
            raise TypeError('Both owner_id and owner_ids are set.')

        if self.owner_ids and not isinstance(self.owner_ids,
                                             collections.abc.Collection):
            raise TypeError(
                f'owner_ids must be a collection not {self.owner_ids.__class__!r}'
            )

        if help_command is _default:
            self.help_command = DefaultHelpCommand()
        else:
            self.help_command = help_command
예제 #5
0
파일: modal.py 프로젝트: z03h/discord.py
import discord
from discord import app_commands

import traceback

# Just default intents and a `discord.Client` instance
# We don't need a `commands.Bot` instance because we are not
# creating text-based commands.
intents = discord.Intents.default()
client = discord.Client(intents=intents)

# We need an `discord.app_commands.CommandTree` instance
# to register application commands (slash commands in this case)
tree = app_commands.CommandTree(client)

# The guild in which this slash command will be registered.
# As global commands can take up to an hour to propagate, it is ideal
# to test it in a guild.
TEST_GUILD = discord.Object(ID)


@client.event
async def on_ready():
    print(f'Logged in as {client.user} (ID: {client.user.id})')
    print('------')

    # Sync the application command with Discord.
    await tree.sync(guild=TEST_GUILD)


class Feedback(discord.ui.Modal, title='Feedback'):
                text += "\nPlease grant it to the bot and send again the command."
            else:
                text += "\nPlease grant them to the bot and send again the command."
            await interaction.response.send_message(
                f"Missing permissions: {text}")
            return -1
        return True

    def edit_commands_used(user_id: int, cmd: str):
        text = f"""INSERT INTO bot_usage(user_id) SELECT({user_id}) WHERE NOT EXISTS(SELECT 1 FROM bot_usage WHERE user_id={user_id})"""
        cursor_modifiable.execute(text)
        text = f"""UPDATE bot_usage SET {cmd} = (SELECT {cmd} FROM bot_usage WHERE user_id={user_id})+1 WHERE user_id={user_id}"""
        cursor_modifiable.execute(text)
        connection_modifiable.commit()

    command_tree = app_commands.CommandTree(Clash_info)

    async def on_error(interaction: discord.Interaction,
                       error: discord.app_commands.AppCommandError):
        if type(error.original) == discord.errors.NotFound:
            if interaction.app_permissions.send_messages:
                await interaction.channel.send(
                    "The command has expired, please try again\n\n*This message will be deleted in 15 seconds*",
                    delete_after=15)
        else:
            print(traceback.format_exc())
        return

    command_tree.on_error = on_error

    @command_tree.command(