async def password(self, ctx, *, msg): """Set your discord acc password to rotate avatars. See wiki for more info.""" avi_config = dataIO.load_json('settings/avatars.json') avi_config['password'] = msg.strip().strip('"').lstrip('<').rstrip('>') dataIO.save_json('settings/avatars.json', avi_config) opt = dataIO.load_json('settings/optional_config.json') opt['password'] = avi_config['password'] dataIO.save_json('settings/optional_config.json', opt) await ctx.message.delete() return await ctx.send(self.bot.bot_prefix + 'Password set. Do ``>avatar`` to toggle cycling avatars.')
def custom(message): success = False config = dataIO.load_json('settings/config.json') customcmd_prefix_len = len(config['customcmd_prefix']) if message.startswith(config['customcmd_prefix']): commands = dataIO.load_json('settings/commands.json') found_cmds = {} for i in commands: if message[customcmd_prefix_len:].lower().startswith(i.lower()): found_cmds[i] = len(i) if found_cmds != {}: match = max(found_cmds, key=found_cmds.get) # If the commands resulting reply is a list instead of a str if type(commands[match]) is list: try: # If index from list is specified, get that result. if message[len(match) + customcmd_prefix_len:].isdigit(): index = int(message.content[len(match) + customcmd_prefix_len:].strip()) else: title = message[len(match) + customcmd_prefix_len:] for b, j in enumerate(commands[match]): if j[0].lower() == title.lower().strip(): index = int(b) break mimetype, encoding = mimetypes.guess_type(commands[match][index][1]) # If value is an image, send as embed if mimetype and mimetype.startswith('image'): return 'embed', commands[match][index][1] else: return 'message', commands[match][index][1] except: # If the index is not specified, get a random index from list index = randint(0, len(commands[match]) - 1) mimetype, encoding = mimetypes.guess_type(commands[match][index][1]) # If value is an image, send as embed if mimetype and mimetype.startswith('image'): return 'embed', commands[match][index][1] else: return 'message', commands[match][index][1] else: mimetype, encoding = mimetypes.guess_type(commands[match]) # If value is an image, send as embed if mimetype and mimetype.startswith('image'): return 'embed', commands[match] else: return 'message', commands[match] if success is True: return None
async def _now(self, context, *username: str): """Shows the current played song""" if self.api_key != '': if not username: settings = dataIO.load_json(self.settings_file) if context.message.author.id in settings['USERS']: username = settings['USERS'][context.message.author.id] else: user_patch = username[0].replace('!', '') settings = dataIO.load_json(self.settings_file) if user_patch[2:-1] in settings['USERS']: username = settings['USERS'][user_patch[2:-1]] else: username = user_patch try: payload = self.payload payload['method'] = 'user.getRecentTracks' payload['username'] = username payload['limit'] = 1 data = await self._api_request(payload) except Exception as e: message = 'Something went terribly wrong! [{}]'.format(e) if 'error' in data: message = '{}'.format(data['message']) await self.bot.say(message) else: user = data['recenttracks']['@attr']['user'] track = data['recenttracks']['track'][0] try: if track['@attr']['nowplaying'] == 'true': artist = track['artist']['#text'] song = track['name'] url = await self._url_decode(track['url']) image = track['image'][-1]['#text'] author = context.message.author em = discord.Embed(url=url) avatar = author.avatar_url if author.avatar else author.default_avatar_url em.set_author(name='{} - {}'.format(artist, song), icon_url=avatar) if not self.bot.get_cog('YouTube'): em.set_image(url=image) await self.bot.say(embed=em) if self.bot.get_cog('YouTube'): await context.invoke(self.bot.get_cog('YouTube')._youtube, query='{} - {}'.format(artist, song)) except KeyError: await self.bot.say('{} is not playing any song right now'.format(user)) else: message = 'No API key set for Last.fm. Get one at http://www.last.fm/api' await self.bot.say(message)
async def _topalbums(self, context, *username: str): """Shows most played albums""" if self.api_key != '': if not username: settings = dataIO.load_json(self.settings_file) if context.message.author.id in settings['USERS']: username = settings['USERS'][context.message.author.id] else: user_patch = username[0].replace('!', '') settings = dataIO.load_json(self.settings_file) if user_patch[2:-1] in settings['USERS']: username = settings['USERS'][user_patch[2:-1]] else: username = user_patch try: payload = self.payload payload['limit'] = '11' payload['method'] = 'user.getTopAlbums' payload['username'] = username data = await self._api_request(payload) except Exception as e: message = 'Something went terribly wrong! [{}]'.format(e) if 'error' in data: message = data['message'] await self.bot.say(message) else: user = data['topalbums']['@attr']['user'] author = context.message.author l = '' for i, album in enumerate(data['topalbums']['album'], 1): albums = album['name'] artist = album['artist']['name'] url = await self._url_decode(album['url']) plays = album['playcount'] if i < 10: l += '`{}`\t **[{}]({})** by **({})** ({} plays)\n'.format(str(i), albums, url, artist, plays) elif i > 10: break else: l += '`{}`\t**[{}]({})** by **({})** ({} plays)\n'.format(str(i), albums, url, artist, plays) em = discord.Embed(description=l, url='http://www.last.fm/user/{}/library/albums'.format(user)) avatar = author.avatar_url if author.avatar else author.default_avatar_url em.set_author(name='Top Albums by {}'.format(user), icon_url=avatar) await self.bot.say(embed=em) else: message = 'No API key set for Last.fm. Get one at http://www.last.fm/api' await self.bot.say(message)
async def _del(self, ctx, channel: discord.Channel=None): """Lists regexes used to filter messages""" server = ctx.message.server self.regexen = dataIO.load_json(JSON_PATH) if not self._re_present(server): await self.bot.say('There are no filter patterns set for this server.') return re_list = {} i = 1 table = ' | '.join(['#'.ljust(4), 'mode', 'pattern']) + '\n' # header for c in self.regexen[server.id]: if c == ALL_CHANNELS or (channel and channel.id == c) or not channel: if c == ALL_CHANNELS: if self._re_present(ALL_CHANNELS): table += '\nServer-wide:\n' else: if not channel: channel = self.bot.get_channel(c) if self._re_present(channel): table += '\n#' + channel.name + '\n' for regex, mode in self.regexen[server.id][c].items(): table += ' | '.join([str(i).ljust(4), mode, regex]) + '\n' re_list[str(i)] = (server.id, c, regex) i += 1 prompt = 'Choose the number of the pattern to delete:\n' await self.bot.say(prompt + '```py\n' + table + '```') msg = await self.bot.wait_for_message(author=ctx.message.author, timeout=15) if msg is None: return msg = msg.content.strip() if msg in re_list: sid, cid, regex = re_list[msg] del(self.regexen[sid][cid][regex]) await self.bot.say('Pattern removed.') dataIO.save_json(JSON_PATH, self.regexen)
def __init__(self, bot): self.bot = bot self.path = "data/the100" self.json = self.path + "/db.json" self.db = dataIO.load_json(self.json) self.session = aiohttp.ClientSession(loop=bot.loop) self.headers = {"Authorization": "Token token=\"{}\"", "content-type": "application/json"}
async def now(self, ctx): """Date time module.""" opt = dataIO.load_json('settings/optional_config.json') thebool = True try: if opt['24hours'] == "true": thebool = True else: thebool = False except IndexError: # No 24 hour bool given so default to true pass dandt, tzerror = self.get_datetime() if embed_perms(ctx.message): em = discord.Embed(color=discord.Color.blue()) if thebool: em.add_field(name=u'\u23F0 Time', value="{:%H:%M:%S}".format(dandt), inline=False) else: em.add_field(name=u'\u23F0 Time', value="{:%I:%M:%S %p}".format(dandt), inline=False) em.add_field(name=u'\U0001F4C5 Date', value="{:%d %B %Y}".format(dandt), inline=False) if tzerror: em.add_field(name=u'\u26A0 Warning', value="Invalid timezone specified, system timezone was used instead.", inline=False) await ctx.send(content=None, embed=em) else: msg = '**Local Date and Time:** ```{:Time: %H:%M:%S\nDate: %Y-%m-%d```}'.format(dandt) await ctx.send(self.bot.bot_prefix + msg) await ctx.message.delete()
def __init__(self, bot): self.bot = bot self.location = 'data/punish/settings.json' self.json = dataIO.load_json(self.location) self.handles = {} self.role_name = 'Punished' bot.loop.create_task(self.on_load())
async def _get(self, context, channel: discord.Channel, number: int): """[channel] [number]""" data = dataIO.load_json(self.ignore_file) current_server = context.message.server.id current_channel = channel.id if current_server not in data: data[current_server] = [] if current_channel not in data[current_server]: log = [] try: async for message in self.bot.logs_from(channel, limit=number): author = message.author content = message.clean_content timestamp = str(message.timestamp)[:-7] log_msg = '[{}] {} ({}): {}'.format(timestamp, author.name, author.id, content) log.append(log_msg) try: t = self.file.format(str(time()).split('.')[0]) with open(t, encoding='utf-8', mode="w") as f: for message in log[::-1]: f.write(message+'\n') f.close() await self.bot.send_file(context.message.channel, t) os.remove(t) except Exception as error: print(error) except discord.errors.Forbidden: await self.bot.say('Nope can\'t do, I don\'t have permission you savage!')
def __init__(self, *args, **kwargs): def prefix_manager(bot, message): """ Returns prefixes of the message's server if set. If none are set or if the message's server is None it will return the global prefixes instead. Requires a Bot instance and a Message object to be passed as arguments. """ return bot.settings.get_prefixes(message.server) self.counter = Counter() self.uptime = datetime.datetime.utcnow() # Refreshed before login self._message_modifiers = [] self.settings = Settings() self._intro_displayed = False self._shutdown_mode = None self.logger = set_logger(self) self._last_exception = None self.oauth_url = "" try: self._cog_registry = dataIO.load_json("data/red/cogs.json") except Exception: self._cog_registry = {} if 'self_bot' in kwargs: self.settings.self_bot = kwargs['self_bot'] else: kwargs['self_bot'] = self.settings.self_bot if self.settings.self_bot: kwargs['pm_help'] = False super().__init__(*args, command_prefix=prefix_manager, **kwargs)
def __init__(self, bot): self.bot = bot self.config = dataIO.load_json('data/sentryio/config.json') self.clientid = self.config.get("clientid", "") self.raven = None self.load_sentry()
def __init__(self, bot): self.bot = bot self.path = "data/downloader/" self.file_path = "data/downloader/repos.json" # {name:{url,cog1:{installed},cog1:{installed}}} self.repos = dataIO.load_json(self.file_path) self.executor = ThreadPoolExecutor(NUM_THREADS) self._do_first_run()
def __init__(self, bot): self.bot = bot self.location = 'data/punish/settings.json' self.json = dataIO.load_json(self.location) self.min = ['m', 'min', 'mins', 'minutes', 'minute'] self.hour = ['h', 'hour', 'hours'] self.day = ['d', 'day', 'days'] self.task = bot.loop.create_task(self.check_time())
def check_files(): if not os.path.isfile(SETTINGS): print("Creating default imdb settings.json...") dataIO.save_json(SETTINGS, DEFAULT) else: # Consistency check try: current = dataIO.load_json(SETTINGS) except JSONDecodeError: dataIO.save_json(SETTINGS, DEFAULT) current = dataIO.load_json(SETTINGS) if current.keys() != DEFAULT.keys(): for key in DEFAULT.keys(): if key not in current.keys(): current[key] = DEFAULT[key] print( "Adding " + str(key) + " field to imdb settings.json") dataIO.save_json(SETTINGS, DEFAULT)
async def _info(self, context, *username: str): """Retrieve general information""" if self.api_key != '': if not username: settings = dataIO.load_json(self.settings_file) if context.message.author.id in settings['USERS']: username = settings['USERS'][context.message.author.id] else: user_patch = username[0].replace('!', '') settings = dataIO.load_json(self.settings_file) if user_patch[2:-1] in settings['USERS']: username = settings['USERS'][user_patch[2:-1]] else: username = user_patch try: payload = self.payload payload['method'] = 'user.getInfo' payload['username'] = username data = await self._api_request(payload) except Exception as e: message = 'Something went terribly wrong! [{}]'.format(e) if 'error' in data: message = '{}'.format(data['message']) await self.bot.say(message) else: user = data['user']['name'] playcount = data['user']['playcount'] registered = datetime.datetime.fromtimestamp(data['user']['registered']['#text']).strftime('%Y-%m-%d') image = data['user']['image'][1]['#text'] author = context.message.author em = discord.Embed(url='http://www.last.fm/user/{}'.format(user), description='\a\n') avatar = author.avatar_url if author.avatar else author.default_avatar_url em.set_author(name='Last.fm profile of {} ({})'.format(user, author.name), icon_url=avatar) if 'realname' in data['user']: realname = data['user']['realname'] em.add_field(name='Name', value=realname) if 'country' in data['user']: if data['user']['country']: em.add_field(name='Country', value=data['user']['country']) em.add_field(name='Scrobbles', value=playcount) em.add_field(name='Registered', value=registered) em.set_thumbnail(url=image) await self.bot.say(embed=em) else: message = 'No API key set for Last.fm. Get one at http://www.last.fm/api' await self.bot.say(message)
async def _api(self, context, key: str): """Set an API key for this cog. Get one at: """ data = dataIO.load_json(self.settings_file) data['API_KEY'] = key self.key = key message = 'API Key set' dataIO.save_json(self.settings_file, data) await self.bot.say('*{}*'.format(message))
def _load_perms(self): try: ret = dataIO.load_json("data/permissions/perms.json") except: ret = {} os.mkdir("data/permissions") dataIO.save_json("data/permissions/perms.json", ret) return ret
def load_cogs(): try: if sys.argv[1] == "--no-prompt": no_prompt = True else: no_prompt = False except: no_prompt = False try: registry = dataIO.load_json("data/red/cogs.json") except: registry = {} bot.load_extension('cogs.owner') owner_cog = bot.get_cog('Owner') if owner_cog is None: print("You got rid of the damn OWNER cog, it has special functions" " that I require to run.\n\n" "I can't start without it!") print() print("Go here to find a new copy:\n{}".format( "https://github.com/Twentysix26/Red-DiscordBot")) exit(1) failed = [] extensions = owner_cog._list_cogs() for extension in extensions: if extension.lower() == "cogs.owner": continue in_reg = extension in registry if not (in_reg or no_prompt): print("\nNew extension: {}".format(extension)) print("Load it?(y/n)") if not get_answer(): registry[extension] = False continue registry[extension] = True if not registry[extension]: continue try: owner_cog._load_cog(extension) except Exception as e: print("{}: {}".format(e.__class__.__name__, str(e))) logger.exception(e) failed.append(extension) registry[extension] = False if extensions: dataIO.save_json("data/red/cogs.json", registry) if failed: print("\nFailed to load: ", end="") for m in failed: print(m + " ", end="") print("\n") return owner_cog
def user_post(key_users, user): if time.time() - float(key_users[user][0]) < float(key_users[user][1]): return False, [time.time(), key_users[user][1]] else: log = dataIO.load_json("settings/log.json") now = time.time() log["keyusers"][user] = [now, key_users[user][1]] dataIO.save_json("settings/log.json", log) return True, [now, key_users[user][1]]
def __init__(self, bot): self.bot = bot self.events = dataIO.load_json(JSON) self.queue = asyncio.PriorityQueue(loop=self.bot.loop) self.queue_lock = asyncio.Lock() self.pending = {} self.pending_by_event = defaultdict(lambda: list()) self._load_events() self.task = bot.loop.create_task(self.queue_manager())
def __init__(self, bot): self.bot = bot self.settings_file = 'data/lastfm/lastfm.json' settings = dataIO.load_json(self.settings_file) self.api_key = settings['LASTFM_API_KEY'] self.payload = {} self.payload['api_key'] = self.api_key self.payload['format'] = 'json'
def __init__(self, bot): self.bot = bot self.disclaimer_accepted = False self.path = os.path.join("data", "downloader") self.file_path = os.path.join(self.path, "repos.json") # {name:{url,cog1:{installed},cog1:{installed}}} self.repos = dataIO.load_json(self.file_path) self.executor = ThreadPoolExecutor(NUM_THREADS) self._do_first_run()
def _load_loyalty(self, file_path, achievement): self.accounts = dataIO.load_json(file_path) for key_server, value_server in self.accounts.items(): self.accounts[key_server] = {} for key_user, value_user in value_server.items(): self.accounts[key_server][key_user] = {} for key_achievement, value_achievement in value_user.items(): temp = self.accounts[key_server][key_user][key_achievement]._current self.accounts[key_server][key_user][key_achievement] = achievement(current=temp)
async def _apikey(self, context, *key: str): """Sets the Last.fm API key - for bot owner only.""" settings = dataIO.load_json(self.settings_file) if key: settings['LASTFM_API_KEY'] = key[0] self.api_key = key[0] dataIO.save_json(self.settings_file, settings) await self.bot.say('**Done**') else: await self.bot.say('**I need more than that!**')
def __init__(self, bot): self.bot = bot # load to-do list in from file todo_list = dataIO.load_json("settings/todo.json") for i in todo_list: if type(todo_list[i]) is str: todo_list[i] = [todo_list[i], i, 0, True, 0, 0] dataIO.save_json("settings/todo.json", todo_list) self.todo_list = todo_list
def _unpunish_data(self, member): """Removes punish data entry and cancels any present callback""" self.json = dataIO.load_json(self.location) sid = member.server.id if sid in self.json and member.id in self.json[sid]: del(self.json[member.server.id][member.id]) dataIO.save_json(self.location, self.json) if sid in self.handles and member.id in self.handles[sid]: self.handles[sid][member.id].cancel() del(self.handles[member.server.id][member.id])
def __init__(self, bot): self.bot = bot self.levels = [ "debug", "warning", "critical", "info", "error", "notset" ] self._saved_levels = dataIO.load_json('data/logger/saved_levels.json')
def get_info_data(self, repo_name, cog=None): if cog is not None: cogs = self.list_cogs(repo_name) if cog in cogs: info_file = os.path.join(cogs[cog].get('folder'), "info.json") if os.path.isfile(info_file): try: data = dataIO.load_json(info_file) except: return None return data else: repo_info = os.path.join(self.path, repo_name, 'info.json') if os.path.isfile(repo_info): try: data = dataIO.load_json(repo_info) return data except: return None return None
def __init__(self, bot): global default_settings self.bot = bot self.bank = Bank(bot, "data/economy/bank.json") self.file_path = "data/economy/settings.json" self.settings = dataIO.load_json(self.file_path) if "PAYDAY_TIME" in self.settings: # old format default_settings = self.settings self.settings = {} self.settings = defaultdict(lambda: default_settings, self.settings) self.payday_register = defaultdict(dict) self.slot_register = defaultdict(dict)
def __init__(self, bot): self.bot = bot self.settings = dataIO.load_json('data/githubcards/settings.json') if 'Mod' not in bot.cogs: log.info('GithubCards: Mod not loaded, will not ignore channels') self.ignore = False else: self.ignore = True self.colour = { 'open': 0x6cc644, 'closed': 0xbd2c00, 'merged': 0x6e5494 }
def __init__(self, bot): self.bot = bot self.session = aiohttp.ClientSession(loop=self.bot.loop) self.apifile = "data/Cleverio/apikey.json" self.api = dataIO.load_json(self.apifile) self.clever = None
def set_cog(cog, value): # TODO: move this out of red.py data = dataIO.load_json("data/red/cogs.json") data[cog] = value dataIO.save_json("data/red/cogs.json", data)
def __init__(self, bot): self.bot = bot self.users_loc = "data/userprofiles/users.json" self.users = dataIO.load_json(self.users_loc)
def __init__(self, bot): self.bot = bot self.settings = dataIO.load_json(JSON) self.task = bot.loop.create_task(self.loop_task())
def __init__(self, bot): self.bot = bot self.filter = dataIO.load_json('data/whitelist/whitelist.json')
def __init__(self, bot): self.bot = bot self.profile = 'data/melon/melon.json' self.riceCog = dataIO.load_json(self.profile)
def __init__(self, bot): self.bot = bot if not os.path.exists('settings/server_mute.json'): dataIO.save_json('settings/server_mute.json', []) self.mute_data = dataIO.load_json('settings/server_mute.json')
async def on_command_error(self, ctx, error): asdf = dataIO.load_json(self.setting) dddd = self.bot.get_user(431085681847042048) asdf = lang({"_id": ctx.guild.id}) try: if asdf['language'] == 'ko': data = dataIO.load_json(self.ko) else: data = dataIO.load_json(self.en) except: data = dataIO.load_json(self.en) if isinstance(error, commands.CommandInvokeError): # A bit hacky, couldn't find a better way no_dms = "Cannot send messages to this user" is_help_cmd = ctx.command.qualified_name == "help" is_forbidden = isinstance(error.original, discord.Forbidden) if is_help_cmd and is_forbidden and error.original.text == no_dms: msg = ( "당신에게 DM으로 보내드리려고 했는데 전송이 안되요! DM차단을 풀어주시면 다시 시도 하시면 보내드리겠어요!\nI was going to send it to you by DM, but it's not! If you untie the DM block, I'll send it to you!" ) await ctx.send(msg) return log = "".join( traceback.format_exception(type(error), error, error.__traceback__)) for page in pagify(log): asdf = f'```py\n{log}\n```' embed = discord.Embed( title=f'{ctx.command.qualified_name} 명령어에 에러가 발생하였습니다!', colour=discord.Colour.green()) embed.add_field(name='유저', value=ctx.author) embed.add_field(name='서버', value=ctx.guild) await ctx.send( '에러 내용을 봇 관리진에게 보냈습니다! 빠른 시일내에 고치도록 하겠습니다!\nI send Error code to Bot Administrator! I will fix that!' ) print(asdf) elif isinstance(error, commands.CommandNotFound): blacklist = dataIO.load_json('blacklist.json') try: if str(ctx.author.id) in blacklist['blacklist']: em = discord.Embed(colour=discord.Colour.green()) em.add_field( name='당신은 키위봇 블랙리스트입니다!', value= f'당신은 키위봇 버그를 악용 혹은 악성 유저로 생각되어 키위봇 개발자에 의해 블랙리스트에 추가되었습니다!\n문의를 하시려면 {dddd} ({dddd.id}로 문의해주시기 바랍니다!)' ) return await ctx.send(embed=em) except KeyError: pass lan = data['command_none'] em = discord.Embed(colour=ctx.author.colour) em.add_field(name=lan['1'], value=lan['2'].format(ctx)) em.set_footer(text=lan['3']) return await ctx.send(embed=em) elif isinstance(error, commands.CheckFailure): lan = data['admin_command'] em = discord.Embed(colour=ctx.author.colour) em.add_field(name=lan['1'], value=lan['2'].format(ctx)) em.set_footer(text=lan['3']) return await ctx.send(embed=em) elif isinstance(error, commands.CommandOnCooldown): asdf = time.strftime("%M", time.gmtime(error.retry_after)) asss = time.strftime("%S", time.gmtime(error.retry_after)) em = discord.Embed(colour=ctx.author.colour) em.add_field( name='쿨타임 발생!', value=f'이 명령어 에는 쿨타임이 걸려있습니다!\n`{asdf}분 {asss}초` 후에 다시 시도 해주세요!' ) return await ctx.send(ctx.author.mention, embed=em) elif isinstance(error, commands.CommandError): if not ctx.author.web_status == 'offline': return
def __init__(self, bot): self.bot = bot self.pressfcount = dataIO.load_json("data/pressf/pressf.json")
def set_play(self, boolean): self.is_playing = boolean self.settings = dataIO.load_json(SETTINGS_JSON) self.settings['playing'] = self.is_playing dataIO.save_json(SETTINGS_JSON, self.settings)
async def crclip(self, ctx, filename=None, times=1,user:discord.User=None): ''' syntax: filename must be a filename in my folder or filenames in my folder, separated by a / times must be a number or it will just do it once user must be a mention, id, username and it will find the voice channel in the server where the user is, and play it to them. specifying user only works for mods. ''' # print('checking') # print(await ctx.invoke(self.perm_to_join_to_user)) server = ctx.message.server mod_role = settings.get_server_mod(server) admin_role = settings.get_server_admin(server) mod_or_admin = False roles = list(map(lambda x: x.name, ctx.message.author.roles)) mod_or_admin = admin_role in roles or mod_role in roles or checks.is_owner_check(ctx) if user == None or not mod_or_admin: user = ctx.message.author filenames = [] if filename == None: await self.bot.say("You must specify a filename to play") return if '/' in filename: filenames = filename.split('/') else: filenames = [filename] for name in filenames: if name + self.exten not in os.listdir(AUDIOPATH) and name + self.exten not in os.listdir(TTSPATH): await self.bot.say("The file, `{}` is not saved in the audio folder.".format(name+self.exten)) return try: client = await self.connect_with_user(ctx,user) except UserNotConnected as e: await self.bot.say(e.msg) return filenames = list(map(lambda filename:os.path.join(AUDIOPATH if filename +self.exten in os.listdir(AUDIOPATH) else TTSPATH, filename + self.exten), filenames)) try: times = int(times) except: times = 1 if times>5: times=5 elif times<1: times=1 self.is_playing = dataIO.load_json(SETTINGS_JSON)['playing'] if self.is_playing: await self.bot.say("You may not play anything if it is already playing something.") return self.set_play(True) dataIO.save_json(SETTINGS_JSON, self.settings) n = 0 if times==1: for name in filenames: if n>0: while player.is_playing(): await asyncio.sleep(.2) player = client.create_ffmpeg_player(name) player.start() n += 1 else: for x in range(times): for name in filenames: if n>0: while player.is_playing(): await asyncio.sleep(.2) player = client.create_ffmpeg_player(name) player.start() n += 1 while player.is_playing(): await asyncio.sleep(.2) self.set_play(False)
def __init__(self, bot): self.bot = bot self.quotes = dataIO.load_json(JSON) self.analytics = CogAnalytics(self)
def __init__(self, bot): self.bot = bot self.settings = dataIO.load_json('data/reporttool/settings.json') for s in self.settings: self.settings[s]['usercache'] = []
def __init__(self, bot): self.bot = bot self.settings = dataIO.load_json('data/imgwelcome/settings.json') self.version = "0.1.8" self.session = aiohttp.ClientSession()
def __init__(self, bot): self.bot = bot self.settings = dataIO.load_json(JSON)
def __init__(self, bot): self.bot = bot self.settings = dataIO.load_json("data/marry/settings.json")
def __init__(self, bot): self.bot = bot self.settings = dataIO.load_json('data/repl/settings.json') self.output_file = "data/repl/temp_output.txt" self.sessions = set() self.reaction_remove_events = {}
def __init__(self, bot): self.bot = bot self.settings = dataIO.load_json('data/wolfram/settings.json') self.session = aiohttp.ClientSession()
def __init__(self, bot): """Init.""" self.bot = bot self.settings = nested_dict() self.settings.update(dataIO.load_json(SETTINGS_JSON))
def __init__(self, bot): """Constructor.""" self.bot = bot self.settings = dataIO.load_json(JSON)
def __init__(self, bot, file_path): self.accounts = dataIO.load_json(file_path) self.bot = bot
def __init__(self, bot): self.bot = bot self.settings_file = 'data/goodreads/settings.json' self.gateway = 'https://www.goodreads.com/book/{}.xml?' self.payload = {} self.key = dataIO.load_json(self.settings_file)['API_KEY']
def __init__(self, bot): self.bot = bot self.settings = dataIO.load_json(JSON) self.handles = {} self.lock = False self.session = aiohttp.ClientSession(loop=self.bot.loop)
def __init__(self, bot): self.bot = bot self.bot.remove_command("help") self.file = "data/customhelp/settings.json" self.customhelp = dataIO.load_json(self.file)
def __init__(self, bot): self.bot = bot try: self.settings = dataIO.load_json(path + '/settings.json') except Exception: self.settings = {}
def __init__(self, bot): self.bot = bot self.regexen = dataIO.load_json(JSON_PATH) self.recache = {} self.analytics = CogAnalytics(self) bot.loop.create_task(self.compile_regexen())
def __init__(self, bot): self.bot = bot self.settings = dataIO.load_json(SETTINGS) self.cache = dataIO.load_json(CACHE) # These should be supported by translated.net (RFC3066) self.ISO_LANG = [["Abkhazian", "AB"], ["Afar", "AA"], ["Afrikaans", "AF"], ["Albanian", "SQ"], ["Amharic", "AM"], ["Arabic", "AR"], ["Armenian", "HY"], ["Assamese", "AS"], ["Aymara", "AY"], ["Azerbaijani", "AZ"], ["Bashkir", "BA"], ["Basque", "EU"], ["Bengali, Bangla", "BN"], ["Bhutani", "DZ"], ["Bihari", "BH"], ["Bislama", "BI"], ["Breton", "BR"], ["Bulgarian", "BG"], ["Burmese", "MY"], ["Byelorussian", "BE"], ["Cambodian", "KM"], ["Catalan", "CA"], ["Chinese", "ZH"], ["Corsican", "CO"], ["Croatian", "HR"], ["Czech", "CS"], ["Danish", "DA"], ["Dutch", "NL"], ["English, American", "EN"], ["Esperanto", "EO"], ["Estonian", "ET"], ["Faeroese", "FO"], ["Fiji", "FJ"], ["Finnish", "FI"], ["French", "FR"], ["Frisian", "FY"], ["Gaelic (Scots Gaelic)", "GD"], ["Galician", "GL"], ["Georgian", "KA"], ["German", "DE"], ["Greek", "EL"], ["Greenlandic", "KL"], ["Guarani", "GN"], ["Gujarati", "GU"], ["Hausa", "HA"], ["Hebrew", "IW"], ["Hindi", "HI"], ["Hungarian", "HU"], ["Icelandic", "IS"], ["Indonesian", "IN"], ["Interlingua", "IA"], ["Interlingue", "IE"], ["Inupiak", "IK"], ["Irish", "GA"], ["Italian", "IT"], ["Japanese", "JA"], ["Javanese", "JW"], ["Kannada", "KN"], ["Kashmiri", "KS"], ["Kazakh", "KK"], ["Kinyarwanda", "RW"], ["Kirghiz", "KY"], ["Kirundi", "RN"], ["Korean", "KO"], ["Kurdish", "KU"], ["Laothian", "LO"], ["Latin", "LA"], ["Latvian, Lettish", "LV"], ["Lingala", "LN"], ["Lithuanian", "LT"], ["Macedonian", "MK"], ["Malagasy", "MG"], ["Malay", "MS"], ["Malayalam", "ML"], ["Maltese", "MT"], ["Maori", "MI"], ["Marathi", "MR"], ["Moldavian", "MO"], ["Mongolian", "MN"], ["Nauru", "NA"], ["Nepali", "NE"], ["Norwegian", "NO"], ["Occitan", "OC"], ["Oriya", "OR"], ["Oromo, Afan", "OM"], ["Pashto, Pushto", "PS"], ["Persian", "FA"], ["Polish", "PL"], ["Portuguese", "PT"], ["Punjabi", "PA"], ["Quechua", "QU"], ["Rhaeto-Romance", "RM"], ["Romanian", "RO"], ["Russian", "RU"], ["Samoan", "SM"], ["Sangro", "SG"], ["Sanskrit", "SA"], ["Serbian", "SR"], ["Serbo-Croatian", "SH"], ["Sesotho", "ST"], ["Setswana", "TN"], ["Shona", "SN"], ["Sindhi", "SD"], ["Singhalese", "SI"], ["Siswati", "SS"], ["Slovak", "SK"], ["Slovenian", "SL"], ["Somali", "SO"], ["Spanish", "ES"], ["Sudanese", "SU"], ["Swahili", "SW"], ["Swedish", "SV"], ["Tagalog", "TL"], ["Tajik", "TG"], ["Tamil", "TA"], ["Tatar", "TT"], ["Tegulu", "TE"], ["Thai", "TH"], ["Tibetan", "BO"], ["Tigrinya", "TI"], ["Tonga", "TO"], ["Tsonga", "TS"], ["Turkish", "TR"], ["Turkmen", "TK"], ["Twi", "TW"], ["Ukrainian", "UK"], ["Urdu", "UR"], ["Uzbek", "UZ"], ["Vietnamese", "VI"], ["Volapuk", "VO"], ["Welsh", "CY"], ["Wolof", "WO"], ["Xhosa", "XH"], ["Yiddish", "JI"], ["Yoruba", "YO"], ["Zulu", "ZU"]]
async def post_clans(self, channel, *args, msg=None): """Post clans to channel.""" config = self.clans_config clan_tags = [clan.tag for clan in config.clans if not clan.hide] use_cache = False clans = [] try: clans = await self.get_clans(clan_tags) dataIO.save_json(CACHE, clans) except json.decoder.JSONDecodeError: use_cache = True except asyncio.TimeoutError: use_cache = True if use_cache: data = dataIO.load_json(CACHE) clans = data await self.bot.say("Cannot load from API. Loading info from cache.") em = discord.Embed( title=config.name, description=config.description, color=discord.Color(int(config.color, 16)), timestamp=dt.datetime.utcnow() ) badge_url = None show_member_count = "-m" not in args show_clan_tag = "-t" not in args for clan in clans: desc = clan.get('description', '') # trophies, pb, psf match = re.search('[\d,O]{4,}', desc) pb_match = re.search('PB', desc) psf_match = re.search('PSF', desc) name = clan.get('name') if match is not None: trophies = match.group(0) trophies = trophies.replace(',', '') trophies = trophies.replace('O', '0') else: trophies = clan.get('requiredTrophies') pb = '' if pb_match is not None: pb = ' PB' psf = '' if psf_match is not None: psf = ' PSF' # member count member_count = '' if show_member_count: if self.api_provider == 'official': member_count = clan.get('members') else: member_count = len(clan.get('members')) member_count = ', {} / 50'.format(member_count) # clan tag clan_tag = '' if show_clan_tag: clan_tag = ', {}'.format(clan.get('tag')) # cw coverage cw = "" match = re.search('(\d+)L(\d+)G', desc) if match is not None: legendary = match.group(1) gold = match.group(2) if len(gold) == 1: gold = "{}0".format(gold) if len(legendary) == 1: legendary = "{}0".format(legendary) gold = int(gold) legendary = int(legendary) cw = "\nCWR: {}% Legendary, {}% Gold".format( legendary, gold ) # clan scores + cw trophies clan_score_cw_trophies = "{trophy}{cw_trophy}".format( trophy=emoji_value('laddertrophy', clan.get('clanScore', 0), 5), cw_trophy=emoji_value('cwtrophy', clan.get('clanWarTrophies', 0), 5), ) # aux requirements aux = "" for c in config.clans: if c.tag in clan.get('tag'): if c.get('aux'): aux = '\n{}'.format(c.get('aux')) # embed value value = '`{trophies}{pb}{psf}{member_count}{clan_tag}`{cw}{aux}\n{clan_score_cw_trophies}'.format( clan_tag=clan_tag, member_count=member_count, trophies=trophies, pb=pb, psf=psf, cw=cw, aux=aux, clan_score_cw_trophies=clan_score_cw_trophies) em.add_field(name=name, value=value, inline=False) if badge_url is None: if self.api_provider == 'official': for badge in self.badges: if badge.get('id') == clan.get('badgeId'): badge_url = 'https://royaleapi.github.io/cr-api-assets/badges/{}.png'.format( badge.get('name')) else: badge_url = clan['badge']['image'] if badge_url is not None: em.set_thumbnail(url=badge_url) if config.get('url'): em.url = config.get('url') for inf in config.info: em.add_field( name=inf.name, value=inf.value ) if msg is None: # delete channel messages await self.bot.purge_from(channel, limit=5, before=msg) msg = await self.bot.send_message(channel, embed=em) else: await self.bot.edit_message(msg, embed=em) return msg
def __init__(self, bot): self.bot = bot self.quotes = dataIO.load_json("data/quote_generator/quotes.json")
async def update(self, ctx): """Updates cogs""" tasknum = 0 num_repos = len(self.repos) min_dt = 0.5 burst_inc = 0.1 / (NUM_THREADS) touch_n = tasknum touch_t = time() def regulate(touch_t, touch_n): dt = time() - touch_t if dt + burst_inc * (touch_n) > min_dt: touch_n = 0 touch_t = time() return True, touch_t, touch_n return False, touch_t, touch_n + 1 tasks = [] for r in self.repos: task = partial(self.update_repo, r) task = self.bot.loop.run_in_executor(self.executor, task) tasks.append(task) base_msg = "Downloading updated cogs, please wait... " status = ' %d/%d repos updated' % (tasknum, num_repos) msg = await self.bot.say(base_msg + status) updated_cogs = [] new_cogs = [] deleted_cogs = [] failed_cogs = [] error_repos = {} installed_updated_cogs = [] for f in as_completed(tasks): tasknum += 1 try: name, updates, oldhash = await f if updates: if type(updates) is dict: for k, l in updates.items(): tl = [(name, c, oldhash) for c in l] if k == 'A': new_cogs.extend(tl) elif k == 'D': deleted_cogs.extend(tl) elif k == 'M': updated_cogs.extend(tl) except UpdateError as e: name, what = e.args error_repos[name] = what edit, touch_t, touch_n = regulate(touch_t, touch_n) if edit: status = ' %d/%d repos updated' % (tasknum, num_repos) msg = await self._robust_edit(msg, base_msg + status) status = 'done. ' for t in updated_cogs: repo, cog, _ = t if self.repos[repo][cog]['INSTALLED']: try: await self.install(repo, cog, no_install_on_reqs_fail=False) except RequirementFail: failed_cogs.append(t) else: installed_updated_cogs.append(t) for t in updated_cogs.copy(): if t in failed_cogs: updated_cogs.remove(t) if not any(self.repos[repo][cog]['INSTALLED'] for repo, cog, _ in updated_cogs): status += ' No updates to apply. ' if new_cogs: status += '\nNew cogs: ' \ + ', '.join('%s/%s' % c[:2] for c in new_cogs) + '.' if deleted_cogs: status += '\nDeleted cogs: ' \ + ', '.join('%s/%s' % c[:2] for c in deleted_cogs) + '.' if updated_cogs: status += '\nUpdated cogs: ' \ + ', '.join('%s/%s' % c[:2] for c in updated_cogs) + '.' if failed_cogs: status += '\nCogs that got new requirements which have ' + \ 'failed to install: ' + \ ', '.join('%s/%s' % c[:2] for c in failed_cogs) + '.' if error_repos: status += '\nThe following repos failed to update: ' for n, what in error_repos.items(): status += '\n%s: %s' % (n, what) msg = await self._robust_edit(msg, base_msg + status) if not installed_updated_cogs: return patchnote_lang = 'Prolog' shorten_by = 8 + len(patchnote_lang) for note in self.patch_notes_handler(installed_updated_cogs): if note is None: continue for page in pagify(note, delims=['\n'], shorten_by=shorten_by): await self.bot.say(box(page, patchnote_lang)) await self.bot.say("Cogs updated. Reload updated cogs? (yes/no)") answer = await self.bot.wait_for_message(timeout=15, author=ctx.message.author) if answer is None: await self.bot.say("Ok then, you can reload cogs with" " `{}reload <cog_name>`".format(ctx.prefix)) elif answer.content.lower().strip() == "yes": registry = dataIO.load_json("data/red/cogs.json") update_list = [] fail_list = [] for repo, cog, _ in installed_updated_cogs: if not registry.get('cogs.' + cog, False): continue try: self.bot.unload_extension("cogs." + cog) self.bot.load_extension("cogs." + cog) update_list.append(cog) except: fail_list.append(cog) msg = 'Done.' if update_list: msg += " The following cogs were reloaded: "\ + ', '.join(update_list) + "\n" if fail_list: msg += " The following cogs failed to reload: "\ + ', '.join(fail_list) await self.bot.say(msg) else: await self.bot.say("Ok then, you can reload cogs with" " `{}reload <cog_name>`".format(ctx.prefix))