JustToThePoint English Website Version
JustToThePoint en español
JustToThePoint in Thai

Current Bitcoin & stocks. Reading emals in Gmail

“Hell is empty, all the devils and motherfuckers are here, and you are the greatest whore ever. Your cunt is a common shore, but your brain is a deserted island. It is full of palm trees, but no coconuts, Apocalypse, Anawim, #justtothepoint.

Current prices of Bitcoin and stocks

"""
This script utilizes external APIs to fetch and display the current price of Bitcoin and various stocks.

- The Bitcoin price is retrieved from CoinDesk's Bitcoin Price Index (BPI).
- Stock prices are fetched using the Alpha Vantage API.

Requirements:
- Requests module for API requests.
- Colorama module for colored terminal output.
- An API key for Alpha Vantage, set as an environment variable.
"""
import requests
import os
from colorama import Back, Fore, init, Style
import os # It is used for accessing environment variables

def bitcoin():
    """
    Fetches and prints the current Bitcoin price in USD from the CoinDesk API.
    """
    
    # Initialize Colorama to auto-reset after each print statement.
    init(autoreset=True)
    r = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json')
    print("------------------------------------------------")
    # "USD":{"code":"USD","symbol":"$", ****  "rate":"126.5235",   ****   "description":"United States Dollar","rate_float":126.5235},
    print (Style.RESET_ALL + Fore.GREEN + "The current price of Bitcoin is: $" + r.json()['bpi']['USD']['rate'])


def get_stock_price(name, symbol):
    """
    Fetches and prints the current stock price for a given company symbol using the Alpha Vantage API.

    Parameters:
    - name (str): The name of the company.
    - symbol (str): The stock symbol of the company.
    """

    # Retrieve News API key from environment variables
    # For security reason we will hide this key within environment variables on Linux
    # vi ~/.zshrc, export VARIABLE_NAME=VARIABLE_VALUE, in our particular case VARIABLE_NAME is API_KEY_ALPHAVANTAGE
    api_key = os.getenv("News_API_KEY")
    API_URL = "https://www.alphavantage.co/query"
    params = {
        "function": "GLOBAL_QUOTE",
        "symbol": symbol,
        "apikey": api_key
    }
    
    response = requests.get(API_URL, params=params)
    response_json = response.json()
    
    if "Global Quote" in response_json:
        data = response_json["Global Quote"]
        price = data.get("05. price", "Unavailable")
        if price != "Unavailable":
            print(f"Current price of {name}, {symbol}: ${float(price):.2f}")
        else:
            print(f"Price data unavailable for {symbol}.")
    else:
        print(f"Failed to fetch data for {symbol}. Error or limit reached.")

if __name__ == '__main__':
    bitcoin()
    company_symbols = {
        "Apple Inc.": "AAPL",
        "Alphabet": "GOOGL",
        "Amazon": "AMZN",
        "Meta Platforms": "META",
        "Microsoft": "MSFT",
        "Nvidia": "NVDA",
        "Tesla": "TSLA"
    }
    for name, symbol in company_symbols.items():
        get_stock_price(name, symbol)

A more secure approach is to have environment variable exports located outside of your .zshrc file (or any shell initialization file like .bashrc for bash users), you can create a separate file to store them and then source this file whenever you need the variables to be available in your environment.

  1. Create a new file: _nvim .zshenv
  2. Open .zshenv and add your environment variable declarations in the following format: export VAR_NAME=“value”. The content of this file could be saved for future migrations to KeePassXC.
  3. Source the file. Edit Your .zshrc or .bashrc and add the line: source ~/.zshenv
  4. Add to .gitignore. Navigate to the root directory of your project (cd dotfiles) and add it (~/.zshenv).

Read the subjects of your emails in Gmail

Google is constantly changing its APIs, prices, etc., and making it more complicated and pricey. Let’s go old school.

'''
File: googleGmail.py
Author: Máximo Núñez Alarcón
Description: Python script to access and read emails from Gmail using IMAP
It connects to Gmail's IMAP server, logs in using your credentials, selects the inbox, and searches for your emails. 
For each email found, it retrieves the sender, subject, and prints them to the console.
Using plain passwords is not recommended for security reasons. Instead, consider using OAuth2 for authentication, which is far more secure.
Usage: Import the myGmail function and call it without arguments or $python googleGmail.py
'''

import imaplib
import email
from email.header import decode_header
import osUsage: Import the myGmail function and call it without arguments or $python googleGmail.py

def authenticate():
    '''  Gmail requires an application-specific password to log in via IMAP. This is a security measure implemented by Gmail to prevent unauthorized access to your account.
    If you have two double authentication, go to the Google Account security page: https://myaccount.google.com/security. Under "Signing in to Google," go to How you sign in to Google, "2-Step Verification", and click on "App passwords."
    Scroll down to the "App passwords" section, select "Select app" and choose "Mail" from the dropdown menu. Select "Select device" and choose "Other (Custom name)" from the dropdown menu.
    Enter a name for the application, click "Generate", and copy Google's 16-character application-specific password.'''

    # IMAP configuration
    IMAP_SERVER = 'imap.gmail.com'
    IMAP_PORT = 993
    EMAIL = 'user_name@gmail.com'

    # Retrieve MAIL_PASSWORD from environment variables
    # For security reason we will hide this key within environment variables on Linux
    # vi ~/.zshrc, export VARIABLE_NAME=VARIABLE_VALUE, in our particular case VARIABLE_NAME is News_API_KEY
    PASSWORD = os.getenv("MAIL_PASSWORD")
    
    return IMAP_SERVER, IMAP_PORT, EMAIL, PASSWORD

def decode_subject(subject):
    """
    Decode the email subject from bytes to a string.

    Args:
    - subject (str): The subject of the email as a byte string.

    Returns:
    - str: The decoded subject as a string.
    """

    decoded = decode_header(subject)
    decoded_subject = ''
    for part, encoding in decoded:
        if isinstance(part, bytes):
            if encoding:
                decoded_subject += part.decode(encoding)
            else:
                decoded_subject += part.decode()
        else:
            decoded_subject += part
    return decoded_subject

def myGmail(IMAP_SERVER, IMAP_PORT, EMAIL, PASSWORD):
    """
    Retrieve and display the subjects of emails from the user's INBOX.

    Args:
    - IMAP_SERVER (str): The IMAP server address.
    - IMAP_PORT (int): The IMAP server port number.
    - EMAIL (str): The user's email address.
    - PASSWORD (str): The user's email password.
    """
    
    # Login to Gmail
    imap = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT)
    imap.login(EMAIL, PASSWORD)

    # Select the inbox
    status, messages = imap.select('INBOX')

    # Search for all emails
    status, search_result = imap.search(None, 'ALL')

    if status == 'OK':
        for num in search_result[0].split():
            status, message_data = imap.fetch(num, '(RFC822)')
            if status == 'OK':
                raw_email = message_data[0][1]
                email_message = email.message_from_bytes(raw_email)
                sender = email_message['From']
                subject = decode_subject(email_message['Subject'])
                # If the email is multipart, iterate over each part
                if email_message.is_multipart():
                    for part in email_message.walk():
                        content_type = part.get_content_type()
                        if content_type == 'text/plain':
                            body = part.get_payload(decode=True).decode()
                            print(f"Subject: {subject}")
                            print(f"From: {sender}")
                else:
                    body = email_message.get_payload(decode=True).decode()
                    print(f"Subject: {subject}")
                    print(f"From: {sender}")
                    print("Body:")
                    print(body)

    # Logout from Gmail
    imap.close()
    imap.logout()

if __name__ == '__main__':
# Execute the main function to fetch Gmail messages
    IMAP_SERVER, IMAP_PORT, EMAIL, PASSWORD = authenticate()
    myGmail(IMAP_SERVER, IMAP_PORT, EMAIL, PASSWORD)
Bitcoin donation

JustToThePoint Copyright © 2011 - 2024 Anawim. ALL RIGHTS RESERVED. Bilingual e-books, articles, and videos to help your child and your entire family succeed, develop a healthy lifestyle, and have a lot of fun. Social Issues, Join us.

This website uses cookies to improve your navigation experience.
By continuing, you are consenting to our use of cookies, in accordance with our Cookies Policy and Website Terms and Conditions of use.