def __init__(self, config, **kwargs): super().__init__( command_prefix=kwargs.pop("command_prefix", config["general"]["prefix"]), case_insensitive=kwargs.pop("case_insensitive", True), max_messages=kwargs.pop("max_messages", 10_000), help_command=kwargs.pop("help_command", commands.MinimalHelpCommand()), allowed_mentions=kwargs.pop( "allowed_mentions", discord.AllowedMentions(everyone=False, roles=False, users=False), ), activity=discord.Activity( type=discord.ActivityType.listening, name=f"{config['general']['prefix']}help", ), intents=discord.Intents.all(), **kwargs, ) self.config = config self.ready_once = False self.guild = None self.prompt_tasks = [] self.logging_channel = None self.add_check(self.only_one_guild)
def __init__(self, started_at, **kwargs): super().__init__(command_prefix=settings.prefix, description="sQUIRE, Defender of Bikini Bottom", help_command=commands.MinimalHelpCommand(), intents=discord.Intents.all(), **kwargs) self.version = settings.version self.started_at = started_at self.session = aiohttp.ClientSession() self.add_check(lambda ctx: is_mod(ctx.author)) self._exit_code = 0
def __init__(self): super().__init__(command_prefix=commands.when_mentioned_or('-'), help_command=commands.MinimalHelpCommand(), description='Bot for Strawberry Lamb server', case_insensitive=True, intents=discord.Intents.all(), allowed_mentions=discord.AllowedMentions(everyone=False), activity=discord.Activity(type=discord.ActivityType.watching, name='over the school')) self.start_time = datetime.utcnow() self.session = aiohttp.ClientSession(loop=self.loop) self.mod_level = {}
def __init__(self, **kwargs): kwargs.setdefault("help_command", commands.MinimalHelpCommand()) kwargs.setdefault("prefix_emoji", "\U0001f97a") kwargs.setdefault("listening_emoji", "\U0001f449") super().__init__(get_prefix, **kwargs) self.session: aiohttp.ClientSession for cog in config.cogs: try: self.load_extension(cog) except Exception as exc: print('Could not load extension {0} due to {1.__class__.__name__}: {1}'.format(cog, exc)) self.loop.create_task(self.after_on_ready())
def __init__(self, token, db_url, **kwargs): super().__init__(command_prefix=prefix, case_insensitive=True, description='Best Bot <3', **kwargs) self.__token = token self.__db_url = db_url self._nwunder = None self._running = False self._user_blacklist = [] self._guild_blacklist = [] self.db = Database(db_url) self.help_command = commands.MinimalHelpCommand() self.add_check(global_checks) logger.info(f'Initialization complete.')
def __init__(self): intents = discord.Intents(messages=True, guilds=True, reactions=True) super().__init__( command_prefix=get_prefix, description=description, case_insensitive=True, activity=discord.Game("Starting up..."), help_command=commands.MinimalHelpCommand(), intents=intents, ) self.log = log log.info("Starting bot...") log.info("Loading config file...") self.config = self.load_config("config.yml") # Config checks if self.config["server-type"].lower() not in ["java", "bedrock"]: raise InvalidServerType(self.config["server-type"]) if self.config["refresh-rate"] < 30: raise InvalidRefreshRate(self.config["refresh-rate"]) log.info("Loading extensions...") for extension in initial_extensions: self.load_extension(extension) log.info("Setting initial status before logging in...") status_cog = self.get_cog("Status") status, text = self.loop.run_until_complete(status_cog.get_status()) game = discord.Game(text) status_cog.activity = game self._connection._status = status self.activity = game self.init_ok = None self.restart_signal = None try: self.load_extension("jishaku") self.get_command("jishaku").hidden = True except Exception: log.info("jishaku is not installed, continuing...")
def __init__(self, name, logger, **kwargs): super().__init__(name, logger=logger, command_prefix=prefix, case_insensitive=True, description='Best Bot <3', **kwargs) self._init_args = [name, logger] self._init_kwargs = kwargs self._nwunder = None self.config = None self._user_blacklist = [] self._guild_blacklist = [] self._locked = False self.table = None self.help_command = commands.MinimalHelpCommand() self.add_check(checks.global_checks) self.logger.info(f'Initialization complete. [{name}]')
def __init__(self) -> None: super().__init__( allowed_mentions=discord.AllowedMentions(everyone=False, users=False, roles=False), case_insensitive=True, command_prefix=get_prefix, intents=discord.Intents(messages=True, guilds=True), help_command=commands.MinimalHelpCommand(dm_help=True), activity=discord.Game("+help / ;help"), ) slash = SlashCommand(self, sync_commands=True, sync_on_cog_reload=True) for extension in EXTENSIONS: try: self.load_extension(extension) except Exception as e: print(e, file=stderr) config = {} try: f = open(f"{ROOT_DIR}/config.json", encoding="utf-8") config = json.load(f) self.token = config["token"] except IOError: print("No config file found, trying backwards compatible method.") try: f = open(f"{ROOT_DIR}/token", "r", encoding="utf-8") self.token = f.read().strip() except IOError: print("No bot token found. ") exit(1) finally: f.close() if not config: print("Please create a config.json file.") exit(1) self.redis = Redis( host=config["redis_hostname"] if "redis_hostname" in config else "localhost", port=config["redis_port"] if "redis_port" in config else 6379, db=(config["redis_db"] if "redis_db" in config else 0), decode_responses=True, )
def __init__(self) -> None: super().__init__( allowed_mentions=discord.AllowedMentions(everyone=False, users=False, roles=False), case_insensitive=True, command_prefix=get_prefix, intents=discord.Intents(messages=True, guilds=True), help_command=commands.MinimalHelpCommand(dm_help=True), activity=discord.Game("+help / ;help"), ) slash = SlashCommand(self, sync_commands=True, sync_on_cog_reload=True) for extension in EXTENSIONS: try: self.load_extension(extension) except Exception as e: print(e, file=stderr) with open(f"{ROOT_DIR}/token", "r", encoding="utf-8") as f: self.token = f.read().strip()
def __init__(self, config: ConfigBox, **kwargs): super().__init__( command_prefix=kwargs.pop("command_prefix", config.general.prefix), case_insensitive=kwargs.pop("case_insensitive", True), max_messages=kwargs.pop("max_messages", 10_000), help_command=kwargs.pop("help_command", commands.MinimalHelpCommand()), allowed_mentions=kwargs.pop( "allowed_mentions", discord.AllowedMentions(everyone=False, roles=False, users=False), ), activity=discord.Activity( type=discord.ActivityType.listening, name=f"{config.general.prefix}help", ), **kwargs, ) self.config: ConfigBox = config self.ready_once = False
import discord from discord.ext import commands from config.config import TOKEN class Bot(commands.Bot): """A subclassed version of commands.Bot to add functionality""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def add_cog(self, cog: commands.Cog) -> None: """Adds a cog to the bot and logs it.""" super().add_cog(cog) def load_extensions(self, cogs: list): """Loads a list of cogs""" for cog in cogs: try: super().load_extension(cog) except Exception as e: print(e) if __name__ == "__main__": bot = Bot(command_prefix="!", help_command=commands.MinimalHelpCommand()) cogs = ["cogs.rcon"] bot.load_extensions(cogs) bot.run(TOKEN)
def teardown(bot): bot.help_command = commands.MinimalHelpCommand()
def __init__(self, description, *args, **kwargs): self.version = VERSION self.description = description self._filesystem_setup() self.app_info = None with open("config/config.json") as cfg: config = json.load(cfg) self.database = config["Database"] self.backup_db = config["BackupDB"] self.config_prefix = config["Prefix"] self.mention_cmds = config["MentionCommands"] self.config_token = config["Token"] self.cmd_on_edit = config["CommandsOnEdit"] self.delete_cmds = config["DeleteCommands"] self.log_file = config["LogFile"] self.log_messages = config["LogMessages"] self.log_edits = config["LogEdits"] self.log_deletes = config["LogDeletes"] self.log_commands = config["LogCommands"] self.botmasters = config["Botmasters"] self.log = get_logger(self.log_file) self.db = None self.blocklist = [] self.plugins = [] self.servers = {} self.first_launch = True db_file = f"db/{self.database}" if os.path.exists(db_file) and self.backup_db: timestamp = f"{pretty_datetime(datetime.now(), display='FILE')}" try: shutil.copyfile(db_file, f"db/backups/{self.database}-{timestamp}.sql") except IOError as e: error_file = f"db/backups/{self.database}-{timestamp}.sql" self.log.error( f"Unable to create file {error_file}\n - {e}") self.db = SqliteDict( filename=f"db/{self.database}", tablename="discord-bot", encode=json.dumps, decode=json.loads, autocommit=True, ) if "blocklist" not in self.db: self.db["blocklist"] = [] if "servers" not in self.db: self.db["servers"] = {} self.blocklist = self.db["blocklist"] self.servers = self.db["servers"] if self.mention_cmds: self.mode = commands.when_mentioned_or(self.config_prefix) else: self.mode = self.config_prefix super(DiscordBot, self).__init__( self.mode, description=description, help_command=commands.MinimalHelpCommand( paginator=commands.Paginator(max_size=800, prefix=None, suffix=None), sort_commands=False, ), *args, **kwargs, )
"help", 'aliases': [ "HELP", "helps", "HELPS", "hell", "HELL", "h", "H", "command", "COMMAND", "commands", "COMMANDS", "how", "HOW", "com", "COM", "c", "C", "Koala", "kola", "KOALA" ], 'cooldown': commands.Cooldown( 1, 5.0, commands.BucketType.user ) # Lets users run the help command once every 5 seconds to reduce spam } # During declaration # help_object = commands.HelpCommand(command_attrs = attributes) # Needs the following to be added to the COMMAND_PREFIX sections: help_command = help_object # OR through attribute assignment help_object = commands.MinimalHelpCommand() # HelpCommand help_object.command_attrs = attributes # Variables started = False if discord.__version__ != "1.3.4": logging.info("Intents Enabled") intent = discord.Intents.default() intent.members = True intent.guilds = True intent.messages = True client = commands.Bot(command_prefix=COMMAND_PREFIX, intents=intent, help_command=help_object) else: logging.info("discord.py v1.3.4: Intents Disabled")
prefixes = [db_records[0]['prefix']] else: prefixes = ['!'] return commands.when_mentioned_or(*prefixes)(bot, ctx) # Define gateway intents intents = discord.Intents.default() intents.members = True # Privileged intent, needs Verification at 100+ Guilds # Disable spammy intents intents.typing = False intents.presences = False # Define bot bot = commands.Bot( command_prefix=_get_prefix, owner_id=shared_recources.botSettings['owner_id'], intents=intents, help_command=commands.MinimalHelpCommand() ) # Checks if the bot is ready. Nothing executes boefore the check has passed. @bot.event async def on_ready(): logging.info('The bot is now ready!') logging.info(f'Logged in as {bot.user}') # Initialize database pool await shared_recources.initialize_pool() await bot.loop.run_in_executor(None, shared_recources.initialize_gspread_service_account) # Load cogs from settings file for cog_str in shared_recources.botSettings['cogs']: bot.load_extension(cog_str)
def __init__(self, **kwargs): intents = discord.Intents(guilds=True, members=True, emojis=True, messages=True, reactions=True) super().__init__(command_prefix='$', fetch_offline_members=True, help_command=commands.MinimalHelpCommand(), intents=intents) self.config = kwargs.pop('config') self.pool = kwargs.pop('pool') self.session = kwargs.pop('session') for extension in initial_extensions: try: self.load_extension(extension) except Exception: log.exception('Failed to load extension %r', extension) else: log.info('Successfully loaded extension %r', extension) self.start_time = datetime.utcnow() self.add_check(self.global_check)
def cog_unload(self): self.bot.help_command = commands.MinimalHelpCommand() if self.backup['minimal'] else commands.DefaultHelpCommand()
def setup(bot): bot.help_command = commands.MinimalHelpCommand(verify_checks=False) bot.add_cog(Meta())
if not any(convert_emoji_reaction(p) == convert_emoji_reaction(r) for r in reactions): return False if ev.message_id == message.id and self.user.id != ev.user_id: return check(ev) return (await self.wait_for("raw_reaction_add", check=c, timeout=40)).emoji async def get_webhook_for_channel(self, channel): for wb in await channel.webhooks(): if wb.name == "qc": return wb else: try: return await channel.create_webhook(name="qc") except discord.Forbidden: return None add_listener_object = _true_partial(_listener_bind, "add_listener") remove_listener_object = _true_partial(_listener_bind, "remove_listener") if __name__ == "__main__": token = get_env_value("token") prefix = get_env_value("prefix") intents = discord.Intents.default() intents.dm_reactions = True DiscordBot(prefix, help_command=commands.MinimalHelpCommand(), case_insensitive=True, intents=intents).run(token)
from discord.ext import commands from bot.bot import run cogs = [ "utility.general", "utility.charinfo", "core.status", "core.misc", "core.config", "fun.catpics", "fun.dogpics", "fun.cables", "fun.stickbug" ] cogs = ["bot.cogs." + cog for cog in cogs] cogs.append("jishaku") run(cogs, help_command=commands.MinimalHelpCommand())
import helpers.pregenerator from discord.ext import commands class Bot(commands.Bot): """A subclassed commands.Bot""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def load_extensions(self, cogs: list): """Loads a list of cogs""" for cog in cogs: try: super().load_extension(cog) except Exception as e: print(e) if __name__ == "__main__": bot = Bot( command_prefix="!", max_messages=10000, #allowed_mentions=discord.AllowedMentions(everyone=False, users=True, roles=False), help_command=commands.MinimalHelpCommand(dm_help=True, no_category="General")) cogs = [] bot.load_extensions(cogs) bot.run(os.environ["TOKEN"])
data = manager.json_mngr().read('./prefixes.json') prefixf = open('./token', 'r') prefix = prefixf.readlines() prefix = base64.b64encode(bytes(prefix[0], 'utf-8')) prefixf.close() def get_prefix(b0t, message): return commands.when_mentioned_or("ym!" if str( message.guild.id) not in data.keys() else data[str(message.guild.id)])( b0t, message) bot = commands.AutoShardedBot(command_prefix=get_prefix, case_insensitive=True, help_command=commands.MinimalHelpCommand(), owner_id=421698654189912064) bot.last_tb = 'nerd, im bug free so far!' print("+===+ STATUS +===+") @bot.event async def on_shard_ready(shard): print("|Shard {}:ONLINE|".format(shard)) @bot.event async def on_ready(): bot.load_extension('jishaku') bot.load_extension('cogs.core') print('|MAIN BOT: ONLINE|')
from checks import channel from keep_alive import keep_alive load_dotenv() install() # VARS prefix = "!P" intents = discord.Intents.default() intents.members = True client = commands.Bot( command_prefix=prefix, help_command=commands.MinimalHelpCommand( sort_commands=False, aliases_heading="También: ", no_category="General", dm_help=None, dm_help_treshold=500, case_insensitive=True, ), intents=intents, ) tz = pytz.timezone("Europe/Madrid") # On ready @client.event async def on_ready(): print("Connected as:") print("{}: {}".format(client.user.name, client.user.id)) print(f"Prefix: {prefix}") print(dt.now(tz).strftime("%H:%M:%S %d/%m/%Y"))
import traceback from datetime import datetime from discord.ext import commands from json import load from sys import stderr # Sets up the bot prefixes = None token = None with open("config.json") as configFile: config = load(configFile) prefixes = config["prefixes"] token = config["token"] helpCommand = commands.MinimalHelpCommand(no_category="Other:") bot = commands.Bot(command_prefix=prefixes, help_command=helpCommand) # Sets up logging of verbosity INFO into a file named "log.txt" logger = logging.getLogger("discord") logger.setLevel(logging.INFO) handler = logging.FileHandler(filename="log.txt", encoding="utf-8", mode="a") handler.setFormatter( logging.Formatter("%(asctime)s:%(levelname)s:%(name)s: %(message)s")) logger.addHandler(handler) # Sets up error logging @bot.event async def on_command_error(ctx, error): # Get the original error, if it exists
def __init__(self, client): self.client = client self._original_help_command = commands.MinimalHelpCommand() client.help_command = MinimalEmbedPaginatorHelp() client.help_command.cog = self self.start_time = datetime.datetime.now()