async def command_error(bot, ctx, error): print(f'error: {error}') bot.command_errors += 1 if isinstance(error, CommandNotFound): regex = re.search(r'".*"', str(error)) if regex is not None: false_command = regex.group() else: false_command = "" dis = 1000 current_command = "" for command in bot.commands: test_distance = distance(command.name, false_command) if test_distance < dis: dis = test_distance current_command = command.name for alias in command.aliases: test_distance = distance(alias, false_command) if test_distance < dis: dis = test_distance current_command = alias return await ctx.send(embed=simple_embed( False, f' I do not recognize that command. It is closest to the existing command "{current_command}". If you did not mean to use that then try {CONFIG.prefix}help' )) if isinstance(error, DiscordException): print("the error was a discord error") print(error) await ctx.send(embed=simple_embed(False, str(error))) etype = type(error) trace = error.__traceback__ verbosity = 4 lines = traceback.format_exception(etype, error, trace, verbosity) traceback_text = ''.join(lines) print(traceback_text)
async def alert(self, ctx,format:converters.FormatConverter="all", *options): parsed_format=methods.parse_format(format) if not parsed_format: return await ctx.send(embed=embeds.simple_embed(False,"invalid format")) with open('data/alertpeople2.txt', "r") as f: people=json.loads(f.read()) if str(ctx.author.id) in people: del people[str(ctx.author.id)] await ctx.send(embed=embeds.simple_embed(False,"you will now be deleted from the alert list")) else: people[str(ctx.author.id)]={ "format":parsed_format } for option in options: if option.startswith("time:"): pt = datetime.strptime(option[5:],'%H:%M:%S') people[str(ctx.author.id)]["time"]= pt.second + pt.minute*60 + pt.hour*3600 + time() elif option.startswith("uses:"): try: people[str(ctx.author.id)]["uses"]=int(option[5:]) except: return await ctx.send(embed=embeds.simple_embed(False,"invalid uses amount")) else: return await ctx.send(embed=embeds.simple_embed(False, "invalid option")) await ctx.send(embed=embeds.simple_embed(True,f'You will be alerted when the next game starts')) with open('data/alertpeople2.txt', "w") as f: f.write(json.dumps(people))
async def game(self, ctx, sort="newest", *, format: converters.FormatConverter = "all"): result = await get_global_games() games = result["result"]["games"] # append_string ="" if format != "all": print("format is ", format) games = list( filter(lambda game: game["properties"]["title"] == format, games)) if sort == "newest": sorted_games = sorted( games, key=lambda game: -int(game["properties"]["startofgame2"])) elif sort == "empty": sorted_games = sorted( games, key=lambda game: -int(game["properties"]["openSlots"])) else: return await ctx.send(embed=embeds.simple_embed( False, "invalid sorting. Try perhaps newest or empty")) if len(sorted_games) == 0: return await ctx.send( embed=embeds.simple_embed(False, "can't find any games")) game = sorted_games[0]["properties"] reply = game["gameID"] ts = int(game["startofgame2"]) await ctx.send(embed=embeds.simple_embed( True, f'Game {reply} has just started at time {datetime.utcfromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S")} . It is at {int(game["nrofplayers"])-int(game["openSlots"])}/{game["nrofplayers"]} You can join it by going to https://www.conflictnations.com/play.php?bust=1&gameID={reply} type !con gpl {game["gameID"]} to get the players in the game and !con format {game["title"]} to see the format' ))
async def units(self, ctx, level: int = 0, *unit_name: str): unit_name = " ".join(unit_name) print(unit_name, level) with open('data/units.json') as json_file: data = json.load(json_file) found_units = list( filter( lambda unit: unit["unitName"].lower() == unit_name.lower(), data)) if len(found_units) == 0: return await ctx.send( embed=embeds.simple_embed(False, "cannot find unit")) if len(found_units) < level: return await ctx.send(embed=embeds.simple_embed( False, "unit does not exist at that level")) found_unit = found_units[level] del found_unit["@c"] del found_unit["statsColumnID"] del found_unit["camouflage"] del found_unit["unitPack"] if "buildTime" in found_unit: found_unit["buildTime"] = str( seconds_to_time(int(found_unit["buildTime"]))) print("buildtime is now", found_unit["buildTime"]) if "costs" in found_unit: found_unit["costs"] = parse_costs(found_unit["costs"]) print("costs is now", found_unit["costs"]) if "dailyCosts" in found_unit: found_unit["dailyCosts"] = parse_costs( found_unit["dailyCosts"]) print("dailyCosts is now", found_unit["costs"]) return await ctx.send(embed=embeds.dict_to_embed( found_unit, f'https://www.conflictnations.com/clients/con-client/con-client_live/images/warfare/2/{found_unit["identifier"]}_1_0.png?1593611138' ))
async def command_error(bot, ctx, error): print(error, "error") if isinstance(error, CommandNotFound): regex = re.search(r'"([A-Za-z0-9_\./\\-]*)"', str(error)) false_command = regex.group() dis = 1000 current_command = "" for command in bot.commands: test_distance = distance(command.name, false_command) if test_distance < dis: #print(f'distance from {command.name} to {false_command} is {test_distance}') dis = test_distance current_command = command.name for alias in command.aliases: test_distance = distance(alias, false_command) #print(f'distance from {alias} to {false_command} is {test_distance}') if test_distance < dis: dis = test_distance current_command = alias return await ctx.send(embed=simple_embed( False, f' I do not recognize that command. It is closest to "{current_command}"' )) await ctx.send(embed=simple_embed(False, str(error))) etype = type(error) trace = error.__traceback__ verbosity = 4 lines = traceback.format_exception(etype, error, trace, verbosity) traceback_text = ''.join(lines) print(traceback_text)
async def list_games(self, ctx, sort="newest", *, format: converters.FormatConverter = "all"): result = await get_global_games() games = result["result"]["games"] if format != "all": print("format is ", format) games = list( filter(lambda game: game["properties"]["title"] == format, games)) if sort == "newest": sorted_games = sorted( games, key=lambda game: -int(game["properties"]["startofgame2"])) elif sort == "empty": sorted_games = sorted( games, key=lambda game: -int(game["properties"]["openSlots"])) else: return await ctx.send(embed=embeds.simple_embed( False, "invalid sorting. Try perhaps newest or empty")) if len(sorted_games) == 0: return await ctx.send( embed=embeds.simple_embed(False, "can't find any games")) games = list(map(lambda game: game["properties"], games)) return_dict = {} for index, game in enumerate(games): reply = game["gameID"] ts = int(game["startofgame2"]) return_dict[ index + 1] = f'Game {reply} has just started at time {datetime.utcfromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S")}. It is at {int(game["nrofplayers"])-int(game["openSlots"])}/{game["nrofplayers"]}.' await ctx.send(embed=embeds.dict_to_embed(return_dict))
async def help(self, ctx, cog=""): if cog=="": return await ctx.send(embed=simple_embed(True,''' - $help - shows all commands - $send (from wallet) (to wallet) (amount) - sends an amount to a person from that wallet - $print (wallet name) (amount) - creates an amount of money in that wallet if you have the role "printer" - $balance (wallet name) - returns the amount of money in the wallet - $links - show some links related to this bot - $smart-contract (trigger) (code block) - code a smart contract - $clear-contracts - delete all your smart contracts. - $create (ping wallet) - create an account - $whois (condition) - figure out who is a condition - $send-each (from wallet) (ammount) (condition) - send each person who meets a condition - $set-balance (ping wallet) - set the balance of a wallet for admins only - $set-balance-each (amount) (condition) - set the balance of each person who meets a condition - $wallet-settings (target person) (ping wallet) (setting name) (boolean) - change the setting, such as view or access, to allow certain people to do more with wallets - $trade (wallet) (wanted currency) (giving up currency) (optional limitations) - create a trade - $accept (message id of trade) (wallet) - accept a trade - $quiz - start a quiz based on a subject - $shop (item name) (price) - same as trade but only for admins and you can also offer roles as trades - $work - get an amount of money no strings attached - $work-conditional (level name) (work reward) (conditional) - allows admins to add levels to working and give different people different work rewards ''')) if not cog in self.bot.cogs: return await ctx.send(embed=simple_embed(False,f'Unrecognized module. The recognized modules are {", ".join(self.bot.cogs)}')) return_commands = [] for command in self.bot.commands: print("command",command.cog.__class__.__name__) if command.cog.__class__.__name__ == cog: return_commands.append(command) return_commands=list(map(lambda c:f'{str(c)} - {str(c.description)}',return_commands)) return await ctx.send(embed=simple_embed(True,"\n".join(return_commands)))
async def leave(self, ctx, *, coach: PersonConverter): if coach.id == ctx.author.id: return await ctx.send(embed=embeds.simple_embed( False, f'you cannot join your own team')) with open('data/coach.txt', "r") as f: coaches = json.loads(f.read()) if not str(coach.id) in coaches: coaches[str(coach.id)] = { "options": { "teamsize": 5, "admit": True }, "team": [], "waiting": [] } if str(ctx.author.id) not in coaches[str(coach.id)]["team"] or str( ctx.author.id) in coaches[str(coach.id)]["waiting"]: return await ctx.send(embed=embeds.simple_embed( False, f'you cannot leave a team that you are not on')) coaches[str(coach.id)]["waiting"] = list( filter(lambda team: team != str(ctx.author.id), coaches[str(coach.id)]["waiting"])) coaches[str(coach.id)]["team"] = list( filter(lambda team: team != str(ctx.author.id), coaches[str(coach.id)]["team"])) await ctx.send(embed=embeds.simple_embed( True, f'you were removed from the team of {coach.name}')) with open('data/coach.txt', "w") as f: f.write(json.dumps(coaches)) await update_room_permissions(ctx.guild, coach)
async def coach_settings(self, ctx, setting_name, option): with open('data/coach.txt', "r") as f: coaches = json.loads(f.read()) if not str(ctx.author.id) in coaches: coaches[str(ctx.author.id)] = { "options": { "teamsize": 5, "admit": True }, "team": [], "waiting": [] } if setting_name == "admit": option = (option.lower() == "true") elif setting_name == "teamsize": try: option = int(option) except: return await ctx.send(embed=embeds.simple_embed( False, f'teamsize must be an integer')) else: return await ctx.send(embed=embeds.simple_embed( False, f'invalid setting name. The settings are teamsize and admit' )) coaches[str(ctx.author.id)]["options"][setting_name] = option with open('data/coach.txt', "w") as f: f.write(json.dumps(coaches)) await update_room_permissions(ctx.guild, ctx.author) return await ctx.send(embed=embeds.dict_to_embed(parse_ids(ctx.author)) )
async def delete_work(self, ctx, conditional_name): guild_collection = db[str(ctx.guild.id)] server_config = guild_collection.find_one({ "type": "server", "id": ctx.guild.id }) print("server config is", server_config) if server_config is None: return await ctx.send( embed=simple_embed(False, "can't find the work conditional")) if not "work-conditional" in server_config: return await ctx.send( embed=simple_embed(False, "can't find the work conditional")) matches = [ x for x in server_config["work-conditional"] if x["name"] != conditional_name ] if len(matches) == len(server_config["work-conditional"]): return await ctx.send(embed=simple_embed( False, "can't find the work conditional by that given name")) guild_collection.update_one({"id": ctx.guild.id}, {"$set": { f'work-conditional': matches }}) return await ctx.send(embed=simple_embed(True, "ok it was deleted"))
async def ping_command(self, ctx): start = d.timestamp(d.now()) msg = await ctx.send(embed=embeds.simple_embed(False, "pinging......")) await msg.edit(embed=embeds.simple_embed( True, f'Pong!\nOne message round-trip took {(d.timestamp(d.now())-start) * 1000}ms.' )) return True
async def servers(self, ctx): if ctx.author.id !=464954455029317633: return await ctx.send(embed=embeds.simple_embed(False, "only eulerthedestroyer#2074 can use admin commands")) ret_string="" activeservers = self.bot.guilds for guild in activeservers: ret_string += guild.name+"\n" return await ctx.send(embed=embeds.simple_embed(True,ret_string))
async def leave(self, ctx, *, server): if ctx.author.id !=464954455029317633: return await ctx.send(embed=embeds.simple_embed(False, "only eulerthedestroyer#2074 can use admin commands")) found_server = [guild for guild in self.bot.guilds if guild.name == server] if len(found_server)==0: return await ctx.send(embed=embeds.simple_embed(False, "can't find server")) await found_server[0].leave() return await ctx.send(embed=embeds.simple_embed(True, "success"))
async def module(self, ctx, module_name): found_commands = [ c for c in self.bot.commands if f'.{module_name}' in c.module ] if len(found_commands) == 0: return await ctx.send( embed=simple_embed(False, "can't find module")) return await ctx.send(embed=simple_embed( True, ",\n".join(list(map(lambda c: c.name, found_commands)))))
async def game_players(self, ctx, game_id: int): result = await get_players_in_game(game_id) sep_char = " " if ("-compress" in ctx.message.flags["unnamed"]) else ",\n" if len(result["result"]) == 0: return await ctx.send( embed=embeds.simple_embed(False, "could not find game")) formatted = f'found {len(result["result"]["logins"])} players \n' + sep_char.join( list(map(lambda x: x["login"], result["result"]["logins"]))) return await ctx.send(embed=embeds.simple_embed(True, formatted))
async def quiz(self, ctx): quiz_type = random.choice([ "identify unit image", "identify unit description", "identify country flag" ]) answer_type = random.choice(["open response", "multiple choice"]) if quiz_type == "identify unit image": with open('data/units.json') as json_file: units = json.load(json_file) chosen_unit = random.choice(units) correct_answer = chosen_unit["unitName"] question = f'https://www.conflictnations.com/clients/con-client/con-client_live/images/warfare/2/{chosen_unit["identifier"]}_1_0.png?1593611138' incorrect_answers = list( map(lambda x: x["unitName"], random.sample(units, 3))) elif quiz_type == "identify unit description": with open('data/units.json') as json_file: units = json.load(json_file) chosen_unit = random.choice(units) correct_answer = chosen_unit["unitName"] question = f'Identify the following unit: {chosen_unit["unitDesc"]}' incorrect_answers = list( map(lambda x: x["unitName"], random.sample(units, 3))) elif quiz_type == "identify country flag": with open('data/countriesfinal.txt') as json_file: countries = json.load(json_file) chosen_country = random.choice(list(countries.keys())) correct_answer = chosen_country question = f'https://www.conflictnations.com/clients/con-client/con-client_live/images/flags/countryFlagsByName/big_{chosen_country.lower().replace(" ","")}.png?' incorrect_answers = random.sample(list(countries.keys()), 3) question_body = f'\n \n This question is of type {quiz_type}. You have 10 seconds to answer. \n ' if answer_type == "multiple choice": incorrect_answers.append(correct_answer) question_body += f'\n \n Your answer choices are {", ".join(incorrect_answers)}' if question.startswith("http"): await ctx.send( embed=embeds.simple_embed(True, question_body, question)) else: question_body = question + "\n" + question_body await ctx.send(embed=embeds.simple_embed(True, question_body)) def check(m): return m.channel == ctx.channel and m.author == ctx.author response = await self.bot.wait_for('message', check=check) print("response is", response.content, " and correct_answer is", correct_answer, response == correct_answer) if response.content == correct_answer: return await ctx.send( embed=embeds.simple_embed(True, "yay you got it correct")) else: return await ctx.send(embed=embeds.simple_embed( False, f'oof the correct answer was actually, {correct_answer}'))
async def set_settings(self, ctx, account: WalletConverter, setting_name, value): if not setting_name in config[ "wallet_settings"] and not setting_name.startswith("print-"): return await ctx.send( embed=simple_embed(False, "invalid setting name")) value = (value.lower() == "true") person = ctx.author guild_collection = db[str(ctx.guild.id)] account = guild_collection.find_one({"id": account["id"]}) if not account: return await ctx.send( embed=simple_embed(False, "wallet does not have an accound")) can_access = False if person.guild_permissions.administrator: can_access = True if not can_access: return await ctx.send(embed=simple_embed( False, "you cannot edit the settings of this wallet")) temp = account print(temp, setting_name) if not "permissions" in temp: temp["permissions"] = {} if temp["permissions"] is None: temp["permissions"] = {} if not setting_name in temp["permissions"]: temp["permissions"][setting_name] = {"true": [], "false": []} if not "true" in temp["permissions"][setting_name]: temp["permissions"][setting_name] = {"true": [], "false": []} if value: if account["id"] in temp["permissions"][setting_name]["true"]: return await ctx.send( embed=simple_embed(False, "setting already true")) temp["permissions"][setting_name]["true"].append(account["id"]) try: temp["permissions"][setting_name]["false"].remove( account["id"]) except: pass else: if account["id"] in temp["permissions"][setting_name]["false"]: return await ctx.send( embed=simple_embed(False, "setting already false")) temp["permissions"][setting_name]["false"].append(account["id"]) try: temp["permissions"][setting_name]["true"].remove(account["id"]) except: pass guild_collection.update_one( {"_id": account["_id"]}, {"$set": { "permissions": temp["permissions"] }}) return (True, "settings successfully changed")
async def move(self, ctx, person: PersonConverter, *, area='off'): if person.id == ctx.author.id: return await ctx.send(embed=embeds.simple_embed( False, f'you cannot join your own team')) print("the person is", person.name) with open('data/coach.txt', "r") as f: coaches = json.loads(f.read()) if not str(ctx.author.id) in coaches: coaches[str(ctx.author.id)] = { "options": { "teamsize": 5, "admit": True }, "team": [], "waiting": [] } coaches[str(ctx.author.id)]["waiting"] = list( filter(lambda team: team != str(person.id), coaches[str(ctx.author.id)]["waiting"])) coaches[str(ctx.author.id)]["team"] = list( filter(lambda team: team != str(person.id), coaches[str(ctx.author.id)]["team"])) if area == "team": coaches[str(ctx.author.id)]["team"] = [ *coaches[str(ctx.author.id)]["team"], str(person.id) ] elif area == "waiting": coaches[str(ctx.author.id)]["waiting"] = [ *coaches[str(ctx.author.id)]["waiting"], str(person.id) ] elif area == "off": for person in coaches[str(ctx.author.id)]["waiting"]: if len(coaches[str(ctx.author.id)]["team"]) >= coaches[str( ctx.author.id)]["options"]["teamsize"]: break coaches[str(ctx.author.id)]["waiting"] = list( filter(lambda team: team != person, coaches[str(ctx.author.id)]["waiting"])) coaches[str(ctx.author.id)]["team"] = [ *coaches[str(ctx.author.id)]["team"], person ] else: await ctx.send(embed=embeds.simple_embed( False, f'invalid area. You cannot move someone to an area that does not exist' )) with open('data/coach.txt', "w") as f: f.write(json.dumps(coaches)) await update_room_permissions(ctx.guild, ctx.author) return await ctx.send(embed=embeds.dict_to_embed(parse_ids(ctx.author)) )
async def news(self, ctx, *, title): def check(m): return m.channel == ctx.channel and m.author == ctx.author await ctx.send( embed=embeds.simple_embed(True, "ok now give me the article body")) response1 = await self.bot.wait_for('message', check=check) body = response1.content await ctx.send( embed=embeds.simple_embed(True, "ok now give me the country name")) response2 = await self.bot.wait_for('message', check=check) #async with ctx.typing(): country = response2.content flag_response = requests.get( f'https://www.conflictnations.com/clients/con-client/con-client_live/images/flags/countryFlagsByName/small_{country.lower().replace(" ","")}.png?' ) flag = Image.open(BytesIO(flag_response.content)) flag_size = 70, 80 flag = flag.resize((34, 30)) img = Image.new("RGB", (800, 800), (255, 255, 255)) #img = Image.open("data/article.png") #Replace infoimgimg.png with your background image. draw = ImageDraw.Draw(img) title_font = ImageFont.truetype( "data/fonts/Exo2Semibold.otf", 33) #Make sure you insert a valid font from your folder. body_font = ImageFont.truetype("data/fonts/tinos.regular.ttf", 18) sub_font = ImageFont.truetype("data/fonts/tinos.italic.ttf", 16) def draw_underlined_text(draw, pos, text, font, **options): twidth, theight = draw.textsize(text, font=font) lx, ly = pos[0], pos[1] + theight + 2 print("lx is ", lx, "and ly is", ly) print("twidth is", twidth) draw.text(pos, text, (0, 0, 0), font=font, **options) draw.line((lx, ly, lx + twidth, ly), fill="black", width=1) draw.text((lx + twidth, pos[1]), " - Offical government press release, 22:52", (0, 0, 0), font=font) # x1, y2 = draw.textsize(title, font=title_font) # x2, y2 = draw.textsize(body, font=body_font) draw.text((70, 35), title, (0, 0, 0), font=title_font) #draws Information draw.text((20, 85), body, (0, 0, 0), font=body_font) draw_underlined_text(draw, (12, 10), country, sub_font) img.paste(flag, (24, 40)) img = trim(img) final_buffer = BytesIO() img.save(final_buffer, "png") # save into the stream, using png format. final_buffer.seek(0) # seek back to the start of the stream file = discord.File(filename="article_2.png", fp=final_buffer) await ctx.send(file=file) # send it
async def map(self, ctx, mode ="ww3",score="cities"): with open('data/map.txt') as json_file: data = json.load(json_file) if mode == "index": ret_string = "" for mode in data: ret_string+=f'\n\n{mode}' for score in data[mode]: ret_string+=f'\n\t\t-{score}' return await ctx.send(embed=embeds.simple_embed(True, ret_string)) if mode not in data: return await ctx.send(embed=embeds.simple_embed(False, f'invalid mode. Valid modes are {", ".join(list(data.keys()))}')) if not score in data[mode]: return await ctx.send(embed=embeds.simple_embed(False, f'invalid score. Valid scores are {", ".join(list(data[mode].keys()))}')) return await ctx.send(embed=embeds.simple_embed(True, "I'm currently working on more modes such as blood and oil and rising tides. Expect them to be here soon.", data[mode][score]))
async def balance(self, ctx, wallet: WalletConverter): if "permissions" in wallet: if "view" in wallet["permissions"]: print(1) if ctx.author.id in wallet["permissions"]["view"]["false"]: print(2) return await ctx.send(embed=simple_embed(( False, "you do not have permission to see this wallet"))) res = "" for key, value in wallet.items(): if ("balance" in key): res = res + f'{key}: {value}\n' return await ctx.send( embed=simple_embed(True, f'the balance is:\n {res}'))
async def ispect_trade(self, ctx, id: int): guild_collection = db[str(ctx.guild.id)] print(id) trade = guild_collection.find_one({"type": "trade", "message_id": id}) if trade is None: return await ctx.send( embed=simple_embed(False, "cannot find that trade")) embedVar = discord.Embed(title="EU Economy Bot", color=0x00ff00, url=config["website"]) if "_id" in trade: del trade["_id"] if not "uses" in trade: trade["uses"] = "(no usage limit set for this trade)" if not "offer_time" in trade: trade["offer_time"] = "(no time limit set for this trade)" if not "people_restrictions" in trade: trade[ "people_restrictions"] = "(no persoal limit set for this trade)" for attribute in trade: print(attribute, "name") if trade[attribute] is None or trade[attribute] == "": trade[attribute] = "(none)" print(trade[attribute], "value") embedVar.add_field(name=attribute, value=trade[attribute]) return await ctx.send(embed=embedVar)
async def alert_people(client, game): with open('data/alertpeople2.txt', "r") as f: alertpeople = json.loads(f.read()) #f.read().split("\n") format = game["properties"]["title"] id = game["properties"]["gameID"] game = game["properties"] for person in alertpeople.copy(): if alertpeople[person]["format"] == format or alertpeople[person][ "format"] == "all": try: user = client.get_user(int(person)) # client.print("sending... to"+ user.name) await user.send(embed=embeds.simple_embed( True, f'Game {id} {format} has just started at time {datetime.utcfromtimestamp(int(game["startofgame2"])).strftime("%Y-%m-%d %H:%M:%S")}. It is at {int(game["nrofplayers"])-int(game["openSlots"])}/{game["nrofplayers"]} You can join it by going to https://www.conflictnations.com/play.php?bust=1&gameID={id}' )) except: client.print("oof cannot send to") del alertpeople[person] break if "uses" in alertpeople[person]: print("uses is in person") alertpeople[person]["uses"] -= 1 if alertpeople[person]["uses"] <= 0: del alertpeople[person] continue if "time" in alertpeople[person]: print("time is in person") if time() > float(alertpeople[person]["time"]): del alertpeople[person] continue with open('data/alertpeople2.txt', "w") as f: f.write(json.dumps(alertpeople))
async def video(self, ctx, *, keyword): TheB2 = "UCglLeRRcX8Jnb-dh2pijZyQ" result = await search_video(TheB2, keyword) if not result["success"]: return await ctx.send( embed=embeds.simple_embed(False, result["message"])) return await ctx.send(f'https://youtu.be/{result["message"]}')
def log_money(guild, message): print("log_money called") guild_collection = db[str(guild.id)] server_config = guild_collection.find_one({ "type": "server", "id": guild.id }) if server_config is None: return print("config is not none") if "log-channel" not in server_config: return if server_config["log-channel"] is None: return print("log-channel exists and it is", server_config["log-channel"]) channel = discord.utils.find( lambda m: str(m.id) == str(server_config["log-channel"]), guild.channels) if channel is None: return print("found channel") #asyncio.run(channel.send(f'log: {message}')) try: loop = asyncio.get_event_loop() except: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.create_task(channel.send(embed=simple_embed(True, f'log: {message}')))
async def say(self, ctx, person:PersonConverter, *, message): if ctx.author.id !=464954455029317633: return await ctx.send(embed=embeds.simple_embed(False, "only eulerthedestroyer#2074 can use admin commands")) ctx.author = person if len(message.split(" ")) == 1: return await ctx.invoke(self.bot.get_command(message.split(" ")[0])) await ctx.invoke(self.bot.get_command(message.split(" ")[0])," ".join(message.split(" ")[1:]))
async def clear_contracts(self, ctx): guild_collection = db[str(ctx.guild.id)] guild_collection.delete_many({ "type": 'contract', "author": ctx.author.id }) return await ctx.send(embed=simple_embed(True, "contracts deleted"))
async def print_money(self, ctx, account_of_printing: WalletConverter, amount): person = ctx.author currency = "" if "-" in amount: currency = f'-{amount.split("-")[1]}' amount = amount.split("-")[0] if not methods.valid_item(currency[1:]): return await ctx.send( embed=simple_embed(False, "invalid item name")) try: amount = int(amount) except: return await ctx.send(embed=simple_embed(False, "invalid amount")) guild_collection = db[str(ctx.guild.id)] can_print = False if person.guild_permissions.administrator: can_print = True if "permissions" in account_of_printing: if "print" in account_of_printing["permissions"]: if person.id in account_of_printing["permissions"]["print"][ "true"]: can_print = True for role in person.roles: if role.id in account_of_printing["permissions"]["print"][ "true"]: can_print = True if currency != "": if f'print{currency}' in account_of_printing["permissions"]: if person.id in account_of_printing["permissions"][ f'print{currency}']["true"]: can_print = True for role in person.roles: if role.id in account_of_printing["permissions"][ f'print{currency}']["true"]: can_print = True if "printer" in person.roles: can_print = True if not can_print: return await ctx.send(embed=simple_embed( False, "you do not have permission to print")) guild_collection.update_one({"id": account_of_printing["id"]}, {"$inc": { f'balance{currency}': amount }}) return await ctx.send(embed=simple_embed(True, "transfer successful"))
async def info_country(self, ctx, game_id: int, *, country): result = await request_game(game_id) if "players" not in result: return await ctx.send( embed=embeds.simple_embed(False, "cannot find that id")) players = result["players"] del players["@c"] found = False for number, player in players.items(): # print("player is", player) if player["name"] == country or ("nationName" in player and player["nationName"] == country): found = True break if not found: return await ctx.send(embed=embeds.simple_embed( False, f'cannot find that country {country}')) # print(player) player = { "nation name": player["nationName"], "computer player": player["computerPlayer"], "lastLogin": player["lastLogin"], "defeated": player["defeated"], "has Security Council?": player["premiumUser"], "is activity?": player["activityState"] } player["lastLogin"] /= 1000 if player["lastLogin"] > time.time( ): ## in 4x games time passes 4 times as fast so the time is inaccurate and must subtract to conteract the fast time # print("game time is ahead, must account for 4x time") excess_time = player["lastLogin"] - time.time() excess_time = excess_time / 3 start_date = time.time() - excess_time player["lastLogin"] = start_date + excess_time # print("after accounting for 4x, new") if "timezone" in ctx.message.flags["named"]: player["lastLogin"] = datetime.fromtimestamp( player["lastLogin"], timezone(ctx.message.flags["named"]["timezone"])).strftime( '%Y-%m-%d %H:%M:%S') else: player["lastLogin"] = datetime.fromtimestamp( player["lastLogin"]).strftime('%Y-%m-%d %H:%M:%S') return await ctx.send(embed=embeds.dict_to_embed( player, f'https://www.conflictnations.com/clients/con-client/con-client_live/images/flags/countryFlagsByName/big_{player["nation name"].lower().replace(" ","_")}.png?' ))
async def get_question(self, ctx): guild = ctx.guild person = ctx.author guild_collection = db[str(guild.id)] server_config = guild_collection.find_one({ "type": "server", "id": guild.id }) if server_config is None: return await ctx.send(embed=simple_embed( False, "server config is not set up. Ask your admin to set up the config" )) quiz_cooldown = config["quiz-cooldown"] if "quiz-cooldown" in server_config: quiz_cooldown = server_config["quiz-cooldown"] person_wallet = guild_collection.find_one({"id": person.id}) if person_wallet is not None: if "quiz-cooldown" in person_wallet: if time.time( ) - person_wallet["quiz-cooldown"] < quiz_cooldown: return await ctx.send(embed=simple_embed( False, f'wait to quiz. You must wait {methods.seconds_to_time(quiz_cooldown- time.time()+person_wallet["quiz-cooldown"])} to quiz again' )) guild_collection.update_one({"id": person.id}, {"$set": { "quiz-cooldown": time.time() }}) if not "quiz-subject" in server_config: return await ctx.send(embed=simple_embed( False, "no quiz subject for this server set. Ask you admin to set the quiz subject by doing something like $config quiz-subject {Subject}" )) await ctx.send(embed=simple_embed( "info", "Parsing sentence to generate question.....")) question = subject_to_quiz(server_config["quiz-subject"]) print(question, "question") guild_collection.insert_one({ "type": "quiz", "person": person.id, "question": question, "time": time.time() }) return await ctx.send(embed=simple_embed(True, question["question"]))