How to use get_file_from method in autotest

Best Python code snippet using autotest_python

image-bot.py

Source:image-bot.py Github

copy

Full Screen

...25]26palette = hitherdither.palette.Palette(27 [0xffffff,0xff0000,0x000000,0x00ff00,0x0000ff,0xff00ff,0x00ffff,0xffff00]28)29async def get_file_from(message):30 if len(message.attachments) > 0:31 attachment = message.attachments[0]32 #get and download file33 filename = "tmp/"+attachment.filename34 async with aiohttp.ClientSession(headers={"Referer": "https://discordapp.com"}) as session:35 async with session.get(attachment.url) as resp:36 f = await aiofiles.open(filename, mode='wb')37 await f.write(await resp.read())38 await f.close()39 else:40 for substring in message.content.replace("\n"," ").split(" "):41 if substring.startswith("http"):42 if ("tenor" in substring or "gfycat" in substring) and not ".gif" in substring: url = substring.split("?")[0]+".gif"43 elif "giphy" in substring: url = "https://media.giphy.com/media/"+substring.split("/")[4]+"/giphy.gif"44 else: url = substring.split("?")[0]45 filename = "tmp/"+str(random.randint(10000000,99999999))+"."+url.split(".")[len(url.split("."))-1]46 async with aiohttp.ClientSession(headers={"Referer": "https://discordapp.com"}) as session:47 async with session.get(url) as resp:48 f = await aiofiles.open(filename, mode='wb')49 await f.write(await resp.read())50 await f.close()51 return filename52bot = discord.Client()53@bot.event54async def on_ready():55 await bot.change_presence(activity=discord.Game("!help"))56 print("image bot is now ready")57@bot.event58async def on_message(message):59 if message.content.startswith("!help"):60 embed = discord.Embed(name="command list", color=0xddff00)61 embed.set_author(name="commands list (necessary) [optional]")62 embed.add_field(name="!shift (shiftyness) [url]", value="bitshifts an image. looks cool", inline = True)63 embed.add_field(name="!avatar (@someone)", value="grabs someone's avatar", inline = True)64 embed.add_field(name="!dither [url]", value="dither time", inline = True)65 embed.add_field(name="!impact (top text) | (bottom text) [url]", value="funny image machine", inline = True)66 embed.add_field(name="!jpg [quality from 1-100] [url]", value="ah! the quality!", inline = True)67 embed.add_field(name="!caption (caption) [url]", value="ifunny gif caption", inline = True)68 embed.add_field(name="!shuffle [url]", value="turn gif to mush", inline = True)69 embed.set_thumbnail(url="https://thumbs.dreamstime.com/z/help-wanted-vector-clip-art-31368648.jpg")70 await message.channel.send(embed=embed)71 if message.content.lower().startswith("!shift"):72 if len(message.attachments) == 0 and not "http" in message.content: await message.channel.send("you gotta attach an image")73 elif len(message.content.split(" ")) < 2 or not message.content.split(" ")[1].isdigit(): await message.channel.send("you gotta specify the amount of shiftage")74 elif int(message.content.split(" ")[1]) == 0: await message.channel.send("shut it")75 elif int(message.content.split(" ")[1]) > 7 or int(message.content.split(" ")[1]) < 1: await message.channel.send("that number sucks. try something from 1 to 7")76 else: 77 try:78 status = await message.channel.send("getting file...")79 await bot.change_presence(activity=discord.Game("!help"),status=discord.Status.dnd)80 await message.channel.trigger_typing()81 filename = await get_file_from(message)82 #turn into bmp83 await status.edit(content="converting file...")84 im = Image.open(filename)85 canvas = Image.new('RGBA', im.size, (54,57,63,255))86 if im.mode == "RGBA": canvas.paste(im, mask=im)87 else: canvas.paste(im)88 canvas.thumbnail([im.width, im.height], Image.ANTIALIAS)89 canvas = canvas.convert('RGB')90 converted_file = filename.replace(filename.split(".")[len(filename.split("."))-1],"") + "bmp"91 canvas.save(converted_file)92 93 #bitshift!94 await message.channel.trigger_typing()95 await status.edit(content="bitshifting...")96 shifted_file = converted_file.replace("bmp","_shifted.bmp")97 shift_count = int(message.content.split(" ")[1])98 increment = 199 with open(converted_file, 'rb') as f:100 bits = bytearray(f.read())101 start_byte = bits[10]102 i = 0103 goodly_named_variable = (len(bits) - start_byte)104 nf = open(shifted_file,"ab")105 for i in range(0,goodly_named_variable,increment):106 bits[start_byte + i] = (bits[start_byte + i] << shift_count) & 0xFF107 nf.write(bits)108 nf.close()109 #reconvert110 await status.edit(content="reconverting file...")111 final_file = shifted_file.replace("bmp","png")112 im = Image.open(shifted_file)113 im.save(final_file)114 115 #send116 await status.edit(content="sending...")117 await message.channel.send(file=discord.File(final_file))118 await status.delete()119 os.remove(final_file)120 os.remove(filename)121 os.remove(converted_file)122 os.remove(shifted_file)123 await bot.change_presence(activity=discord.Game("!help"),status=discord.Status.online)124 except:125 await message.channel.send(random.choice(error_msgs))126 if message.content.lower().startswith("!avatar"):127 if len(message.mentions) == 0: await message.channel.send("you gotta @ the user to get the avatar")128 else:129 try:130 await bot.change_presence(activity=discord.Game("!help"),status=discord.Status.dnd)131 status = await message.channel.send("getting avatar...")132 await message.channel.trigger_typing()133 #download134 url = str(message.mentions[0].avatar_url).split("?size")[0]135 og_file = "tmp/"+str(random.randint(10000000,99999999))+"."+url.split(".")[len(url.split("."))-1]136 async with aiohttp.ClientSession(headers={"Referer": "https://discordapp.com"}) as session:137 async with session.get(url+"?size=1024") as resp:138 f = await aiofiles.open(og_file, mode='wb')139 await f.write(await resp.read())140 await f.close()141 142 #convert143 await status.edit(content="converting avatar...")144 final_file = og_file.replace("webp","png")145 im = Image.open(og_file)146 if not im.mode == 'RGBA':147 im = im.convert('RGBA')148 im.save(final_file)149 os.remove(og_file)150 #send151 await status.edit(content="sending...")152 await message.channel.send(file=discord.File(final_file))153 await status.delete()154 os.remove(final_file)155 await bot.change_presence(activity=discord.Game("!help"),status=discord.Status.online)156 157 except:158 await message.channel.send(random.choice(error_msgs))159 if message.content.lower().startswith("!dither"):160 if len(message.attachments) == 0 and not "http" in message.content: await message.channel.send("you gotta attach an image")161 else: 162 try:163 status = await message.channel.send("getting file...")164 await bot.change_presence(activity=discord.Game("!help"),status=discord.Status.dnd)165 await message.channel.trigger_typing()166 filename = await get_file_from(message)167 #turn into small png168 await status.edit(content="converting file...")169 im = Image.open(filename)170 canvas = Image.new('RGBA', im.size, (54,57,63,255))171 if im.mode == "RGBA": canvas.paste(im,mask=im)172 else: canvas.paste(im)173 canvas.thumbnail([im.width, im.height], Image.ANTIALIAS)174 canvas = canvas.convert('RGB')175 im2 = canvas.resize((canvas.size[0]//4,canvas.size[1]//4),Image.NEAREST)176 converted_file = filename.replace(filename.split(".")[len(filename.split("."))-1],"") + "png"177 im2.save(converted_file)178 179 #dither180 await status.edit(content="dithering file...")181 img = Image.open(converted_file)182 img_dithered = hitherdither.ordered.bayer.bayer_dithering(img, palette, [256/4, 256/4, 256/4], order=8)183 new_filename = converted_file.replace(".","_dithered.")184 img_dithered_resized = img_dithered.resize((img_dithered.size[0]*4,img_dithered.size[1]*4),Image.NEAREST)185 img_dithered_resized.save(new_filename)186 #send187 await status.edit(content="sending...")188 await message.channel.send(file=discord.File(new_filename))189 await status.delete()190 os.remove(new_filename)191 os.remove(filename)192 try: os.remove(converted_file)193 except: pass194 await bot.change_presence(activity=discord.Game("!help"),status=discord.Status.online)195 196 except:197 await message.channel.send(random.choice(error_msgs))198 if message.content.lower().startswith("!jpg"):199 if len(message.attachments) == 0 and not "http" in message.content: await message.channel.send("you gotta attach an image")200 else: 201 if len(message.content.split(" "))>1 and message.content.split(" ")[1].isdigit(): quality = int(message.content.split(" ")[1])202 else: quality = 10203 if quality < 1 or quality > 100:204 await message.channel.send("sorry, humans can't comprehend images of this quality")205 return206 try:207 #get file208 status = await message.channel.send("getting file...")209 await bot.change_presence(activity=discord.Game("!help"),status=discord.Status.dnd)210 await message.channel.trigger_typing()211 filename = await get_file_from(message)212 #lower quality213 await status.edit(content="jpg-ifying...")214 im = Image.open(filename)215 canvas = Image.new('RGBA', im.size, (54,57,63,255))216 if im.mode == "RGBA": canvas.paste(im,mask=im)217 else: canvas.paste(im)218 canvas.thumbnail([im.width, im.height], Image.ANTIALIAS)219 canvas = canvas.convert('RGB')220 converted_file = filename.replace(filename.split(".")[len(filename.split("."))-1],"") + "jpg"221 canvas.save(converted_file, quality=quality)222 #send223 await status.edit(content="sending...")224 await message.channel.send(file=discord.File(converted_file))225 await status.delete()226 os.remove(converted_file)227 await bot.change_presence(activity=discord.Game("!help"),status=discord.Status.online)228 229 except:230 await message.channel.send(random.choice(error_msgs))231 if message.content.lower().startswith("!impact"):232 if len(message.attachments) == 0 and not "http" in message.content: await message.channel.send("you gotta attach an image")233 else: 234 try:235 msg = message.content.split(" ")236 new_msg = ""237 for piece in msg:238 if not piece == "!impact" and not piece.startswith("http"):239 new_msg = new_msg + piece + " "240 top = new_msg.split("|")[0]241 bottom = new_msg.split("|")[1]242 except:243 await message.channel.send("make sure you have !impact (top text) | (bottom text) [url]")244 return245 try:246 #get image247 await message.channel.trigger_typing()248 status = await message.channel.send("getting file...")249 await bot.change_presence(activity=discord.Game("!help"),status=discord.Status.dnd)250 filename = await get_file_from(message)251 252 await status.edit(content="converting file...")253 im = Image.open(filename)254 canvas = Image.new('RGBA', im.size, (54,57,63,255))255 if im.mode == "RGBA": canvas.paste(im, mask=im)256 else: canvas.paste(im)257 canvas.thumbnail([im.width, im.height], Image.ANTIALIAS)258 canvas = canvas.convert('RGB')259 converted_file = filename.replace(filename.split(".")[len(filename.split("."))-1],"") + "jpg"260 canvas.save(converted_file,quality=100)261 #make image262 await status.edit(content="impactifying...")263 new_filename = "tmp/"+str(random.randint(10000000,99999999))+".jpg"264 os.system("python impact.py {0} \"{1}\" \"{2}\" {3}".format(converted_file,top,bottom,new_filename))265 #send266 await status.edit(content="sending...")267 await message.channel.send(file=discord.File(new_filename))268 await status.delete()269 os.remove(new_filename)270 os.remove(converted_file)271 try: os.remove(filename)272 except: pass273 await bot.change_presence(activity=discord.Game("!help"),status=discord.Status.online)274 275 except:276 await message.channel.send(random.choice(error_msgs))277 if message.content.lower().startswith("!caption"):278 if len(message.attachments) == 0 and not "http" in message.content: await message.channel.send("you gotta attach an image")279 else: 280 try:281 msg = message.content.replace("\n"," ").split(" ")282 caption_text = ""283 for piece in msg:284 if not piece == "!caption" and not piece.startswith("http"):285 caption_text = caption_text + piece + " "286 caption_text = caption_text.replace("\n","")287 except:288 await message.channel.send("make sure you have !caption (text) [url]")289 return290 if True:#try:291 #get image292 await message.channel.trigger_typing()293 status = await message.channel.send("getting file...")294 await bot.change_presence(activity=discord.Game("!help"),status=discord.Status.dnd)295 filename = await get_file_from(message)296 #make image297 await status.edit(content="captioning...")298 new_filename = "tmp/"+str(random.randint(10000000,99999999))+".gif"299 os.system("python3.6 caption.py {0} \"{1}\" {2}".format(filename,caption_text,new_filename))300 #send301 await status.edit(content="uploading...")302 gif = upload(["bot","image"],new_filename,username="imagebot",api_key="XPumBNP6Lw0QijMqlvXwVNXBo3udxFfn")303 await message.channel.send(gif.url)304 await status.delete()305 os.remove(new_filename)306 #try: os.remove(filename)307 #except: pass308 await bot.change_presence(activity=discord.Game("!help"),status=discord.Status.online)309 310 #except:311 # await message.channel.send(random.choice(error_msgs))312 if message.content.lower().startswith("!shuffle"):313 if len(message.attachments) == 0 and not "http" in message.content: await message.channel.send("you gotta attach an image")314 else: 315 if True:#try:316 #get image317 await message.channel.trigger_typing()318 status = await message.channel.send("getting file...")319 await bot.change_presence(activity=discord.Game("!help"),status=discord.Status.dnd)320 filename = await get_file_from(message)321 #make image322 await status.edit(content="shuffling...")323 new_filename = "tmp/"+str(random.randint(10000000,99999999))+".gif"324 os.system("python shuffle.py {0} {1}".format(filename,new_filename))325 #send326 await status.edit(content="uploading...")327 gif = upload(["bot","image"],new_filename,username="imagebot",api_key="XPumBNP6Lw0QijMqlvXwVNXBo3udxFfn")328 await message.channel.send(gif.url)329 await status.delete()330 os.remove(new_filename)331 try: os.remove(filename)332 except: pass333 await bot.change_presence(activity=discord.Game("!help"),status=discord.Status.online)334 ...

Full Screen

Full Screen

colorful

Source:colorful Github

copy

Full Screen

...10import random11import configparser12import re13from pprint import pprint14def get_file_from(dir, rand=False):15 """Returns a filename from directory after user specifies which"""16 files = [f for f in os.listdir(dir) if isfile(join(dir, f))]17 input = random.randrange(0, len(files))18 return dir + files[int(input) - 1]19def define_argparser():20 """Return and define arguments and help documentation"""21 parser = argparse.ArgumentParser(22 prog="colorful",23 description="Retheme that pos.")24 25 parser.add_argument(26 "-f", "--file", metavar='FILE', dest='file',27 help="The image file to work with.",)28 parser.add_argument(29 '-w', action="store_true",30 default=False,31 help="make this image the current wallpaper [default: False]")32 parser.add_argument(33 '-p', "--pipe", dest="pipename",34 metavar="F", default="/tmp/display_data",35 help="write the hexidecimal output to a new file [default: /tmp/display_data]")36 parser.add_argument(37 "-d", "--dir", dest="dir",38 metavar="D",39 help="Choose a directory and then choose a file from the prompt.")40 parser.add_argument(41 '-n', dest='n', metavar='N', type=int,42 default=64,43 help="The number of colors to fetch [default: 64]")44 parser.add_argument(45 '-q', dest='q', default=False,46 action="store_true",47 help="Set this flag to save the output to a hex file")48 parser.add_argument(49 '-r', dest='r', default=False,50 action='store_true',51 help="When used with the directory option chooses a random file")52 return parser.parse_args()53def do_configs(image):54 dir = "/home/cody/code/colorful/config/"55 files = [f for f in os.listdir(dir) if isfile(join(dir, f))]56 for i, file in enumerate(files):57 if 'conf' not in file:58 del(files[i])59 config = configparser.ConfigParser()60 for file in files:61 config.read(dir + file)62 palette = image.get_palette()63 output_file = config.get('app', 'conf')64 layout_file = config.get('app', 'layout')65 target = None66 with open(layout_file, 'r') as file:67 target = file.read()68 parser = LayoutParser(target,69 config.get('app', 'format'),70 image,71 config.get('app', 'is_term'))72 with open(output_file, 'w+') as file:73 file.write(parser.target)74def main():75 args = define_argparser()76 config = configparser.ConfigParser()77 config.read(os.environ['HOME'] + '/code/colorful/default.conf')78 dir = config.get('colorful', 'default_directory')79 80 if args.file:81 file = args.file82 else: 83 if not args.dir:84 file = get_file_from(dir, True)85 elif args.file:86 file = args.file87 elif args.dir:88 file = get_file_from(args.dir, True)89 else:90 print>> sys.stderr, "No image specified."91 image = Colorful(file)92 if args.q:93 image.write_colors(args.n)94 do_configs(image)95 w = config.get('colorful', 'wallpaper')96 if args.w or w:97 image.paper_me_baby()98 subprocess.check_output('i3-msg reload', shell=True)99 subprocess.check_output('xrdb -load /home/cody/.config/i3/Xresources', shell=True)100 # os.popen("i3-msg reload &> /dev/null").read()101 # os.popen("xrdb -load /home/cody/.config/i3/Xresources").read()102if __name__ == "__main__":...

Full Screen

Full Screen

main.py

Source:main.py Github

copy

Full Screen

...5from fastapi.responses import HTMLResponse6from starlette.responses import FileResponse789def get_file_from(CID):10 res = requests.get(f"https://cloudflare-ipfs.com/ipfs/{CID}")11 return res.text1213app = FastAPI()1415def decrypting(data, key):16 Encrypt = Fernet(key)17 enc_data = Encrypt.decrypt(data)18 new_file = open("nft.png", 'wb')19 new_file.write(enc_data)20 new_file.close()212223@app.post("/get_cid/")24async def get_cid_file(cid1: str = Form(...), cid2: str = Form(...), cid3: str = Form(...), cid4: str = Form(...), golden_key: str = Form(...)):25 all_cids = [cid1,cid2,cid3,cid4]26 all_bin = bytes()27 for c in all_cids:28 all_bin += get_file_from(c).encode("utf-8")29 decrypting(all_bin, golden_key)3031 return FileResponse("nft.png", media_type='application/octet-stream',filename="nft.png")323334@app.get("/")35async def main():36 content = """37<body>38<form action="/get_cid/" method="post">39<label>cid1: </label>40<input name="cid1" type="text" ><br /><br />41<label>cid2: </label>42<input name="cid2" type="text" ><br /><br /> ...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run autotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful