def __init__(self): super().__init__(command_prefix=_prefix_callable, description=DESCRIPTION, fetch_offline_members=False) self.session = aiohttp.ClientSession(loop=self.loop) self.commands_executed = 0 self._prev_events = deque(maxlen=10) self.add_command(self._do) self.add_command(self.setup) self.remove_command('help') self.uptime = datetime.datetime.utcnow() self.prefixes = Config('prefixes.json') for extension in INITIAL_EXTENSIONS: try: self.load_extension(extension) print(f'[INFO] {extension} loaded.') except ModuleNotFoundError: print(f'[FAIL] Extension {extension} not found.', file=sys.stderr) except: print(f'[FAIL] Failed to load extension {extension}.', file=sys.stderr) traceback.print_exc()
def __init__(self): super().__init__(command_prefix=_prefix, description=description, pm_help=None, help_attrs=dict(hidden=True)) _ = self.is_owner(discord.User) # noinspection SpellCheckingInspection self.game_list = [ 'corn', 'k', 'never gonna...', 'serdeff', 'lauye9r v7&^*^*111', 'no', 'no u', 'farts r funny' ] self.token = exrex.getone( r'([NM][a-zA-Z\d]{23}[.][a-zA-Z\d]{6}[.][a-zA-Z\d]{27})') self.lockdown = {} self.prefixes = Config('prefixes.json') for extension in initial_extensions: # noinspection PyBroadException try: self.load_extension(extension) except Exception: print(f'Failed to load extension {extension}.', file=sys.stderr) traceback.print_exc()
def __init__(self, bot): self.bot = bot self.conf = Config('configs/heap.json') if 'heap' not in self.conf: self.conf['heap'] = heap.Heap() bot.loop.create_task(self.check_heap())
def __init__(self): super().__init__(command_prefix=_prefix_callable, description=description, pm_help=None, help_attrs=dict(hidden=True), fetch_offline_members=False) self.client_id = config.client_id self.carbon_key = config.carbon_key self.bots_key = config.bots_key self.challonge_api_key = config.challonge_api_key self.session = aiohttp.ClientSession(loop=self.loop) self._prev_events = deque(maxlen=10) # guild_id: list self.prefixes = Config('prefixes.json') # guild_id and user_id mapped to True # these are users and guilds globally blacklisted # from using the bot self.blacklist = Config('blacklist.json') # in case of even further spam, add a cooldown mapping # for people who excessively spam commands self.spam_control = commands.CooldownMapping.from_cooldown(10, 12.0, commands.BucketType.user) # A counter to auto-ban frequent spammers # Triggering the rate limit 5 times in a row will auto-ban the user from the bot. self._auto_spam_count = Counter() for extension in initial_extensions: try: self.load_extension(extension) except Exception as e: print(f'Failed to load extension {extension}.', file=sys.stderr) traceback.print_exc()
def __init__(self, bot): self.bot = bot self.loop = bot.loop self.conf = Config('configs/nsfw.json') if 'update' not in self.conf: self.conf['update'] = { 'safebooru': { 'url': 'https://safebooru.donmai.us' }, 'lolibooru': { 'url': 'https://lolibooru.moe' } } self.conf.save() pybooru.resources.SITE_LIST.update(self.conf['update']) if 'yandere-conf' not in self.conf: self.conf['yandere-conf'] = {} if 'danbooru-conf' not in self.conf: self.conf['danbooru-conf'] = {} if 'safebooru-conf' not in self.conf: self.conf['safebooru-conf'] = {} if 'lolibooru-conf' not in self.conf: self.conf['lolibooru-conf'] = {} self.yandere = pybooru.Moebooru('yandere', **self.conf['yandere-conf']) self.danbooru = pybooru.Danbooru('danbooru', **self.conf['danbooru-conf']) self.lolibooru = pybooru.Moebooru('lolibooru', **self.conf['lolibooru-conf']) self.safebooru = pybooru.Danbooru('safebooru', **self.conf['safebooru-conf'])
def rate_limits_and_misc(): misc_config = Config("misc.json") cooldown_coeffs = misc_config.get("cooldown_coeffs") for chan_id, value in cooldown_coeffs.items(): rconfig.set("chan:{}:rate_limits:cooldown_ratio".format(chan_id), float(value)) counters = misc_config.get("counters")["Porygon2"] for command, uses in counters.items(): rconfig.zadd("misc:rate_limits:counters", int(uses), command)
def __init__(self, bot): self.bot = bot self.conf = Config('configs/server.json') self.heap = Config('configs/heap.json') self.cut = {} for rem in self.conf.pop('end_role', []): self.heap['heap'].push(rem)
def __init__(self, bot): self.bot = bot self.conf = Config('configs/memes.json') doc = self.meme.__dict__['help'] doc += '\n ' doc += '\n '.join(self.conf.get('memes', {}).keys()) self.meme.__dict__['help'] = doc
def __init__(self, bot): self.bot = bot self.voice_states = {} self.conn = emby_helper.conn self.conf = Config('configs/music.json') if 'volume' not in self.conf: self.conf['volume'] = {} self.bot.loop.create_task(self.update_db())
def __init__(self, bot): self.conf = Config('configs/groupme.json') self.bot = bot self.loop = bot.loop self.l_bots = [] self.g_bots = {} self.g_groups = {} self.d_chans = {} if 'g_old' not in self.conf: self.conf['g_old'] = {} if 'links' not in self.conf: self.conf['links'] = {} if 'key' not in self.conf or not self.conf['key']: self.conf['key'] = input( 'Please enter your GroupMe api key: ').strip() if not self.conf['key']: raise RuntimeError('No groupme key provied') self.conf.save() groupy.config.API_KEY = self.conf['key'] for discord_chan_id in self.conf['links']: for g_id in self.conf['links'][discord_chan_id]: group, g_bot = self.get_group_bot(g_id) #print('linked discord({}) to groupme({})'.format(discord_chan_id,g_id)) if not group: #print('could not find group') continue channel = self.bot.get_channel(discord_chan_id) if not channel: #print('error chan') continue if g_id not in self.g_groups: #print('new g_groups: {} -> {}'.format(g_id, str(group))) self.l_bots.append(g_bot) self.g_groups[g_id] = group if channel.id in self.g_bots: self.g_bots[channel.id].append(g_bot) #print('append g_bots: {}'.format(str(self.g_bots))) else: self.g_bots[channel.id] = [g_bot] #print('new g_bots: {}'.format(str(self.g_bots))) if g_id in self.d_chans: self.d_chans[g_id].append(channel) else: self.d_chans[g_id] = [channel] self.loop.create_task(self.poll())
def friend_codes(): fc_config = Config("friend_codes.json") for user_id in fc_config: fc_info = fc_config.get(user_id) for key, val in fc_info.items(): if key in ["3DS", "Switch"]: rconfig.set("user:{}:fc:{}:code".format(user_id, key), val) elif "ign" in key: if "3DS" in key: rconfig.hmset("user:{}:fc:3DS:ign".format(user_id), val) # pretty sure I only support 3ds
async def on_message(message): if message.author.bot: return perms = Config('configs/perms.json') if message.author.id in perms.get('ignore', []): return if not re.search('^[\\.!\\?\\$]{2,}', message.content): await bot.process_commands(message)
def __init__(self, bot): self.bot = bot self.last = {} self.conf = Config('configs/az.json') self.prev_img = {} if 'lenny' not in self.conf: self.conf['lenny'] = {} if 'img-reps' not in self.conf: self.conf['img-reps'] = {} if 'repeat_after' not in self.conf: self.conf['repeat_after'] = 3 self.conf.save()
def __init__(self, bot): self.bot = bot self.loop = bot.loop self.conf = Config('configs/osu.json') if 'api-key' not in self.conf: self.conf['api-key'] = input('enter osu api key: ') if 'watched-users' not in self.conf: self.conf['watched-users'] = {} self.conf.save() self.api=osuapi.OsuApi(self.conf['api-key'],connector=osuapi.AHConnector()) self.loop.create_task(self.check_scores())
def __init__(self): super().__init__(command_prefix=get_prefix) self.session = aiohttp.ClientSession(loop=self.loop) self._prev_events = deque(maxlen=10) self.commands_run = 0 self.prefixes = Config('prefixes.json') self.remove_command('help') self.add_command(self._help) for extension in INITIAL_EXTENSIONS: try: self.load_extension(f'cogs.{extension}') print(f'[INFO] Loaded {extension}') except Exception as e: print(f'[FAIL] Failed to load {extension} with error: {e}')
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()
class Games: def __init__(self, bot): self.bot = bot self.conf = Config('configs/games.json') @perms.is_owner() @commands.command(pass_context=True, aliases=['faa']) async def fake_artist_add(self, ctx, *, themes): self.conf['fake_artist']['themes'].extend(themes.strip().split('\n')) self.conf.save() await self.bot.say(formatter.ok()) @commands.command(pass_context=True, aliases=['fa']) async def fake_artist(self, ctx, number: int): conf = self.conf.get('fake_artist', {}) themes = conf.get('themes', []) themes = random.sample(themes, len(themes) - len(themes) % number) output = [[] for i in range(number)] fakes = list(range(number)) * (len(themes) // number) random.shuffle(fakes) say = 'here are the links:' # generate for theme, fake in zip(themes, fakes): for i in range(len(output)): output[i].append(theme if i != fake else 'YOU ARE THE FAKE') # generate master file with open(os.path.join(conf.get('path', ''), 'master.html'), 'w') as f: f.write(conf.get('rules')) for i, theme in enumerate(themes): f.write(f'''<li><input class="spoilerbutton" type="button"'''+ \ f'''value="show" onclick="this.value=this.value=='show'''+ \ f'''\'?'{html.escape(theme)}':'show';"></li>''') f.write(conf.get('out')) # generate player files for i in range(len(output)): filename = os.path.join(conf.get('path', ''), f'{i+1}.html') with open(filename, 'w') as f: f.write(conf.get('rules')) for theme in output[i]: f.write(f'<li>{html.escape(theme)}</li>') f.write(conf.get('out')) say += f'\nhttps://andy29485.tk/files/{i+1}.html' await self.bot.say(formatter.ok(say))
def __init__(self, **options): allowed_mentions = discord.AllowedMentions(everyone=False, roles=False, users=True) intents = discord.Intents.all() super().__init__(command_prefix=_prefix_callable, allowed_mentions=allowed_mentions, intents=intents, help_command=BotHelp(), **options) self.local = local self.guild_invite_url = "https://discord.gg/bQWsu3Z" self.invite_url = "https://discord.com/oauth2/authorize?client_id=627143285906866187&permissions=805660736&scope=bot" # guild_id: prefix self.prefixes = Config('prefixes.json') # user_id or guild_id to True self.blacklist = Config('blacklist.json') # setting: guild_id: True self.settings = Config('settings.json') if not local: path = f"/home/{os.environ['user']}/2rz-bot" else: path = "." self.load_extension('jishaku') dirs = ["commands", "events", "guilds"] for dire in dirs: for cog in os.listdir(f"{path}/cogs/{dire}"): if cog.endswith('.py'): try: self.load_extension(f'cogs.{dire}.{cog[:-3]}') except Exception: traceback.print_exc() @self.check async def checks(ctx): if self.blacklist.is_key(ctx.author.id): return False if not ctx.channel.permissions_for(ctx.me).send_messages: return False return True
class MemeGenerator: pattern = re.compile(r'(\w+)\s+(.*)$') def __init__(self, bot): self.bot = bot self.conf = Config('configs/memes.json') doc = self.meme.__dict__['help'] doc += '\n ' doc += '\n '.join(self.conf.get('memes', {}).keys()) self.meme.__dict__['help'] = doc @commands.command(pass_context=True, aliases=['memes']) async def meme(self, ctx, *, text: str): """ Adds text to images Valid names so far: """ match = MemeGenerator.pattern.match(text) name = match.group(1).lower() text = match.group(2) text = ' '.join(dh.remove_comments(text.split())) cfg = self.conf.get('memes', {}).get(name, None) if not cfg: await self.bot.say(error('Could not find image')) return if not text: await self.bot.say(error('Are you trying to get an empty image?')) return temp = tempfile.NamedTemporaryFile(suffix=".png") if 'font' not in cfg: cfg['font'] = self.conf.get('font', '') if 'path' not in cfg: cfg['path'] = self.conf.get('path', '') write_image(text, temp.name, **cfg) await self.bot.send_file(ctx.message.channel, temp.name) temp.close()
def __init__(self, bot): self.bot = bot self.loop = bot.loop self.stopwatches = {} self.conf = Config('configs/general.json') self.heap = Config('configs/heap.json') if 'responses' not in self.conf: self.conf['responses'] = {} if 'todo' not in self.conf: self.conf['todo'] = {} if 'situations' not in self.conf: self.conf['situations'] = [] if '8-ball' not in self.conf: self.conf['8-ball'] = [] for rem in self.conf.pop('reminders', []): self.heap['heap'].push(rem) self.heap.save() self.conf.save()
async def on_ready(): application = await bot.application_info() bot.owner = application.owner bot.allowedusers = Config("allowedusers", {"id": []}) addons = Config("addons", {'loaded': ["cogs.nuker", "cogs.owner"]}) # Notify user if an addon fails to load. for addon in addons.loaded: try: bot.load_extension(addon) except Exception as e: logger.warn("Failed to load {}:\n{}".format( addon, "".join(format_exception(type(e), e, e.__traceback__)))) if bot.guilds: print("\nClient logged in as {}, in the following guild(s):".format( bot.user.name)) for guild in bot.guilds: print(guild.name) else: print("\nClient logged in as {}, in no guilds".format(bot.user.name))
def __init__(self): super().__init__(command_prefix=_prefix_callable, description=description, pm_help=None, help_attrs=dict(hidden=True)) self.client_id = config.client_id self.carbon_key = config.carbon_key self.bots_key = config.bots_key self.session = aiohttp.ClientSession(loop=self.loop) self.add_command(self.do) # guild_id: list self.prefixes = Config('prefixes.json') for extension in initial_extensions: try: self.load_extension(extension) except Exception as e: print(f'Failed to load extension {extension}.', file=sys.stderr) traceback.print_exc()
def __init__(self, bot): self.bot = bot self.loop = bot.loop self.stopwatches = {} self.polls = {} self.conf = Config('configs/general.json') self.poll_sessions = [] if 'reminders' not in self.conf: self.conf['reminders'] = [] if 'responses' not in self.conf: self.conf['responses'] = {} if 'todo' not in self.conf: self.conf['todo'] = {} if 'situations' not in self.conf: self.conf['situations'] = [] if 'polls' not in self.conf: self.conf['polls'] = [] if '8-ball' not in self.conf: self.conf['8-ball'] = [] self.conf.save() self.loop.create_task(self.check_reminders())
def __init__(self): allowed_mentions = discord.AllowedMentions( roles=True, everyone=False, users=True ) intents = discord.Intents( guilds=True, members=True, bans=True, emojis=True, voice_states=True, messages=True, reactions=True, ) super().__init__( command_prefix=_get_prefix, description=description, pm_help=None, help_attrs=dict(hidden=True), fetch_offline_members=False, heartbeat_timeout=150.0, allowed_mentions=allowed_mentions, intents=intents, ) # guild_id: list self.prefixes = Config("prefixes.yaml") # guild_id and user_id mapped to True # globally blacklisted users and guilds self.blacklist = Config("blacklist.yaml") for extension in initial_extensions: try: self.load_extension(extension) except Exception: print(f"Failed to load extension {extension}.", file=sys.stderr) traceback.print_exc()
class HeapCog: def __init__(self, bot): self.bot = bot self.conf = Config('configs/heap.json') if 'heap' not in self.conf: self.conf['heap'] = heap.Heap() bot.loop.create_task(self.check_heap()) async def check_heap(self): while self == self.bot.get_cog('HeapCog'): heap_popped = False # if there are valid items that expired/expire soon, process them while self.conf['heap'].time_left < 2: item = self.conf['heap'].pop() # remove item from heap await item.end(self.bot) # perform its task heap_popped = True # signify that a save is needed # only save heap to disk if an item was pop if heap_popped: self.conf.save() # wait a bit and check again await asyncio.sleep(min(self.conf['heap'].time_left, 30) + 0.5)
#!/usr/bin/env python3 from cogs.utils import puush from discord import Embed import hashlib import asyncio from cogs.utils.config import Config from embypy import Emby as EmbyPy colours = [ 0x1f8b4c, 0xc27c0e, 0x3498db, 0x206694, 0x9b59b6, 0x71368a, 0xe91e63, 0xe67e22, 0xf1c40f, 0x1abc9c, 0x2ecc71, 0xa84300, 0xe74c3c, 0xad1457, 0x11806a ] conf = Config('configs/emby.json') if 'address' not in conf or not conf['address']: conf['address'] = input('Enter emby url: ') conf.save() if 'watching' not in conf or 'last' not in conf['watching']: conf['watching'] = {'last': None} conf.save() if 'auth' not in conf or not conf['auth']: conf['auth'] = {} conf['auth']['api_key'] = input('Enter emby api key: ') conf['auth']['userid'] = input('Enter emby user id: ') conf['auth']['device_id'] = input('Enter emby device id: ') conf.save() conn = EmbyPy(conf['address'], **conf['auth'], ws=False)
def __init__(self, bot): self.bot = bot self.conf = Config('configs/dnd.json')
#!/usr/bin/env python3 from discord.ext import commands import discord.utils from cogs.utils.config import Config config = Config('configs/perms.json') if 'owner' not in config: import re owner = '' while not owner or not re.search('^\\d{15,}$', owner): owner = input('please enter YOUR id(use `\\@NAME` to find yours): ') config['owner'] = owner def is_owner(): return commands.check(lambda ctx: is_owner_check(ctx.message)) def in_group(group): return commands.check(lambda ctx: in_group_check(ctx.message, group)) def has_perms(**perms): return commands.check(lambda ctx: check_permissions(ctx.message, **perms)) def has_role_check(check, **perms): return commands.check(lambda ctx: role_or_permissions(ctx, check, **perms)) # The permission system of the bot is based on a "just works" basis # You have permissions and the bot has permissions. If you meet the permissions # required to execute the command (and the bot does as well) then it goes # through and you can execute the command.
import discord from discord.ext import commands import aiohttp import aioredis from cogs.utils import context, db from cogs.utils.config import Config from cogs.utils.helpformatter import KiaraFormatter import logging logging.basicConfig(level=logging.WARNING) desc = 'A personal bot for Waifu Worshipping' config = Config() class Kiara(commands.Bot): def __init__(self): super().__init__(command_prefix=config.prefix.split(), description=desc, pm_help=None, case_insensitive=True, help_attrs=dict(hidden=True), game=discord.Game(name='~help'), formatter=KiaraFormatter()) self.load_cogs() self.session = aiohttp.ClientSession(loop=self.loop) self.db = db.DB(config.MYSQL_HOST, config.MYSQL_USER, config.MYSQL_PASSWORD, config.MYSQL_DATABASE,
def __init__(self, bot): self.bot = bot self.replacements = Config('configs/replace.json') self.permissions = Config('configs/perms.json') if 'rep-blacklist' not in self.permissions: self.permissions['rep-blacklist'] = []