def __init__(self): self.PREFIX = PREFIX self.ready = False self.cogs_ready = Ready() self.guild = None self.scheduler = AsyncIOScheduler() intents = Intents.default() db.autosave(self.scheduler) super().__init__(command_prefix=PREFIX, owner_ids=OWNER_IDS, intents=Intents.default())
def __init__(self, config: dict): # Intents # https://discordpy.readthedocs.io/en/stable/intents.html intents = Intents.default() # Need members intent for lib.utils.checks.is_guild_member intents.members = True super().__init__(config, intents=intents)
def __init__(self): # Get paths for files self.bot_directory = __file__.strip("bot.py") self.settings_location = self.bot_directory + "settings.json" self.ready_responses_location = self.bot_directory + "ready_responses.txt" self.cogs_directory = self.bot_directory + "cogs" # Load settings from settings.json self.settings = read_json(self.settings_location) # Token and command prefix self.token = self.settings["token"] self.prefix = self.settings["prefix"] # Blacklisted users self.blacklisted = self.settings["blacklisted"] # Ready messages and status change messages with open(self.ready_responses_location) as file: self.ready = [response.strip() for response in file.readlines()] self.status = cycle([f"Try {self.prefix}help!", "with 1s and 0s"]) # Intent initialization intents = Intents.default() # Client initialization super().__init__(command_prefix=self.prefix, intents=intents)
def __init__(self, *, config): self.config = config intents = Intents.default() # members intent is required to resolve discord.User/discord.Member # on command parameters intents.members = True intents.typing = False self.client = commands.Bot(intents=intents, command_prefix=commands.when_mentioned) self.client.add_cog(Management(self.client, self.config)) self.session = aiohttp.ClientSession(loop=self.client.loop) self.client.loop.create_task(self._sender()) self._queue = [] self._incoming = asyncio.Event() #: { int: (timestamp, str) } self._avatar_cache = {} #: { (jid, xmpp_message_id): discord_message_id } # the message id store serves as a way for edited messages coming # from a xmpp room to have the edit reflected on the discord channel. # # the high level overview is as follows: # when sending a message, check if its an edit and the edited id exists in the cache # if so, issue a patch (since we have the webhook url AND message id) # if not, issue a post, and store the message id for later # # the store has a maximum of 1k messages, and lets an xmpp message # be last corrected for an hour self._message_id_store = ExpiringDict(max_len=1000, max_age_seconds=3600)
def main(debug, maintenance): DEBUG = debug MAINTENANCE = maintenance # Load environment variables like connection tokens # Other environment variables are loaded in utility/constants.py load_dotenv() if (DEBUG): pass if (MAINTENANCE): pass # Enable member intents intents = Intents.default() intents.members = True PREFIX = os.getenv("PREFIX") TOKEN = os.getenv("DISCORD_TOKEN") # Create bot object descr = "Bot desription" bot = baseBot(intents=intents, command_prefix=PREFIX, debug=DEBUG, maintenance_mode=MAINTENANCE, description=descr) bot.add_cog(baseCog(bot, baseHelp())) # Start bot bot.run(TOKEN)
def __init__(self) -> None: intents = Intents.default() intents.members = True self.http_session = ClientSession() super().__init__(command_prefix=constants.PREFIX, intents=intents) self.load_extensions()
def __init__(self, *args, **kwargs): self.description = 'To be continued' # Configs & token with open('config.json') as f: self.config = json.load(f) intent = Intents.default() intent.members = True super().__init__(command_prefix=">>", description=self.description, intents=intent, chunk_guilds_at_startup=True, pm_help=None, *args, **kwargs) # Startup extensions (none yet) self.startup_ext = [x.stem for x in Path('cogs').glob('*.py')] # aiohttp session self.session = aiohttp.ClientSession(loop=self.loop) # Make room for the help command self.remove_command('help') # Embed color self.user_color = 0x781D1D self.quick_access = {}
def __init__(self, args: list): intents = Intents.default() intents.members = True super().__init__([get_constant('default_prefix')], intents=intents) self.load_all_extensions() get_event_loop().run_until_complete( self.start( config('TOKEN') if 'b' not in args else config('BETA_TOKEN')))
def __init__(self, user_manager, command_prefix='!'): intents = Intents.default() intents.members = True super().__init__(command_prefix=command_prefix, intents=intents) self.voice = Voice(self) self.user_manager = user_manager self.ws_server = WSServer(self)
def __init__(self): super().__init__( command_prefix=get_config("prefix"), description="Bot to monitor uptime of services", reconnect=True, intents=Intents.default(), ) self.bot = bot
def __init__(self): self.ready = False self.scheduler = AsyncIOScheduler() intents = discordINTENTS.default() intents.members = True # this allows the bot to see other members intents.presences = True # this allows the bot to see other member's presences intents.reactions = True # allows the bot to react to comments intents.messages = True # allow the bot to send server and direct messages super().__init__(command_prefix='=', intents=intents)
def __init__(self) -> None: intents = Intents.default() intents.members = True intents.presences = True self.http_session = ClientSession() super().__init__(command_prefix=constants.PREFIX, help_command=None, intents=intents)
def intents() -> Intents: intent = Intents.default() intent.members = False intent.presences = False intent.bans = False intent.integrations = False intent.invites = False intent.webhooks = False intent.typing = False return intent
def __init__(self, config_: Config): self.config: Config = config_ intents = Intents.default() intents.members = True super().__init__(command_prefix=self.config.prefix, owner_id=self.config.owner, status=Status.online, intents=intents) self.loop.create_task(self.startup()) self.remove_command("help") # Remove help command
def create_bot(command_prefix: str = ">"): intents = Intents.default() intents.members = True bot = commands.Bot( command_prefix=commands.when_mentioned_or(command_prefix), intents=intents) load_extensions(bot) return bot
def start_santa_bot(): #initialize config file config = None try: config = ConfigObj(CONFIG.cfg_path, file_error=True) except Exception as e: try: os.mkdir(CONFIG.bot_folder) except Exception as e: pass config = ConfigObj() config.filename = CONFIG.cfg_path config['programData'] = {'exchange_started': False} config['members'] = {} config.write() # initialize the SQLite db sqlitehelper = SQLiteHelper(CONFIG.sqlite_path) sqlitehelper.create_connection() #set up discord connection debug logging discord_api_logger = logging.getLogger('discord') discord_api_logger.setLevel(logging.DEBUG) discord_api_handler = logging.FileHandler(filename=os.path.join( str(pathlib.Path(__file__).parent), CONFIG.bot_folder, "discord_api.log"), encoding='utf-8', mode='w') discord_api_handler.setFormatter( logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')) discord_api_logger.addHandler(discord_api_handler) # set up SantaBot debug logging santabot_logger = logging.getLogger('SantaBot') santabot_logger.setLevel(logging.DEBUG) santabot_log_handler = logging.FileHandler(filename=CONFIG.dbg_path, encoding='utf-8', mode='w') santabot_log_handler.setLevel(logging.DEBUG) santabot_log_handler.setFormatter( logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')) santabot_logger.addHandler(santabot_log_handler) # add the cogs intents = Intents.default() intents.members = True bot = commands.Bot(command_prefix=CONFIG.prefix, intents=intents) bot.add_cog(SantaAdministrative(bot)) bot.add_cog(SantaMiscellaneous(bot)) bot.add_cog(SantaUtilities(bot, sqlitehelper)) bot.add_cog(SecretSanta(bot, config)) # kick off the bot bot.run(CONFIG.discord_token, reconnect=True)
def __init__(self, command_prefix, intent: Optional[Intents]=None): if not intent: intent = Intents.default() super().__init__(command_prefix, intent=intent) for cog in INITIAL_EXTENSIONS: try: self.load_extension(cog) except Exception: traceback.print_exc()
def main(): load_dotenv(verbose=True) setup_logging() # Extended intents are needed for retrieving user activities (Spotify) intents = Intents.default() intents.members = True intents.presences = True bot = DamaBot(intents=intents) bot.run(os.environ["DISCORD_TOKEN"])
def load_intents(): # load intents intents = Intents.default() intents.members = True intents.guilds = True intents.emojis = True intents.messages = True intents.guild_messages = True intents.dm_messages = True intents.reactions = True intents.guild_reactions = True return intents
def __init__(self, config: dict, *, intents: Intents = Intents.default()): super().__init__(command_prefix=config["command_prefix"], intents=intents) self.log = logging.getLogger(self.__class__.__name__) self.version = check_output( "git rev-parse --short HEAD".split(" ")).decode("utf-8").strip() self._config = config self._done_setup = False self.run(config["token"])
def __init__(self, *args, **kwargs): self.logger = logging.getLogger("mokiatu.core") self.logger.setLevel(logging.INFO) self.logger.info("Starting up...") intents = Intents.default() super().__init__( command_prefix='m.', intents=intents, help_command=Help(), activity=Game(name="m.help"), *args, **kwargs, )
def __init__(self, token): self.__TOKEN = token intents = Intents.default() intents.members = True activity = discord.Activity(type=discord.ActivityType.watching, name="over Numbani") self.__client = discord.Client(intents=intents, activity=activity) self.on_ready = self.__client.event(self.on_ready) self.on_message = self.__client.event(self.on_message) self.on_member_join = self.__client.event(self.on_member_join) self.__START = datetime.datetime.now() self.__filename = self.__START.strftime("%Y_%m_%d_%H_%M_%S") + ".log" self.__numBugs = 0 self.__numInstr = 0 self.__dbservice = DBService() self.__coreservice = CoreService() self.__channels = channels self.__roles = roles
def __init__(self, core) -> None: self.core = core bot_intents = Intents.default() bot_intents.members = True super().__init__( command_prefix=self.get_trigger_prefix, description="RPANBot: A bot helping link Discord and RPAN.", case_insensitive=True, intents=bot_intents, activity=Activity( type=ActivityType.watching, name=f"RPAN | {self.core.settings.links.site}", ), ) # Start a database session. self.db_session = self.core.db_handler.Session() # Load the modules. self.module_prefix = "discord.modules.{name}" modules = [ "general", "rpan", "events", "management", "developer", "notifications_watcher", "help_command", "tasks", ] for module in modules: try: self.load_extension(self.module_prefix.format(name=module)) print(f"DISCORD: Loaded {module}.") except Exception: print(f"DISCORD: Failed to load {module}.") print_exc() # Initiate some of the caches. self.prefix_cache = ExpiringDict(max_len=25, max_age_seconds=1800) self.excluded_user_cache = ExpiringDict(max_len=25, max_age_seconds=600)
def __init__( self, plugins_dir: str, roleplays_dir: str, admins: List[str], loop: Optional[BaseEventLoop] = None ): intents = Intents.default() intents.members = True super().__init__(intents=intents, loop=loop) self.admins = admins self.plugins_dir = plugins_dir self.roleplays_dir = roleplays_dir self.plugins = {} self.roleplays = {} self.chronicles = {} self.reload()
def __init__(self, *args, **kwargs): intents = Intents.default() intents.members = True super().__init__( command_prefix=self.get_prefix, intents=intents, allowed_mentions=AllowedMentions(everyone=False, users=False, roles=False), help_command=Help(), activity=Game(name="ping for prefix"), *args, **kwargs, ) self.session: Optional[ClientSession] = None self.db: Database = Database()
def main(args: List[str]): parser = argparse.ArgumentParser() parser.add_argument('configuration_file', help='the path to the desired bot configuration file') parse_result = vars(parser.parse_args(args)) with open(parse_result['configuration_file'], 'r') as config_file: try: config = json.load(config_file) except (ValueError, TypeError) as e: print(f'Encountered error loading configuration file: {e}') return 1 bot_intents = Intents.default() bot_intents.members = True bot = AIOSetupBot(backend_auth_token=config['backend_authorization_code'], command_prefix=config['bot_prefix'], fetch_offline_members=True, intents=bot_intents) bot.run(config['discord_bot_token']) print('bot exiting') return 0
def main(): if not DISCORD_TOKEN: print('The DISCORD_TOKEN variable is not set', file=sys.stderr) sys.exit(1) # guilds (get_channel) # members (get_member) # voice_states (VoiceChannel.members, voice_states) # guild_messages (on_reaction_add) # guild_reactions (..) intent = Intents.default() intent.guilds = True intent.members = True intent.voice_states = True intent.guild_messages = True intent.guild_reactions = True print(f'{intent=}') bot = Natalia(command_prefix='!', intent=intent) bot.run(DISCORD_TOKEN)
async def send_to_discord_async(token, userid, message): intents = DiscordIntents.default() intents.members = True client = DiscordClient(intents=intents) @client.event async def on_ready(userid=userid, message=message): user_found = False for user in client.get_all_members(): if ("%s#%s" % (user.name, user.discriminator) == userid and not user.bot): embed = DiscordEmbed() embed.description = message await user.send(embed=embed) user_found = True break if not user_found: logger.info("User %s not found by Discord bot" % userid) await client.close() await client.start(token)
def __init__(self, settings={}, console_variables={}): intents = Intents.default() intents.members = True super().__init__(intents=intents) self.settings = settings self.main_settings = settings.bot self.logger = set_up_logging(settings.bot.logs) self._event_handlers = defaultdict(list) self.commands = Commands(self) self.database = Database(self, self.main_settings.db_name) self.avatar_manager = AvatarManager(self, settings.bot.avatar) user_level.owner_usernames = self.main_settings.owner_usernames user_level.database = self.database console_variables['bot'] = self ConsoleInput(self, console_variables) if settings.bot.message_splitting.enabled: send_splitter.wrap(Messageable, settings.bot.message_splitting)
import asyncio import asyncpg from discord import AllowedMentions, Intents from . import constants from .bot import Bot from .help_command import Help db = asyncpg.create_pool(constants.DATABASE_URL) intents = Intents.default() intents.members = True intents.typing = False intents.voice_states = False bot = Bot(db, intents=intents, allowed_mentions=AllowedMentions(everyone=False), help_command=Help()) bot.load_extensions() bot.load_extension("jishaku") if __name__ == '__main__': bot.loop.run_until_complete(bot.start(constants.BOT_TOKEN))