async def on_ready(): print("Stonks time") status = discord.Game("Monitering Stonks") await client.change_presence(status=discord.Status.idle, activity=status) client.help_command = commands.DefaultHelpCommand(no_category='Commands')
async def on_ready(): print("Pastey ready") await client.change_presence(activity=discord.Activity( name="Protecting the campus enviorment")) client.help_command = commands.DefaultHelpCommand( no_category='Commands')
def start(): help_command = commands.DefaultHelpCommand(no_category = 'dCTF') bot = commands.Bot(command_prefix='>>', help_command = help_command) @bot.command(name='register', help='Register your team. Format: >>register <team_name>') async def register(ctx, team: str): response = team_controller.register(team) await ctx.send(response) @bot.command(name='login', help='Login with team token. Format: >>login <team_token>') async def login(ctx, token: str): response = team_controller.login(str(ctx.author.id), token) await ctx.send(response) @bot.command(name='create-challenge', help='Format: >>create-challenge <name> <category> <description> <files> <flag>') @commands.has_role(credential.role) async def create_task(ctx, name: str, category: str, description: str, files: str, flag: str): response = task_controller.create_task(name, category, description, files, flag) await ctx.send(response) @bot.command(name='release-challenge', help='Format: >>release-challenge <challenge_id>') @commands.has_role(credential.role) async def release_task(ctx, task_id: int): response = task_controller.release_task(task_id) await ctx.send(response) @bot.command(name='hide-challenge', help='Hide a challenge. Format: >>hide-challenge <challenge_id>') @commands.has_role(credential.role) async def hide_task(ctx, task_id: int): response = task_controller.hide_task(task_id) await ctx.send(response) @bot.command(name='delete-challenge', help='Format: >>delete-challenge <challenge_id>') @commands.has_role(credential.role) async def delete_task(ctx, task_id: int): response = task_controller.delete_task(task_id) await ctx.send(response) @bot.command(name='submit', help='Submit flag. Format: >>submit <flag>') async def submit(ctx, flag: str): response = audit_controller.submit(str(ctx.author.id), flag) await ctx.send(response) @bot.command(name='challenges', help='List all challenges. Format: >>challenges') async def challenges(ctx): response = view_controller.challenges() await ctx.send(embed=response) @bot.command(name='challenges-info', help='Get challenges info. Format: >>chllenges-info <name>') async def challenges_info(ctx, name: str): response = view_controller.challenges_info(name) await ctx.send(embed=response) @bot.command(name='scoreboard', help='Update scoreboard. Format: >>scoreboard') async def scoreboard(ctx): response=view_controller.scoreboard_before_freeze() await ctx.send(response) bot.run(credential.token)
def __enter__(self): self.bot = commands.Bot( command_prefix='!', help_command=commands.DefaultHelpCommand( command_attrs=dict(name='help'), width=120, dm_help=True) ) #, status = '!help'))#, aliases=['hex_help', 'help_hex', 'hex-help']))) self.pick_timeout.start()
def __init__(self, config: dict, startup_extensions: List[str]): # TODO: Change prefix to . when syncing # commands.when_mentioned_or('e!') super().__init__(command_prefix='.', case_insensitive=True, description='A bot to run CSGO PUGS.', help_command=commands.DefaultHelpCommand(verify_checks=False), intents=discord.Intents( guilds=True, members=True, bans=True, emojis=True, integrations=True, invites=True, voice_states=True, presences=False, messages=True, guild_messages=True, dm_messages=True, reactions=True, guild_reactions=True, dm_reactions=True, typing=True, guild_typing=True, dm_typing=True )) self.token: str = config['discord_token'] self.bot_IP: str = config['bot_IP'] self.steam_web_api_key = config['steam_web_API_key'] self.servers: List[CSGOServer] = [] # Will need to change for when there is multiple server queue self.users_not_ready: List[discord.Member] = [] for i, server in enumerate(config['servers']): self.servers.append( CSGOServer(i, server['server_address'], server['server_port'], server['server_password'], server['RCON_password'])) self.web_server = WebServer(bot=self) self.dev: bool = False self.version: str = __version__ self.queue_ctx: commands.Context = None self.queue_voice_channel: discord.VoiceChannel = None logger = logging.getLogger('discord') logger.setLevel(logging.DEBUG) handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w') handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')) logger.addHandler(handler) for extension in startup_extensions: self.load_extension(f'cogs.{extension}')
def __init__(self): """ Sets the Command Prefix and then call the __init__ method of the commands.Bot class. """ intents = discord.Intents.default() intents.members = True super().__init__(command_prefix=get_command_prefix, intents=intents) help_command_ = commands.DefaultHelpCommand() self.help_command = help_command_ try: with open( f'{self.config.general_config.database_directory_global_state}/{self.config.general_config.database_name_global_state}', 'rb') as file: self.state = pickle.load(file) self.state.config = self.config logger.info('Global State reinitialized.') except FileNotFoundError: no_global_state_found_text = "No global state found! Create new global state." logger.warning(no_global_state_found_text) print(no_global_state_found_text, file=sys.stderr) self.state = GeneralState(self.config) for guild in self.guilds: self.state.add_guild_state(guild.id)
def get_discord_bot() -> discord.ext.commands.bot.Bot: """ Returns a discord.py bot which we will use to listen to commands """ help_cmd = commands.DefaultHelpCommand(no_category="Commands", width=120) description = """Hello I am PastaBot, I get copypasta posts from Reddit so you don't have to! Prefixes: \"pastabot!\" | \"pasta!\" | \"pb!\" | \"p!\" or you can mention @PastaBot with a command Examples: --------- p!rand Get random submission (defaults to 100 hot pastas) p!rand top 10 Get random submission from 10 top pastas p!list top 10 List 10 submissions from top p!get new 10 Get 10th submission from new p!show https://www.reddit.com/r/copypasta/comments/luau3v/if_you_repost_a_popular_copypasta_thats_less_than/ """ pastabot = commands.Bot( command_prefix=commands.when_mentioned_or("pasta!", "pastabot!", "pb!", "p!"), description=description, help_command=help_cmd, ) return pastabot
def __init__(self): super().__init__( command_prefix=["!"], description="https://github.com/iamsix/palbot/ by six", case_insensitive=True, help_command=commands.DefaultHelpCommand(dm_help=None), intents=intents) self.logger = logging.getLogger("palbot") self.moddir = "modules" self.config = __import__('config') self.utils = __import__('utils') print(self.intents) print(self.intents.members) # This contains a list of tuples where: # [0] = User's command Message obj # [1] = the bot's response Message obj # [2] = Paginator (None if not paginating) self.recent_posts = deque([], maxlen=10) for module in Path(self.moddir).glob('*.py'): try: self.load_extension("{}.{}".format(self.moddir, module.stem)) except Exception as e: print(f'Failed to load cog {module}', file=sys.stderr) traceback.print_exception(type(e), e, e.__traceback__, file=sys.stderr)
def __init__(self, config: dict, startup_extensions: List[str]): super().__init__(command_prefix=commands.when_mentioned_or('icl.'), case_insensitive=True, description='ICL Bot', help_command=commands.DefaultHelpCommand(verify_checks=False), intents=discord.Intents( guilds=True, members=True, bans=True, emojis=True, integrations=True, invites=True, voice_states=True, presences=False, messages=True, guild_messages=True, dm_messages=True, reactions=True, guild_reactions=True, dm_reactions=True, typing=True, guild_typing=True, dm_typing=True )) fileConfig('logging.conf') self.logger = logging.getLogger(f'ICL_bot.{__name__}') self.logger.debug(f'Version = {__version__}') self.logger.debug(f'config.json = \n {pprint.pformat(config)}') self.token: str = config['discord_token'] self.faceit_token: str = config['faceit_token'] self.bot_IP: str = config['bot_IP'] if 'bot_port' in config: self.bot_port: int = config['bot_port'] else: self.bot_port: int = 3000 self.web_server = WebServer(bot=self) self.dev: bool = False self.version: str = __version__ self.matches: List[Match] = [] for extension in startup_extensions: self.load_extension(f'cogs.{extension}')
def __init__(self, command_prefix, help_command=None, description=None, **options): """ Overwrite Defualt __init__ """ # Set default Help command if not help_command: help_command = commands.DefaultHelpCommand() super().__init__(command_prefix, help_command, description, **options) self.start_time = datetime.datetime.utcnow() self.trust_session = ClientSession() # Define database here so It's easier to be use. self.database = Database() self.planner = planner.Planner(self) self.manager = manager.Manager(self) self.config = config self.log_channel = None self.dump_channel = None """import cProfile import pstats with cProfile.Profile() as pr: self.planner.get_embed(728482381215826000) stats = pstats.Stats(pr) stats.sort_stats(pstats.SortKey.TIME) stats.dump_stats("stats.prof")""" log.debug("bot subclass Created.")
def __init__(self, config_file, *args, **kwargs): self.config_file = config_file self.description = "qtbot is a big qt written in python3 and love." self.do_not_load = ("league", "poll", "music", "timer", "ris", "timer", "wiki") with open(self.config_file) as f: self.api_keys = json.load(f) self.token = self.api_keys["discord"] super().__init__( command_prefix=self.get_prefix, description=self.description, help_command=commands.DefaultHelpCommand(dm_help=True), case_insensitive=True, *args, **kwargs, ) self.aio_session = aiohttp.ClientSession(loop=self.loop) # self.rune_client = lolrune.AioRuneClient() self.redis_client = aredis.StrictRedis(host="localhost", decode_responses=True) self.startup_extensions = [x.stem for x in Path("cogs").glob("*.py")] self.loop.run_until_complete(self.create_db_pool()) self.loop.run_until_complete(self.load_all_prefixes())
def __init__(self, *args, **kwargs): super().__init__( help_command=commands.DefaultHelpCommand(dm_help=True), *args, **kwargs) self.config = lib.get('./settings.json') self.start_time = time.time() self.app_info = None self.setup()
def __init__(self): """ CustomClient constructor. Serves to initialize the command prefix. """ self.cmd_prefix = '-' super(CustomBot, self).__init__(command_prefix=self.cmd_prefix) self.help_command = commands.DefaultHelpCommand(width=80000) self.add_command(self.start_poll) print(self.commands)
async def default_help_command( self, ctx: Kaantext, ) -> None: """ set default help command """ self.bot.help_command = commands.DefaultHelpCommand()
async def toggle_help(self, ctx: commands.Context): """: Toggle how the bot send the help menu in a pm""" dm_help = not self.bot.help_command.dm_help self.bot.help_command = commands.DefaultHelpCommand(dm_help=dm_help) self.bot.settings.data["Bot Settings"]["pm_help"] = dm_help self.bot.settings.save() if dm_help: await ctx.channel.send("The help menu will be sent as a PM now.") else: await ctx.channel.send("The help menu will be posted locally.")
def main(): """Main script to run the bot.""" bot = PPBot((".", "!")) bot.help_command = commands.DefaultHelpCommand(dm_help=None) print(f"Starting the bot!") bot.load_cogs() bot.run(bot.config["token"]) return bot.exitcode
def __init__(self, **kwargs): super().__init__( description="Football lookup bot by Painezor#8489", help_command=commands.DefaultHelpCommand(dm_help_threshold=20), command_prefix=".tb ", owner_id=210582977493598208, activity=discord.Game(name="Use .tb help")) self.db = kwargs.pop("database") self.credentials = credentials self.initialised_at = datetime.utcnow() self.session = aiohttp.ClientSession(loop=self.loop)
def __init__(self, **kwargs: Any) -> None: self.launch_time = perf.start() super().__init__( command_prefix='!', help_command=commands.DefaultHelpCommand(dm_help=True), case_insensitive=True, **kwargs) self.voice = None self.achievement_cache: Dict[str, Dict[str, str]] = {} for task in TASKS: asyncio.ensure_future(task(self), loop=self.loop)
def __init__(self, intents: discord.Intents): super().__init__( command_prefix=commands.when_mentioned_or(config.prefix), intents=intents, owner_ids=config.owner_ids, help_command=commands.DefaultHelpCommand(command_attrs={ "name": "commands", "aliases": ["command"] }), ) self.db: typing.Optional[asyncpg.pool.Pool] = None
def main(): """ Main function, loads extension and starts the bot """ for ext in config.extensions: bot.load_extension(f"extensions.{ext}") logger.info(f"Loaded {ext}") bot.help_command = commands.DefaultHelpCommand(no_category="Core") bot.run(config.token)
def __init__(self, config: dict, startup_extensions: List[str]): super().__init__( command_prefix=commands.when_mentioned_or('.'), case_insensitive=True, description='A bot to run CSGO PUGS.', help_command=commands.DefaultHelpCommand(verify_checks=False), intents=discord.Intents(guilds=True, members=True, bans=True, emojis=True, integrations=True, invites=True, voice_states=True, presences=False, messages=True, guild_messages=True, dm_messages=True, reactions=True, guild_reactions=True, dm_reactions=True, typing=True, guild_typing=True, dm_typing=True)) fileConfig('logging.conf') self.logger = logging.getLogger(f'10man.{__name__}') self.logger.debug(f'Version = {__version__}') self.logger.debug(f'config.json = \n {pprint.pformat(config)}') self.token: str = config['discord_token'] self.bot_IP: str = config['bot_IP'] if 'bot_port' in config: self.bot_port: int = config['bot_port'] else: self.bot_port: int = 3000 self.steam_web_api_key = config['steam_web_API_key'] self.servers: List[CSGOServer] = [] # Will need to change for when there is multiple server queue self.users_not_ready: List[discord.Member] = [] for i, server in enumerate(config['servers']): self.servers.append( CSGOServer(i, server['server_address'], server['server_port'], server['server_password'], server['RCON_password'])) self.web_server = WebServer(bot=self) self.dev: bool = False self.version: str = __version__ self.queue_ctx: commands.Context = None self.queue_voice_channel: discord.VoiceChannel = None self.match_size = 10 self.spectators: List[discord.Member] = [] self.connect_dm = False self.queue_captains: List[discord.Member] = [] for extension in startup_extensions: self.load_extension(f'cogs.{extension}')
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.add_check(self.perms_check) self.help_command = commands.DefaultHelpCommand( command_attrs={"aliases": ["h"]}) for extension in startup_extensions: try: self.load_extension(extension) except Exception as e: exc = f"{type(e).__name__}: {e}" print(f"Failed to load extension {extension}\n{exc}") self.check_memed_users.start()
def __init__(self, cfg: BotConfig, **kwargs) -> None: """Initialize a BotBase from a :class:`BotConfig` and other kwargs. The kwargs override any related BotConfig values and are all passed to :class:`commands.bot.BotBase`'s initializer. """ #: The bot's :class:`BotConfig`. self.config = cfg command_prefix = kwargs.pop("command_prefix", compute_command_prefix(cfg)) description = kwargs.pop("description", self.config.description) help_command = kwargs.pop( "help_command", commands.DefaultHelpCommand(dm_help=cfg.dm_help) ) intents_specifier = cfg.intents intents = discord.Intents.default() if isinstance(intents_specifier, list): kwargs = {key: True for key in intents_specifier} intents = discord.Intents(**kwargs) elif hasattr(discord.Intents, intents_specifier): intents = getattr(discord.Intents, intents_specifier)() super().__init__( command_prefix=command_prefix, description=description, help_command=help_command, intents=intents, **kwargs, ) #: The bot's :class:`Context` subclass to use when invoking commands. #: Falls back to :class:`Context`. self.context_cls = kwargs.get("context_cls", lifesaver.commands.Context) if not issubclass(self.context_cls, lifesaver.commands.Context): raise TypeError(f"{self.context_cls} is not a lifesaver Context subclass") #: The bot's logger. self.log = logging.getLogger(__name__) #: The Postgres pool connection. self.pool: Optional["asyncpg.pool.Pool"] = None #: A list of extensions names to reload when calling :meth:`load_all`. self.load_list = LoadList() #: A list of included extensions built into lifesaver to load. self._included_extensions: List[str] = INCLUDED_EXTENSIONS self._hot_task = None self._hot_reload_poller = None self._hot_plug = None
def __init__(self, command_prefix, configpath: str, help_command=commands.DefaultHelpCommand(), description=None, **options): self.configpath = configpath self.config = configparser.ConfigParser() self.config.read(configpath) super().__init__(command_prefix, help_command=help_command, description=description, **options)
async def _set_bot_configs(bot): bot.uptime = datetime.datetime.now() bot.description = str(constants.DESCRIPTION) bot.help_command = commands.DefaultHelpCommand(dm_help=True) bot.settings = BotUtils.get_all_ini_file_settings( constants.SETTINGS_FILENAME) bot.settings["bot_webpage_url"] = str(constants.BOT_WEBPAGE_URL) bot.settings["version"] = constants.VERSION bot.settings["full_db_name"] = BotUtils.get_full_db_name(bot) bot.settings["EmbedOwnerColor"] = BotUtils.get_color_settings( bot.settings["EmbedOwnerColor"]) bot.settings["EmbedColor"] = BotUtils.get_color_settings( bot.settings["EmbedColor"])
async def startup(): setup_logging() if discord.version_info.major < 1: logger.error( "discord.py is not at least 1.0.0x. (current version: %s)", discord.__version__) return 2 if sys.hexversion < 0x30900F0: # 3.9 logger.error("Kurisu requires 3.9 or later.") return 2 if not IS_DOCKER: # attempt to get current git information try: commit = check_output(['git', 'rev-parse', 'HEAD']).decode('ascii')[:-1] except CalledProcessError as e: logger.error("Checking for git commit failed: %s: %s", type(e).__name__, e) commit = "<unknown>" try: branch = check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']).decode()[:-1] except CalledProcessError as e: logger.error("Checking for git branch failed: %s: %s", type(e).__name__, e) branch = "<unknown>" else: commit = os.environ.get('COMMIT_SHA') branch = os.environ.get('COMMIT_BRANCH') try: albmain(['--raiseerr', 'upgrade', 'head']) engine = await gino.create_engine(DATABASE_URL) db.bind = engine except Exception: logger.exception("Failed to connect to postgreSQL server", exc_info=True) return logger.info("Starting Kurisu on commit %s on branch %s", commit, branch) bot = Kurisu(command_prefix=['.', '!'], description="Kurisu, the bot for Nintendo Homebrew!", commit=commit, branch=branch) bot.help_command = commands.DefaultHelpCommand(dm_help=None) bot.engine = engine await bot.start(TOKEN)
def setup(bot): a = Authentication(bot) bot.add_cog(a) try: bot.remove_command("help") except: pass global helpcommand global helpcommand1 helpcommand = commands.DefaultHelpCommand(command_attrs=dict( name=_("help"), brief=_("Show help.")), verify_checks=False) helpcommand1 = commands.DefaultHelpCommand(command_attrs=dict( name=_("help command two"), brief=_("Show help.")), verify_checks=False) #helpcommand2 = commands.DefaultHelpCommand(command_attrs=dict(name="leo",brief="Hilfe anzeigen.")) helpcommand._add_to_bot(bot) helpcommand1._add_to_bot(bot) #helpcommand2._add_to_bot(bot) # allow unverified users to verify: b5('ext').whitelistCommand('Registrierung', _('rhrk')) b5('ext').whitelistCommand('Registrierung', _('ersti')) b5('ext').whitelistCommand('Registrierung', _('code')) b5('ext').whitelistCommand('Registrierung', _('erstihelp')) b5('ext').whitelistCommand(None, _("help")) b5('ext').whitelistCommand(None, _("help command two")) b5('ext').register('auth', a) b5('user').registerField('auth', 'verified', bool, False) b5('user').registerField('auth', 'authCode', int, 0, showToUser=False) b5('user').registerField('auth', 'authCodeValidUntil', float, 0.0) b5('user').registerField('auth', 'accountType', str, "UNVERIFIED") b5('user').registerField('auth', 'rhrk', str, '')
def __init__(self, **kwargs: Any) -> None: self.launch_time = perf.start() commit_id = subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode() redis.store('discordbot:commit_id', commit_id) super().__init__( command_prefix=commands.when_mentioned_or('!'), help_command=commands.DefaultHelpCommand(dm_help=True), case_insensitive=True, **kwargs) self.voice = None self.achievement_cache: Dict[str, Dict[str, str]] = {} for task in TASKS: asyncio.ensure_future(task(self), loop=self.loop) discordbot.commands.setup(self)
def __init__(self, config): super().__init__( command_prefix=_prefix_callable, case_insensitive=True, intents=intents, help_command=commands.DefaultHelpCommand(no_category="Assorted", dm_help=True, verify_checks=False), ) self.config = config self.database = Database(config.database_url, config.database_conns) self.destiny = Pydest( api_key=config.destiny.api_key, client_id=config.destiny.client_id, client_secret=config.destiny.client_secret, ) self.the100 = The100(config.the100.api_key, config.the100.base_url) self.twitter = None if (config.twitter.consumer_key and config.twitter.consumer_secret and config.twitter.access_token and config.twitter.access_token_secret): self.twitter = PeonyClient(**config.twitter.asdict()) self.ext_conns = { "database": self.database, "destiny": self.destiny, "twitter": self.twitter, "the100": self.the100, "redis_cache": None, "redis_jobs": None, } for extension in STARTUP_EXTENSIONS: try: self.load_extension(extension) except Exception as e: exc = traceback.format_exception(type(e), e, e.__traceback__) log.error(f"Failed to load extension {extension}: {exc}") if config.enable_activity_tracking: self.update_members.start() self.cache_clan_members.start()
def __init__(self, **kwargs: Any) -> None: self.launch_time = perf.start() commit_id = subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode() redis.store('discordbot:commit_id', commit_id) help_command = commands.DefaultHelpCommand(dm_help=None, no_category='Commands') intents = discord.Intents.default() intents.members = True intents.presences = True intents.typing = False super().__init__(command_prefix=commands.when_mentioned_or('!'), help_command=help_command, case_insensitive=True, intents=intents, **kwargs) super().load_extension('jishaku') self.voice = None self.achievement_cache: Dict[str, Dict[str, str]] = {} for task in TASKS: asyncio.ensure_future(task(self), loop=self.loop) discordbot.commands.setup(self)