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,module1:{installed},module1:{installed}}} self.repos = dataIO.load_json(self.file_path) self.executor = ThreadPoolExecutor(NUM_THREADS) self._do_first_run()
def get_info_data(self, repo_name, module=None): if module is not None: modules = self.list_modules(repo_name) if module in modules: info_file = os.path.join(modules[module].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 load_modules(bot): defaults = ("autoresponder", "audio", "customcom", "downloader", "lockdown", "general", "image", "mod", "speedtest") try: registry = dataIO.load_json("data/projectpython/modules.json") except: registry = {} bot.load_extension('modules.owner') owner_module = bot.get_cog('Owner') if owner_module is None: print("The owner module is missing. It contains core function without " "which ProjectPython cannot function. Reinstall.") exit(1) if bot.settings._no_modules: bot.logger.debug("Skipping initial modules loading (--no-modules)") if not os.path.isfile("data/projectpython/modules.json"): dataIO.save_json("data/projectpython/modules.json", {}) return failed = [] extensions = owner_module._list_modules() if not registry: for ext in defaults: registry["modules." + ext] = True for extension in extensions: if extension.lower() == "modules.owner": continue to_load = registry.get(extension, False) if to_load: try: owner_module._load_module(extension) except Exception as e: print("{}: {}".format(e.__class__.__name__, str(e))) bot.logger.exception(e) failed.append(extension) registry[extension] = False dataIO.save_json("data/projectpython/modules.json", registry) if failed: print("\nFailed to load: {}\n".format(" ".join(failed)))
async def addbot(self, ctx, oauth_url): # From Squid-Plugins for Red-DiscordBot: # https://github.com/tekulvw/Squid-Plugins """Requires your OAUTH2 URL to automatically approve your bot to join""" server = ctx.message.server key = dataIO.load_json("data/SelfBot/self_token.json")["token"] parsed = up.urlparse(oauth_url) queryattrs = up.parse_qs(parsed.query) queryattrs['client_id'] = int(queryattrs['client_id'][0]) queryattrs['scope'] = queryattrs['scope'][0] queryattrs.pop('permissions', None) full_url = self.base_api_url + up.urlencode(queryattrs) status = await self.get_bot_api_response(full_url, key, server.id) if status < 400: await self.bot.say("Succeeded!") else: await self.bot.say("Failed, error code {}. ".format(status))
def set_module(module, value): data = dataIO.load_json("data/projectpython/modules.json") data[module] = value dataIO.save_json("data/projectpython/modules.json", data)
dictionary = { "clear-day": ":sunny:", "clear-night": ":night_with_stars:", "rain": ":cloud_rain:", "snow": ":cloud_snow:", "sleet": ":snowflake:", "wind": ":wind_blowing_face: ", "fog": ":foggy:", "cloudy": ":white_sun_cloud:", "partly-cloudy-day": ":white_sun_small_cloud:", "partly-cloudy-night": ":night_with_stars:", "": ":sunny:" } config = dataIO.load_json("data/SelfBot/config.json") class Weather: apikey = config["dark_sky_api_key"] def __init__(self, bot: commands.Bot): self.bot = bot @commands.command(pass_context=True) async def weather(self, ctx, place: str = None): """Shows weather in provided place""" if place is None: place = config["hometown"] g = geocoder.google(place) if len(g.latlng) == 0:
"signature_title": "Username", "signature_desc": "From Selfbot", "signature_url": "http://google.com", "signature_colour": 0, "signature_field_name": "«Sometimes, i dream about cheese»", "signature_field_content": "Some text about cheese" } if not os.path.exists("data/SelfBot"): os.makedirs("data/SelfBot") if not dataIO.is_valid_json("data/SelfBot/config.json"): print("<!>[ERROR] Incorrect or missing config.json\n<!> Recreating...") dataIO.save_json("data/SelfBot/config.json", def_config) config = dataIO.load_json("data/SelfBot/config.json") formatter = helpformat.CustomHelp(show_check_failure=False) # Set's bot's description and prefixes in a list description = config["description"] + "\n" + "Version: \"" + version + "\"" ######################################################################################################################## class Bot(commands.Bot): def __init__(self): self.uptime = datetime.datetime.utcnow() # Refreshed before login super().__init__(command_prefix=[config["prefix"]], max_messages=GenericHelper.check_param("max_messages", 5000), description=description,
async def update(self, ctx): """Updates modules""" 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 modules, please wait... " status = ' %d/%d repos updated' % (tasknum, num_repos) msg = await self.bot.say(base_msg + status) updated_modules = [] new_modules = [] deleted_modules = [] failed_modules = [] error_repos = {} installed_updated_modules = [] 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_modules.extend(tl) elif k == 'D': deleted_modules.extend(tl) elif k == 'M': updated_modules.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_modules: repo, module, _ = t if self.repos[repo][module]['INSTALLED']: try: await self.install(repo, module, no_install_on_reqs_fail=False) except RequirementFail: failed_modules.append(t) else: installed_updated_modules.append(t) for t in updated_modules.copy(): if t in failed_modules: updated_modules.remove(t) if not any(self.repos[repo][module]['INSTALLED'] for repo, module, _ in updated_modules): status += ' No updates to apply. ' if new_modules: status += '\nNew modules: ' \ + ', '.join('%s/%s' % c[:2] for c in new_modules) + '.' if deleted_modules: status += '\nDeleted modules: ' \ + ', '.join('%s/%s' % c[:2] for c in deleted_modules) + '.' if updated_modules: status += '\nUpdated modules: ' \ + ', '.join('%s/%s' % c[:2] for c in updated_modules) + '.' if failed_modules: status += '\nModules that got new requirements which have ' + \ 'failed to install: ' + \ ', '.join('%s/%s' % c[:2] for c in failed_modules) + '.' 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_modules: return patchnote_lang = 'Prolog' shorten_by = 8 + len(patchnote_lang) for note in self.patch_notes_handler(installed_updated_modules): 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("Modules updated. Reload updated modules? (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 modules with" " `{}reload <module_name>`".format(ctx.prefix)) elif answer.content.lower().strip() == "yes": registry = dataIO.load_json( os.path.join("data", "projectpython", "modules.json")) update_list = [] fail_list = [] for repo, module, _ in installed_updated_modules: if not registry.get('modules.' + module, False): continue try: self.bot.unload_extension("modules." + cmoduleog) self.bot.load_extension("modules." + module) update_list.append(module) except: fail_list.append(module) msg = 'Done.' if update_list: msg += " The following modules were reloaded: "\ + ', '.join(update_list) + "\n" if fail_list: msg += " The following modules failed to reload: "\ + ', '.join(fail_list) await self.bot.say(msg) else: await self.bot.say("Ok then, you can reload modules with" " `{}reload <module_name>`".format(ctx.prefix))