Esempio n. 1
0
def menu_screen(account: act) -> str:

    chalk.cyan("""$$$$---BANK OF MOOLA MENU---$$$$
        
Type s >> See My Savings Balance
Type c >> See My Checking Balance
Type d >> Deposit Moola
Type w >> Withdrawal Moola
    """)
    start_menu_choice = input("How may we help you? >>> ")

    if start_menu_choice == 's':
        clear()  # makes space in terminal view
        funds = account.get_funds()
        chalk.red(f"You're Savings balance is ${funds}.")
        chalk.red('--------------------------------')
        menu_screen(account)
    elif start_menu_choice == 'c':
        clear()
        funds_ch = account.get_funds_ch()
        chalk.red(f"You're Checking balance is ${funds_ch}.")
        chalk.red('--------------------------------')
        menu_screen(account)

    elif start_menu_choice == 'd':
        clear()
        deposit_acc(account)
    elif start_menu_choice == 'w':
        clear()
        withdrawal_acc(account)
def candidate_input(candidates):
    """
    Presents the list of candidates, asks user to vote until done, prints the results of the voting.
    
    :param candidates: dict
    :return: 
    """
    options = {index: goof for index, goof in enumerate(candidates, start=1)}

    while True:
        display_ballot(candidates)
        i_choose = input(
            "Enter your choice for President or type 'done' to see the results. ➙  "
        )

        try:
            i_choose = int(i_choose)

        except ValueError:

            if i_choose == 'done':
                chalk.cyan(f"Total votes per candidate: {candidates}")
                winner = max(candidates.items(), key=lambda t: t[-1])
                chalk.magenta(
                    f"The winner is {winner[0]} with {winner[1]} votes.")
                break

            chalk.red('Please enter the number to the left of the name.')
            continue

        if input_is_valid(i_choose):

            choice = options[i_choose]

            candidates[choice] += 1
    async def on_ready(self):  #When the bot is ready
        print("\n")
        print(chalk.green(f"[SUCCESS] Connected to Discord as: {self.b.user}"))
        if conf.sharding is False:  #If sharding is disabled
            print(chalk.red(f"[WARNING] Sharding: Disabled"))
        elif conf.sharding is True:  #If sharding is Enabled
            print(chalk.green("[INFO] Sharding: Enabled"))
            print(chalk.yellow(f"[INFO] Using SHARD's {self.b.shard_ids}")
                  )  #Shows us how many shards we are currently using

        print(chalk.cyan(f"[INFO] Config name: '{conf.name}'")
              )  #Shows us the name defined in the config
        print(
            chalk.cyan(
                f"[INFO] Default Prefix: 'Prefix 1: {conf.prefix1} | Prefix 2: {conf.prefix2}'"
            ))  #Shows us the 2 prefixes defined in the config
        print(chalk.cyan("[INFO] Are you braindead: Most Likely"))  #Yup
        print(
            chalk.cyan(
                f"[INFO] I'm currently in [{len(self.b.guilds)}] server(s).")
        )  #Shows us how many servers we are in
        aaa = True
        for guild in self.b.guilds:  #Set all guild the doki is in to have triggers enabled on startup otherwise they no be in list which means triggers are off.
            conf.w_tog_on.insert(0, guild.id)
        while aaa:  #A loop to make the game activity change every 900 seconds
            for list in conf.playing_msg:
                await self.b.change_presence(activity=discord.Game(name=list))
                await asyncio.sleep(900)
Esempio n. 4
0
def menu():
    chalk.cyan("""
    -----------MENU-------------    
    Type 'help' to view this menu.
    -----------------------------
    Type 'view' ------> view phonebook.
    Type 'add' -------> add a person.
    Type 'find' ------> find a person.
    Type 'remove' ----> remove a person.
    Type 'quit' ------> quit the phonebook.
    """)
Esempio n. 5
0
 async def on_ready(self):
     print("\n")
     print(chalk.green(f"[SUCCESS] Connected to Discord as: {self.b.user}"))
     print(chalk.cyan(f"[INFO] Config name: '{conf.name}'")) #Shows us the name defined in the config
     print(chalk.cyan(f"[INFO] Default Prefix: 'Prefix 1: {conf.prefix1} | Prefix 2: {conf.prefix2}'")) #Shows us the 2 prefixes defined in the config
     print(chalk.cyan(f"[INFO] I'm currently in [{len(self.b.guilds)}] server(s).")) #Shows us how many servers we are in
     for guild in self.b.guilds: #Set all guild the doki is in to have triggers enabled on startup otherwise they no be in list which means triggers are off.
         conf.w_tog_on.insert(0, guild.id)
     while True: #A loop to make the game activity change every 900 seconds
         for list in conf.playing_msg:
             await self.b.change_presence(activity=discord.Game(name=list))
             await asyncio.sleep(900)
Esempio n. 6
0
def ballot_maker(candidates):
    display_marquee()

    nominees = dict()
    for i, p in enumerate(candidates, start=1):
        nominees.update({p: 0})  #  Build up vote dictionary
        ballot = f"{i} ---> {p}"
        chalk.cyan(ballot)

    voting_machine(
        nominees
    )  # call function 'voting_machine' with 'vote' dictionary passed thru
Esempio n. 7
0
    async def on_ready(self):
        botguild = next((item for item in self.bot.guilds if item.id == 615228970568515626), None)
        log = botguild.get_channel(625767405641007106)
        if not hasattr(self.bot, 'uptime'):
            self.bot.uptime = datetime.utcnow()

        print(chalk.bold(chalk.cyan('Ready: ')) + chalk.green(f'{self.bot.user}') + chalk.yellow(' | ') + chalk.bold(
            chalk.cyan('Servers: ')) + chalk.green(
            f'{len(self.bot.guilds)}'))
        await self.bot.change_presence(activity=discord.Game(type=0, name=self.config.playing),
                                       status=discord.Status.online)

        await log.send(f'```css\nReady! Guilds: {len(self.bot.guilds)}```')
Esempio n. 8
0
def show(proj_name, task_name):
	try:
		with open(IDEA_CONFIG_FILE_PATH, 'r') as f:
			data = f.read()
			data = decryption(data)
			data = json.loads(data)
		f.close()
	except:
		chalk.red("File not exist, operation aborted.")
		return
	for proj, task in data.items():
		chalk.yellow(proj)
		for task, desc in task:
			chalk.cyan('\t' + task)
			chalk.cyan('\t\t' + desc)
Esempio n. 9
0
def page_contents_with_mentions(page_contents, mentions_by_entity):
    chalked_contents = page_contents
    sorted_mentions = sort_mentions(mentions_by_entity)
    for mention in reversed(sorted_mentions):
        start = mention['offset']
        end = mention['offset'] + len(mention['text'])
        chalked_contents = chalked_contents[:start] + chalk.green(
            page_contents[start:end]) + chalk.cyan(
                mention['entity'], underline=True) + chalked_contents[end:]
    print(chalked_contents)
Esempio n. 10
0
    async def on_command(self, ctx):
        botguild = next((item for item in self.bot.guilds if item.id == 615228970568515626), None)
        log = botguild.get_channel(625767405641007106)
        try:
            print(chalk.bold(chalk.cyan(f'{ctx.guild.name}')) + chalk.yellow(' > ') + chalk.bold(
                chalk.green(f'{ctx.author}')) + chalk.yellow(': ') + f'{ctx.message.clean_content}')
            await log.send(f'```md\n[{ctx.guild.name}]({ctx.channel.name}) {ctx.author}: {ctx.message.clean_content}```')

        except AttributeError:
            print(chalk.yellow(f"Private message > {ctx.author} > {ctx.message.clean_content}"))
            await log.send(f'```md\n< Private message > {ctx.author}: {ctx.message.clean_content}```')
Esempio n. 11
0
 def cache(self):
     if w3.eth.blockNumber > self.scan_height:
         self.scan()
         print(
             chalk.cyan('[CACHER]') + '(' + chalk.green('Event: NewBlock') +
             ') - New block found, scanning')
         self.ws_server.send_message_to_all(
             json.dumps({
                 'type': 'block_update',
                 'data': w3.eth.blockNumber
             }))
     cache = Timer(3.0, self.cache)
     cache.start()
Esempio n. 12
0
def main() -> None:
    args: Namespace = get_args()

    # start main script
    print(chalk.green('Distinct Happy Number Range Counter\n'))
    print('Range:', chalk.red(args.r))
    time_start: float = perf_counter()  # start timer

    count: int = get_dist_happy(args.r)

    time_end: float = perf_counter()  # end timer
    time_delta: float = time_end - time_start
    print('Count Total: {count}'.format(count=chalk.cyan(count)))
    print('Calc Time (s): {}'.format(chalk.magenta(format_dec(time_delta))))
Esempio n. 13
0
def show(project_name, task_name):
    """
    all the saved entries are displayed
    :param project_name:
    :param task_name:
    :return:
    """
    try:
        with open(IDEA_CONFIG_FILE_PATH) as f:
            data = f.read()
            data = decryption(data)
            data = json.loads(data)
        f.close()
    except:
        click.echo(
            chalk.red(
                'There are no saved ideas for now. Please run "yoda ideas add" to add a new idea'
            ))
        return
    for proj, task in data.items():
        click.echo(chalk.yellow(proj))
        for _task_name, _task_description in task:
            click.echo(chalk.cyan('\t' + _task_name))
            click.echo(chalk.cyan('\t\t' + _task_description))
Esempio n. 14
0
	def wrapper_welcome():
		ascii_art_1 = """
  _____ _                                _      
 |_   _(_)_ __ ___   ___   ___  ___ __ _| | ___ 
   | | | | '_ ` _ \ / _ \ / __|/ __/ _` | |/ _ \\
   | | | | | | | | |  __/ \__ | (_| (_| | |  __/
   |_| |_|_| |_| |_|\___| |___/\___\__,_|_|\___|"""
		ascii_art_2 = """
,--,--'                        .      
`- | . ,-,-. ,-.   ,-. ,-. ,-. |  ,-. 
 , | | | | | |-'   `-. |   ,-| |  |-' 
 `-' ' ' ' ' `-'   `-' `-' `-^ `' `-'"""
		message = "The timescalecalculus python library."
		star = emoji.emojize(':star:', use_aliases=True)
		print(chalk.green(ascii_art_1, bold = True))
		print(chalk.yellow(ascii_art_2, bold = True))
		print(chalk.magenta(3*star + " " + message + 3*star))
		print(chalk.cyan("¡Bienvenido matemático!"))
		func()
Esempio n. 15
0
    async def on_guild_join(self, guild):
        guild_template = {
            'guild_id': str(guild.id),
            'name': guild.name,
            'prefix': self.config.prefix
        }
        guild_id = Guild.insert_one(guild_template).inserted_id
        print(chalk.cyan(f"Joined Guild > ") + chalk.yellow(f'{guild.name}'))
        if not self.config.join_message:
            return

        try:
            to_send = sorted([chan for chan in guild.channels if
                              chan.permissions_for(guild.me).send_messages and isinstance(chan, discord.TextChannel)],
                             key=lambda x: x.position)[0]
        except IndexError:
            pass
        else:
            await to_send.send(self.config.join_message)
            botguild = next((item for item in self.bot.guilds if item.id == 615228970568515626), None)
            log = botguild.get_channel(625767405641007106)
            await log.send(f"```css\nJoined Guild > {guild.name}```")
Esempio n. 16
0
def output(score: int, file_name: str) -> None:
    """
    takes an integer stored in score, compares against dictionary of ages/levels and prints a text eval
    
    :return: None
    """
    ari_scale = {
        1: {
            'ages': '5-6',
            'grade_level': 'Kindergarten'
        },
        2: {
            'ages': '6-7',
            'grade_level': '1st Grade'
        },
        3: {
            'ages': '7-8',
            'grade_level': '2nd Grade'
        },
        4: {
            'ages': '8-9',
            'grade_level': '3rd Grade'
        },
        5: {
            'ages': '9-10',
            'grade_level': '4th Grade'
        },
        6: {
            'ages': '10-11',
            'grade_level': '5th Grade'
        },
        7: {
            'ages': '11-12',
            'grade_level': '6th Grade'
        },
        8: {
            'ages': '12-13',
            'grade_level': '7th Grade'
        },
        9: {
            'ages': '13-14',
            'grade_level': '8th Grade'
        },
        10: {
            'ages': '14-15',
            'grade_level': '9th Grade'
        },
        11: {
            'ages': '15-16',
            'grade_level': '10th Grade'
        },
        12: {
            'ages': '16-17',
            'grade_level': '11th Grade'
        },
        13: {
            'ages': '17-18',
            'grade_level': '12th Grade'
        },
        14: {
            'ages': '18-22',
            'grade_level': 'College'
        }
    }

    score = ceil(score)
    look_up = ari_scale.get(score, ari_scale[14])

    grade_range, age_range = look_up['grade_level'], look_up['ages']

    decor_border = '-' * 62

    text_output = f"""
    The ARI for the file, {file_name.upper()}, is {score}.
    This corresponds to a {grade_range} level of difficulty
    that is suitable for an average person {age_range} years old.
    """

    chalk.cyan(decor_border)
    chalk.red(text_output)
    chalk.cyan(decor_border)
Esempio n. 17
0
#!/usr/bin/env python

import chalk

chalk.red("Hello world!!")
chalk.yellow("This looks like a warning...")
chalk.cyan('...more formatting', opts=('bold', 'underscore'))
Esempio n. 18
0
def cyan(str):
    if not enable:
        return
    chalk.cyan(str)
Esempio n. 19
0
        gathered_posts = set(json.loads(f.read()))
else:
    gathered_posts = set()

if os.path.exists("cache/gathered_hubs.json"):
    print(chalk.green("Getting gathered hubs list from cache"))
    with open("cache/gathered_hubs.json") as f:
        gathered_hubs = json.loads(f.read())
else:
    gathered_hubs = {}

posts = []
expected_traffic = 1024 * 1024 * 512
for i, hub in enumerate(hubs):
    print(chalk.green("Handling hub"), "#{}".format(chalk.yellow(hub["id"])),
          "{}/{}".format(chalk.cyan(str(i)), chalk.blue(str(len(hubs)))))

    if hub["id"] not in gathered_hubs:
        gathered_hubs[hub["id"]] = {"full": False, "url": hub["href"]}
    elif gathered_hubs[hub["id"]]["full"]:
        continue

    url = gathered_hubs[hub["id"]]["url"]
    while url is not None:
        print("URL:", chalk.blue(url).ljust(60), end="")
        page_posts, url = gatherPosts(url)
        cnt = 0
        for post in page_posts:
            if post["address"] not in gathered_posts:
                gathered_posts.add(post["address"])
                posts.append(post)
Esempio n. 20
0
 def produce_report(self):
     linter_version = self.master.get_linter_version()
     if self.master.is_plugin is True:
         linter_doc_url = (self.master.linter_url or self.master.linter_repo
                           or
                           "[linter_url should be defined on descriptor]")
     else:
         linter_doc_url = (
             f"{DOCS_URL_DESCRIPTORS_ROOT}/{self.master.descriptor_id.lower()}_"
             f"{self.master.linter_name.lower().replace('-', '_')}")
     # Linter header prints
     msg = [
         "",
         c.bold(f"### Processed [{self.master.descriptor_id}] files"),
         f"- Using [{self.master.linter_name} v{linter_version}] {linter_doc_url}",
     ]
     if self.master.descriptor_id != self.master.name:
         msg += [f"- MegaLinter key: [{self.master.name}]"]
     if self.master.config_file is not None:
         msg += [f"- Rules config: [{self.master.config_file_label}]"]
     else:
         msg += [
             f"- Rules config: identified by [{self.master.linter_name}]"
         ]
     if self.master.config_file_error is not None:
         logging.warning(self.master.config_file_error)
     if self.print_all_files is False and self.master.cli_lint_mode != "project":
         msg += [
             f"- Number of files analyzed: [{len(self.master.files_lint_results)}]"
         ]
     logging.info("\n".join(msg))
     # Output results
     for res in self.master.files_lint_results:
         file_nm = utils.normalize_log_string(res["file"])
         if self.master.cli_lint_mode == "file":
             file_errors = str(res.get("errors_number", 0))
             line = f"[{self.master.linter_name}] {file_nm} - {res['status'].upper()} - {file_errors} error(s)"
         else:
             line = f"[{self.master.linter_name}] {file_nm}"
         if res["fixed"] is True:
             line += " - FIXED"
             line = c.cyan(line)
         if res["status_code"] in [0, None
                                   ]:  # file ok or file from list_of_files
             if self.print_all_files is True:
                 logging.info(line)
         else:
             logging.error(c.red(line))
             logging.error(c.red(f"--Error detail:\n{res['stdout']}"))
     # Output stdout if not file by file
     if self.master.cli_lint_mode in ["list_of_files", "project"]:
         if self.master.status != "success":
             logging.error(f"--Error detail:\n{self.master.stdout}")
         elif self.report_type == "detailed":
             logging.info(f"--Log detail:\n{self.master.stdout}")
     # Output linter status
     base_phrase = f"Linted [{self.master.descriptor_id}] files with [{self.master.linter_name}]"
     elapse = str(round(self.master.elapsed_time_s, 2)) + "s"
     total_errors = str(self.master.total_number_errors)
     if self.master.return_code == 0 and self.master.status == "success":
         logging.info(c.green(f"✅ {base_phrase} successfully - ({elapse})"))
     elif self.master.return_code == 0 and self.master.status != "success":
         logging.warning(
             c.yellow(
                 f"✅ {base_phrase}: Found {total_errors} non blocking error(s) - ({elapse})"
             ))
     elif self.master.return_code != 0 and self.master.status != "success":
         logging.error(
             c.red(
                 f"❌ {base_phrase}: Found {total_errors} error(s) - ({elapse})"
             ))
     else:
         logging.error(
             f"❌ There is a MegaLinter issue, please report it: {self.master.return_code} / {self.master.status}"
         )
 def is_fly(self):
     if self.isFly == True:
         print(chalk.cyan('{} can fly'.format(self.name)))
     else:
         print(chalk.red("{} can't fly".format(self.name)))
Esempio n. 22
0
            if permissions.can_react(self.context):
                await self.context.message.add_reaction(chr(0x2709))
        except discord.Forbidden:
            pass

        try:
            destination = self.get_destination(no_pm=no_pm)
            for page in self.paginator.pages:
                await destination.send(page)
        except discord.Forbidden:
            destination = self.get_destination(no_pm=True)
            await destination.send(
                "Couldn't send help to you due to blocked DMs...")


print(chalk.cyan("Logging in..."))


async def prefixes_for(guild):
    _guild = Guild.find_one({'guild_id': str(guild.id)})
    if not _guild:
        guild_template = {
            'guild_id': str(guild.id),
            'name': guild.name,
            'prefix': config.prefix
        }
        guild_id = Guild.insert_one(guild_template).inserted_id
        _guild = Guild.find_one({'guild_id': str(guild.id)})

    return _guild.prefix
 def is_climb(self):
     if self.isClimb == True:
         print(chalk.cyan('{} can climb'.format(self.name)))
     else:
         print(chalk.red("{} can't climb".format(self.name)))
Esempio n. 24
0
@contact: [email protected]
@date 2015-05-09 23:29
"""

import os
import sys

currentPath = os.path.normpath(os.path.dirname(os.path.realpath(__file__)))
rootPath = os.path.normpath(os.path.dirname(currentPath))
sys.path.insert(0, rootPath)

import chalk

print "%s %s %s %s %s %s %s" % (
    chalk.bold("bold"),
    chalk.dim("dim"),
    chalk.italic("italic"),
    chalk.underline("underline"),
    chalk.inverse("inverse"),
    chalk.strikethrough("strikethrough"),
    chalk.black(chalk.gray("black")),
)
print "%s %s %s %s %s %s %s %s" % (
    chalk.red("red"), chalk.green("green"), chalk.yellow("yellow"),
    chalk.blue("blue"), chalk.magenta("magenta"), chalk.cyan("cyan"),
    chalk.white("white"), chalk.gray("gray"))
print "%s %s %s %s %s %s %s" % (
    chalk.bgRed("bgRed"), chalk.bgGreen("bgGreen"), chalk.bgYellow("bgYellow"),
    chalk.bgBlue("bgBlue"), chalk.bgMagenta("bgMagenta"),
    chalk.bgCyan("bgCyan"), chalk.bgWhite("bgWhite"))
Esempio n. 25
0
 def process_response(self, req, resp, resource, req_succeeded):
     print(chalk.green(req.method) + ' ' + chalk.cyan(req.relative_uri) + ' ' + chalk.yellow(resp.status[:3]))
Esempio n. 26
0
def main():
	command=""
	print chalk.blue("Yes sir?")
	while 1:
		if command.lower() in stop:
			break
		else:
			global reply 
			reply = ""
			print chalk.cyan("\nWhat would you like me to do?")
			command = raw_input('> ')
			try:
				ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN_APIAI)
				requestai = ai.text_request()
				requestai.lang = 'en' 
				requestai.session_id = "<SESSION ID, UNIQUE FOR EACH USER>"
				requestai.query = command
				response = requestai.getresponse()
				reply0 = json.loads(response.read())
				reply1 = reply0['result']['fulfillment']['messages']
				reply = reply1[0]['speech']
			except :
				pass
			if reply in fallback:
				word_tokens = word_tokenize(command)
				command_words = [w for w in word_tokens if not w in stop_words]
				if command not in stop:
					for i in command_words:

                        #shorten_url
						if i in ['shorten','short','small','smaller']:
							flag=0
							print chalk.yellow(random.choice(yes))
							for i in command_words:
								try:
									url = 'http://'+i
									reply = "\rThe shortened url is {}".format(shortener.short(url))
									print chalk.green(reply)
									flag=1
								except :
									pass
							
							if flag==0:
								reply = "Sorry sir, cannot shorten this url"
								print chalk.red(reply)
							reply=''
							break

                        #expand_url
						elif i in ['expand','enlarge','big','large']:
							flag=0
							print chalk.yellow(random.choice(yes))
							for i in command_words:
								try:
									url = i
									if url_start in url:
										reply = "The expanded url is {}".format(shortener.expand(url))
									else:
										url = url_start+i
										reply = "The expanded url is {}".format(shortener.expand(url))
									flag=1
									print chalk.green(reply)
				
								except :
									pass

							if flag==0:
								reply = "Sorry sir, cannot expand this url"
								print chalk.red(reply)

							reply = ''
							break

                        #speedtest
						elif i in ['server','speed','network','connection','download','upload','ping','speedtest']:
							print chalk.yellow(random.choice(yes))
							reply =  "BEST SERVER: " + st.get_best_server()['url'] + "\nDOWNLOAD: " + str(st.download()/(1024*1024)) + " MBPS\nUPLOAD: " + str(st.upload()/(1024*1024)) +  " MBPS"
							print chalk.green(reply)
							reply = ''
							break
						
						#calendar
						elif i in ['datetime','date','month','calendar','year','time']:
							print chalk.yellow(random.choice(yes))
							y=dt.now().year
							m=dt.now().month
							d=dt.now().day	
							c = calendar.TextCalendar(calendar.SUNDAY)
							cal = c.formatmonth(y, m)
							print chalk.blue(cal)
							hour = dt.now().hour
							half = ' AM'
							if hour > 12:
								hour -= 12
								half = ' PM'
							minute = dt.now().minute
							if minute < 10:
								minute = "0"+str(minute)
							time = str(hour)+":"+ str(minute) + half
							print chalk.green("NOW : ")
							reply = str(d)+"/"+str(m)+"/"+str(y)+" - "+ time
							print chalk.green(reply)
							reply =''
							break

						#email
						elif i in ['mail','email','attach','electronic-mail']:
							print chalk.yellow(random.choice(yes))
							fromaddr = raw_input("~Enter Your Email Address: ")
							pas = getpass.getpass()
							toaddr = raw_input("~Enter Reciever's Email Address: ")							 
							msg = MIMEMultipart()
							msg['From'] = fromaddr
							msg['To'] = toaddr
							msg['Subject'] = raw_input("~Enter the subject of the mail: ")	
							body = raw_input("~Enter the body of the mail: ")
							part1 = MIMEText(body,'plain')
							msg.attach(MIMEText(body, 'plain'))
							choice = raw_input("~Enter 1 to make an attachment: ")
							if choice == "1":
								filename = raw_input("~Enter the name of the attachment: ")
								path_to_file = raw_input("~Enter the path to the attachment: ")
								attachment = open(path_to_file, "rb")
								part = MIMEBase('application', 'octet-stream')
								part.set_payload((attachment).read())
								encoders.encode_base64(part)
								part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
								msg.attach(part)					 
							server = smtplib.SMTP('smtp.gmail.com', 587)
							server.starttls()
							server.login(fromaddr, pas)
							text = msg.as_string()
							server.sendmail(fromaddr, toaddr, text)
							server.quit()
							print chalk.green("Mail successfully sent!")
							reply=""
							break

						#weather
						elif i in ['weather','weathers','condition','temperature','hot','cold']:
							print chalk.yellow(random.choice(yes))
							try:
								place = command.split(i+" of ")[1] #raw_input('~Enter the name of city: ')
							except:
								place = command.split(i)[1]
							if place == '':
								place = raw_input('~Enter the name of the city: ')
							r = requests.get('http://api.openweathermap.org/data/2.5/weather?q='+place+'&APPID=eaa27a7b42b031a60e68312e9a689569')
							a = r.json()
							temp = str(int(a['main']['temp']) - 273)
							print chalk.green("Weather conditions of "+place+" is: " + a['weather'][0]['description'] + "\nTemperature: " + temp + "\nHumidity: " + str(a['main']['humidity']) +  "\nPressure : "+str(a['main']['pressure']) + "\nWind : " + str(a['wind']['speed']))
							reply = ""
							break

						#diary
						elif i in ['note down','write down','jot down','jot','write','note','diary']:
							print chalk.yellow(random.choice(yes))
							db = sqlite3.connect('diary.db')
							c = db.cursor()
							try:
								c.execute(''' CREATE TABLE note(id INTEGER PRIMARY KEY, d TEXT, t TEXT, entry TEXT)
								''')
								db.commit()
							except:
								pass
							c = db.cursor()
							day = dt.now().day
							month = dt.now().month
							year = dt.now().year
							dateNote = str(day)+"/"+str(month)+"/"+str(year)
							hourNote = dt.now().hour
							half = ' AM'
							if hourNote > 12:
								hourNote -= 12
								half = ' PM'
							minuteNote = dt.now().minute
							if minuteNote < 10:
								minuteNote = "0"+str(minuteNote)
							timeNote = str(hourNote)+":"+ str(minuteNote) + half
							textNote = str(raw_input("What should I note down sir? "))
							c.execute(''' INSERT INTO note(d, t, entry)
                  					VALUES(?,?,?) ''', (dateNote, timeNote, textNote))
							db.commit()
							print chalk.green('Sucessfully noted down sir!')
							ch = raw_input('~Enter 1 to view all notes: ')
							if ch == '1':
								c.execute('''SELECT * FROM note ORDER BY d,t''')
								allNotes = c.fetchall()
								print chalk.yellow("Date \t\tTime \t\tText")
								for i in allNotes:
									print chalk.blue(str(i[1])+" \t"+str(i[2])+" \t"+str(i[3]))
							reply=""
							break

						#wallet
						elif i in ['wallet','transaction','money','balance']:
							print chalk.yellow(random.choice(yes))
							db2 = sqlite3.connect('wallet.db')
							c = db2.cursor()
							try:
								c.execute(''' CREATE TABLE wallet(id INTEGER PRIMARY KEY, d TEXT, details TEXT,  type TEXT, amount INTEGER, balance INTEGER)
								''')
								c = db2.cursor()
								date0 = '05/05/2018'
								detail0 = 'Open'
								type0 = 'O'
								amount = 0
								balance = 0
								c.execute(''' INSERT INTO wallet(details, d, type, amount, balance)
								              VALUES(?,?,?,?,?) ''', (detail0,date0,type0,amount,balance))
								db2.commit()
							except:
								pass

							if command in ['show balance','display balance','money left','balance','wallet','wallet balance']:
								c.execute("SELECT * FROM wallet ORDER BY id DESC LIMIT 1")
								result = c.fetchone()
								balance = result[5]
								print chalk.green("Current Balance is : " + str(balance))
								ch2 = raw_input('Enter 1 to view wallet transactions: ')
								if ch2 =='1':
									c.execute('''SELECT * FROM wallet''')
									allTx = c.fetchall()
									print chalk.yellow("ID \tDate \t\tDetails \tType \tAmount \tBalance")
									for i in allTx:
										print chalk.blue(str(i[0])+" \t"+str(i[1])+" \t"+str(i[2])+" \t\t"+str(i[3])+" \t"+str(i[4])+" \t"+str(i[5]))
								reply = ''
								break
							else:
								c = db2.cursor()
								print chalk.white("------------Transaction Details------------")
								date1 = raw_input('~Enter the date (dd/mm/yyyy) : ')
								detail1 = raw_input('~Enter the details : ')
								type1 = raw_input('~Enter C/D for Credit/Debit : ')
								while type1 not in ['C','D']:
									print "Wrong input"
									type1 = raw_input('~Enter C/D for Credit/Debit : ')	
								amount1 = int(raw_input('~Enter the amount : '))
								c.execute("SELECT * FROM wallet ORDER BY id DESC LIMIT 1")
								result = c.fetchone()
								balance = result[5]
								if type1 == 'C':
									balance+=amount1
								else:
									balance-=amount1
								c.execute(''' INSERT INTO wallet(details, d, type, amount, balance)
								              VALUES(?,?,?,?,?) ''', (detail1,date1,type1,amount1,balance))
								db2.commit()
								print "-------------------------------------------"
							ch2 = raw_input('Enter 1 to view wallet transactions: ')
							if ch2 =='1':
									c.execute('''SELECT * FROM wallet''')
									allTx = c.fetchall()
									print chalk.yellow("ID \tDate \t\tDetails \tType \tAmount \tBalance")
									for i in allTx:
										print chalk.blue(str(i[0])+" \t"+str(i[1])+" \t"+str(i[2])+" \t\t"+str(i[3])+" \t"+str(i[4])+" \t"+str(i[5]))
							reply = ''
							break

						#googlesearch
						elif i in ['google','search','look up','find']:
							print chalk.yellow(random.choice(yes))
							w = command.split(i+" ")
							word = w[1]
							try:
								resp = gs().search(word)
								allr = resp.results
								i=1
								if len(allr) > 10:
									allr = allr[:10]
								for r in allr:
									print  chalk.blue(str(i) + ". " + r.title + " - " + r.url) 								
									i+=1
								reply="There are " + str(i-1) + " matching results"
								print chalk.green(reply)
								reply = ''
							except:
								pass

			print chalk.red(reply)
			reply = ""

	if command.lower() in stop:
		print chalk.blue("I'll not be listening now\n")
Esempio n. 27
0
    def scan(self):
        listings_created = self.get_event_entries('ListingCreated')
        listings_fulfilled = self.get_event_entries('ListingFulfilled')
        listings_cancelled = self.get_event_entries('ListingCancelled')

        for event in listings_created:
            listing_id = event.args.id
            listings_table = db['listings']
            events_table = db['events']
            listings = listings_table.find({'id': listing_id})

            if listings.count() < 1:
                print(
                    chalk.cyan('[CACHER]') + '(' +
                    chalk.green('Event: ListingCreated') +
                    ') - New listing created, listing id: ' + str(listing_id))
                listing = self.contract.call().listings(listing_id)
                self.ws_server.send_message_to_all(
                    json.dumps({
                        'type': 'listing_created',
                        'data': listing_id
                    }))

                local_listing = {
                    'id': listing_id,
                    'date': listing[1],
                    'merchant': listing[2],
                    'asset': listing[3],
                    'amount': str(listing[4]),
                    'value': str(listing[5]),
                    'status': listing[6],
                    'market': config.get('NETWORK', 'MARKET_ADDRESS')
                }

                local_event = {
                    'date': local_listing.get('date'),
                    'type': 'ListingCreated',
                    'parties': [listing[2]],
                    'ref': local_listing
                }

                events_table.insert_one(local_event)
                listings_table.insert_one(local_listing)

                with open('market/core_contracts/build/contracts/EIP20.json',
                          'r') as abi_definition:
                    info_json = json.load(abi_definition)
                    abi = info_json["abi"]
                asset_contract = w3.eth.contract(address=listing[3], abi=abi)
                tokens_table = db['tokens']
                local_asset = tokens_table.find({'address': listing[3]})
                if local_asset.count() < 1:
                    print(
                        chalk.cyan('[CACHER]') + '(' +
                        chalk.green('Event: TokenDiscovered') +
                        ') - New token discovered: ' +
                        asset_contract.call().name())

                    asset = {
                        'name': asset_contract.call().name(),
                        'address': listing[3],
                        'symbol': asset_contract.call().symbol(),
                        'decimals': asset_contract.call().decimals()
                    }
                    tokens_table.insert_one(asset)

        for event in listings_fulfilled:
            listing_id = event.args.id
            listings_table = db['listings']
            events_table = db['events']
            listings = listings_table.find({'id': listing_id})
            if listings.count() > 0 and listings[0].get(
                    'fulfilled_at') is None:
                print(
                    chalk.cyan('[CACHER]') + '(' +
                    chalk.green('Event: ListingFulfilled') +
                    ') - Listing has been fulfilled, listing id: ' +
                    str(listing_id))
                self.ws_server.send_message_to_all(
                    json.dumps({
                        'type': 'listing_fulfilled',
                        'data': listing_id
                    }))

                print('BUYER', event.args.buyer)
                print('MERCHANAT', listings[0].get('merchant'))
                local_event = {
                    'date': listings[0].get('date'),
                    'type': 'ListingFulfilled',
                    'parties': [listings[0].get('merchant'), event.args.buyer],
                    'ref': listings[0]
                }

                events_table.insert_one(local_event)

                db['listings'].update_one(
                    {'id': listing_id},
                    {'$set': {
                        'status': 1,
                        'fulfilled_at': time.time()
                    }},
                    upsert=False)

        for event in listings_cancelled:
            listing_id = event.args.id
            listings_table = db['listings']
            events_table = db['events']
            listings = listings_table.find({'id': listing_id})
            if listings.count() > 0 and listings[0].get('status') is not 2:
                print(
                    chalk.cyan('[CACHER]') + '(' +
                    chalk.green('Event: ListingCancelled') +
                    ') - Listing has been cancelled, listing id: ' +
                    str(listing_id))
                self.ws_server.send_message_to_all(
                    json.dumps({
                        'type': 'listing_cancelled',
                        'data': listing_id
                    }))

                local_event = {
                    'date': listings[0].get('date'),
                    'type': 'ListingCancelled',
                    'parties': [listings[0].get('merchant')],
                    'ref': listings[0]
                }

                events_table.insert_one(local_event)

                db['listings'].update_one({'id': listing_id},
                                          {'$set': {
                                              'status': 2
                                          }},
                                          upsert=False)

        self.scan_height = w3.eth.blockNumber
Esempio n. 28
0
#!/usr/bin/env python

import chalk

chalk.blue("Hello world!!")
chalk.yellow("Listen to me!!!")
chalk.red("ERROR", pipe=chalk.stderr)
chalk.magenta('This is pretty cool', opts='bold')
chalk.cyan('...more stuff', opts=('bold', 'underscore'))