async def cmd_randomgroup(self, *args, channel, member, client, **_): if len(args) >= 2: if not args[1].isdigit(): raise InvalidArgs("2nd Argument must be a channel ID") target = client.get_channel(int(args[1])) if not target: raise NotFound(f"Channel ID {args[1]} not found") else: if not member.voice or not member.voice.channel: raise NotFound("Impossible de récupérer les joueurs : Vous n'êtes pas connecté à un channel vocal") target = member.voice.channel members = target.members if not members: raise NotFound("Member not found in channels") if not args: raise InvalidArgs("Invalid syntax: `/randomgroup {number_of_group}`") if not args[0].isdigit(): raise InvalidArgs("1st Argument must be a number") random.shuffle(members) nb = int(args[0]) groups = [] div, mod = divmod(len(members), nb) x = 0 for i in range(nb): y = div+(i<mod) await channel.send(f"`group {i+1}`: {', '.join(f'<@{i.id}>' for i in members[x:x+y])}") x += y
async def sell_champ(*args, channel, member): if len(args) < 2: raise InvalidArgs("/tftsell {nom du champion} {niveau}") if not args[-1].isdigit(): raise InvalidArgs( f"Le niveau doit être un nombre et non \"{args[-1]}\"") champion = ' '.join(args[:-1]) level = int(args[-1]) d = {"name": champion, "level": level} if champion not in CHAMPIONS_PRICES.keys(): raise NotFound( f"Le champion nommé \"{champion}\" n'est pas disponible dans ce set" ) with Database() as db: # type: Database champ_json = db.get_champions(member.id) if not champ_json: raise NotFound(f"No champion found for {member}") if d not in champ_json: raise NotFound( f"Champion {champion} lvl: {level} non trouvé dans l'équipe" ) champ_json.remove(d) gold = db.get_gold(member.id) gain = CHAMPIONS_PRICES[champion] * 3**(level - 1) db.update_gold(member.id, gold + gain) db.update_champions(member.id, champ_json) await channel.send( f"{member.mention} a vendu {champion} lvl {level} pour {gain} gold ({gold + gain})" )
async def roll_by_comp(comp, name, bonus): """ Args: comp (List[Tuple[str, int, COMP_LEVEL]]): comp sheet Tuple[comp_name, score] name (str): comp name the player want roll bonus (int): bonus/malus dice member (discord.Member): discord member message (discord.Message): discord message channel (discord.Channel): discord channel Returns: None """ possibilities = [i for i in comp if i[0].startswith(name)] if not possibilities: raise NotFound(f"Compétence \"{name}\"non trouvée dans la fiche de personnage") if len(possibilities) > 1: raise NotFound(f"Plusieurs compétence porte un nom similaire, conflit entre : {', '.join([i[0] for i in possibilities])}") comp_name, comp_score, comp_level = possibilities[0] total_bonus = bonus + (comp_level == COMP_LEVEL.MAITRE) r = roll(f"{1+ abs(total_bonus)}d100") rr = sum(r.results, []) old_dice = "" if len(rr) == 1: final_dice = r.total else: final_dice = (min if total_bonus > 0 else max)(rr) if comp_level >= COMP_LEVEL.ADEPTE: old_dice = f"~~{final_dice}~~ " final_dice -= 10 verdict = get_final_result(final_dice, comp_score) return {"result": r, "old_dice": old_dice, "final_dice": final_dice, "comp_name": comp_name, "comp_level": comp_level, "comp_score": comp_score, "verdict": verdict}
def update(self, id="", **kwargs): if not id or not kwargs: raise ParamNone(id=id) LOG.info("kwargs 111:%r" % kwargs) user_info = db_api.user_get(id) current_user_level = kwargs.pop("current_user_level") if not user_info or current_user_level >= user_info.level: raise FormalError(current_user_level=current_user_level, level=user_info.level) if kwargs.get("school_id", ""): _ = db_api.school_get(kwargs.get("school_id", "")) if not _: raise NotFound(school_id=kwargs.get("school_id", "")) name = kwargs.get("name", "") if name and convert.bs2utf8( user_info.name) != name and db_api.user_list(name=name): raise ParamExist(name=name) phone = kwargs.get("phone", "") if phone and convert.bs2unicode( user_info.phone) != phone and db_api.user_list(phone=phone): raise ParamExist(phone=phone) if kwargs.get("pwd", ""): kwargs.pop("pwd") LOG.info("kwargs 444:%r" % kwargs) _ = db_api.user_update(id, kwargs) return _
async def cmd_info(self, *args, message, member, **_): summ_id, name = None, None if not args: verif = load_verif() if str(member.id) in verif: summ_id = verif[str(member.id)] else: name = member.display_name else: name = " ".join(args) if summ_id: data = await panth.getSummoner(summ_id) else: data = await panth.getSummonerByName(name) if not data: raise NotFound("Impossible de trouver l'invocateur") icon = "http://ddragon.canisback.com/latest/img/profileicon/"+str(data['profileIconId'])+".png" score = load_score() score[data['id']] = await get_ranked_score(data['id']) txt = "" for i in ["SoloQ", "FlexQ", "3v3TT", "TFT"]: lead = await get_leaderboard_place(message, data['id'], i) if lead: txt += "``{}: {} {:>2}/{}``\n".format(i, score[str(data['id'])][i][1], *lead) colour = 0xDDDDDD if summ_id: colour = member.colour elif message.guild: target = message.guild.get_member_named(name) if target : colour = target.colour em = discord.Embed(title="Information de l'invocateur", description=txt + "", colour=colour) em.set_author(name=data['name'], icon_url=icon) await message.channel.send(embed=em) save_score(score)
async def cmd_memberinfo(self, *args, member, channel, guild, **_): if args: member = get_member(guild, ' '.join(args)) if not member: raise NotFound("Membre non trouvé :(") em = discord.Embed(title=member.display_name, colour=member.colour) em.add_field(name="Nom", value=member.name) em.add_field(name="Discriminator", value="#" + member.discriminator) em.add_field(name="ID", value=str(member.id)) if member.id in [384274248799223818, 427867039135432714, 244453201036836864, 221290866717884417]: em.add_field(name="Type", value="Dragon") else: em.add_field(name="Type", value="Robot" if member.bot else "Humain") em.add_field(name="Status", value=str(member.status)) em.add_field(name="Couleur", value=str(member.colour)) em.add_field(name="Jeu", value=(lambda x: str(x) if x else "Aucun")(member.activity)) if len(member.roles) > 1: em.add_field(name="Roles", value=', '.join([f"<@&{i.id}>" for i in reversed(member.roles) if i.id != guild.id])) else: em.add_field(name="Roles", value='Aucun') em.add_field(name="Serveur rejoint", value=format_time(member.joined_at), inline=False) em.add_field(name="Compte créé", value=format_time(member.created_at)) # p = await member.profile() # badge = {"Staff": p.staff, "Partenaire": p.partner, "Bug Hunter": p.bug_hunter, # "Nitro": p.nitro, "Early Supporter": p.early_supporter, "Hypesquad": p.hypesquad, # "House of Brillance": p.hypesquad_houses.brilliance, "House of Balance": p.hypesquad_houses.brilliance, # "House of Bravery": p.hypesquad_houses.bravery} # user_badge = [k for k, v in badge.items() if v] # if user_badge: # em.add_field(name="Badges", value=format_time(member.created_at), inline=False) em.set_image(url=member.avatar_url) await channel.send(embed=em)
async def cmd_help(self, *args, channel, **_): if not args: em = discord.Embed(title="Help") em.set_footer(text="Entrez /help {module} pour plus de détail") for k, v in helper.items(): em.add_field(name=f"**{k}**", value=', '.join([f"``{i}``" for i in v.keys()]), inline=False) await channel.send(embed=em) elif args[0] in helper: d = helper[args[0]] em = discord.Embed(title=f"Help {args[0]}") for k, v in d.items(): if v.startswith('``'): a, t = v.split('``')[1], '``'.join(v.split('``')[2:]) em.add_field(name=f"**{k}** ``{a}``", value=t, inline=False) else: em.add_field(name=f"**{k}**", value=v, inline=False) await channel.send(embed=em) else: raise NotFound( "Erreur: J'ai pas trouvé le module dans mon manuel :(")
async def cmd_unvalidreport(self, *args, member, force, client, channel, **_): if not is_arbitre(member, client=client) and not force: raise Forbidden("You must be Arbitre for use this command") if not args: raise InvalidArgs("Command must take one argument") if not args[0].isdigit(): raise InvalidArgs("Argument must be a number") match = db.get_match(args[0]) if not match: raise NotFound("Match not found") if not match.validated: raise BotError("Match is already unvalided") db.unvalid_match(match) # update Players Stats database for i in match.report.players: db.unregister_plstats( i.id, match.report.gametype, i.position <= POSITION_REQUIRE_FOR_WIN[match.report.gametype]) # Verif if players are eligible to new roles civfr: nextcord.Guild = client.get_guild(CIVFR_GUILD_ID) tasks = [ recalc_role_for(civfr.get_member(i.id)) for i in match.report.players ] await asyncio.gather(*tasks) # Change embed validation_msg = await client.get_channel( REPORT_CHANNEL).fetch_message(match.check_msg_id) await validation_msg.edit(embed=match.to_embed(member.id)) await validation_msg.clear_reactions() await channel.send("Match invalidé.")
def input(self, name="", pwd="", affirm_pwd="", activate=0, phone="", school_id="", level=1): if pwd != affirm_pwd: raise FormalError(pwd=pwd, affirm_pwd=affirm_pwd) if not convert.is_mobile(phone): raise FormalError(phone=phone) if db_api.user_list(name=name): raise ParamExist(name=name) if db_api.user_list(phone=phone): raise ParamExist(phone=phone) values = { "name": name, "pwd": encry_md5(pwd.strip()), "activate": activate, "phone": phone, "level": level } if school_id: if not db_api.school_get(school_id): raise NotFound(school_id=school_id) values.update({"school_id": school_id}) user_obj = db_api.user_create(values) return user_obj
async def cmd_setcivfr(self, *args, member, guild, channel, force, **_): if not is_arbitre(member) and not force: raise Forbidden("You must be Arbitre for use this command") member = guild.get_member(int(args[0])) if not member: raise NotFound(f"Member {args[0]} not found") db.manual_query_set(*args) await channel.send("Stats changed") await recalc_role_for(member)
async def cmd_addreaction(self, *args: str, client, channel, message, **_): if len(args) < 2: raise InvalidArgs( "Invalid syntax, ``/addreaction message_id emoji_name``") if not args[0].isdigit(): raise InvalidArgs( f"First argument must be a number, got \"{args[0]}\"") msg = await channel.fetch_message(int(args[0])) if not msg: raise NotFound(f"Message with id \"{args[0]}\" not found") emoji = nextcord.utils.get(client.emojis, name=args[1]) if not emoji: raise NotFound(f"Emoji named \"{args[1]}\" not found") try: await message.delete() except: pass await msg.add_reaction(emoji)
async def cmd_gameinfo(self, *args, member, channel, **_): summ_id, name = None, None # type: str if not args: verif = load_verif() if str(member.id) in verif: summ_id = verif[str(member.id)] else: name = member.display_name else: name = " ".join(args) try: if summ_id: summ_info = await panth.getSummoner(summ_id) else: summ_info = await panth.getSummonerByName(name) except: raise NotFound("Impossible de trouver l'invocateur") try: spec_data = await panth.getCurrentGame(summ_info["id"]) except: return await channel.send( "L'invocateur n'est pas en jeu actuellement") msg = await channel.send(embed=nextcord.Embed( title="Récupération des informations ...")) team1 = await asyncio.gather( *(format_player_info(participant) for participant in spec_data["participants"] if participant["teamId"] == 100)) team2 = await asyncio.gather( *(format_player_info(participant) for participant in spec_data["participants"] if participant["teamId"] == 200)) em = nextcord.Embed(title=f"Game de {summ_info['name']}") em.add_field( name="Équipe bleu", value= f"Champions bannis :\n{' '.join([(CHAMP_ID_TO_EMOJI[str(i['championId'])] if str(i['championId']) != '-1' else CHAMP_NONE_EMOJI) for i in spec_data['bannedChampions'] if i['teamId'] == 100])}", inline=False) for i, name in enumerate( ["Invocateurs", "Runes et Classement", "Masteries"]): em.add_field(name=name, value='\n'.join([player[i] for player in team1]), inline=True) em.add_field( name="Équipe rouge", value= f"Champions bannis :\n{' '.join([(CHAMP_ID_TO_EMOJI[str(i['championId'])] if str(i['championId']) != '-1' else CHAMP_NONE_EMOJI) for i in spec_data['bannedChampions'] if i['teamId'] == 200])}", inline=False) for i, name in enumerate(["Invocateurs", "Runes", "Masteries"]): em.add_field(name=name, value='\n'.join([player[i] for player in team2]), inline=True) await msg.edit(embed=em)
async def cmd_getstats(self, *args, member, channel, guild, **_): if not args: target = member else: name = ' '.join(args) target = get_member(guild, name) if not target: raise NotFound(f"Member named \"{name}\" not found") pl = db.get_stat_for(target.id) await channel.send(str(pl))
async def cmd_music(self, *args, message, channel, force, client, **_): global clients if not args: raise InvalidArgs("Aucun argument reçu.") music_client = await get_client(message, client) if args[0] == "disconnect": await music_client.disconnect() await channel.send("Client déconnecté") elif args[0] == "pause": if not music_client.voice_client: await channel.send("le client n'est pas connecté") elif music_client.voice_client.is_paused(): await channel.send("déjà en pause") elif not music_client.voice_client.is_playing(): await channel.send("aucune musique en cours") else: music_client.voice_client.pause() await channel.send( "mise en pause ... (``/music resume`` pour reprendre)") elif args[0] == "resume": if not music_client.voice_client: await channel.send("le client n'est pas connecté") elif not music_client.voice_client.is_paused(): await channel.send("la pause n'est pas activé") else: music_client.voice_client.resume() elif args[0] == "skip": await music_client.play_next_music() elif args[0] == "queue": await music_client.display_queue(channel) elif args[0] == "search": music = await search_music('+'.join(args[1:])) if not music: raise NotFound("J'ai trouvé aucune musique portant ce nom :(") await music_client.add_to_queue([music]) else: if not re.match(r".*www\.youtube\.com/watch\?v=.*", args[0]): music = await search_music('+'.join(args)) if not music: raise NotFound( "J'ai trouvé aucune musique portant ce nom :(") return await music_client.add_to_queue([music]) await music_client.add_to_queue(args)
async def cmd_getstats(self, *args, member, channel, guild, force, **_): if not isinstance(channel, nextcord.DMChannel ) and channel.id != 258920360907374593 and not force: raise Forbidden("Arrêtez de spam les mauvais chan") if not args: target = member else: name = ' '.join(args) target = get_member(guild, name) if not target: raise NotFound(f"Member named \"{name}\" not found") pl = db.get_stat_for(target.id) await channel.send(str(pl))
async def cmd_afkmeter(self, *args, message, member, **_): """/afkmeter {*nom d'invocateur}""" count = {} if not args: summonerName = member.name else: summonerName = "".join(args) accountId, summonerId, iconId = await getSummoner(summonerName) if not accountId: raise NotFound("Invocateur non trouvé : {}".format(summonerName)) try: colour = message.guild.get_member_named(summonerName).colour except: colour = 0xC0C0C0 icon = "http://ddragon.canisback.com/latest/img/profileicon/" + str( iconId) + ".png" msg = await message.channel.send( embed=nextcord.Embed(title="Afk Meter", colour=colour).set_author( name=summonerName, icon_url=icon)) matches, timelines = await getSeasonMatches(accountId, timeline=True) for i in range(len(matches)): for participant in matches[i]["participantIdentities"]: if str(participant["player"]["accountId"]) == str(accountId): id = str(participant["participantId"]) oldpos, afk = "None", 0 for frame in timelines[i]["frames"]: try: j = frame["participantFrames"][str(id)]["position"] except: j = {"x": "None", "y": "None"} pos = str(j["x"]) + "," + str(j["y"]) if pos == oldpos: afk += 1 if afk >= 2: try: count[str(matches[i]["gameId"])] += 1 except: count[str(matches[i]["gameId"])] = 2 else: afk = 0 oldpos = pos txt, nb, mt = "", 0, 0 for x, y in count.items(): txt += "\ngame n°" + str(x) + " : **" + str(y) + "** minute(s)" nb += 1 mt += y em = nextcord.Embed( title="Afk Meter :", description="Sur les " + str(len(matches)) + " dernières parties\n" + summonerName + " a AFK **" + str(nb) + "** games pour un total de **" + str(mt) + "** minutes\n\n" + txt, colour=colour) await msg.edit(embed=em.set_author(name=summonerName, icon_url=icon))
async def cmd_bbgdisplayvote(self, *args, client, channel, **_): target = int(args[0]) for vote_channel_id in [SERIOUS_VOTE_ID, CASUAL_VOTE_ID]: vote_channel: nextcord.TextChannel = client.get_channel( vote_channel_id) try: message = await vote_channel.fetch_message(target) except nextcord.errors.NotFound: message = None if message: break else: raise NotFound( f"Can't find message in channel <#{SERIOUS_VOTE_ID}> <#{CASUAL_VOTE_ID}>" ) await self.diplay_vote(message, channel)
async def cmd_takedamage(self, *args : List[str], message, member, channel, guild, client, heal=False, **_): """ Args: *args (str): member (discord.Member): channel (discord.Channel): guild (discord.Guild): client (discord.Client): **_: Returns: """ if len(args) < 1: raise InvalidArgs("Usage: /takedamage [joueur] {domage}") if len(args) == 1: target = member else: membername = ' '.join(args[:-(len(args) - 1)]) target = get_member(guild, membername) # type: discord.Member if not target: raise NotFound(f"Member named {membername} not found") expr = args[-1] roll_result = roll(expr) damage = roll_result.total if damage < 0: damage = 0 elif heal: damage = -damage wsh = gc.open_by_key(CHAR_SHEET[str(target.id)]).sheet1 cell_list = wsh.range('P3:P6') old_hp = int(cell_list[0].value) new_hp = old_hp - damage if new_hp > int(cell_list[1].value): new_hp = int(cell_list[1].value) if old_hp > 0 and new_hp < 0: new_hp = 0 knock = cell_list[2].value == 'TRUE' injury = cell_list[3].value == 'TRUE' em = discord.Embed(colour=target.colour) if roll_result.dices: em.add_field(name="Lancé de dé", value=f"{member.mention} {roll_result.intro_sentence}\n{roll_result.format_results}") if damage > 0: em.add_field(name="Resultat", value=f"{target.mention} a pris **{damage}** point{'s' if damage > 1 else ''} de dégats.\n" f"Il lui reste **{new_hp}** / {cell_list[1].value}", inline=False) else: em.add_field(name="Resultat", value=f"{target.mention} a gagné **{-damage}** point{'s' if damage > 1 else ''} de vie.\n" f"Il lui reste **{new_hp}** / {cell_list[1].value}", inline=False) em.set_author(name=target.name, icon_url=target.avatar_url) em.set_footer(text=message.content) msg = await channel.send(embed=em) img = await create_image(target.avatar_url_as(format="png", size=1024), new_hp, int(cell_list[1].value), injury, knock) trash_msg = await client.get_channel(POUBELLE_ID).send(file=discord.File(fp=img, filename="a.png")) #type: discord.Message em.set_image(url=trash_msg.attachments[0].url) await msg.edit(embed=em) cell_list[0].value = new_hp wsh.update_cell(3, 12, new_hp)
async def cmd_pingvocal(self, *args, channel, member, **_): members = get_member_in_channel(member.voice) if not members: raise NotFound("Member not found in channels") await channel.send(' '.join(member.mention for member in members))
async def cmd_kikimeter(self, *args, message, member, **_): """/kikimeter {*nom d'invocateur}""" if not args: summonerName = member.name else: summonerName = "".join(args) accountId, summonerId, iconId = await getSummoner(summonerName) if not accountId or not summonerId: raise NotFound("Invocateur : {} non trouvé".format(summonerName)) league = await getLeagueSoloQ(summonerId) if not league: return await message.channel.send( "Cet invocateur n'est pas classé en SoloQ (et il y a que ça qui compte)" ) msg = await message.channel.send( "Récupération des données en cours ...") dic1 = { "BRONZE": 1, "SILVER": 1.5, "GOLD": 2.2, "PLATINUM": 3, "DIAMOND": 4, "MASTER": 4.5, "CHALLENGER": 5.5 } dic2 = {"V": 0.0, "IV": 0.1, "III": 0.3, "II": 0.4, "I": 0.5} league_bonus = dic1[league['tier']] + dic2[league['rank']] seasonMatches = await getSoloQSeasonMatches(accountId) kills, deaths, assists, damage, duration, win = 0, 0, 0, 0, 0, 0 for match in seasonMatches: id = get_player_id(match["participantIdentities"], accountId) stat = match["participants"][id - 1]["stats"] kills += stat["kills"] deaths += stat["deaths"] assists += stat["assists"] damage += stat["totalDamageDealt"] duration += match["gameDuration"] win += stat["win"] bonus = await get_bonus(summonerId, win, len(seasonMatches)) total_bonus = sum(bonus.values()) if not deaths: deaths = 0.75 kda = round((kills + assists * 0.75) / deaths, 2) dps = round(damage / duration, 2) epenis = round( ((kills + assists * 0.75) / deaths + damage / duration / 40) * league_bonus + total_bonus * (league_bonus / 2), 2) average_kda = [ str(round(i / len(seasonMatches), 1)) for i in [kills, deaths, assists] ] title = "{} possède un e-penis de {} cm\n".format(summonerName, epenis) recap = "__Recap des points__:\n" recap += "KDA ({}) : **{}**\n".format("/".join(average_kda), str(kda)) recap += "DPS ({}) : **{}**\n".format(dps, round(damage / duration / 40, 2)) recap += "Multiplicateur ({} {}) : **x{}**\n".format( league['tier'].capitalize(), league['rank'], league_bonus) if bonus: recap += "BONUS / MALUS : ```diff" for i, j in bonus.items(): recap += "\n{} {} : {}".format("-" if j < 0 else "+", i, str(j)) if bonus: recap += "```" try: colour = message.guild.get_member_named(summonerName).colour except: colour = 0xC0C0C0 em = nextcord.Embed(title=title, description=recap, colour=colour) em.set_footer(text="INFO : " + str(len(seasonMatches)) + " matchs analysés") em.set_author( name=summonerName, icon_url="http://ddragon.canisback.com/latest/img/profileicon/" + str(iconId) + ".png") await msg.edit(content=".", embed=em)
def get_member_in_channel(voice: discord.VoiceState): if not voice or not voice.channel: raise NotFound( "Impossible de récupérer les joueurs : Vous n'êtes pas connecté à un channel vocal" ) return voice.channel.members