Ejemplo n.º 1
0
    async def add_commands(self, slash: SlashCommand):
        base_command = self.configuration.get("command_prefix",
                                              "") + "randovania-faq"

        for game in enum_lib.iterate_enum(RandovaniaGame):
            faq_entries = list(game.data.faq)
            if not faq_entries:
                continue

            def _shorten(n: str) -> str:
                if len(n) > 100:
                    return n[:97] + "..."
                return n

            slash.add_subcommand(
                functools.partial(self.faq_game_command, game=game),
                base_command,
                name=game.value,
                description=f"Prints the answer to a FAQ for {game.long_name}.",
                options=[
                    manage_commands.create_option(
                        "question",
                        "Which question to answer?",
                        option_type=SlashCommandOptionType.STRING,
                        required=True,
                        choices=[
                            manage_commands.create_choice(
                                f"question_{question_id}", _shorten(question))
                            for question_id, (question,
                                              answer) in enumerate(faq_entries)
                        ])
                ],
            )
Ejemplo n.º 2
0
    def __init__(self, slash: SlashCommand):
        self.methods = CachedRequest(
            60, "https://tweaked.cc/index.json",
            lambda contents: {
                k.lower(): {"original_name": k, **v}
                for k, v in json.loads(contents).items()
            }
        )

        slash.get_cog_commands(self)
Ejemplo n.º 3
0
    def __init__(self, bot):
        self.bot = bot
        self.slash = SlashCommand(bot, override_type=True)
        # Cog is only supported by commands ext, so just skip checking type.

        # Make sure all commands should be inside `__init__`
        # or some other functions that can put commands.
        @self.slash.slash(name="test")
        async def _test(ctx: SlashContext):
            await ctx.send(content="Hello, World!")
Ejemplo n.º 4
0
    async def add_commands(self, slash: SlashCommand):
        slash.add_slash_command(
            self.database_command,
            name=self.configuration.get("command_prefix", "") +
            "database-inspect",
            description=
            "Consult the Randovania's logic database for one specific room.",
            guild_ids=None,
            options=[
                manage_commands.create_option(
                    "game",
                    "The game's database to check.",
                    option_type=SlashCommandOptionType.STRING,
                    required=True,
                    choices=[
                        manage_commands.create_choice(game.value,
                                                      game.long_name)
                        for game in enum_lib.iterate_enum(RandovaniaGame)
                    ])
            ],
        )

        def add_id(custom_id: str, call, **kwargs):
            self._on_database_component_listener[
                custom_id] = functools.partial(call, **kwargs)

        for game in enum_lib.iterate_enum(RandovaniaGame):
            db = default_database.game_description_for(game)
            world_options = await create_split_worlds(db)
            self._split_worlds[game] = world_options

            add_id(f"{game.value}_world",
                   self.on_database_world_selected,
                   game=game)
            add_id(f"back_to_{game.value}",
                   self.on_database_back_to_game,
                   game=game)

            for i, split_world in enumerate(world_options):
                add_id(f"{game.value}_world_{i}",
                       self.on_database_area_selected,
                       game=game,
                       split_world=split_world,
                       world_id=i)
                for j, area in enumerate(split_world.areas):
                    add_id(f"{game.value}_world_{i}_area_{j}",
                           self.on_area_node_selection,
                           game=game,
                           area=area)

        slash.add_component_callback(
            self.on_database_component,
            components=list(self._on_database_component_listener.keys()),
            use_callback_name=False,
        )
Ejemplo n.º 5
0
    def __init__(self, env, storage, config, db):
        self.env = env
        self.storage = storage
        self.config = config
        self.db = db
        intents = discord.Intents.default()
        intents.members = True

        # we are moving away from commands
        # but still want to support the main ones for a while
        print(f"setting prefix to {self.config['commands']['prefix']}")
        super().__init__(command_prefix=self.config['commands']['prefix'],
                         intents=intents)

        # "global" interactions without explicit guild_ids
        # take hours to register
        self.guild_ids = None
        override_guild_ids = env['GUILD_IDS']
        if override_guild_ids is not None:
            self.guild_ids = list(map(int, override_guild_ids.split(',')))
            print(
                f"setting guild_ids to {self.guild_ids} for faster slash command registration"
            )

        self.slash = SlashCommand(self,
                                  sync_commands=True,
                                  sync_on_cog_reload=True,
                                  override_type=True)
        self.add_slash_command(self.ping, name="ping")

        initial_cogs = [
            cogs.PresenceCog,
            cogs.PostingCog,
            cogs.WelcomeCog,
            cogs.RolerCog,
            cogs.AfterdarkCog,
            cogs.RealtalkCog,
            cogs.ActivityCog,
            cogs.LurkersCog,
            cogs.AnimeCog,
            cogs.NoveltyCog,
            cogs.AnnoyingCog,
        ]
        for cog in initial_cogs:
            self.add_cog(cog(self))

        # set the db up
        self.db.generate_mapping(create_tables=False)

        self.heartbeat_loop.start()
Ejemplo n.º 6
0
def init():
    from discord.ext import commands
    import discord
    from discord_slash import SlashCommand
    from os import walk

    intents = discord.Intents.all()
    bot = commands.Bot(command_prefix="!", intents=intents, help_command=None)
    slash = SlashCommand(bot, sync_commands=True)

    unloadCogList = [""]
    print("Loading Cogs: (", end="")
    for root, subdirs, files in walk('./Cogs'):
        root = root.replace("\\", ".", -1).replace('/', ".", -1)
        for f in files:
            if f.endswith('cog.py') and f not in unloadCogList:
                bot.load_extension(f"{root[2:]}.{f[:-3]}")
                print(f"{root[2:]}.{f[:-3]}, ", end="")
    print(")")

    @bot.event
    async def on_ready():
        print(f"BOT ID: {bot.user.id}")
        print("===BOT READY===")
        cur_status = discord.Game("개발")
        await bot.change_presence(status=discord.Status.online,
                                  activity=cur_status)

    @bot.event
    async def on_message(message):
        await bot.process_commands(message)
        return

    return bot
Ejemplo n.º 7
0
def main():
    intents = discord.Intents.default()
    intents.members = True
    bot = commands.Bot(command_prefix='!', intents=intents)
    slash = SlashCommand(bot, sync_commands=True, sync_on_cog_reload=True)

    config = parse_config()
    certificate = credentials.Certificate(config['firebase_credentials'])
    initialize_app(certificate, {'databaseURL': config['firebase_db']})
    firebase_ref = db.reference()
    twitter_api = twitter.Api(consumer_key=config['consumer_key'], consumer_secret=config['consumer_secret'], access_token_key=config['access_token_key'], access_token_secret=config['access_token_secret'], tweet_mode='extended')
    insta_api = instaloader.Instaloader(max_connection_attempts=1)
    insta_api.load_session_from_file(config['instagram_user'], filename='./.instaloader-session')
    calendar = build('calendar', 'v3', http=file.Storage('credentials.json').get().authorize(Http()))

    bot.add_cog(Help(bot))
    bot.add_cog(Oshi(bot))
    bot.add_cog(Info(bot))
    bot.add_cog(Events(bot))
    bot.add_cog(Tags(bot, firebase_ref))
    bot.add_cog(Pics(bot, twitter_api, insta_api))
    bot.add_cog(Misc(bot, config))
    bot.add_cog(Loop(bot, config, firebase_ref, calendar, twitter_api, insta_api))
    bot.add_cog(Listen(bot))

    bot.run(config['token'])
    def __init__(self):
        intents = discord.Intents.all()
        super().__init__(command_prefix=None, intents=intents)

        self.config = ConfigManger(self)
        self.config.load_key()

        self.start_time = datetime.utcnow()

        self.command_prefix = prefix
        self.description = "All things related to Vcc"
        self.help_command = VccHelpCommand()

        self.owner_id = int(self.config["OWNERS"])
        self.token = self.config["TOKEN"]
        self.version = __version__

        self.path_to_cogs = "cogs."
        self.load_cogs = ["vc", "info", "debug", "owner", "event", "setting"]

        self.log_file_name = os.path.join(temp_dir, "Vcc.log")
        self._configure_logging()

        SlashCommand(self,
                     sync_commands=True,
                     override_type=True,
                     delete_from_unused_guilds=True,
                     sync_on_cog_reload=True)

        self.startup()
Ejemplo n.º 9
0
    def __init__(self,
                 prefix='!',
                 channel_data_dir: str = '.',
                 no_sync: bool = False):
        if DiscordCore.__instance__ is None:
            DiscordCore.__instance__ = self
        else:
            raise RuntimeError(
                "You cannot create another instance of DiscordCore")

        self._no_sync = no_sync
        self._channel_data_dir = channel_data_dir
        self._lock_json = True
        self._commandlist = {}
        self._excluded_commands = []
        self._ordered_message_handlers = []

        self.emoji_map = {}

        super().__init__(
            # intents=Intents.all(),
            command_prefix=prefix,
            owner_id=os.getenv('DISCORD_OWNER_ID'),
            help_command=None)

        self._slash = SlashCommand(self, sync_commands=not no_sync)
Ejemplo n.º 10
0
    def __init__(self, **kwargs) -> None:
        self.config = bot_config

        super().__init__(intents=INTENTS,
                         command_prefix=commands.when_mentioned_or('radio '),
                         case_insensitive=True,
                         **kwargs)

        format = logging.Formatter(
            "[%(asctime)s %(name)s/%(levelname)s] %(message)s")
        log = logging.getLogger("radiobot")
        log.setLevel(logging.DEBUG)
        stream_handler = logging.StreamHandler()
        stream_handler.setFormatter(format)
        rotating_handler = RotatingFileHandler('radiobot.log',
                                               encoding='utf-8',
                                               mode='a',
                                               maxBytes=2 * 1024 * 1024)
        rotating_handler.setFormatter(format)
        log.handlers = [stream_handler, rotating_handler]
        self.log = log

        self.loop.create_task(self.connect_postgres())

        self.blacklist = Config('blacklist.json')

        self.slash = SlashCommand(self,
                                  sync_commands=True,
                                  sync_on_cog_reload=True,
                                  override_type=True)

        self.load_initial_cogs()
Ejemplo n.º 11
0
def init_slashcommands(client):
    global slash
    slash = SlashCommand(
        client,
        sync_commands=True)  # Declares slash commands through the client.
    for i in commands:
        i()
    print("slash commands initialized!")
Ejemplo n.º 12
0
    def __init__(self, command_prefix, intents):
        # スーパークラスのコンストラクタに値を渡して実行。
        super().__init__(command_prefix, case_insensitive=True, intents=intents, help_command=None)
        slash = SlashCommand(self, sync_commands=True)

        # INITIAL_EXTENSIONSに格納されている名前から、コグを読み込む。
        for cog in INITIAL_EXTENSIONS:
            self.load_extension(cog)
Ejemplo n.º 13
0
    def __init__(self, **kargs):
        self.version = kargs.get("version")
        self.token = kargs.get("bot_token")
        self.prefix = kargs.get("prefix")
        self.is_debug = kargs.get("debug_mode")

        super().__init__(command_prefix=self.prefix)
        self.slash = SlashCommand(self, sync_commands=True)
Ejemplo n.º 14
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.slash = SlashCommand(self,
                               override_type=True,
                               auto_register=True,
                               auto_delete=True)
     self.db = sqlite_db.SQLiteDB("userdata")
     self.discodo = discodo.ClientManager()  # Change to remote maybe.
Ejemplo n.º 15
0
 def __init__(self, bot):
     if not hasattr(bot, "slash"):
         bot.slash = SlashCommand(bot,
                                  override_type=True,
                                  auto_register=True,
                                  auto_delete=True)
     self.bot = bot
     self.bot.slash.get_cog_commands(self)
    def __init__(self, command_prefix, intents):
        # スーパークラスのコンストラクタに値を渡して実行。
        super().__init__(command_prefix, case_insensitive=True, intents=intents)
        slash = SlashCommand(self, sync_commands=True) # ココにslashをおこう!(第一引数はself)
        LOG.info('cogを読むぞ!')

        # INITIAL_COGSに格納されている名前から、コグを読み込む。
        for cog in INITIAL_EXTENSIONS:
            self.load_extension(cog)
Ejemplo n.º 17
0
 def __init__(self, bot):
     if not hasattr(bot, "slash"):
         # Creates new SlashCommand instance to bot if bot doesn't have.
         bot.slash = SlashCommand(bot, override_type=True)
     self.bot = bot
     self.bot.slash.get_cog_commands(self)
     self.firestore_client = FIRESTORE_CLIENT
     self.delete_slash_commands()
     self.create_slash_commands()
Ejemplo n.º 18
0
    def __init__(self):
        if Bert.instance is not None:
            raise Exception("This class is a singleton")

        Bert.instance = self
        super().__init__()

        self.slash = SlashCommand(self, sync_commands=True)
        self.commandManager = CommandManager.getInstance()
Ejemplo n.º 19
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.debug = self.get_settings("debug")
     self.slash = SlashCommand(self, auto_register=True)
     self.db = SQLiteDB("main")
     self.logger = logging.getLogger("cork")
     self.koreanbots = koreanbots.Client(self,
                                         self.get_settings("kor_token"),
                                         postCount=not self.debug)
Ejemplo n.º 20
0
    def __init__(self, client):
        self.client = client
        self.slash = SlashCommand(client, override_type=True)
        # Cog is only supported by commands ext, so just skip checking type.

        # Make sure all commands should be inside `__init__`
        # or some other functions that can put commands.
        @self.slash.slash(name="hello")
        async def _hello(ctx: SlashContext):
            await ctx.send(content=":wave: Hello")

        @self.slash.slash(name="ping")
        async def _ping(ctx: SlashContext):
            embed = discord.Embed(color=discord.Colour.from_rgb(255, 130, 53))
            embed.add_field(
                name="**Ping**",
                value=f":table_tennis: Pong! {self.client.latency * 1000} ms")
            await ctx.send(embeds=[embed])
Ejemplo n.º 21
0
 def __init__(self, configuration: dict):
     super().__init__("%unused-prefix%")
     self.slash = SlashCommand(
         self,
         debug_guild=configuration["debug_guild"],
     )
     self.configuration = configuration
     self.load_extension("randovania.server.discord.preset_lookup")
     self.load_extension("randovania.server.discord.database_command")
     self.load_extension("randovania.server.discord.faq_command")
Ejemplo n.º 22
0
 def __init__(self):
     super().__init__(
         command_prefix=commands.when_mentioned_or(
             environ.get('PREFIX', './')),
         help_command=None,
     )
     self.logging = logging
     # self.logging.basicConfig(level=logging.DEBUG)
     self.system = System()
     self.slash = SlashCommand(self, sync_commands=True)
Ejemplo n.º 23
0
    def __init__(
        self,
        discord_token: str,
        bot_version: str,
        command_prefix: Optional[str] = None,
        help_command: Optional[HelpCommand] = None,
        description: str = "2021 학년도 경희고등학교 3학년 3반 디스코드 서버 용 class bot",
        case_insensitive: bool = False,
        sync_commands: bool = False,
        delete_from_unused_guilds: bool = False,
        sync_on_cog_reload: bool = False,
        override_type: bool = False,
    ) -> None:
        """KHSClass Core \n
        Github: https://github.com/zeroday0619/KHSClassBOT

        :param discord_token: discord developer portal에서 발급한 토큰
        :param bot_version: KHSClassBOT Version
        :param command_prefix: command prefix
        :param help_command: help command implementation to use
        :param description: KHSClassBOT description
        :param case_insensitive: case-insensitive
        :param sync_commands: Whether to sync commands automatically. Default `False`.
        :param delete_from_unused_guilds: If the bot should make a request to set no commands for guilds that haven't got any commands registered in :class:``SlashCommand``. Default `False`.
        :param sync_on_cog_reload: Whether to sync commands on cog reload. Default `False`.
        :param override_type: Whether to override checking type of the client and try register event.
        """

        self.discord_token: str = discord_token
        self.bot_version: str = bot_version

        self._command_prefix: str = command_prefix if command_prefix else "!"
        self._description: str = description

        self._help_command = help_command
        self._case_insensitive = case_insensitive
        self._sync_commands = sync_commands
        self._delete_from_unused_guilds = delete_from_unused_guilds
        self._sync_on_cog_reload = sync_on_cog_reload
        self._override_type = override_type

        self.message: List[str] = ["!help", "@zeroday0619#4000"]
        super(KHSClass, self).__init__(
            command_prefix=self._command_prefix,
            help_command=self._help_command,
            description=self._description,
            case_insensitive=self._case_insensitive,
        )
        SlashCommand(
            client=self,
            sync_commands=self._sync_commands,
            delete_from_unused_guilds=self._delete_from_unused_guilds,
            sync_on_cog_reload=self._sync_on_cog_reload,
            override_type=self._override_type,
        )
Ejemplo n.º 24
0
async def _setup() -> None:
    faqs = ccfaq.faq_list.load()
    LOG.info('Successfully loaded %d FAQs!', len(faqs))

    slash = SlashCommand(bot, sync_commands=True)

    bot.add_cog(AboutCog(bot, faqs))
    bot.add_cog(DocsCog())
    bot.add_cog(FAQCog(faqs))

    add_faq_slashcommands(slash, faqs)
Ejemplo n.º 25
0
def init_slashcommands(client_import, PLAYERHP_import):
    global client, slash, PLAYERHP
    client = client_import
    slash = SlashCommand(
        client,
        sync_commands=True)  # Declares slash commands through the client.
    PLAYERHP = PLAYERHP_import

    for i in commands:
        i()
    print("slash commands initialized!")
Ejemplo n.º 26
0
    def __init__(self, bot):
        self.bot = bot
        self.slash = SlashCommand(bot, override_type=True)

        @self.slash.slash(name="ping")
        async def ping_slash(ctx):
            await ctx.send(content=f"Pong! (`{round(bot.latency*1000)}`ms)")

        @self.slash.slash(name="calculator")
        async def add_slash(ctx, mode, number1, number2):
            print("lol")
Ejemplo n.º 27
0
 def __init__(self):
     self.bot = commands.Bot(command_prefix='!')
     self.slash = SlashCommand(self.bot, sync_commands=True)
     self.table_handler = TableHandler(self)
     self.message = None
     self.reaction_payload = None
     self.message_history = {}
     self.message_list = []
     self.embed = Embed()
     self.image_url = 'https://clashbotimages.s3.us-east-2.amazonaws.com/'
     self.lock = Lock()
Ejemplo n.º 28
0
Archivo: main.py Proyecto: yupix/ssm
def run(loop_bot, loop_api):
    global bot
    global slash_client
    asyncio.set_event_loop(loop_bot)
    intents = discord.Intents.all()
    bot = Ssm(command_prefix=f'{bot_prefix}', intents=intents)
    slash_client = SlashCommand(bot, sync_commands=True)
    if bool(strtobool(use_api)) is True:
        future = asyncio.gather(bot_run(loop_bot), api_run(loop_api))
    else:
        future = asyncio.gather(bot_run(loop_bot))
    loop_bot.run_until_complete(future)
Ejemplo n.º 29
0
 def __init__(self):
     super().__init__(
         command_prefix=commands.when_mentioned_or(environ.get('PREFIX', './')),
         help_command=None,
     )
     self.db = Database(self)
     self.system = System()
     self.slash = SlashCommand(self, sync_commands=True)
     # self.qt = Question(self)
     with open("json/qu.json", mode="r", encoding='utf-8') as f:
         self.qu = json.load(f)
         f.close()
Ejemplo n.º 30
0
 def __init__(self, config, *args, **kwargs):
     self.dynamic_prefix = _utils.PrefixHandler(config['prefix'])
     super().__init__(command_prefix=self.dynamic_prefix.handler,
                      *args,
                      **kwargs)
     self.slash = SlashCommand(self, sync_commands=True, override_type=True)
     self.config = config
     if self.config['debug']:
         DOZER_LOGGER.level = logging.DEBUG
         DOZER_HANDLER.level = logging.DEBUG
     self._restarting = False
     self.check(self.global_checks)