def _load(self): """ Loads the ignore list from json """ Storage.load(self) for el in Storage.get(self): self.add(IgnoreDataset.deserialize(self.bot, el, self), True)
def update_config_from_1_to_2(self, old_config): """ Updates the configuration from version 1 (indicator: contains '_prefix') to version 2 :param old_config: the old config dict """ logging.info("Update Custom CMD config from version 1 to version 2") new_config = self.default_config() new_config['prefix'] = old_config['_prefix'] logging.info(f"Converting {len(old_config) - 1} custom commands...") new_cmds = {} for cmd in old_config.keys(): if cmd == '_prefix': continue cmd_name = cmd.lower() if cmd_name in new_cmds: new_cmds[cmd_name]['texts'].append(old_config[cmd]) else: new_cmds[cmd_name] = Cmd(cmd_name, 0, [old_config[cmd]]).serialize() Storage.set(self, new_cmds) # Config.save(self) Storage.save(self) logging.info("Converting finished.")
async def dsc_status(self, ctx): if Storage.get(self)['status']: status_msg = Lang.lang(self, 'status_base', Storage.get(self)['status']) else: status_msg = Lang.lang(self, 'status_base', Lang.lang(self, 'status_none')) await ctx.send(status_msg)
def write(self): r = {} for el in self.complaints: complaint = self.complaints[el] r[complaint.id] = complaint.serialize() Storage.get(self)["complaints"] = r Storage.save(self)
async def cmd_ladder(self, ctx, *args): if len(args) != 1: await ctx.message.add_reaction(Lang.CMDERROR) return embed = discord.Embed() entries = {} for uid in Storage().get(self)["ladder"]: member = discord.utils.get(ctx.guild.members, id=uid) points = Storage().get(self)["ladder"][uid] if points not in entries: entries[points] = [member] else: entries[points].append(member) values = [] keys = sorted(entries.keys(), reverse=True) place = 0 for el in keys: for user in entries[el]: values.append("**#{}:** {} - {}".format( place, el, get_best_username(Storage().get(self), user))) if len(values) == 0: await ctx.send("So far, nobody is on the ladder.") return embed.add_field(name="Ladder:", value="\n".join(values)) await ctx.send(embed=embed)
async def bugscore_increment(self, ctx, user, increment): if discord.utils.get(ctx.author.roles, id=Config().BOTMASTER_ROLE_ID) is None: await ctx.message.add_reaction(Lang.CMDNOPERMISSIONS) return # find user try: user = await commands.MemberConverter().convert(ctx, user) except (commands.CommandError, IndexError): await ctx.send(Lang.lang(self, "bugscore_user_not_found", user)) await ctx.message.add_reaction(Lang.CMDERROR) return try: increment = int(increment) except (ValueError, TypeError): await ctx.send(Lang.lang(self, "bugscore_nan", increment)) await ctx.message.add_reaction(Lang.CMDERROR) return if user.id in self.storage["bugscore"]: self.storage["bugscore"][user.id] += increment else: self.storage["bugscore"][user.id] = increment if self.storage["bugscore"][user.id] <= 0: del self.storage["bugscore"][user.id] Storage.save(self) await ctx.message.add_reaction(Lang.CMDSUCCESS)
async def cmd_emoji(self, ctx, *args): # Delete emoji if len(args) == 1: if ctx.message.author.id in Storage().get(self)["emoji"]: del Storage().get(self)["emoji"][ctx.message.author.id] await ctx.message.add_reaction(Lang.CMDSUCCESS) Storage().save(self) else: await ctx.message.add_reaction(Lang.CMDERROR) return # Too many arguments if len(args) != 2: await ctx.message.add_reaction(Lang.CMDERROR) return emoji = args[1] try: await ctx.message.add_reaction(emoji) except HTTPException: await ctx.message.add_reaction(Lang.CMDERROR) return Storage().get(self)["emoji"][ctx.message.author.id] = emoji Storage().save(self) await ctx.message.add_reaction(Lang.CMDSUCCESS)
def update_ladder(self, member, points): ladder = Storage().get(self)["ladder"] if member.id in ladder: ladder[member.id] = int( round(ladder[member.id] * 3 / 4 + points * 1 / 4)) else: ladder[member.id] = int(round(points * 3 / 4)) Storage().save(self)
async def role_update(self, ctx, *message_content): if len(message_content) > 0: Storage().get(self)['message']['content'] = " ".join( message_content) Storage().save(self) await self.update_role_management(ctx) await ctx.send(Lang.lang(self, 'role_update')) await utils.log_to_admin_channel(ctx)
async def get_init_msg(self): """Returns the role management init message or None if not set""" if self.has_init_msg_set(): channel = self.bot.get_channel( Storage().get(self)['message']['channel_id']) return await channel.fetch_message( Storage().get(self)['message']['message_id']) else: return None
def save(self): """Saves the commands to the storage and the plugin config""" cmd_dict = {} for k in self.commands: cmd_dict[k] = self.commands[k].serialize() Storage.set(self, cmd_dict) Storage.save(self) Config.save(self)
def load(self): """Loads the commands""" # Update from old config versions if "_prefix" in Storage.get(self): self.update_config_from_1_to_2(Storage.get(self)) if "_prefix" in Config.get(self): self.update_config_from_1_to_2(Config.get(self)) # actually load the commands for k in Storage.get(self).keys(): self.commands[k] = Cmd.deserialize(k, Storage.get(self)[k])
def remove_reminder(self, reminder_id): """ Removes the reminder if in config :param reminder_id: the reminder ID """ if reminder_id in self.reminders: self.reminders[reminder_id].cancel() del (self.reminders[reminder_id]) if reminder_id in Storage().get(self)['reminders']: del (Storage().get(self)['reminders'][reminder_id]) Storage().save(self) logging.info("Reminder {} removed".format(reminder_id))
def save(self): """Saves the current ignorelist to json""" full_list = [] full_list.extend(self.users) full_list.extend(self.cmds) full_list.extend(self.user_cmds) jsondata = [] for el in full_list: jsondata.append(el.serialize()) Storage.set(self, jsondata) Storage.save(self)
def __init__(self, bot): super().__init__(bot) bot.register(self, help.DefaultCategories.MISC) self.reminders = {} reminders_to_remove = [] for reminder_id in Storage().get(self)['reminders']: reminder = Storage().get(self)['reminders'][reminder_id] if not self.register_reminder(reminder['chan'], reminder['user'], reminder['time'], reminder_id, reminder['text'], True): reminders_to_remove.append(reminder_id) for el in reminders_to_remove: self.remove_reminder(el)
def register_reminder(self, channel_id: int, user_id: int, remind_time: datetime, reminder_id: int, text, is_restart: bool = False): """ Registers a reminder :param channel_id: The id of the channel in which the reminder was set :param user_id: The id of the user who sets the reminder :param remind_time: The remind time :param reminder_id: The reminder ID :param text: The reminder message text :param is_restart: True if reminder is restarting after bot (re)start :returns: True if reminder is registered, otherwise False """ if remind_time < datetime.now(): logging.debug("Attempted reminder {} in the past: {}".format( reminder_id, remind_time)) return False logging.info("Adding reminder {} for user with id {} at {}: {}".format( reminder_id, user_id, remind_time, text)) job_data = { 'chan': channel_id, 'user': user_id, 'time': remind_time, 'text': text, 'id': reminder_id } timedict = timers.timedict(year=remind_time.year, month=remind_time.month, monthday=remind_time.day, hour=remind_time.hour, minute=remind_time.minute) job = self.bot.timers.schedule(self.reminder_callback, timedict, repeat=False) job.data = job_data self.reminders[reminder_id] = job if not is_restart: Storage().get(self)['reminders'][reminder_id] = job_data Storage().save(self) return True
async def create_message_text(self, server_roles, ctx): """ Returns the message text for the role manage init message including the reactions and mod roles for the roles :param server_roles: the roles on the server :param ctx: The context of the used command to create the new message """ msg = "{}\n".format(Storage().get(self)['message']['content']) for rid in self.rc(): role = discord.utils.get(server_roles, id=rid) emote_msg = "" modrole_msg = "" if self.rc()[rid]['emoji']: emote_msg = Lang.lang( self, 'init_reaction', await utils.emojize(self.rc()[rid]['emoji'], ctx)) if self.rc()[rid]['modrole'] != 0: modrole = discord.utils.get(server_roles, id=self.rc()[rid]['modrole']) modrole_msg = Lang.lang(self, 'init_modrole', modrole.name) if emote_msg and modrole_msg: todo_part = "{}, {}".format(emote_msg, modrole_msg) elif emote_msg: todo_part = emote_msg elif modrole_msg: todo_part = modrole_msg else: todo_part = Lang.lang(self, 'init_admin') msg += "\n{} - {}".format(role.name, todo_part) return msg
def embed(self, end=False, sort_by_points=False): embed = discord.Embed(title=Lang.lang(self.plugin, "results_title")) ladder = self.ladder(sort_by_points=sort_by_points) place = 0 for i in range(len(ladder)): user = ladder[i] if i == 0 or self._score[user] < self._score[ladder[i - 1]]: place += 1 # embed name = "**#{}** {}".format( place, get_best_username(Storage().get(self.plugin), user)) value = "Correct answers: {}".format(self._score[user]) if len(self) > 1: value = "{}\nScore: {}".format(value, self.calc_points(user)) embed.add_field(name=name, value=value) i += 1 if len(ladder) == 0: if end: embed.add_field(name="Nobody has scored!", value=" ") else: embed.add_field(name="**#1** Geckarbot", value="I won! :)") return embed
async def end(self): embed = self.score.embed() winners = [get_best_username(Storage().get(self.plugin), x) for x in self.score.winners()] # Übergangslösung points = self.score.points() for user in points: self.plugin.update_ladder(user, points[user]) msgkey = "quiz_end" if len(winners) > 1: msgkey = "quiz_end_pl" elif len(winners) == 0: msgkey = "quiz_end_no_winner" winners = utils.format_andlist(winners, ands=Lang.lang(self.plugin, "and"), emptylist=Lang.lang(self.plugin, "nobody")) msg = Lang.lang(self.plugin, msgkey, winners) if msg is None: await self.channel.send(embed=embed) elif embed is None: await self.channel.send(msg) else: await self.channel.send(msg, embed=embed) self.plugin.end_quiz(self.channel)
async def status(self, msg): """ Called when the status command is invoked. """ embed = discord.Embed(title="Kwiss: question {}/{}".format( self.quizapi.current_question_index() + 1, len(self.quizapi))) embed.add_field(name="Category", value=self.quizapi.category_name(self.category)) embed.add_field(name="Difficulty", value=Difficulty.human_readable(self.difficulty)) embed.add_field(name="Mode", value="Points (Everyone answers)") embed.add_field(name="Initiated by", value=get_best_username(Storage().get(self.plugin), self.requester)) status = ":arrow_forward: Running" if self.state == Phases.REGISTERING: status = ":book: Signup phase" # status = ":pause_button: Paused" embed.add_field(name="Status", value=status) if self.ranked: embed.add_field(name="Ranked", value=":memo:") if self.debug: embed.add_field(name="Debug mode", value=":beetle:") if self.gecki: embed.add_field(name="Gecki", value="I'm in! 😍") await self.channel.send(embed=embed)
async def end(self): embed = self.score.embed() winners = [get_best_username(Storage().get(self.plugin), x) for x in self.score.winners()] msgkey = "quiz_end" if len(winners) > 1: msgkey = "quiz_end_pl" elif len(winners) == 0: msgkey = "quiz_end_no_winner" winners = utils.format_andlist(winners, ands=Lang.lang(self.plugin, "and"), emptylist=Lang.lang(self.plugin, "nobody")) msg = Lang.lang(self.plugin, msgkey, winners) if msg is None: await self.channel.send(embed=embed) elif embed is None: await self.channel.send(msg) else: await self.channel.send(msg, embed=embed) if self.ranked: for player in self.registered_participants: self.plugin.update_ladder(player, self.score.calc_points(player)) self.plugin.end_quiz(self.channel)
def __init__(self, bot): super().__init__(bot) self.can_reload = True bot.register(self, category="DSC") self.log = logging.getLogger("dsc") self._fill_rule_link() Storage().save(self)
async def storagedump(self, ctx, name): plugin = converter.get_plugin_by_name(self.bot, name) if plugin is None: await ctx.message.add_reaction(Lang.CMDERROR) await ctx.send("Plugin {} not found.".format(name)) return await ctx.message.add_reaction(Lang.CMDSUCCESS) dump = pprint.pformat(Storage.get(plugin), indent=4).split("\n") prefix = "" if not Storage.has_structure(plugin): prefix = "**Warning: plugin {} does not have a storage structure.** " \ "This is the default storage.".format(name) for el in utils.paginate(dump, prefix=prefix, msg_prefix="```", msg_suffix="```"): await ctx.send(el)
async def bugscore_del(self, ctx, user): if discord.utils.get(ctx.author.roles, id=Config().BOTMASTER_ROLE_ID) is None: await ctx.message.add_reaction(Lang.CMDNOPERMISSIONS) return try: user = await commands.MemberConverter().convert(ctx, user) except (commands.CommandError, IndexError): await ctx.send(Lang.lang(self, "bugscore_user_not_found", user)) await ctx.message.add_reaction(Lang.CMDERROR) return if user.id in self.storage["bugscore"]: del self.storage["bugscore"][user.id] Storage.save(self) await ctx.message.add_reaction(Lang.CMDSUCCESS) else: await ctx.message.add_reaction(Lang.CMDNOCHANGE)
async def cmd_react(self, ctx, *args): if len(args) != 1: await ctx.message.add_reaction(Lang.CMDERROR) return emoji = Storage().get(self)["emoji"].get(ctx.message.author.id) if emoji is None: emoji = Lang.CMDERROR await ctx.message.add_reaction(emoji)
async def choose(self, ctx, *args): full_options_str = " ".join(args) if "sabaton" in full_options_str.lower(): await ctx.send(Storage.lang(self, 'choose_sabaton')) options = [i for i in full_options_str.split("|") if i.strip() != ""] if len(options) < 1: await ctx.send(Lang.lang(self, 'choose_noarg')) return result = random.choice(options) await ctx.send(Lang.lang(self, 'choose_msg') + result.strip())
async def cmd_del(self, ctx, *args): if len(args) != 2: await ctx.message.add_reaction(Lang.CMDERROR) return if not permChecks.check_full_access(ctx.message.author): await ctx.message.add_reaction(Lang.CMDERROR) return try: user = await commands.MemberConverter().convert(ctx, args[1]) except (commands.CommandError, IndexError): await ctx.message.add_reaction(Lang.CMDERROR) return ladder = Storage().get(self)["ladder"] if user.id in ladder: del ladder[user.id] Storage().save(self) await ctx.message.add_reaction(Lang.CMDSUCCESS) else: await ctx.message.add_reaction(Lang.CMDNOCHANGE)
async def eval(self): """ Is called when the question is over. Evaluates scores and cancels the timer. :return: """ self.plugin.logger.debug("Ending question") # End timeout timer if self.current_question_timer is not None: try: self.current_question_timer.cancel() except utils.HasAlreadyRun: self.plugin.logger.warning("This should really, really not happen.") self.current_question_timer = None else: # We ran into a timeout and need to give that function time to communicate this fact await asyncio.sleep(1) if self.current_reaction_listener is not None: self.current_reaction_listener.unregister() question = self.quizapi.current_question() # Normalize answers for el in self.registered_participants: if len(self.registered_participants[el]) != 1: self.registered_participants[el] = None else: self.registered_participants[el] = self.registered_participants[el][0] # Increment scores correctly_answered = [] for user in self.registered_participants: if question.check_answer(self.registered_participants[user], emoji=True): correctly_answered.append(user) for user in correctly_answered: self.score.increase(user, self.current_question, totalcorr=len(correctly_answered)) correct = [get_best_username(Storage().get(self.plugin), el) for el in correctly_answered] correct = utils.format_andlist(correct, Lang.lang(self.plugin, "and"), Lang.lang(self.plugin, "nobody")) if self.config["emoji_in_pose"]: ca = question.correct_answer_emoji else: ca = question.correct_answer_letter await self.channel.send(Lang.lang(self.plugin, "points_question_done", ca, correct)) # Reset answers list for user in self.registered_participants: self.registered_participants[user] = [] await asyncio.sleep(self.config["question_cooldown"]) self.state = Phases.QUESTION
async def bugscore_show(self, ctx): users = sorted(sorted( [(utils.get_best_username( discord.utils.get(self.bot.guild.members, id=user)), n) for (user, n) in self.storage["bugscore"].items()], key=lambda x: x[0].lower()), key=lambda x: x[1], reverse=True) lines = ["{}: {}".format(user, p) for (user, p) in users] for msg in utils.paginate(lines, prefix="{}\n".format( Storage.lang(self, "bugscore_title"))): await ctx.send(msg)
def __init__(self, bot): super().__init__(bot) bot.register(self) self.storage = Storage.get(self) self.complaints = {} self.highest_id = None # Load complaints from storage if self.storage is None: self.storage = deepcopy(self.default_storage()) else: print("Feedback storage: {}".format(self.storage)) str_keys_to_int(self.storage["complaints"]) for cid in self.storage["complaints"]: self.complaints[cid] = Complaint.deserialize( self.bot, cid, self.storage["complaints"][cid]) # Migration 1.7 -> 1.8 if "bugscore" not in self.storage: self.storage["bugscore"] = {} Storage.save(self) self.get_new_id(init=True)