async def getproxy(self, ctx): languageserver = await settings.collectionlanguage.find_one( {"guild_id": ctx.guild.id}) if languageserver is None: message = await ctx.send( embed=languageEmbed.languageembed(self, ctx)) await message.add_reaction('👍') else: server_language = languageserver["Language"] if server_language == "Thai": url = "https://raw.githubusercontent.com/ShiftyTR/Proxy-List/master/proxy.txt" async with aiohttp.ClientSession() as session: async with session.get(url) as r: r = await r.text() with open("data/proxy.txt", "w") as file: file.write(r) file.close() f = nextcord.File("data/proxy.txt", filename="proxy.txt") await ctx.send(file=f) if server_language == "English": url = "https://raw.githubusercontent.com/ShiftyTR/Proxy-List/master/proxy.txt" async with aiohttp.ClientSession() as session: async with session.get(url) as r: r = await r.text() with open("data/proxy.txt", "w") as file: file.write(r) file.close() file = nextcord.File("data/proxy.txt", filename="proxy.txt") await ctx.send(file=file)
async def captcha(self, ctx, *, text): languageserver = await settings.collectionlanguage.find_one( {"guild_id": ctx.guild.id}) if languageserver is None: message = await ctx.send( embed=languageEmbed.languageembed(self, ctx)) await message.add_reaction('👍') else: server_language = languageserver["Language"] if server_language == "Thai": image = ImageCaptcha() image.write(text, 'image/captcha.png') file = nextcord.File("image/captcha.png", filename="captcha.png") embed = nextcord.Embed(colour=0x00FFFF, title="Captcha") embed.set_image(url="attachment://captcha.png") embed.set_footer(text=f"┗Requested by {ctx.author}") await ctx.send(embed=embed, file=file) if server_language == "English": image = ImageCaptcha() image.write(text, 'image/captcha.png') file = nextcord.File("image/captcha.png", filename="captcha.png") embed = nextcord.Embed(colour=0x00FFFF, title="Captcha") embed.set_image(url="attachment://captcha.png") embed.set_footer(text=f"┗Requested by {ctx.author}") await ctx.send(embed=embed, file=file)
async def start(self) -> None: channel = self.channel name, original_img, black_img = await self.get() print(name) embed = Embed() embed.set_author(name="Who's that pokemon?", icon_url=ICONS['pokemon']) embed.set_image(url="attachment://image.png") guess_embed = embed.copy() guess_embed.set_footer(text=self.guess_string(name)) guess_msg = await self.channel.send(embed=guess_embed, file=nextcord.File( black_img, "image.png")) winner_embed = embed.copy() someone_answered = False def check(m: nextcord.Message) -> bool: nonlocal someone_answered if m.content: someone_answered = True if m.author.id not in self.scoreboard: self.scoreboard[m.author.id] = 0 return m.channel == channel and m.content.lower() == name.lower() try: msg = await self.bot.wait_for("message", check=check, timeout=30) except asyncio.TimeoutError: winner_embed.description = "**No one**" if not someone_answered: self.timed_out = True self.status = 0 else: if msg.author.id not in self.scoreboard: self.scoreboard[msg.author.id] = 1 else: self.scoreboard[msg.author.id] += 1 winner_embed.description = f"**{msg.author.name}**" winner_embed.description += ( f" got the correct answer!\nThe answer is **{name}**") await self.bot.delete_message(guess_msg) await channel.send(embed=winner_embed, file=nextcord.File(original_img, "image.png")) if not someone_answered: await channel.send(embed=Embed( "Pokemon game stopped because no one tried to answer it."))
async def archive_one_channel(self, channel): """Download a channel's history""" # Write the chat log. Replace attachments with their filename (for easy reference) text_log_path = os.path.join( archive_constants.ARCHIVE, channel.name + '_' + archive_constants.TEXT_LOG_PATH) with open(text_log_path, 'w') as f: async for msg in channel.history(limit=None, oldest_first=True): #print(f"{msg.created_at} - {msg.author.display_name.rjust(25, ' ')}: {msg.clean_content}") f.write(f"[ {msg.created_at.strftime('%m-%d-%Y, %H:%M:%S')} ] " f"{msg.author.display_name.rjust(25, ' ')}: " f"{msg.clean_content}") # Save attachments TODO is this necessary? Might waste space for attachment in msg.attachments: f.write(f" {attachment.filename}") # change duplicate filenames # img.png would become img (1).png original_path = os.path.join(archive_constants.ARCHIVE, archive_constants.IMAGES, attachment.filename) proposed_path = original_path dupe_counter = 1 while os.path.exists(proposed_path): proposed_path = original_path.split('.')[ 0] + f" ({dupe_counter})." + original_path.split( '.')[1] dupe_counter += 1 await attachment.save(proposed_path) # Important: Write the newline after each comment is done f.write("\n") text_file_size = f.tell() ZIP_FILENAME = os.path.join(archive_constants.ARCHIVE, channel.name + '_archive.zip') # Create a zipfile and then walk through all the saved chatlogs and images, and zip em up with zipfile.ZipFile(ZIP_FILENAME, mode='w') as zf: for root, directories, files in os.walk(archive_constants.ARCHIVE): for filename in files: if filename == ZIP_FILENAME.split( '/')[-1]: # Don't include self #TODO : It means that the first zipfile in the channel with the same name gets ignored. Minor big continue zf.write(os.path.join(root, filename), compress_type=self.compression) zf_file_size = zf.fp.tell() # TODO: It may often be the case that we will be above 8MB (max filesize). # In that case, we just need to send the textfile return nextcord.File(ZIP_FILENAME), zf_file_size, nextcord.File( text_log_path), text_file_size
async def export_list(self, ctx, *args): cursor = self.cursor guild_id = ctx.guild.id selectQuery = "SELECT * from OsuQuiz where server_id = ?;" cursor.execute(selectQuery, (guild_id,)) record = cursor.fetchall() msg = "" if len(record) == 0: await ctx.send("등록된 곡이 없습니다!") return for i, song in enumerate(record): msg += str(song[1]) + " " + song[2] + "\n" try: file = open("./tmp/texts/omq/backup.txt", "w+") n = file.write(msg) file.close() except: await ctx.send("목록 내보내기에 실패했습니다!") return txt = open("./tmp/texts/omq/backup.txt", 'rb') await ctx.send(file=nextcord.File(fp=txt, filename="songlist.txt")) txt.close()
def package(self, novel: Novel, packagers: Iterable[BasePackager]): formats = ", ".join(p.keywords()[0] for p in packagers) self.session.send_sync( f"Packing the novel into the formats: {formats}…") for packager in packagers: output = packager.package(novel) if output.is_dir(): self.session.send_sync(f"Archiving {output.name}…") archive = shutil.make_archive(str(output), "zip", str(output)) output = Path(archive) # discord does not allow uploads greater than 8mb # hence, they are relegated to a third-party if output.stat().st_size <= 7.99 * 1024 * 1024: self.session.send_sync(f"Uploading {output.name}…") self.session.send_sync(file=nextcord.File(output, output.name)) else: self.session.send_sync( f"File is bigger than 8Mb, uploading to {self.filehost.name()}…" ) try: url = self.filehost.upload( output, "An upload by novelsave discord bot") self.session.send_sync(url) except Exception as e: logger.exception(e) self.session.send_sync( utils.error(f"Failed to upload file.\nError: {e}"))
async def cmd(self, ctx, *, text): msg = "" try: output = await self.run_subprocess(text, loop=self.bot.loop) await ctx.send("\n".join(output)) except: await ctx.send(file=discord.File(fp=io.StringIO(msg), filename="output.txt"))
def send_file(self, file_path, target=-1, server=None): dfile = nextcord.File(file_path) async def send_file(channel, dfile): if self.get_server().id in bot_replies: old_reply = bot_replies[self.get_server().id].get_old_reply(self.msg) if old_reply and old_reply._raw.channel.id == channel.id: try: await channel.delete_messages([old_reply._raw]) msg = Message(await channel.send(file=dfile)) except: print(traceback.format_exc()) add_bot_reply(self.get_server().id, self.msg._raw, msg) return msg try: msg = Message(await channel.send(file=dfile)) except: print(traceback.format_exc()) add_bot_reply(self.get_server().id, self.msg._raw, msg) return msg asyncio.run_coroutine_threadsafe( send_file(self.get_channel(target, server), dfile), bot.loop )
async def bonobo(self, ctx, users: commands.Greedy[DiscordMonke]): if len(users) == 0 and len(ctx.message.clean_content.split()) == 1: users = [LazyRandom()] * random.choice(tuple(self.templates)).faces get_best_random( users, ctx.guild.members, ) available_templates = list( filter(lambda t: t.faces == len(users), self.templates)) # Randomize the ordering for maximum fun random.shuffle(users) if len(available_templates) == 0: await ctx.send("Invalid usage.") return template = random.choice(available_templates) # Handle any randoms get_best_random(users, ctx.guild.members) im = Image.open(template.filename).convert("RGBA") for count, user in enumerate(users): top = await self.get_avatar(user) im = pasteImg(im, top, template.upperleftcord(count), template.lowerrightcord(count)) buffer = BytesIO() im.save(buffer, "png") buffer.seek(0) await ctx.send(file=nextcord.File(filename="love.png", fp=buffer))
async def export_cases(storage, event, reply): try: out_file = io.StringIO(newline="") field_names = [ "Case ID", "Type", "Reason", "Date", "Expire date", "Link", "User", "Author", ] writer = csv.DictWriter(out_file, field_names, extrasaction="ignore") writer.writeheader() all_reasons = [] if "reasons" in storage: for user in storage["reasons"].values(): for reason in user: all_reasons.append(reason) all_reasons.sort(key=lambda x: x["Case ID"]) for reason in all_reasons: writer.writerow(reason) await event.channel.async_send_file( nextcord.File(fp=io.BytesIO(out_file.getvalue().encode("utf-8")), filename="data.csv")) except Exception as e: reply("Couldn't export cases: %s" % repr(e))
async def get(self, ctx, path): target = fileutils.PathBuilder(self._path, self._root)\ .join(path)\ .build() if os.path.isfile(target): await ctx.send(file=nextcord.File(target)) else: await reactions.confusion(ctx.message, f'{target} is not a file')
async def backup_database(self): output = await self.get_cog("Developer").run_subprocess( f'PGPASSWORD="******"DB_PASS")}" pg_dump {os.getenv("DB_NAME")}' ) output = "\n".join(output) await self.get_channel( self.static_data.backup_channel ).send(file=discord.File(fp=io.StringIO(output), filename="dump"))
async def export(self, ctx, namespace): if len([r for r in ctx.author.roles if r.id == 644301991832453120]) == 0: return path = os.path.join("data", f"{namespace}.json") if not os.path.exists(path): await ctx.send(f"No such namespace: {namespace}") else: with open(path, "r") as json_file: await ctx.send(f"Here you go", file=nextcord.File(json_file))
async def meme(self, ctx: commands.Context, name: str = None, tipo: str = None): """Meme random de los nuestros""" # If all memes have been sent, delete history memes_path = get_server_path(ctx.guild) + "/memes/" if name is None: output = random.choice(os.listdir(memes_path)) await ctx.send(file=nextcord.File(memes_path + output)) else: uwu = [] for filenames in os.listdir(memes_path): if name.lower() in filenames.lower(): uwu.append(filenames) # check if exists a meme with the filters if len(uwu) == 0: await ctx.send("No hay memes con " + name) return if (tipo == "video" and not any(".mp4" in s for s in uwu)) or ( tipo == "imagen" and not any(".jpg" in s for s in uwu) ): await ctx.send("No hay memes de " + tipo + " que sean de " + name) return if tipo is not None: if tipo == "video": output = "0" while ".mp4" not in output: output = random.choice(uwu) if tipo == "imagen": output = "0" while ".jpg" not in output: output = random.choice(uwu) else: output = random.choice(uwu) await ctx.send(file=nextcord.File(memes_path + output)) logging.info("Meme " + output + " sent")
async def undertale( self, ctx: commands.Context, texto: str, usuario: nextcord.Member = None ): """Bajo cuento""" avatar_info = [ { "url": get_user(ctx, usuario).avatar.url, "size": 160, "x": 120, "y": 88, } ] character_image_size = 200 # Get user avatar_url = get_user(ctx, usuario).avatar.url sprite = ( Image.open(io.BytesIO(requests.get(avatar_url).content)) .convert("L") .resize((character_image_size, character_image_size)) ) # Open resources image = Image.open(meme_resources_path + "dialogue_box.png") font = ImageFont.truetype( meme_resources_path + "Determination-Sans.otf", size=60 ) txtPic1 = Image.new("RGBA", (800, 270)) draw = ImageDraw.Draw(txtPic1) # Convert character picture wpercent = character_image_size / float(sprite.size[0]) hsize = int((float(sprite.size[1]) * float(wpercent))) sprite = sprite.resize((character_image_size, hsize), Image.ANTIALIAS) image.paste(sprite, (70, 90)) # Add text lines = textwrap.wrap(texto, width=25) Y = 20 for line in lines: width, height = font.getsize(line) draw.text(((10, Y)), line, font=font, fill=(255, 255, 255, 255)) Y = Y + height image.paste(txtPic1, (350, 50), txtPic1) # Send image bytes_io = io.BytesIO() image.save(bytes_io, "PNG") bytes_io.seek(0) await ctx.send(file=nextcord.File(bytes_io, "output.png"))
async def send_image(self, msg, request, msg_text=""): forecast = await request.read() buffer = io.BytesIO() buffer.write(forecast) buffer.seek(0) return await utils.delay_send( msg.channel, msg=msg_text, file=nextcord.File(buffer, filename="weather.png"), reply_to=msg, )
async def on_command_error(self, ctx, error): error = getattr(error, 'original', error) if isinstance(error, commands.CommandNotFound): return elif isinstance(error, commands.UserInputError): ctx.command.reset_cooldown(ctx) command = ctx.command.qualified_name cog = ctx.command.cog.qualified_name await ctx.send(tt.w + f"invalid command parameters provided!" + ( f'\n{tt.s}{tt.s}`{ctx.prefix if str(self.bot.user.id) not in ctx.prefix else "@eli bot "}{cmds._c_[cog][1][command][0]}`' if cog in cmds._c_ and command in cmds._c_[cog][1] else '')) elif isinstance(error, commands.DisabledCommand): await ctx.send( tt.x + f"this command is currently disabled for maintenance!") elif isinstance(error, commands.NoPrivateMessage): await ctx.send(tt.x + "this command can only be used in servers!") elif isinstance(error, commands.BotMissingPermissions): await ctx.send( tt.x + f"i need {format_perms(error)} to use this command!") elif isinstance(error, commands.MissingPermissions): await ctx.send( tt.x + f"you need {format_perms(error)} to use this command!") elif isinstance(error, commands.CommandOnCooldown): await ctx.send( tt.h + f"please wait `{f.seconds(math.ceil(error.retry_after))}` before using this command again!" ) elif isinstance(error, checks.GuildCommandDisabled): await ctx.send(tt.x + "this command is disabled in this server!") elif isinstance(error, commands.CheckFailure): await ctx.send(tt.x + "you do not have permission to use this command!") else: f.log( f"Ignoring exception in command '{ctx.command.qualified_name}':\n" + ''.join( traceback.format_exception(type(error), error, error.__traceback__)), False, ['temp/error.txt', 'w'], tt.ansi.red + tt.ansi.bold) await ctx.send( tt.w + f"i ran into an error running this command! the error log is attached, please report it with 't!report'!\n**note: eli bot is currently in a testing stage for nextcord.py 2.0; if you experience any errors, i highly encourage you report them!**", file=nextcord.File('temp/error.txt'))
async def quien( self, ctx: commands.Context, text1: str, text2: str, user: nextcord.Member = None, ): """Quien ha sido? Uso: fur quien <texto1> <texto2> @<usuario> Ejemplo: fur quien "Le gustan los chilenos?" "Si" @Thedax """ Y = 20 Y_aux = 10 avatar_info = [ { "url": get_user(ctx, user).avatar.url, "size": 130, "x": 210, "y": 570, } ] # Get user avatar avatarUrl = get_user(ctx, user).avatar.url meme = create_meme("quien", avatar_info) txtPic = Image.new("RGBA", (200, 200)) img = Image.open(meme).convert("RGBA") draw = ImageDraw.Draw(txtPic) font = ImageFont.truetype(meme_resources_path + "Calibri.ttf", 24) lines = textwrap.wrap(text1, width=18) for line in lines: draw.text(((0, Y)), line, font=font, fill=(0, 0, 0, 255)) Y = Y + 25 draw.text(((170, 170)), text2, font=font, fill=(0, 0, 0, 255)) img.paste(txtPic, (180, 10), txtPic) # Save bytes_io = io.BytesIO() img.save(bytes_io, "PNG") bytes_io.seek(0) # Send meme await ctx.send(file=nextcord.File(bytes_io, "output.png"))
async def dictionary(self, ctx: commands.Context, *, word: str) -> None: """Searches for a word in Merriam Webster.""" msg = await ctx.send(embed=Embed("Searching...")) res = await self.session.get( f"https://www.dictionaryapi.com/api/v3/references/sd4/json/{word}", params={"key": self.bot.env.str("DICTIONARY_API")}, ) await self.bot.delete_message(msg) try: data = await res.json() except aiohttp.ContentTypeError: error = await res.text() raise ApiError(error) if not data or not isinstance(data[0], dict): await ctx.send(embed=Embed("Word not found."), delete_after=5) return dictionary = data[0] prs = dictionary['hwi']['prs'][0] or dictionary['vrs'][0]['prs'][0] audio = prs['sound']['audio'] if audio: url = f"https://media.merriam-webster.com/soundc11/{audio[0]}/{audio}.wav" res = await self.session.get(url) term = dictionary['meta']['id'] if ":" in term: term = term[0:term.rfind(":")] embed = Embed() embed.add_field( name=term, value=(f"*{prs['mw']}*" if prs['mw'] else "") + "\n" + dictionary['shortdef'][0], ) embed.set_author( name="Merriam-Webster Dictionary", icon_url=ICONS['merriam'], ) embed.set_footer(text=f"Searched by {ctx.author}", icon_url=ctx.author.display_avatar.url) await self.bot.delete_message(msg) await ctx.send(embed=embed) if audio: content = await res.read() await ctx.send(file=nextcord.File(BytesIO(content), word + ".wav"))
async def exportkudos(self, ctx: commands.Context): scores = kudos.get_highest_kudos(100000) file = BytesIO() file.writelines(f"{member_id},{points}\n".encode() for member_id, points in scores) file.seek(0) await ctx.send( f"User kudos totals as of {datetime.utcnow().date().isoformat()}", file=nextcord.File( file, filename= f"member-kudos-{datetime.utcnow().date().isoformat().replace('-', '')}.csv", ), )
async def cute(self, ctx: commands.Context, user: nextcord.Member = None): """You are cute""" avatar_info = [ { "url": get_user(ctx, user).avatar.url, "size": 387, "x": 210, "y": 75, } ] meme = create_meme("cute", avatar_info) # Send meme await ctx.send(file=nextcord.File(meme, "output.png"))
async def impostor(self, ctx: commands.Context, user: nextcord.Member = None): """Quién es el impostor?""" avatar_info = [ { "url": get_user(ctx, user).avatar.url, "size": 205, "x": 323, "y": 175, } ] meme = create_meme("impostor", avatar_info) # Send meme await ctx.send(file=nextcord.File(meme, "output.png"))
async def coding(self, ctx: commands.Context, user: nextcord.Member = None): """Programa como un pro hacker""" avatar_info = [ { "url": get_user(ctx, user).avatar.url, "size": 167, "x": 218, "y": 137, } ] meme = create_meme("coding", avatar_info) # Send meme await ctx.send(file=nextcord.File(meme, "output.png"))
async def unsee(self, ctx: commands.Context, user: nextcord.Member = None): """No por favor""" avatar_info = [ { "url": get_user(ctx, user).avatar.url, "size": 108, "x": 256, "y": 112, } ] meme = create_meme("unsee", avatar_info) # Send meme await ctx.send(file=nextcord.File(meme, "output.png"))
async def palomitas(self, ctx: commands.Context, user: nextcord.Member = None): """Este drama está interesante""" avatar_info = [ { "url": get_user(ctx, user).avatar.url, "size": 125, "x": 278, "y": 67, } ] meme = create_meme("palomitas", avatar_info) # Send meme await ctx.send(file=nextcord.File(meme, "output.png"))
async def slap(self, ctx: commands.Context, user: nextcord.Member = None): """slap""" avatar_info = [ { "url": get_user(ctx, user).avatar.url, "size": 160, "x": 120, "y": 88, } ] meme = create_meme("slap", avatar_info) # Send meme await ctx.send(file=nextcord.File(meme, "output.png"))
async def reviento(self, ctx: commands.Context, user: nextcord.Member = None): """a que me reviento""" avatar_info = [ { "url": get_user(ctx, user).avatar.url, "size": 78, "x": 315, "y": 80, } ] meme = create_meme("reviento", avatar_info) # Send meme await ctx.send(file=nextcord.File(meme, "output.png"))
async def radiopatio(self, ctx: commands.Context, user: nextcord.Member = None): """Es hora del cotilleo""" avatar_info = [ { "url": get_user(ctx, user).avatar.url, "size": 88, "x": 188, "y": 45, } ] meme = create_meme("radiopatio", avatar_info) # Send meme await ctx.send(file=nextcord.File(meme, "output.png"))
async def omni(self, ctx: commands.Context, user: nextcord.Member = None): """Omniman""" avatar_info = [ { "url": get_user(ctx, user).avatar.url, "size": 470, "x": 210, "y": 388, } ] meme = create_meme("omni", avatar_info) # Send meme await ctx.send(file=nextcord.File(meme, "output.png"))
async def mierda(self, ctx: commands.Context, user: nextcord.Member = None): """Menudo montón de mierda""" avatar_info = [ { "url": get_user(ctx, user).avatar.url, "size": 270, "x": 476, "y": 161, } ] meme = create_meme("mierda", avatar_info) # Send meme await ctx.send(file=nextcord.File(meme, "output.png"))