async def on_ready(self): config = read_json('config') telnet_ip = config['SERVER_IP'] telnet_port = config['TELNET_PORT'] telnet_username = config['TELNET_USERNAME'] telnet_password = config['TELNET_PASSWORD'] self.bot.reaction_roles = [] self.bot.telnet_object = telnet(telnet_ip, telnet_port, telnet_username, telnet_password) try: self.bot.telnet_object.connect() except ConnectionError: print("Freedom-01 Telnet failed to connect") else: print( f'[{str(datetime.utcnow().replace(microsecond=0))[11:]} INFO]: [TELNET] Bot logged into Telnet as: {self.bot.telnet_object.username}' ) reaction_data = read_json('config') self.bot.reaction_roles = reaction_data['reaction_roles'] self.bot.command_cache = {} print("command cache initalized") print( f'[{str(datetime.utcnow().replace(microsecond=0))[11:]} INFO]: [Client] {self.bot.user.name} is online.' ) game = discord.Game('play.totalfreedom.me') await self.bot.change_presence(status=discord.Status.online, activity=game) print( f'[{datetime.utcnow().replace(microsecond=0)} INFO]: [Blacklist] Current blacklist:' ) for user_id in self.bot.blacklisted_users: user = self.bot.get_user(user_id) if user: print( f'[{datetime.utcnow().replace(microsecond=0)} INFO]: [Blacklist] - {user.name}' ) else: print( f'[{datetime.utcnow().replace(microsecond=0)} INFO]: [Blacklist] - {user_id}' ) guild_count = len(self.bot.guilds) print( f'[{str(datetime.utcnow().replace(microsecond=0))[11:]} INFO]: [Guilds] bot currently in {guild_count} guilds.' ) for guild in self.bot.guilds: print( f'[{str(datetime.utcnow().replace(microsecond=0))[11:]} INFO]: [Guilds] Connected to guild: {guild.name}, Owner: {guild.owner}' )
def todo(ctx): if not ctx.args: return ctx.send( embed={ "title": "Komendy todo:", "description": "> `todo add (tekst)`, `todo view [osoba]`, `todo remove (id)`, `todo clear`", "color": 0xe74c3c }) user = ctx.data["author"]["id"] users = functions.read_json("users") if not user in users: users[user] = {} if not "todo" in users[user]: users[user]["todo"] = [] if ctx.args[0] == "add": ctx.args = " ".join(ctx.args[1:]) if len(ctx.args) > 100: return handler.error_handler(ctx, "toolongtext", 100) users[user]["todo"].append(ctx.args) ctx.send("Dodano do todo") elif ctx.args[0] == "view": if len(ctx.data["mentions"]) == 1: user = ctx.data["mentions"][0]["id"] user = discord.get_user(user) ctx.send( embed={ "title": f"Todo użytkownika {user['username']}:", "description": "\n".join([ f"{users[user['id']]['todo'].index(i)}. {i}" for i in users[user["id"]]["todo"] ]), "color": 0xe74c3c }) elif ctx.args[0] == "remove": if not len(ctx.args) == 2: return handler.error_handler(ctx, "arguments", "todo remove (id)") del users[user]["todo"][int(ctx.args[1])] ctx.send("Usunięto z todo") elif ctx.args[0] == "clear": del users[user]["todo"] ctx.send("Wyczyszczono todo") functions.write_json("users", users)
def GUILD_ROLE_DELETE(ctx): guild = ctx.data["guild_id"] role = ctx.data["role_id"] guilds = functions.read_json("guilds") if "mute_role" in guilds[guild] and guilds[guild]["mute_role"] == role: del guilds[guild]["mute_role"] functions.write_json("guilds", guilds)
def help(ctx): if len(ctx.args) == 1: if not ctx.args[0] in ctx.commands: return handler.error_handler(ctx, "commandnotfound") return ctx.send(embed = { "title": "POMOC:", "description": f"Opis: `{ctx.commands[ctx.args[0]]['description']}`\nUżycie: `{ctx.commands[ctx.args[0]]['usage']}`", "color": 0xe74c3c, "thumbnail": { "url": f"http://cdn.discordapp.com/avatars/{ctx.bot['id']}/{ctx.bot['avatar']}.png?size=2048" }, "footer": { "text": "() - obowiązkowe, [] - opcjonalne" } }) guild = ctx.data["guild_id"] guilds = functions.read_json("guilds") if guild in guilds and "prefix" in guilds[guild]: prefix = guilds[guild]["prefix"] else: prefix = config.prefix blacklist = ["help", "dev"] categories = {} for command in ctx.commands: if not ctx.commands[command]["category"] in categories: categories[ctx.commands[command]["category"]] = [] for command in ctx.commands: categories[ctx.commands[command]["category"]].append("`" + command + "`") fields = [] for category in categories: if not category in blacklist: fields.append({ "name": category + ":", "value": "> " + ", ".join(categories[category]), "inline": False }) fields.append({ "name": "\u200b", "value": f"\[ [Dodaj bota](https://discord.com/api/oauth2/authorize?client_id={ctx.bot['id']}&permissions=268561494&scope=bot) \] \[ [Support](https://discord.gg/tDQURnVtGC) \] \[ [Kod bota](https://github.com/CZUBIX/cenzura) \] \[ [Strona](https://cenzurabot.pl) \]", "inline": False }) ctx.send(embed = { "title": "POMOC:", "description": f"Prefix na tym serwerze to: `{prefix}`\nWpisz `pomoc [komenda]` by sprawdzić użycie danej komendy", "color": 0xe74c3c, "fields": fields })
def pm(ctx): permission = "ADMINISTRATOR" if not (permissions.has_permission(ctx, ctx.data["author"]["id"], permission) or (ctx.data["author"]["id"] == ctx.guilds[ctx.data["guild_id"]]["owner_id"])): return handler.error_handler(ctx, "nopermission", permission) if not (ctx.args and ctx.data["mention_roles"]): return ctx.send(embed = { "title": "Komendy pm:", "description": "> `pm add (rola) (komenda)`, `pm remove (rola) (komenda)`, `pm delete (rola)`", "color": 0xe74c3c }) blacklist = ["help", "botstats", "profile", "todo", "eval", "reload"] guild = ctx.data["guild_id"] guilds = functions.read_json("guilds") if ctx.args[0] == "add": if not ctx.args[2] in ctx.commands: return handler.error_handler(ctx, "notfound") elif ctx.args[2] in blacklist: return ctx.send("Tej komendy nie można dodać/odebrać!") if not ctx.data["mention_roles"][0] in guilds[guild]["permissions"]: guilds[guild]["permissions"][ctx.data["mention_roles"][0]] = {} guilds[guild]["permissions"][ctx.data["mention_roles"][0]][ctx.args[2]] = True ctx.send("Dodano permisje") elif ctx.args[0] == "remove": if not ctx.args[2] in ctx.commands: return handler.error_handler(ctx, "notfound") elif ctx.args[2] in blacklist: return ctx.send("Tej komendy nie można dodać/odebrać!") if not ctx.data["mention_roles"][0] in guilds[guild]["permissions"]: guilds[guild]["permissions"][ctx.data["mention_roles"][0]] = {} guilds[guild]["permissions"][ctx.data["mention_roles"][0]][ctx.args[2]] = False ctx.send("Usunięto permisje") elif ctx.args[0] == "delete": del guilds[guild]["permissions"][ctx.data["mention_roles"][0]] ctx.send("Usunięto role") else: return ctx.send(embed = { "title": "Komendy pm:", "description": "> `pm add (rola) (komenda)`, `pm remove (rola) (komenda)`, `pm delete (rola)`", "color": 0xe74c3c }) functions.write_json("guilds", guilds)
async def setreaction(self, ctx, role: discord.Role = None, msg: discord.Message = None, emoji=None): if role and msg and emoji: await msg.add_reaction(emoji) self.bot.reaction_roles.append([role.id, msg.id, emoji]) data = read_json('config') data['reaction_roles'].append([role.id, msg.id, emoji]) print(data['reaction_roles']) write_json('config', data)
async def online(self, ctx): """Gives a list of online players.""" if ctx.channel.id == self.bot.gmod_server_chat: return em = discord.Embed() config_file = read_json('config') if ctx.channel.id == 793632795598913546: ip = config_file['SERVER_IP_2'] server = 2 else: ip = config_file['SERVER_IP'] server = 1 port = config_file['PLAYERLIST_PORT'] em.title = f"Player List - freedom-0{server}" try: json = requests.get(f"http://{ip}:{port}/list?json=true", timeout=5).json() if json["online"] == 0: em.description = "There are no online players" else: ranks = list(json.keys()) entries = [] for rank in ranks: if rank not in ['max', 'online'] and json[rank]: rank_fixed = rank.split('_') for word in range(len(rank_fixed)): rank_fixed[word] = rank_fixed[word].capitalize() entries.append(format_list_entry(em, json[rank], f'{" ".join(rank_fixed)}')) order = ['Owners', 'Executives', 'Developers', 'Senior Admins', 'Admins', 'Master Builders', 'Operators', 'Imposters'] players = {} rank_categories = ["owners", "master_builders", "senior_admins", "imposters", "executives", "developers", "operators", "admins"] for x in json: if x in rank_categories: players[x] = json[x] print(players) em.description = f"There are {get_visible_player_count(players)} / {json['max']} online players" sorted_ranks = [entry for rank in order for entry in entries if entry.name == rank] for x in sorted_ranks: em.add_field(name=f'{x.name} ({x.playercount})', value=x.value, inline=False) except Exception as e: em.description = 'Server is offline' print(e) await ctx.send(embed=em)
async def telnetconfig(self, ctx, *args): em = discord.Embed() em.title = 'Telnet config' if not args or args[0] in ['reconnect', 'connect']: try: self.bot.telnet_object.connect() self.bot.telnet_object_2.connect() except Exception as e: em.description = f'Failed reconnection: {e}' em.colour = 0xFF0000 else: em.description = 'Reconnection successful' em.colour = 0x00FF00 elif args[0] == 'name': try: self.bot.telnet_object.session.close() self.bot.telnet_object_2.session.close() self.bot.telnet_object.connect(args[1]) self.bot.telnet_object_2.connect(args[1]) config = read_json('config') config['TELNET_USERNAME'] = self.bot.telnet_object.username write_json('config', config) except Exception as e: em.description = f'Failed config edit: {e}' em.colour = 0xFF0000 else: em.description = 'Configuration successful' em.colour = 0x00FF00 elif args[0] == 'test': command = '' for x in range(1, len(args)): command += f'{args[x]} ' time_sent = str(datetime.utcnow().replace(microsecond=0))[11:] self.bot.telnet_object.session.write( bytes(command, 'ascii') + b"\r\n") self.bot.telnet_object.session.read_until( bytes(f'{time_sent} INFO]:', 'ascii'), 2) if ctx.channel == ctx.guild.get_channel(self.bot.server_chat): self.bot.telnet_object.session.read_until( bytes('\r\n', 'ascii'), 2) next_line = self.bot.telnet_object.session.read_until( bytes('\r\n', 'ascii'), 2) em.description = f"Response from server: {next_line.decode('utf-8')}" else: em.description = f'Command **{args[0]}** not found.' em.colour = 0xFF0000 await ctx.send(embed=em)
def removewarnsevent(ctx): if not functions.has_permission(ctx): return handler.error_handler(ctx, "nopermission", ctx.command) if not len(ctx.args) == 1 or ctx.args[0] not in ["kick", "ban", "mute"]: return handler.error_handler(ctx, "arguments", "warnsevent (kick/ban/mute)") guild = ctx.data["guild_id"] guilds = functions.read_json("guilds") del guilds[guild]["warnsevent"][ctx.args[0]] ctx.send("Usunięto event") functions.write_json("guilds", guilds)
def warnsevent(ctx): if not functions.has_permission(ctx): return handler.error_handler(ctx, "nopermission", ctx.command) if not len(ctx.args) == 2 or ctx.args[0] not in ["kick", "ban", "mute"]: return handler.error_handler(ctx, "arguments", "warnsevent (kick/ban/mute) (ilość warnów)") guild = ctx.data["guild_id"] guilds = functions.read_json("guilds") if not "warnsevent" in guilds[guild]: guilds[guild]["warnsevent"] = {} guilds[guild]["warnsevent"][ctx.args[0]] = str(ctx.args[1]) ctx.send("Dodano event") functions.write_json("guilds", guilds)
def warns(ctx): if not functions.has_permission(ctx): return handler.error_handler(ctx, "nopermission", ctx.command) if not len(ctx.data["mentions"]) == 1: return handler.error_handler(ctx, "arguments", "warns (osoba)") guild = ctx.data["guild_id"] guilds = functions.read_json("guilds") if not "warns" in guilds[guild] or not ctx.data["mentions"][0]["id"] in guilds[guild]["warns"]: return handler.error_handler(ctx, "notfound") ctx.send(embed = { "title": f"Warny użytkownika {ctx.data['mentions'][0]['username']}:", "description": "\n".join([f"{guilds[guild]['warns'][ctx.data['mentions'][0]['id']].index(i)}. {i}" for i in guilds[guild]["warns"][ctx.data["mentions"][0]["id"]]]), "color": 0xe74c3c })
def clearwarns(ctx): if not functions.has_permission(ctx): return handler.error_handler(ctx, "nopermission", ctx.command) if not len(ctx.args) == 1: return handler.error_handler(ctx, "arguments", "clearwarns (osoba)") guild = ctx.data["guild_id"] guilds = functions.read_json("guilds") if not "warns" in guilds[guild] or not ctx.data["mentions"][0]["id"] in guilds[guild]["warns"]: return handler.error_handler(ctx, "notfound") del guilds[guild]["warns"][ctx.data["mentions"][0]["id"]] ctx.send("Wyczyszczono ostrzeżenia") functions.write_json("guilds", guilds)
def removewarn(ctx): if not functions.has_permission(ctx): return handler.error_handler(ctx, "nopermission", ctx.command) if not len(ctx.args) == 2: return handler.error_handler(ctx, "arguments", "removewarn (osoba) (id)") guild = ctx.data["guild_id"] guilds = functions.read_json("guilds") if not "warns" in guilds[guild] or not ctx.data["mentions"][0]["id"] in guilds[guild]["warns"]: return handler.error_handler(ctx, "notfound") del guilds[guild]["warns"][ctx.data["mentions"][0]["id"]][int(ctx.args[1])] ctx.send("Usunięto ostrzeżenie") functions.write_json("guilds", guilds)
def unmute(ctx): if not functions.has_permission(ctx): return handler.error_handler(ctx, "nopermission", ctx.command) if not len(ctx.args) == 1: return handler.error_handler(ctx, "arguments", "unmute (osoba)") guild = ctx.data["guild_id"] guilds = functions.read_json("guilds") if not "mute_role" in guilds[guild]: return handler.error_handler(ctx, "notfound") status = discord.remove_guild_member_role(guild, ctx.data["mentions"][0]["id"], guilds[guild]["mute_role"]) if not status.status_code == 204: return handler.error_handler(ctx, 6) ctx.send("Odmutowano użytkownika")
def GUILD_MEMBER_REMOVE(ctx): guild = ctx.data["guild_id"] guilds = functions.read_json("guilds") if not guild in guilds: return if "leavemsg" in guilds[guild]: discord.send(guilds[guild]["leavemsg"]["channel_id"], guilds[guild]["leavemsg"]["text"].replace( "<>", ctx.data["user"]["username"]).replace( "[]", "<@" + ctx.data["user"]["id"] + ">").replace( "{}", str( len( discord.list_guild_members( ctx.data["guild_id"])))), reply=False)
def mute(ctx): if not functions.has_permission(ctx): return handler.error_handler(ctx, "nopermission", ctx.command) if not len(ctx.args) == 1: return handler.error_handler(ctx, "arguments", "mute (osoba)") guild = ctx.data["guild_id"] guilds = functions.read_json("guilds") if not "mute_role" in guilds[guild]: role = discord.create_guild_role(guild, {"name": "muted"}).json() guilds[guild]["mute_role"] = role["id"] channels = discord.get_guild_channels(guild) for channel in channels: if channel["type"] == 0: a = discord.edit_channel_permissions(channel["id"], role["id"], { "deny": permissions.permissions["SEND_MESSAGES"], "allow": permissions.permissions["ADD_REACTIONS"], "type": 0 }) elif channel["type"] == 2: discord.edit_channel_permissions(channel["id"], role["id"], { "deny": permissions.permissions["SPEAK"], "allow": permissions.permissions["VIEW_CHANNEL"], "type": 0 }) functions.write_json("guilds", guilds) status = discord.add_guild_member_role(guild, ctx.data["mentions"][0]["id"], guilds[guild]["mute_role"]) if not status.status_code == 204: return handler.error_handler(ctx, 6) ctx.send("Zmutowano użytkownika")
def MESSAGE_CREATE(ctx): guild = ctx.data["guild_id"] guilds = functions.read_json("guilds") if not guild in guilds: guilds[guild] = {} functions.write_json("guilds", guilds) if "bot" in ctx.data["author"]: return user = ctx.data["author"]["id"] users = functions.read_json("users") if not user in users: users[user] = {} functions.write_json("users", users) if not hasattr(ctx, "messages"): ctx.messages = {} if not ctx.data["guild_id"] in ctx.messages: ctx.messages[ctx.data["guild_id"]] = {} ctx.messages[ctx.data["guild_id"]][ctx.data["id"]] = { "author": ctx.data["author"], "content": ctx.data["content"], "channel_id": ctx.data["channel_id"] } mentions = [user["id"] for user in ctx.data["mentions"]] if ctx.bot["id"] in mentions and len(ctx.data["content"].split()) == 1: guild = ctx.data["guild_id"] guilds = functions.read_json("guilds") if guild in guilds and "prefix" in guilds[guild]: prefix = guilds[guild]["prefix"] else: prefix = config.prefix return ctx.send(f"Mój prefix na tym serwerze to `{prefix}`") if guild in guilds and "cmd" in guilds[guild] and ctx.data[ "content"] in guilds[guild]["cmd"]: ctx.send(guilds[guild]["cmd"][ctx.data["content"]]["text"].replace( "<>", ctx.data["author"]["username"]).replace( "[]", "<@" + ctx.data["author"]["id"] + ">")) if permissions.has_permission(ctx, ctx.data["author"]["id"], "ADMINISTRATOR"): return if guild in guilds and not "badwords" in guilds[guild]: for badword in arrays.badwords: if badword in ctx.data["content"].upper(): channel = discord.get_channel(ctx.data["channel_id"]) if not channel["nsfw"]: status = discord.delete_message( ctx.data["channel_id"], ctx.data["id"]) if status.status_code == 204: ctx.send( "Na tym serwerze przeklinanie jest wyłączone", reply=False) break elif guild in guilds and not "invites" in guilds[guild]: for url in url_blacklist: if url.upper() in ctx.data["content"].upper(): status = discord.delete_message(ctx.data["channel_id"], ctx.data["id"]) if status.status_code == 204: ctx.send( "Na tym serwerze wysyłanie zaproszeń jest wyłączone", reply=False) break
def on_message(self, msg): msg = json.loads(msg) if msg["op"] == 10: data = {"op": 1, "d": 251} data = json.dumps(data) self.ws.send(data) data = { "op": 2, "d": { "token": f"Bot {self.token}", "intents": self.intents, "properties": { "$os": "linux", "$browser": "cenzuralib", "$device": "cenzuralib" } } } data = json.dumps(data) self.ws.send(data) t = threading.Thread(target=self.heartbeat) t.start() self._heartbeat = t self._heartbeat.stop = False if self.presence: self.set_presence(**self.presence) if "ready" in ctx.events and not self.ready: ctx.data = {"ws": self.ws} ctx.events["ready"](ctx) self.ready = True if msg["t"] == "GUILD_CREATE": ctx.guilds[msg["d"]["id"]] = msg["d"] elif msg["t"] == "GUILD_DELETE": del ctx.guilds[msg["d"]["id"]] elif msg["t"] == "MESSAGE_CREATE": ctx.data = msg["d"] guild = ctx.data["guild_id"] guilds = functions.read_json("guilds") if guild in guilds and "prefix" in guilds[guild]: prefix = guilds[guild]["prefix"] else: prefix = self.prefix if msg["d"]["content"].startswith(prefix): if "bot" in msg["d"]["author"]: return command = msg["d"]["content"].split(" ")[0][len(prefix):] while command[0] == "_": command = command[1:] args = msg["d"]["content"].split(" ")[1:] ctx.command = command ctx.args = args ctx.token = self.token ctx.ws = self.ws if command in ctx.commands: try: ctx.commands[command]["function"](ctx) except Exception: handler.error_handler( ctx, "error", traceback.format_exc().splitlines()[-1]) else: handler.error_handler(ctx, "commandnotfound") else: ctx.args = msg["d"]["content"].split(" ") if msg["t"] in ctx.events: ctx.data = msg["d"] ctx.events[msg["t"]](ctx)
def serve_output(): return jsonify(read_json('./results/servidor.json'))
from functions import get_filename_list, read_json with open("literature_corpus.txt", "w") as corpus: for count, filename in enumerate(get_filename_list()): print(count, filename) paragraphs = read_json(filename, as_list=True) for paragraph in paragraphs: if paragraph: corpus.write(paragraph)
#Simple bot to keep track of Wins and Losses for something import discord,asyncio import functions client=discord.Client() def save_stats(): functions.edit_json('stats',stats) stats=functions.read_json('stats') if 'wins' not in stats.keys(): stats['wins']=0 save_stats() if 'losses' not in stats.keys(): stats['losses']=0 save_stats() @client.event async def on_ready(): print('Logged in as: '+client.user.name) print('Bot ID: '+client.user.id) await client.change_presence(game=discord.Game(name='!help - for commands')) print('------') @client.event async def on_message(message): if message.content.lower().startswith('!set_wins'): msg=message.content[len('!set_wins'):].strip() try:
num_cores = multiprocessing.cpu_count() chunk_size = total_files // num_cores processes = [] manager = multiprocessing.Manager() output = manager.dict() for rank in range(num_cores): if rank + 1 == num_cores: file_chunk = files[rank * chunk_size:] else: file_chunk = files[rank * chunk_size:(rank + 1) * chunk_size] print(f"Reading chunk {rank}...") json_contents_list = [read_json(x, as_list=True) for x in file_chunk] p = multiprocessing.Process(target=process_corpus, args=(json_contents_list, output, rank)) p.start() processes.append(p) for k, p in enumerate(processes): p.join() print(f"{k} has finished") main_corpus = [] for k, v in output: main_corpus.extend(v)
def _set(ctx): if not functions.has_permission(ctx): return handler.error_handler(ctx, "nopermission", ctx.command) if not ctx.args: return ctx.send(embed = { "title": "Komendy set:", "description": "> `set prefix (prefix)`, `set welcomemsg (kanał) (tekst)`, `set offwelcomemsg`, `set leavemsg (kanał) (tekst)`, `set offleavemsg`, `set autorole (rola)`, `set offautorole`, `set onbadwords`, `set offbadwords`, `set oninvites`, `set offinvites`", "color": 0xe74c3c, "footer": { "text": "<> = nick osoby, [] = wzmianka, {} = licznik osób" } }) guild = ctx.data["guild_id"] guilds = functions.read_json("guilds") if ctx.args[0] == "prefix": if not len(ctx.args) == 2: return handler.error_handler(ctx, "arguments", "set prefix (prefix)") guilds[guild]["prefix"] = ctx.args[1] ctx.send(f"Ustawiono prefix na `{ctx.args[1]}`") elif ctx.args[0] == "welcomemsg": if not len(ctx.args) >= 2: return handler.error_handler(ctx, "arguments", "set welcomemsg (kanał) (tekst)") guilds[guild]["welcomemsg"] = {} guilds[guild]["welcomemsg"]["channel_id"] = ctx.args[1].replace("<", "").replace("#", "").replace(">", "") guilds[guild]["welcomemsg"]["text"] = " ".join(ctx.args[2:]) ctx.send("Ustawiono wiadomość powitalną") elif ctx.args[0] == "offwelcomemsg": del guilds[guild]["welcomemsg"] ctx.send("Usunięto wiadomość powitalną") elif ctx.args[0] == "leavemsg": if not len(ctx.args) >= 2: return handler.error_handler(ctx, "arguments", "set leavemsg (kanał) (tekst)") guilds[guild]["leavemsg"] = {} guilds[guild]["leavemsg"]["channel_id"] = ctx.args[1].replace("<", "").replace("#", "").replace(">", "") guilds[guild]["leavemsg"]["text"] = " ".join(ctx.args[2:]) ctx.send("Ustawiono wiadomość pożegnalną") elif ctx.args[0] == "offleavemsg": del guilds[guild]["leavemsg"] ctx.send("Usunięto wiadomość pożegnalną") elif ctx.args[0] == "autorole": if not len(ctx.data["mention_roles"]) == 1: return handler.error_handler(ctx, "arguments", "set autorole (rola)") guilds[guild]["autorole"] = ctx.data["mention_roles"][0] ctx.send("Ustawiono autorole") elif ctx.args[0] == "offautorole": del guilds[guild]["autorole"] ctx.send("Usunięto autorole") elif ctx.args[0] == "onbadwords": guilds[guild]["badwords"] = True ctx.send("Włączono brzydkie słowa na tym serwerze") elif ctx.args[0] == "offbadwords": del guilds[guild]["badwords"] ctx.send("Wyłączono brzydkie słowa na tym serwerze") elif ctx.args[0] == "oninvites": guilds[guild]["invites"] = True ctx.send("Włączono wysyłanie zaproszeń na tym serwerze") elif ctx.args[0] == "offinvites": del guilds[guild]["invites"] ctx.send("Wyłączono wysyłanie zaproszeń na tym serwerze") functions.write_json("guilds", guilds)
def profile(ctx): if not ctx.args: return ctx.send( embed={ "title": "Komendy profile:", "description": "> `profile view [osoba]`, `profile set`, `profile remove`", "color": 0xe74c3c }) user = ctx.data["author"]["id"] users = functions.read_json("users") if not "profile" in users[user]: users[user]["profile"] = {} functions.write_json("users", users) if ctx.args[0] == "view": if not ctx.data["mentions"]: user = ctx.data["author"] else: user = ctx.data["mentions"][0] if not "profile" in users[user["id"]]: users[user["id"]]["profile"] = {} functions.write_json("users", users) name = "nie podano" if not "name" in users[ user["id"]]["profile"] else users[ user["id"]]["profile"]["name"] gender = "" if not "gender" in users[ user["id"]]["profile"] else users[ user["id"]]["profile"]["gender"] age = "nie podano" if not "age" in users[ user["id"]]["profile"] else users[user["id"]]["profile"]["age"] description = "nie podano" if not "description" in users[ user["id"]]["profile"] else users[ user["id"]]["profile"]["description"] color = "0;0;0" if not "color" in users[ user["id"]]["profile"] else users[ user["id"]]["profile"]["color"] polish_chars = { "ą": "a", "ś": "s", "ó": "o", "ł": "l", "ę": "e", "ń": "n", "ź": "z", "ż": "z", "ć": "c" } for char in polish_chars: name = name.replace(char, polish_chars[char]) gender = gender.replace(char, polish_chars[char]) age = age.replace(char, polish_chars[char]) description = description.replace(char, polish_chars[char]) new_description = "" if len(description) >= 40: x = 0 for i in description: if x == 30: new_description += "\n" x = 0 new_description += i x += 1 description = new_description avatar = ctx.requests.get( f"https://cdn.discordapp.com/avatars/{user['id']}/{user['avatar']}.png?size=512" ).content open("images/image.png", "wb").write(avatar) image = Image.new("RGBA", (512, 512), (0, 0, 0)) color = Image.new("RGBA", (512, 160), tuple(map(lambda x: int(x), color.split(";")))) avatar = Image.open("images/image.png").convert("RGBA") prostokaty = Image.open("images/prostokaty.png").convert("RGBA") avatar.thumbnail((125, 125)) prostokaty.thumbnail((512, 512)) username = user["username"] + "#" + user["discriminator"] image.paste(color, (0, 0), color) image.paste(prostokaty, (0, 0), prostokaty) image.paste(avatar, (10, 10), avatar) size = 50 for char in username: size -= 1 draw = ImageDraw.Draw(image) username_font = ImageFont.truetype("fonts/Poppins-Bold.ttf", round(size)) gender_font = ImageFont.truetype("fonts/Poppins-Bold.ttf", 20) text1_font = ImageFont.truetype("fonts/Poppins-Bold.ttf", 15) text2_font = ImageFont.truetype("fonts/Poppins-Bold.ttf", 20) invoked_font = ImageFont.truetype("fonts/Poppins-Bold.ttf", 20) draw.text((150, 40), gender, font=gender_font, fill="black") draw.text((149, 41), gender, font=gender_font) draw.text((150, 54), username, font=username_font, fill="black") draw.text((149, 55), username, font=username_font) draw.text((40, 190), "Imie:", font=text1_font) draw.text((275, 190), "Wiek:", font=text1_font) draw.text((40, 293), "Opis:", font=text1_font) draw.text((40, 215), name, font=text2_font) draw.text((275, 215), age, font=text2_font) draw.text((40, 318), description, font=text2_font) image.save("images/profile.png") ctx.send(files=[("profile.png", open("images/profile.png", "rb"))]) elif ctx.args[0] == "set": if not ctx.args[1:]: return ctx.send( embed={ "title": "Komendy profile set:", "description": "> `profile set name (imie)`, `profile set gender (m/k)`, `profile set age (wiek)`, `profile set description (opis)`, `profile set color (#hex/rgb)`", "color": 0xe74c3c }) if ctx.args[1] == "name": if not len(ctx.args) == 3: return handler.error_handler(ctx, "arguments", "profile set name (imie)") if not len(ctx.args[2]) < 10: return handler.error_handler(ctx, "toolongtext", 10) users[user]["profile"]["name"] = ctx.args[2] ctx.send("Ustawiono imie") elif ctx.args[1] == "gender": if not len(ctx.args) == 3: return handler.error_handler(ctx, "arguments", "profile set gender (m/k)") male = ["M", "MEZCZYZNA"] female = ["K", "KOBIETA"] available = male + female if ctx.args[2].upper() in available: if ctx.args[2].upper() in male: users[user]["profile"]["gender"] = "mężczyzna" elif ctx.args[2].upper() in female: users[user]["profile"]["gender"] = "kobieta" else: return handler.error_handler(ctx, "arguments", "profile set gender (m/k)") ctx.send("Ustawiono płeć") elif ctx.args[1] == "age": if not len(ctx.args) == 3: return handler.error_handler(ctx, "arguments", "profile set age (wiek)") try: if int(ctx.args[2]) > 100: return ctx.send("Za dużo") elif int(ctx.args[2]) < 13: return ctx.send("Za mało") except: return handler.error_handler(ctx, "arguments", "profile set age (wiek)") users[user]["profile"]["age"] = ctx.args[2] ctx.send("Ustawiono wiek") elif ctx.args[1] == "description": if len(" ".join(ctx.args[2:])) > 150: return handler.error_handler(ctx, "toolongtext", 150) users[user]["profile"]["description"] = " ".join(ctx.args[2:]) ctx.send("Ustawiono opis") elif ctx.args[1] == "color": if re.search(r"^#(?:[0-9a-fA-F]{3}){1,2}$", ctx.args[2]): color = ";".join( tuple( str(int(ctx.args[2][1:][i:i + 2], 16)) for i in (0, 2, 4))) elif len(ctx.args[2:]) == 3 and (not False in ( (x.isdigit() and int(x) <= 255) for x in ctx.args[2:])): color = ";".join(ctx.args[2:]) else: return handler.error_handler( ctx, "arguments", "profile set color (hex/rgb)") users[user]["profile"]["color"] = color ctx.send("Ustawiono kolor") else: return ctx.send( embed={ "title": "Komendy profile set:", "description": "> `profile set name (imie)`, `profile set gender (m/k)`, `profile set age (wiek)`, `profile set description (opis)`, `profile set color (#hex/rgb)`", "color": 0xe74c3c }) elif ctx.args[0] == "remove": if not ctx.args[1:]: return ctx.send( embed={ "title": "Komendy profile remove:", "description": "> `profile remove name`, `profile remove gender`, `profile remove age`, `profile remove description`, `profile remove color`", "color": 0xe74c3c }) if ctx.args[1] == "name": del users[user]["profile"]["name"] ctx.send("Usunięto imie z twojego profilu") elif ctx.args[1] == "gender": del users[user]["profile"]["gender"] ctx.send("Usunięto płeć z twojego profilu") elif ctx.args[1] == "age": del users[user]["profile"]["age"] ctx.send("Usunięto wiek z twojego profilu") elif ctx.args[1] == "description": del users[user]["profile"]["description"] ctx.send("Usunięto opis z twojego profilu") elif ctx.args[1] == "color": del users[user]["profile"]["color"] ctx.send("Usunięto kolor z twojego profilu") else: return ctx.send( embed={ "title": "Komendy profile remove:", "description": "> `profile remove name`, `profile remove gender`, `profile remove age`, `profile remove description`, `profile remove color`", "color": 0xe74c3c }) else: return ctx.send( embed={ "title": "Komendy profile:", "description": "> `profile view [osoba]`, `profile set`, `profile remove`", "color": 0xe74c3c }) functions.write_json("users", users)
def cmd(ctx): if not functions.has_permission(ctx): return handler.error_handler(ctx, "nopermission", ctx.command)\ guild = ctx.data["guild_id"] guilds = functions.read_json("guilds") if not "cmd" in guilds[guild]: guilds[guild]["cmd"] = {} if not ctx.args: return ctx.send( embed={ "title": "Komendy cmd:", "description": "> `cmd add (komenda) (tekst)`, `cmd remove (komenda)`, `cmd info (komenda)`, `cmd list`", "color": 0xe74c3c, "footer": { "text": "<> = nazwa użytkownika, [] = wzmianka" } }) if ctx.args[0] == "add": if not len(ctx.args) >= 3: return handler.error_handler( ctx, "arguments", "cmd add (nazwa komendy) (tekst)") guilds[guild]["cmd"][ctx.args[1]] = {} guilds[guild]["cmd"][ctx.args[1]]["author"] = ctx.data["author"] guilds[guild]["cmd"][ctx.args[1]]["text"] = ctx.args[2] ctx.send("Dodano komende") elif ctx.args[0] == "remove": if not len(ctx.args) == 2: return handler.error_handler(ctx, "arguments", "cmd remove (nazwa komendy)") del guilds[guild]["cmd"][ctx.args[1]] ctx.send("Usunięto komende") elif ctx.args[0] == "info": if not len(ctx.args) == 2: return handler.error_handler(ctx, "arguments", "cmd info (nazwa komendy)") ctx.send( embed={ "title": f"Informacje o {ctx.args[1]}:", "color": 0xe74c3c, "fields": [{ "name": "Autor:", "value": f"{guilds[guild]['cmd'][ctx.args[1]]['author']['username']}#{guilds[guild]['cmd'][ctx.args[1]]['author']['discriminator']} ({guilds[guild]['cmd'][ctx.args[1]]['author']['id']})", "inline": False }, { "name": "Tekst w komendzie:", "value": guilds[guild]["cmd"][ctx.args[1]]["text"], "inline": False }] }) elif ctx.args[0] == "list": ctx.send( embed={ "title": f"Lista komend ({len(guilds[guild]['cmd'])}):", "description": "\n".join([x for x in guilds[guild]["cmd"]]), "color": 0xe74c3c }) else: return ctx.send( embed={ "title": "Komendy cmd:", "description": "> `cmd add (komenda) (tekst)`, `cmd remove (komenda)`, `cmd info (komenda)`, `cmd list`", "color": 0xe74c3c, "footer": { "text": "<> = nazwa użytkownika, [] = wzmianka" } }) functions.write_json("guilds", guilds)
import discord,asyncio import functions client=discord.Client() check_messages=functions.read_json('check_messages') server_messages=[] @client.event async def on_ready(): print('Logged in as: '+client.user.name) print('Bot ID: '+client.user.id) await client.change_presence(game=discord.Game(name='Checking Reactions')) for server in client.servers: for channel in server.channels: async for message in client.logs_from(channel,limit=5000): if message.id in check_messages.keys(): client.messages.append(message) print('------') @client.event async def on_reaction_add(reaction,user): if reaction.message.id in check_messages.keys(): if user.bot==True: return if user.id not in check_messages[reaction.message.id]['users']: await client.remove_reaction(reaction.message,reaction.emoji,user) if user.id in check_messages[reaction.message.id]['users']: check_messages[reaction.message.id]['users'].remove(user.id) if len(check_messages[reaction.message.id]['users'])==0: await client.send_message(reaction.message.author,'All users have reacted to message:\n```{}\n\nPosted: {}```'.format(reaction.message.clean_content,reaction.message.timestamp)) del check_messages[reaction.message.id]
import discord from discord.ext import commands from functions import edit_json, read_json bot = commands.Bot(command_prefix='!') reaction_roles = read_json('reaction_roles') active_messages = [] approved_roles = ['Admin'] #Checks if members role is in approved roles def is_approved(): def predicate(ctx): if ctx.message.author is ctx.message.server.owner: return True return any(role.name in approved_roles for role in ctx.message.author.roles) return commands.check(predicate) @bot.event async def on_ready(): print(bot.user.name) print(bot.user.id) for server in bot.servers: print(server.name)
def warn(ctx): if not functions.has_permission(ctx): return handler.error_handler(ctx, "nopermission", ctx.command) if not len(ctx.data["mentions"]) == 1: return handler.error_handler(ctx, "arguments", "warn (osoba) [powód]") if len(ctx.args) >= 2: ctx.args = " ".join(ctx.args[1:]) reason = ctx.args else: reason = "nie podano powodu" guild = ctx.data["guild_id"] guilds = functions.read_json("guilds") if not "warns" in guilds[guild]: guilds[guild]["warns"] = {} if not ctx.data["mentions"][0]["id"] in guilds[guild]["warns"]: guilds[guild]["warns"][ctx.data["mentions"][0]["id"]] = [] guilds[guild]["warns"][ctx.data["mentions"][0]["id"]].append(reason) if "warnsevent" in guilds[guild] and "kick" in guilds[guild]["warnsevent"] and guilds[guild]["warnsevent"]["kick"] == str(len(guilds[guild]["warns"][ctx.data["mentions"][0]["id"]])): status = discord.remove_guild_member(ctx.data["guild_id"], ctx.data["mentions"][0]["id"]) if not status.status_code == 204: return handler.error_handler(ctx, 6) ctx.send(f"Wyrzucono użytkownika `{ctx.data['mentions'][0]['username']}`") elif "warnsevent" in guilds[guild] and "ban" in guilds[guild]["warnsevent"] and guilds[guild]["warnsevent"]["ban"] == str(len(guilds[guild]["warns"][ctx.data["mentions"][0]["id"]])): status = discord.create_guild_ban(ctx.data["guild_id"], ctx.data["mentions"][0]["id"], reason) if not status.status_code == 204: return handler.error_handler(ctx, 6) ctx.send(f"Zbanowano użytkownika `{ctx.data['mentions'][0]['username']}`") elif "warnsevent" in guilds[guild] and "mute" in guilds[guild]["warnsevent"] and guilds[guild]["warnsevent"]["mute"] == str(len(guilds[guild]["warns"][ctx.data["mentions"][0]["id"]])): if not "mute_role" in guilds[guild]: role = discord.create_guild_role(guild, {"name": "muted"}).json() guilds[guild]["mute_role"] = role["id"] channels = discord.get_guild_channels(guild) for channel in channels: if channel["type"] == 0: a = discord.edit_channel_permissions(channel["id"], role["id"], { "deny": permissions.permissions["SEND_MESSAGES"], "allow": permissions.permissions["ADD_REACTIONS"], "type": 0 }) elif channel["type"] == 2: discord.edit_channel_permissions(channel["id"], role["id"], { "deny": permissions.permissions["SPEAK"], "allow": permissions.permissions["VIEW_CHANNEL"], "type": 0 }) status = discord.add_guild_member_role(guild, ctx.data["mentions"][0]["id"], guilds[guild]["mute_role"]) if not status.status_code == 204: return handler.error_handler(ctx, 6) ctx.send("Zmutowano użytkownika") ctx.send(f"Użytkownik `{ctx.data['mentions'][0]['username']}` dostał ostrzeżenie z powodu `{reason}`") functions.write_json("guilds", guilds)