def make_json(mol_dir, mol_name, json_file): """ For a molecule directory, mol_dir, this finds the molecule name, frequencies value, and runtiime and places those into json_file. """ log_files = [x for x in os.listdir(mol_dir) if x.endswith('.log')] if len(log_files) > 0: log_fn = log_files[0] log_path = os.path.join(mol_dir, log_fn) mol = GaussianOutput(log_path) runtime = runtime_from_log(log_path) if mol.properly_terminated: charge = mol.charge try: excitations = mol.read_excitation_energies() except IndexError: excitations = None # Write json json_data = {"molecule_name": mol_name, "excitations": excitations, "charge": charge, "runtime": runtime} write_json(json_data, json_file) print("Data collected for {}".format(mol_name)) else: print("Error. Calculation did not properly terminate for {}".format(mol_name)) else: print("No log file for ", mol_name)
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 create_json_parameters(self, json, local_repo_dest, json_name): try: write_json(json, os.path.join(local_repo_dest, json_name)) except Exception as e: print(e) # def execute_template(self, local_repo_dest, template_executor, parameters): # # execfile('file.py') # os.system('python ' + os.path.join(local_repo_dest, template_executor) '')
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)
def process_input(): try: json_data = request.get_json(force=True) sentence = json_data["sentence"] sentence_type = json_data["sentence_type"] # print(f"request jsondata es: {json_data}") write_json("./input/servidor.json", json_data) detect_and_process(sentence, sentence_type) return sentence #read_json("./results/servidor.json") except: print("key error") return "key error"
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 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 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 make_json(mol_dir, mol_name, json_file): """ For a molecule directory, mol_dir, this finds the energy, xyz, charge, h**o, lumo, homo_lumo_gap, and runtime and places those into json_file. """ # Gather info from log file in mol_dir try: log_fn = [x for x in os.listdir(mol_dir) if x.endswith('.log')][0] log_path = os.path.join(mol_dir, log_fn) mol = GaussianOutput(log_path) if mol.properly_terminated: structure = mol.final_structure xyz = structure.to(fmt="xyz") charge = mol.charge energy = mol.final_energy * 27.2114 num_electrons = mol.electrons[0] eigens = list(mol.eigenvalues.values())[0] h**o = eigens[num_electrons - 1] * 27.2114 lumo = eigens[num_electrons] * 27.2114 homo_lumo_gap = lumo - h**o runtime = runtime_from_log(log_path) normal = 1 else: normal = 0 print("Error. Calculation did not properly terminate for {}".format(mol_name)) except: normal = 0 print("Error. Data NOT collected for {}. Energy calculations may not have finished!".format(mol_name)) # write json file if data was correctly gathered if normal == 1: json_data = { "molecule_name": mol_name, "charge": charge, "structure": xyz, "energy": energy, "h**o": h**o, "lumo": lumo, "homo_lumo_gap": homo_lumo_gap, "runtime": runtime } write_json(json_data, json_file) print("Data collected for {}".format(mol_name))
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 make_json(mol_dir, mol_name, json_file): """ For a molecule directory, mol_dir, this finds the molecule name, omegas value, and runtiime and places those into json_file. """ try: # Gather info from log file in mol_dir log_fn = [x for x in os.listdir(mol_dir) if x.endswith('output.log')][0] log_path = os.path.join(mol_dir, log_fn) runtime = runtime_from_log(log_path) with open(log_path, 'r') as fn: w_data = fn.readlines()[-2].split()[1] w = "0{}".format(w_data.split('.')[1]) # Write json json_data = {"molecule_name": mol_name, "omega": w, "runtime": runtime} write_json(json_data, json_file) print("Data collected for {}".format(mol_name)) except: print( "Error. Omega value NOT collected for {}. wtuning may not have finished!" .format(mol_name))
async def on_message(message): if message.author == bot.user: return else: print( f"User {message.author} said in channel {message.channel}: {message.content}", end="") if not contains_banned_words(message, BANNED_WORDS): print(" OK! No banned words found") for user in DATA['people']: if user['userID'] == message.author.id: unique = False user['xp'] += len(message.content.split(" ")) level_before = user['level'] for x in range(len(LEVELS)): if user['xp'] > LEVELS[x]: user['level'] = x + 1 if level_before != user['level']: await message.channel.send( f"Congratulations {message.author.mention}, you have just hit level {user['level']}!" ) write_json(DATA) break else: unique = True if unique: DATA['people'].append({ 'userID': message.author.id, 'xp': len(message.content), 'level': 1 }) write_json(DATA) else: print(" NOT OK! Curse word found, deleting the message") await message.delete() await message.channel.send(random.choice(CURSE_PHRASES)) await bot.process_commands(message)
def test_write_json(self): # Test that function writes to a JSON file # self.assertEqual(write_json('data/test.json', 'test'), True)
t = [] for item in data: if len(item['entities']['hashtags']) != 0: for h in item['entities']['hashtags']: if h['text'].lower() in pattern: t.append((item['id_str'], item['created_at'], h['text'].lower())) hashtag_counter += 1 text = item['full_text'] text = re.sub(r"http\S+", " ", text) text = re.sub(r"\s+", " ", text) res.append(item['user']['screen_name'] + '\t' + item['id_str'] + '\t' + text + '\t' + item['created_at']) if len(t) > 0: file_name = file_name.split('.', -1)[0] result[file_name] = t sys.stdout.write('\r%d/%d' % (counter, num_of_files)) print("\nnumber of tweets;", tweets_counter) print("found hashtags: ", hashtag_counter) print("final value:", round(hashtag_counter / tweets_counter, 5)) if save: functions.write_json(result, output_dir + 'lexis(' + pattern[0] + ').json') functions.write(res, output_dir + 'lexis(' + pattern[0] + ').txt')
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)
for k, v in threats_dict.items(): if 'Deliberated' in threats_dict[k]: add_word_to_dict(threats_dict, k, 'intentional') # añadimos las palabras para el acrónimo HW for k, v in threats_dict.items(): if 'HW' in threats_dict[k]: add_word_to_dict(threats_dict, k, 'hardware') # añadimos las palabras para el acrónimo SW for k, v in threats_dict.items(): if 'SW' in threats_dict[k]: add_word_to_dict(threats_dict, k, 'software') #print(threats_dict) write_json("./dictionaries/threats_dict.json", threats_dict) #anomalies_dict #-------------------------------------------------------------------------------- anomalies_file = './files/anomalies.txt' terms_list = [] terms_dictionary = {} terms = load_doc(anomalies_file) terms_list += [line.strip() for line in terms] for item in terms_list: terms_dictionary[item] = item.split("_") doc = nlp(' '.join(terms_dictionary[item])) for token in doc: if token.lemma_ not in terms_dictionary[item]: terms_dictionary[item].append(token.lemma_)
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)
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 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 _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)
b_values.append((item['id_str'], item['created_at'])) res.append(item['user']['screen_name']+'\t'+item['id_str']+'\t'+text+'\t'+item['created_at']) for i in ngrams(tokens, 2): if ' '.join([j for j in i]) in A: a_values.append((item['id'], item['created_at'])) res.append(item['user']['screen_name']+'\t'+item['id_str']+'\t'+text+'\t'+item['created_at']) a_values_counter+=len(a_values) b_values_counter+=len(b_values) if len(b_values)>0 or len(a_values)>0: temp['B_values'] = b_values temp['A_values'] = a_values file_name = file_name.split('.',-1)[0] result[file_name] = temp sys.stdout.write('\r%d/%d'%(counter,num_of_files)) print("\nnumber of tweets;", tweets_counter) print("\nnumber of A values: ", a_values_counter) print("number of B values: ", b_values_counter) print("total values: ", a_values_counter+b_values_counter) print("\nfinal A value:", round(a_values_counter/tweets_counter,4)) print("final B value:", round(b_values_counter/tweets_counter,4)) print("final total value:", round((a_values_counter+b_values_counter)/tweets_counter,4)) if save: functions.write_json(result, output_dir+'spelling.json') functions.write(res, output_dir+'spelling.txt')
tags = pos_tag(tokens) grams = [] for j in ngrams(tokens, 2): grams.append(' '.join([x for x in j])) for gram in grams: if gram == i: idx = grams.index(gram) if idx < len(tags) - 2: if tags[idx + 2][1] in ['VB', 'VBP']: id_date.append( (item['id_str'], item['created_at'])) res.append(item['user']['screen_name'] + '\t' + item['id_str'] + '\t' + text + '\t' + item['created_at']) instance_counter += len(id_date) if len(id_date) > 0: file_name = file_name.split('.', -1)[0] result[file_name] = id_date sys.stdout.write('\r%d/%d' % (counter, num_of_files)) print("\nnumber of tweets;", tweets_counter) print("found instaces: ", instance_counter) print("final value:", round(instance_counter / tweets_counter, 4)) if save: functions.write_json(result, output_dir + 'lexico-grammar(' + verb[0] + ').json') functions.write(res, output_dir + 'lexico-grammar(' + verb[0] + ').txt')