def command_prefix(bot, message):
"""Custom prefix function for guild-specific prefixes."""
default = config.prefix
if message.guild is None:
return default
settings = await bot.get_guild_prefix(message.guild.id)
if settings is None:
return commands.when_mentioned_or(default)(bot, message)
if settings['prefix'] is None:
print('prefix is None')
return commands.when_mentioned(bot, message)
valid = [settings['prefix']]
if settings['allow_default']:
if isinstance(default, (tuple, list)):
valid.extend(default)
else:
valid.append(default)
valid.sort(reverse=True)
return commands.when_mentioned_or(*valid)(bot, message)
python类when_mentioned_or()的实例源码
def __init__(self, verbose=False, bleeding=False, reactive=True, *args, **kwargs):
# Rewrite the command_prefix flag to force mention
super().__init__(*args, command_prefix=commands.when_mentioned_or('!'), **kwargs)
self.config = {
'verbose' : verbose,
'bleeding' : bleeding,
'reactive' : reactive,
'rank_whitelist_file': 'rank_whitelist.txt',
'admin_roles_file' : 'admin_roles.txt',
'power_admins_file' : 'power_admins.txt'
}
self.rank_whitelist = self.load(self.config['rank_whitelist_file'])
self.admin_roles = self.load(self.config['admin_roles_file'])
self.power_admins = self.load(self.config['power_admins_file'])
def command_checker(msg):
try:
if isinstance(msg.channel,discord.DMChannel):
if "!reply" in msg.content:
bot.command_prefix = commands.when_mentioned_or("!")
return
if bot.user.id == 181503794532581376:
bot.command_prefix = commands.when_mentioned_or("$")
bot.pm_help = False
return
cmd_prefix= await bot.db.redis.get("{}:Config:CMD_Prefix".format(msg.guild.id))
cmd_prefix= cmd_prefix.split(",")
if '' in cmd_prefix: #check if "none-space" as a command, if true, return, in order to prevent any spam in case, lower chance of getting kick heh.
return
bot.command_prefix = commands.when_mentioned_or(*cmd_prefix)
if "help" in msg.content: #changing setting for help, if guild owner want Help command to be via PM or to guild.
if await bot.db.redis.get("{}:Config:Whisper".format(msg.guild.id)) == "on":
bot.pm_help =True
else:
bot.pm_help=False
except:
pass
def get_prefix(bot, message):
guild_id = 0 if message.guild is None else message.guild.id
guild_settings = bot.session.get(GuildSettings, id=guild_id).one_or_none()
prefix = config['default_prefix'] if guild_settings is None or guild_settings.prefix is None else guild_settings.prefix
return when_mentioned_or(prefix)(bot, message)
def __init__(self,token):
self.client = commands.Bot(command_prefix=commands.when_mentioned_or('!'),description=clientDesc)
self.token = token
#------------------------Setting up cogs---------------------------------------------------------
#setup_ow(self.client)
setup_misc(self.client)
#setup_game(self.client)
setup_music(self.client)
#setup_twitch(self.client)
def _callable_prefix(bot, message):
if message.guild:
prefixes = bot.custom_prefixes.get(message.guild.id, bot.default_prefix)
else:
prefixes = bot.default_prefix
return commands.when_mentioned_or(*prefixes)(bot, message)
def __init__(self, command_prefix=commands.when_mentioned_or("#!"),
formatter=None,
name="BasicBot",
description="""Tnybot is a basic bot that includes custom commands and notifications""",
pm_help=False, **options):
self.unit_tests = options.pop('unit_tests', False)
super().__init__(command_prefix, formatter, description, pm_help, **options)
self.name = name
if not self.unit_tests and not sys.platform.startswith('win'): # pragma: no cover
# This is needed for safe shutdown on Heroku.
self.loop.add_signal_handler(getattr(signal, "SIGTERM"), self.exit)
def __init__(self):
super().__init__(command_prefix=commands.when_mentioned_or('b!'), description=DESCRIPTION)
self.bot_token = config.TOKEN
self.api_key = config.API
for extension in STARTUP_EXTENSIONS:
try:
self.load_extension(extension)
except Exception as exception:
exc = '{}: {}'.format(type(exception).__name__, exception)
print('Failed to load extension {}\n{}'.format(extension, exc))
def __init__(self, **kwargs):
self.activation_str = kwargs.get(self.ACTIVATION_STR_KEY, self.ACTIVATION_STR)
self.description = kwargs.get(self.DESCRIPTION_KEY, self.DESCRIPTION)
self.token_file_path = kwargs.get(self.TOKEN_FILE_PATH_KEY, self.TOKEN_FILE_PATH)
## Todo: pass kwargs to the their modules
## Init the bot and module manager
self.bot = commands.Bot(
command_prefix=commands.when_mentioned_or(self.activation_str),
description=self.description
)
self.module_manager = ModuleManager(self, self.bot)
## Register the modules (Order of registration is important, make sure dependancies are loaded first)
self.module_manager.register(speech.Speech, *[self.bot])
self.module_manager.register(phrases.Phrases, *[self, self.bot],
**dict(pass_context=True, no_pm=True))
self.module_manager.register(music.Music, *[self, self.bot])
self.module_manager.register(admin.Admin, *[self, self.bot])
## Give some feedback for when the bot is ready to go
@self.bot.event
async def on_ready():
print("Logged in as '{}' (version: {}), (id: {})".format(self.bot.user.name, self.VERSION, self.bot.user.id))
## Methods
## Add an arbitary cog to the bot
def getPrefix(self, bot, msg):
return commands.when_mentioned_or(*self.prefix)(bot, msg)
def __init__(self, *args, **kwargs):
super().__init__(command_prefix=when_mentioned_or(setup_file["discord"]["command_prefix"]),
description="A bot for weebs programmed by Recchan")
# Set a custom user agent for Pixie
self.http.user_agent = user_agent
# Logging setup
redirect_logging()
StreamHandler(sys.stderr).push_application()
self.logger = Logger("Pixie")
self.logger.level = getattr(logbook, setup_file.get("log_level", "INFO"), logbook.INFO)
logging.root.setLevel(self.logger.level)
def __init__(self, game: str):
super().__init__(
command_prefix=commands.when_mentioned_or("n!"),
description=DESCRIPTION,
pm_help=True,
game=discord.Game(name=game)
)
cogs.setup(self)
def __init__(self):
self.token = os.environ['TOKEN']
self.presence = discord.Game(name='in a Digital Haunt...',
url="https://www.twitch.tv/ghostofsparkles", type=1)
self.archive_file = []
def get_package_info():
"""Fetches `arg` in `package.json`."""
with open("./package.json") as f:
config = json.load(f)
return config
def get_prefix():
"""Fetches all known prefixes."""
prefixes = ["-",
"Cassandra "]
return commands.when_mentioned_or(*prefixes)
def get_description():
"""Fetches description."""
return f"{get_package_info()['name']}"
def get_game():
"""Fetches game presence."""
return self.presence
super().__init__(command_prefix=get_prefix(), game=get_game(), description=get_description(), pm_help=None,
help_attrs=dict(hidden=True))
startup_extensions = []
for file in os.listdir("./cogs"):
if file.endswith(".py"):
startup_extensions.append(file.replace('.py', ''))
print(startup_extensions)
for extension in startup_extensions:
try:
print(f'cogs.{extension}')
self.load_extension(f'cogs.{extension}')
print(f'Loaded {extension}')
except Exception as e:
error = f'{extension}\n {type(e).__name__}: {e}'
print(f'Failed to load extension {error}')
self.session = None