async def notify(items): global notified notified.load() change = False with open(ping_channels, "r") as serverList: srvs = json.load(serverList) for server in srvs: if server not in notified.dictionary["notified"]: notified.dictionary["notified"][server] = set() for i in [ i for i in items if i not in notified.dictionary["notified"][server] ]: ping_stats = ping_server(server) if DiscordInteractive.client is None: Log.error("No client cant notify users") continue channel = DiscordInteractive.client.get_guild( int(server)).get_channel(ping_stats["channel"]) try: await channel.send(content=ping_stats["role"], embed=i.embed()) except: try: interact(channel.send, content=ping_stats["role"], embed=i.embed()) except: Log.error("could not notify") notified.dictionary["notified"][server].add(i) change = True if change: notified.save()
async def call(self, package): message, args, user_data = package["message_obj"], package[ "args"], package["user_obj"] mods = [] for i in args: if i.startswith("+"): mods = parse_mods_string(i[1:]) if len(args) > 1 and not args[1].startswith("+"): map_link, map_type = get_map_link(args[1]) Users().update_last_message(message.author.id, map_link, map_type, mods, 1, 1, user_data["osu_ign"], None) else: map_link, map_type = user_data["last_beatmap"]["map"] if not mods: mods = user_data["last_beatmap"]["mods"] if map_link is None: Log.error("No Map provided") await help_me(message, "map") return map_obj = MapStats(map_link, mods, map_type) bpm_graph = graph_bpm(map_obj) Log.log("Posting Graph") interact(message.channel.send, file=discord.File(bpm_graph, "BPM_Graph.png")) bpm_graph.close()
async def call(self, package): message, args = package["message_obj"], package['args'] try: cs = float(args[1]) except ValueError: msg = f"{args[1]} is not a valid cs" Log.error(msg) await help_me(message, self.command) return except IndexError: Log.error("No cs provided") await help_me(message, self.command) return mods = args[2].upper() if len(args) > 2 else "" new_cs, mod_list = CalculateMods(mods).cs(cs) output = "" if len(mod_list) > 0: if cs.is_integer(): cs = int(cs) output += f"CS{cs}+{''.join(mod_list).upper()} -> " new_cs = float(f"{new_cs:.2f}") if new_cs.is_integer(): new_cs = int(new_cs) output += f"CS{new_cs}" interact(message.channel.send, output)
async def call(self, package): message, args = package["message_obj"], package['args'] try: hp = float(args[1]) except ValueError: msg = f"{args[1]} is not a valid ar" Log.error(msg) await help_me(message, self.command) return except IndexError: Log.error("No ar provided") await help_me(message, self.command) return mods = args[2].upper() if len(args) > 2 else "" new_ar, ar_ms, mod_list = CalculateMods(mods).ar(hp) output = "" if len(mod_list) > 0: if hp.is_integer(): hp = int(hp) output += f"AR{hp}+{''.join(mod_list).upper()} -> " new_ar = float(f"{new_ar:.2f}") if new_ar.is_integer(): new_ar = int(new_ar) output += f"AR{new_ar} ({ar_ms:.0f}ms)" interact(message.channel.send, output)
def trigger(self, message_obj, _, d): string, sender, server, channel = str(message_obj.content), str(message_obj.author.id), \ str(message_obj.guild.id), str(message_obj.channel.id) if server not in mudaWatchlist: mudaWatchlist[server] = dict() if string.startswith(self.mudaCommand) or sender == self.mudaId: if server in allServers: if channel == allServers[server]: return False, "" if string.startswith(self.mudaCommand ) and sender not in mudaWatchlist[server]: mudaWatchlist[server][channel] = sender Log.log("adding {} to watchlist".format(sender)) return False, "" if channel in mudaWatchlist[server]: length = len( self.lengthMes.format(message_obj.author.name, message_obj.channel.name)) return True, [ mudaWatchlist[server][channel], allServers[server], "!" * int(length * 1.5) ] return False, "" return False, ""
async def call(self, package): message, args = package["message_obj"], package['args'] try: od = float(args[1]) except ValueError: msg = f"{args[1]} is not a valid od" # await message.channel.send(msg) Log.error(msg) await help_me(message, self.command) return except IndexError: Log.error("No od provided") await help_me(message, self.command) return mods = args[2].upper() if len(args) > 2 else "" new_od, od_ms, mod_list = CalculateMods(mods).od(od) output = "" if len(mod_list) > 0: if od.is_integer(): od = int(od) output += f"OD{od}+{''.join(mod_list).upper()} -> " new_od = float(f"{new_od:.2f}") if new_od.is_integer(): new_od = int(new_od) output += f"OD{new_od} ({od_ms:.0f}ms)" interact(message.channel.send, output)
def main(): import traceback _parse_arguments() try: _run() except Exception as e: Log.d(traceback.format_exc()) _die('Error: {error}'.format(error=e))
async def execute_event(event, guild_id): ping_id = ping_server(guild_id) if DiscordInteractive.client is None: Log.error("No client cant execute event") return False channel = DiscordInteractive.client.get_guild(guild_id).get_channel( ping_id) await channel.send(event.description) Log.log("event executed") return True
async def call(self, package): message, args = package["message_obj"], package["args"] try: embed = command_help(args[1]) except IndexError: Log.error("No command provided") await help_me(message, self.command) return interact(message.channel.send, embed=embed)
def warnTime(self, user, message): lastLol = user["time"] if time() - lastLol < timeOut: secs = (timeOut - round((time() - lastLol) + .5)) nextIn = f"You can't use saylol for another {secs}s." if not user["warned"]: interact(message.channel.send, nextIn) Log.log(nextIn) user["warned"] = True return True return False
def _run_android(): androidutils = AndroidUtils() if settings.runchecks: passed = androidutils.check_dependencies(['full'], silent=False, install=True) Log.w('Checks passed: {result}'.format(result=passed)) androidutils.clean() return if not settings.apk and not settings.package: androidutils.clean() _die('Error: No APK or Package specified.') # fixes problems with APK files in same folder if settings.apk and '/' not in settings.apk: settings.apk = './{apk}'.format(apk=settings.apk) if settings.listapps: androidutils.list_apps() elif settings.compile: androidutils.check_dependencies(['static', 'signing'], silent=True) androidutils.compile(settings.compile) else: if settings.static: androidanalysis = AndroidAnalysis(androidutils, apk=settings.apk, package=settings.package) settings.results = androidanalysis.run_analysis('static') else: if not settings.device or not androidutils.online(settings.device): androidutils.clean() _die('Error: Device {device} not found online'.format( device=settings.device)) androidanalysis = AndroidAnalysis(androidutils, apk=settings.apk, package=settings.package) settings.results = androidanalysis.run_analysis() if settings.results: report = Report(output_path=settings.output, alias=androidanalysis.PACKAGE, assessment_type='Android') if not settings.SILENT: report.report_to_terminal(settings.results) report.report_to_json(settings.results) androidutils.clean()
async def on_message(message): Log.log(f"{message.author.name}@{message.channel}: {message.content}") if DiscordInteractive.client != client: DiscordInteractive.client = client if DiscordInteractive.loop != asyncio.get_event_loop(): DiscordInteractive.loop = asyncio.get_event_loop() if message.author == client.user: return Broadcaster(conn).send(message) if message.content.startswith(Config.prefix): Users().load() Users().add_user(message.author.id) mess = message.content[len(Config.prefix):] mess = mess.split(" ") command = mess[0] package = { "message_obj": message, "args": mess, "client": client, "user_obj": Users.users[str(message.author.id)] } comm: Optional[commands.templateClass] = None if command in commands.List.keys(): comm = getattr(commands, sanitize(command))() else: found = False for i, j in commands.List.items(): if any([True for cm in j if cm.search(command)]): comm = getattr(commands, sanitize(i))() found = True break if not found: comm = getattr(commands, "help")() Log.log(f"{command} is not a valid command") # todo change to show list of available commands if comm is not None: asyncio.run_coroutine_threadsafe(comm.call(package), commandsLoop) elif Config.administer: for adm in administrating.List: trig_bool, payload = adm.trigger(message, client, commandsLoop) if trig_bool: await adm.action(message, payload)
async def call(self, package): message = package["message_obj"] server = message.guild.id channel = message.channel.id servername = server if message.guild.id is None else message.guild.name with open(muda_file, "r") as serverList: # will change try: allServers = json.load(serverList) except: allServers = dict() allServers[str(server)] = str(channel) with open(muda_file, "w") as serverList: json.dump(allServers, serverList, indent=" ", sort_keys=True) msg = "<#{0}> is now the default channel for {1}".format(channel, servername) Log.log(msg) interact(message.channel.send, msg)
async def on_ready(): global commandsLoop, workerThread Log.log('Logged in as') Log.log(client.user.name) Log.log(client.user.id) Log.log('------') DiscordInteractive.client = client DiscordInteractive.loop = asyncio.get_event_loop() # message loop commandsLoop = asyncio.new_event_loop() workerThread = Thread(target=start_background_loop, args=(commandsLoop,), daemon=True) workerThread.start()
def _merge_settings(): _path.append(settings.LOCAL_SETTINGS) try: import mat_settings # emulator settings settings.avd = mat_settings.avd if hasattr(mat_settings, 'avd') else settings.avd # boolean / test settings settings.device = mat_settings.device if hasattr( mat_settings, 'device') else settings.device settings.SILENT = mat_settings.SILENT if hasattr( mat_settings, 'SILENT') else settings.SILENT settings.DEBUG = mat_settings.DEBUG if hasattr( mat_settings, 'DEBUG') else settings.DEBUG except ImportError: Log.e('Local settings not imported.')
async def call(self, package): message, args, user_obj = package["message_obj"], package[ "args"], package["user_obj"] try: ign = " ".join(args[2:]) user_id = message.author.id platform = f"{sanitize(args[1]).lower()}_ign" except IndexError: ign = "" user_id = message.author.id platform = "_ign" if len(ign) == 0: Log.error("No ign provided") await help_me(message, self.command) return if platform not in user_obj.keys() or platform == "_ign": Log.error("Bad platform") await help_me(message, self.command) return Users().set(user_id, platform, ign) author = message.author.name author = f"{author}'" if author[-1] == "s" else f"{author}'s" msg = f"successfully set {author} {args[1]} name set to {ign}" Log.log(msg) interact(message.channel.send, msg)
async def call(self, package): message, args, user_data, client = package["message_obj"], package["args"], \ package["user_obj"], package["client"] if len(args) < 2 and user_data["osu_ign"] == "": Log.error("No User provided") await help_me(message, "ign-set") return try: user = get_user(args, user_data["osu_ign"], "osu") except UserNonexistent: interact(message.channel.send, "User does not exist") return index = DIGITS.match(args[0]) if index is None: index = 1 else: index = int(index.captures(1)[0]) try: recent_play = get_recent(user, index) except NoPlays as err: interact(message.channel.send, f"`{err}`") Log.log(err) return try: play_data = stat_play(recent_play) except Exception as err: interact(message.channel.send, err) Log.error(err) return Users().update_last_message(message.author.id, recent_play.beatmap_id, "id", recent_play.enabled_mods, play_data.completion, recent_play.accuracy, user, play_data.replay) embed = embed_play(play_data, client) graph = discord.File(play_data.strain_bar, "strains_bar.png") interact(message.channel.send, file=graph, embed=embed) Log.log(f"Returning recent play #{index} for {user}")
async def call(self, package): message, args, user_data, client = package["message_obj"], package["args"], \ package["user_obj"], package["client"] if len(args) < 2 and user_data["osu_ign"] == "": Log.error("No User provided") await help_me(message, "ign-set") return try: user = get_user(args, user_data["osu_ign"], "osu") except UserNonexistent: interact(message.channel.send, "User does not exist") return index = DIGITS.match(args[0]) rb = True if any([i in args[0] for i in ["rb", "recentbest"]]) else False ob = True if any([i in args[0] for i in ["ob", "oldbest"]]) else False if index is None: index = 1 else: index = int(index.group(1)) try: top_play = get_top(user, index, rb, ob) except NoPlays as err: interact(message.channel.send, err) return try: play_data = stat_play(top_play) except Exception as err: interact(message.channel.send, err) Log.error(err) return Users().update_last_message(message.author.id, top_play.beatmap_id, "id", top_play.enabled_mods, 1, top_play.accuracy, user, play_data.replay) embed = embed_play(play_data, client) graph = discord.File(play_data.strain_bar, "strains_bar.png") interact(message.channel.send, file=graph, embed=embed) Log.log(f"Returning top play #{play_data.pb} for {user}")
async def call(self, package): message, args = package["message_obj"], package["args"] DiscordInteractive.client = package["client"] if regex.match("free-?now", args[0]): if str(message.guild.id) not in notified.dictionary["notified"]: interact( message.channel.send, "Please first run `freeSteam <pingrole>` in the " "channel you want pinging to happen") return removeOutstanding() embed = discord.Embed(title="Games Available Now!", color=0x1b2838, timestamp=arrow.utcnow().datetime) embed.set_thumbnail( url= "https://steamcommunity-a.akamaihd.net/public/shared/images/header/" f"globalheader_logo.png?t={arrow.utcnow().timestamp}") for i in sorted(notified.dictionary["notified"][str( message.guild.id)], key=lambda x: x.promoEnd): embed.add_field( name=i.name, value=f"{i.getApp()}\noffer ends {i.promoEnd.humanize()}", inline=False) interact(message.channel.send, embed=embed) return if regex.match("steamUpdate", args[0]): interact(notify_sales) return if len(args) < 2: Log.error("No command provided") await help_me(message, self.command) return role = " ".join(args[1:]) role_obj = None role_id = None if role.startswith("<@&") and role.endswith(">"): role_id = int(role[3:-1]) elif role.isnumeric(): role_id = int(role) else: for i in message.guild.roles: if i.name.lower() == role.lower(): role_obj = i break if role_id is not None: role_obj = message.guild.get_role(role_id) if role_obj is None: unknown_user = f"[{role}] role was not found" Log.error(unknown_user) interact(message.channel.send, f"> {unknown_user}") return ping_server(message.guild.id, message.channel.id, role_obj.mention) interact( message.channel.send, f"{message.channel} is now the alert channel for {message.guild.name} " f"pinging {role_obj.name}") interact(notify_sales)
async def action(self, message_obj, payload): msg = self.warn.format(*payload) Log.log("{0} is in the wrong chat".format(payload[0])) await message_obj.channel.send(msg) await message_obj.delete()
async def action(self, message_obj, payload): Log.log("{0} says bruh".format(str(message_obj.author.name))) await message_obj.add_reaction(payload)
async def on_disconnect(): global workerThread Log.error("disconnected") if workerThread is not None and workerThread.is_alive(): workerThread = None
def _run_ios(): if settings.modify: binary, find, replace = settings.modify if not _exists(binary): _die('Error: {file} not found'.format(file=binary)) Log.w('Modifying: {bin}'.format(bin=binary)) with open(binary, 'r') as f: content = f.read() if find.decode('hex') not in content: _die( 'Error: String {find} not found in the file'.format(find=find)) if content.find(find.decode('hex')) != content.rfind( find.decode('hex')): _die('Error: More than one instance of {find} was found.'.format( find=find)) Log.w('Backing up file to {file}.bk'.format(file=binary)) with open('{file}.bk'.format(file=binary), 'w') as f: f.write(content) Log.w('Replacing {file}'.format(file=binary)) with open(binary, 'w') as f: f.write(content.replace(find.decode('hex'), replace.decode('hex'))) return iosutils = IOSUtils() if not settings.static: iosutils.start_tcp_relay() if settings.install: iosutils.install(settings.install) elif settings.unproxy: if not iosutils.check_dependencies(['proxy'], True, True): _die('Error: Missing dependency - activator.') iosutils.set_proxy() elif settings.proxy: if not iosutils.check_dependencies(['proxy'], True, True): _die('Error: Missing dependency - activator.') iosutils.set_proxy(settings.proxy[0], int(settings.proxy[1])) elif settings.update: iosutils.update_apps_list() iosutils.list_apps() elif settings.runchecks: passed = iosutils.check_dependencies(['full', 'proxy'], silent=False, install=True) Log.w('Checks passed: {result}'.format(result=passed)) elif settings.listapps: iosutils.list_apps() elif settings.app or settings.ipa: iosanalysis = IOSAnalysis(utils=iosutils, app=settings.app, ipa=settings.ipa) settings.results = iosanalysis.run_analysis( 'static' if settings.static else 'full') if settings.results: report = Report(output_path=settings.output, alias=iosanalysis.APP_INFO['CFBundleExecutable'], assessment_type='iOS') if not settings.SILENT: report.report_to_terminal(settings.results) report.report_to_json(settings.results) else: _die('Error: No IPA or APP specified.') iosutils.clean()
async def call(self, package): global eventsq message, args, user_data = package["message_obj"], package[ "args"], package["user_obj"] DiscordInteractive.client = package["client"] if message.guild.id not in eventsq.dictionary: eventsq.dictionary[message.guild.id] = dict() if len(args) < 2: Log.error("No command provided") await help_me(message, self.command) return if args[1].lower() == "init": ping_server(message.guild.id, message.channel.id) interact( message.channel.send, f"{message.channel} is now the alert channel for {message.guild.name}" ) return if args[1].lower() in [ "new", "add" ]: # todo make it so you can add event in one command if ping_server(message.guild.id) is None: interact(message.channel.send, "Please set a default ping channel") return event = self.new_event(message) if event is None: interact(message.channel.send, "Canceled") eventsq.load() eventsq.dictionary[message.guild.id][hash(event)] = event eventsq.save() return if args[1].lower() == "list": eventsq.load() if not eventsq.dictionary[message.guild.id]: interact(message.channel.send, "No events in this server") return events_str = "```\n" for i in eventsq.dictionary[message.guild.id].values(): events_str += f"> {str(i)}" events_str += "\n\n" events_str += "```" interact(message.channel.send, events_str) return # if args[1].lower() == "edit": # load_events() todo # inx = self.pick_event(message) # edit here # save_events() # return if args[1].lower() == "skip": eventsq.load() if not eventsq.dictionary[message.guild.id]: interact(message.channel.send, "No events in this server") return inx = self.pick_event(message) nxt = eventsq.dictionary[message.guild.id][inx].make_next() change = False if nxt is not None: eventsq.dictionary[message.guild.id][hash(nxt)] = nxt change = True del eventsq.dictionary[message.guild.id][inx] interact(message.channel.send, "Event skipped") if change: eventsq.save() return if args[1].lower() == "del": eventsq.load() if not eventsq.dictionary[message.guild.id]: interact(message.channel.send, "No events in this server") return inx = self.pick_event(message) del eventsq.dictionary[message.guild.id][inx] eventsq.save() interact(message.channel.send, "Event deleted") return await help_me(message, self.command)
async def call(self, package): message = package["message_obj"] msg = 'Hello {0.author.mention}'.format(message) Log.log(msg) interact(message.channel.send, msg)
async def call(self, package): message, args = package["message_obj"], package["args"] DiscordInteractive.client = package["client"] if message.guild.id not in mathUsers.dictionary: mathUsers.dictionary[message.guild.id] = dict() if len(args) < 2 or not args[1].lower() in commands: Log.error("No command provided") await help_me(message, self.command) return math_text = "".join(args[2:]) math_text = regex.sub(r"\n?```\n?", "", math_text).replace("`", "") ans = False if message.author.id in mathUsers.dictionary[message.guild.id] and \ (r"\ans" in math_text or ":ans:" in math_text): ans = mathUsers.dictionary[message.guild.id][message.author.id] math: sympy.Expr = None if args[1].lower() in ["parse", "get", "p"]: if len(args) < 3: Log.error("No math provided") interact(message.channel.send, "Please provide a math equation sympy allowed") return if ans: math_text = math_text.replace(r"\ans", ans).replace(":ans:", ans) math = parse_string_equation(math_text) mathUsers.dictionary[message.guild.id][message.author.id] = str( math) if args[1].lower() in ["parselatex", "getlatex"]: if len(args) < 3: Log.error("No math provided") interact(message.channel.send, "Please provide a latex equation") return if ans: ans = f" {sympy.latex(parse_string_equation(ans))} " math_text = math_text.replace(r"\ans", ans).replace(":ans:", ans) math = parse_latex_equation(math_text) # math = replace_exp(math) mathUsers.dictionary[message.guild.id][message.author.id] = str( math) if math is None and message.author.id in mathUsers.dictionary[ message.guild.id]: math = parse_string_equation( mathUsers.dictionary[message.guild.id][message.author.id]) elif math is not None: pass else: Log.error("No math provided") interact(message.channel.send, "You have no math, parse something first") return Log.log(math) if args[1].lower() in ["latex"]: interact(message.channel.send, f"```\n{sympy.latex(math)}\n```") return if args[1].lower() == "solve": if len(args) < 3: Log.error("No variable provided") interact(message.channel.send, "Please provide a variable to solve for") return symbol = sympy.symbols(args[2]) if symbol not in math.free_symbols: Log.error("Invalid Variable") interact(message.channel.send, "Please provide a valid variable") return solutions = sympy.solve(math, symbol) if len(solutions) == 1: math = sympy.Eq(symbol, solutions[0]) else: eqs = [sympy.Eq(symbol, i) for i in solutions] math = sympy.Matrix(eqs) mathUsers.dictionary[message.guild.id][message.author.id] = str( math) if args[1].lower() == "expand": math = sympy.expand(math) mathUsers.dictionary[message.guild.id][message.author.id] = str( math) if args[1].lower() == "simplify": math = sympy.simplify(math) mathUsers.dictionary[message.guild.id][message.author.id] = str( math) if args[1].lower() == "sub": if len(args) < 3: Log.error("No variable(s) provided") interact(message.channel.send, "Please provide a variable to solve for") return subs = dict() for i in regex.finditer(r"([A-z]+) ?= ?([^ ,]+)", math_text): variable = parse_string_equation(i.group(1)) value = parse_string_equation(i.group(2)) if variable not in math.free_symbols: Log.error("Invalid Variable") interact( message.channel.send, f"Please provide a valid variable, not {variable}") return subs[variable] = value math = math.subs(list(subs.items())) mathUsers.dictionary[message.guild.id][message.author.id] = str( math) if args[1].lower() in ["approx", "n"]: math = sympy.N(math) mathUsers.dictionary[message.guild.id][message.author.id] = str( math) if not any([i in str(math) for i in "()"]): interact(message.channel.send, f"```\n{math}\n```") return mathUsers.save() image = render_latex(math) byteImgIO = BytesIO() image.save(byteImgIO, "PNG") byteImgIO.seek(0) math_image = discord.File(byteImgIO, "mathimage.png") image.close() byteImgIO.close() interact(message.channel.send, file=math_image) return
async def call(self, package): message: discord.Message = package["message_obj"] args: List[str] = package["args"] if len(args) < 2: Log.error("No Role provided") await help_me(message, self.command) return role = " ".join(args[1:]) role_obj: Optional[discord.Role] = None role_id = None if role.startswith("<@&") and role.endswith(">"): role_id = int(role[3:-1]) elif role.isnumeric(): role_id = int(role) else: for i in message.guild.roles: if i.name.lower() == role.lower(): role_obj = i break if role_id is not None: role_obj = message.guild.get_role(role_id) if role_obj is None: unknown_user = f"[{role}] role was not found" Log.error(unknown_user) interact(message.channel.send, f"> {unknown_user}") return embed = discord.Embed(color=role_obj.color, title=role_obj.name, description=role_obj.mention) created = f"Role was created on " \ f"{get(role_obj.created_at).format('dddd[,] MMMM Do YYYY [@] h:mm:ss A [UTC]')} " \ f"{SEPARATOR} " \ f"{get(role_obj.created_at).humanize()}" embed.set_footer(text=created) embed.add_field(name="ID", value=str(role_obj.id), inline=True) nRoles = len(message.guild.roles) embed.add_field(name="Position in Guild:", value=str(nRoles - role_obj.position), inline=True) embed.add_field(name="Can be mentioned:", value=str(role_obj.mentionable), inline=True) embed.add_field(name="Will display separately:", value=str(role_obj.hoist), inline=True) aud = role_obj.guild.audit_logs( action=discord.AuditLogAction.role_update) entries = interact(aud.flatten) for i in entries: if i.target.id == role_obj.id: embed.add_field( inline=True, name="Last Updated:", value= f"{get(i.created_at).format('dddd[,] MMMM Do YYYY [@] h:mm:ss A [UTC]')} " f"{SEPARATOR} " f"{get(i.created_at).humanize()}") break if role_obj.members: embed.add_field(inline=False, name="Owners:", value=", ".join( [i.mention for i in role_obj.members])) perms = { 'create_instant_invite': "Create instant invite", 'kick_members': "Kick members", 'ban_members': "Ban members", 'administrator': "Administrator", 'manage_channels': "Manage channels", 'manage_guild': "Manage guild", 'add_reactions': "Add reactions", 'view_audit_log': "View audit log", 'priority_speaker': "Priority speaker", 'stream': "Stream", 'read_messages': "Read messages", 'send_messages': "Send messages", 'send_tts_messages': "Send text-to-speech messages", 'manage_messages': "Manage messages", 'embed_links': "Embed links", 'attach_files': "Attach files", 'read_message_history': "Read message history", 'mention_everyone': "Mention everyone", 'external_emojis': "External emojis", 'view_guild_insights': "View guild insights", 'connect': "Connect", 'speak': "Speak", 'mute_members': "Mute members", 'deafen_members': "Deafen members", 'move_members': "Move members", 'use_voice_activation': "Use voice activation", 'change_nickname': "Change nickname", 'manage_nicknames': "Manage nicknames", 'manage_roles': "Manage roles", 'manage_webhooks': "Manage webhooks", 'manage_emojis': "Manage emojis" } embed.add_field(inline=False, name="Permissions:", value="```diff\n" + "\n".join([ f"{'+' if i[1] else '-'} {perms[i[0]]}: {i[1]}" for i in role_obj.permissions ]) + "\n```") Log.log(f"stating {role_obj.name}") interact(message.channel.send, embed=embed)
async def call(self, package): message: discord.Message = package["message_obj"] args: List[str] = package["args"] client: discord.Client = package["client"] username = None user: discord.User = message.author name = " ".join(args[1:]) if len(args) >= 2: if name.startswith("<@!") and name.endswith(">"): username = int(name[3:-1]) elif name.startswith("<@") and name.endswith(">"): username = int(name[2:-1]) elif name.isnumeric(): username = int(name) else: for i in client.users: if i.name.lower() == name.lower(): user = i break else: for i in message.guild.members: if i.nick is not None and i.nick.lower() == name.lower( ): user = i break else: unknown_user = f"[{name}] user not found" Log.error(unknown_user) interact(message.channel.send, f"> {unknown_user}") raise UserNonexistent(name) if username: user = client.get_user(username) if user is None: user = interact(client.fetch_user, username) if user is None: unknown_user = f"[{name}] user not found" Log.error(unknown_user) interact(message.channel.send, f"> {unknown_user}") raise UserNonexistent(name) logo = user.avatar_url_as(format="png", static_format='png', size=64) picture = interact(logo.read) img = io.imread(picture, plugin='imageio') if img.shape[2] < 3: img = img[:, :, :-1] average = img.mean(axis=0).mean(axis=0) avgInt = list(map(int, map(round, average))) color = "0x{0:02x}{1:02x}{2:02x}".format(*avgInt) embed = discord.Embed().from_dict({ "color": int(color, 16), "thumbnail": { "url": str(user.avatar_url) }, "footer": { "text": f"On Discord since {get(user.created_at).humanize()} " f"{SEPARATOR} Joined on " f"{get(user.created_at).format('dddd[,] MMMM Do YYYY [@] h:mm:ss A [UTC]')}" } }) embed.add_field(name="ID", value=user.id, inline=True) stat_names = { "online": "Online", "offline": "Offline", "idle": "Idle", "dnd": "Do Not Disturb", "do_not_disturb": "Do Not Disturb", "invisible": "Offline" } member: discord.Member = message.guild.get_member(user.id) if member is None: member = discord.utils.find(lambda m: m.id == user.id, client.get_all_members()) if member is not None: embed.add_field(name="Status", value=stat_names[member.status.name], inline=True) if member.nick: if message.guild.id != member.guild.id: title = f"Nickname in {member.guild.name}" embed.add_field(name=title, value=member.nick, inline=True) else: embed.set_author( name=f"{str(user)} {SEPARATOR} {member.nick}", icon_url=str(user.avatar_url)) if member.joined_at: embed.add_field( name=f"Joined {member.guild.name} on", value= f"{get(member.joined_at).format('dddd[,] MMMM Do YYYY [@] h:mm:ss A [UTC]')} " f"{SEPARATOR} {get(member.joined_at).humanize()}", inline=False) if member.premium_since: embed.add_field( name=f"Nitro boosting {member.guild.name} since", value= f"{get(member.premium_since).format('dddd[,] MMMM Do YYYY [@] h:mm:ss A [UTC]')} " f"{SEPARATOR} {get(member.joined_at).humanize()}", inline=False) if member.guild.id == message.guild.id: roles = member.roles[1:] rls = map(lambda x: x.id, roles) embed.add_field(name=f"Roles [{len(roles)}]", value=", ".join([f"<@&{i}>" for i in rls][::-1]), inline=True) if isinstance(member.activity, discord.activity.CustomActivity) and ( member.activity.state or member.activity.emoji is not None): string = "" if member.activity.emoji is not None: string += f"{member.activity.emoji} " if member.activity.name is not None: string += member.activity.name embed.add_field(name="Message", value=string, inline=True) # todo: add support for Game, Spotify and Stream activitys if not embed.author: embed.set_author(name=str(user), icon_url=str(user.avatar_url)) Log.log(f"stating {user.name}") interact(message.channel.send, embed=embed)
async def call(self, package): message, args, user_data, client = package["message_obj"], package["args"], \ package["user_obj"], package["client"] if len(args) < 2 and user_data["osu_ign"] == "": Log.error("No User provided provided") await help_me(message, "ign-set") return try: user = get_user(args, user_data["osu_ign"], "osu") except UserNonexistent: interact(message.channel.send, "User does not exist") return try: user_profile = osu.get_user(user) except UserNonexistent as err: interact(message.channel.send, err) return profile = user_profile[0] grades = \ f"{get_rank_emoji('XH', client)} {int(profile['count_rank_ssh']):,} " \ f"{get_rank_emoji('X', client)} {int(profile['count_rank_ss']):,} " \ f"{get_rank_emoji('SH', client)} {int(profile['count_rank_sh']):,} " \ f"{get_rank_emoji('S', client)} {int(profile['count_rank_s']):,} " \ f"{get_rank_emoji('A', client)} {int(profile['count_rank_a']):,}" seconds = int(profile['total_seconds_played']) play_time = f"{round(seconds / 3600)}h {round(seconds % 3600 / 60)}m" embed = discord.Embed().from_dict({ "color": 0xbb5577, "thumbnail": { "url": f"https://a.ppy.sh/{profile['user_id']}?{int(time())}" }, "author": { "name": f"{profile['username']} – {float(profile['pp_raw']):,.2f}pp (#{int(profile['pp_rank']):,}) " f"({profile['country']}#{int(profile['pp_country_rank']):,})", "icon_url": f"https://a.ppy.sh/{profile['user_id']}?{int(time())}", "url": f"https://osu.ppy.sh/u/{profile['user_id']}" }, "footer": { "text": f"Playing for {profile['join_date'].humanize(only_distance=True)} " f"{SEPARATOR} Joined on {profile['join_date'].format('D MMMM YYYY')}" }, "fields": [{ "name": 'Ranked Score', "value": f"{int(profile['ranked_score']):,}", "inline": True }, { "name": 'Total score', "value": f"{int(profile['total_score']):,}", "inline": True }, { "name": 'Play Count', "value": f"{int(profile['playcount']):,}", "inline": True }, { "name": 'Play Time', "value": play_time, "inline": True }, { "name": 'Level', "value": f"{float(profile['level']):.2f}", "inline": True }, { "name": 'Hit Accuracy', "value": f"{float(profile['accuracy']):.2f}%", "inline": True }, { "name": 'Grades', "value": grades }] }) interact(message.channel.send, embed=embed)