Skip to content

Commit

Permalink
auto lint & format fixes (#145)
Browse files Browse the repository at this point in the history
beyond the minimum ruff config
  • Loading branch information
daabr authored Jan 5, 2025
1 parent 43e9afc commit ad2817d
Show file tree
Hide file tree
Showing 40 changed files with 190 additions and 179 deletions.
5 changes: 3 additions & 2 deletions auth0_to_hubspot/program.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""This program adds new Auth0 users to HubSpot as contacts."""

from datetime import UTC, datetime
from datetime import datetime, UTC
import os

from autokitteh.auth0 import auth0_client
Expand All @@ -17,7 +17,8 @@
def check_for_new_users(event):
"""Workflow entrypoint.
Looks up new Auth0 users in the last `HOURS` hours and adds them to HubSpot as contacts.
Looks up new Auth0 users in the last `HOURS` hours,
and adds them to HubSpot as contacts.
"""
start, end = _get_time_range(LOOKUP_HOURS)
query = f"created_at:[{start} TO {end}]"
Expand Down
18 changes: 9 additions & 9 deletions aws_health_to_slack/program.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
https://aws.amazon.com/blogs/mt/tag/aws-health-api/
"""

from datetime import UTC, datetime, timedelta
from datetime import datetime, timedelta, UTC
import json
import os
import re
Expand Down Expand Up @@ -67,11 +67,11 @@ def _aws_health_events() -> list[dict]:
resp = aws.describe_events(filter=filter)
events = resp.get("events", [])

nextToken = resp.get("nextToken")
while nextToken:
resp = aws.describe_events(filter=filter, nextToken=nextToken)
next_token = resp.get("nextToken")
while next_token:
resp = aws.describe_events(filter=filter, nextToken=next_token)
events += resp.get("events", [])
nextToken = resp.get("nextToken")
next_token = resp.get("nextToken")

return events

Expand All @@ -97,11 +97,11 @@ def _affected_aws_entities(events: list[dict]) -> list[dict]:
resp = aws.describe_affected_entities(filter=filter)
entities = resp.get("entities", [])

nextToken = resp.get("nextToken")
while nextToken:
resp = aws.describe_affected_entities(filter=filter, nextToken=nextToken)
next_token = resp.get("nextToken")
while next_token:
resp = aws.describe_affected_entities(filter=filter, nextToken=next_token)
entities += resp.get("entities", [])
nextToken = resp.get("nextToken")
next_token = resp.get("nextToken")

return entities
except Exception as e:
Expand Down
7 changes: 4 additions & 3 deletions break_glass/program.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,12 @@
and justification for the request.
4. AutoKitteh sends a notification to the SRE (Site Reliability Engineering) team
with an approve/deny message, including the details of the request.
5. The SRE team reviews the request and makes a decision to approve or deny the request.
5. The SRE team reviews the request and makes a decision to approve or deny the
request.
6. AutoKitteh sends a message to the developer with the decision, notifying them
whether the request was approved or denied.
The program integrates with Jira to verify ticket existence and ensure that the requester
The program integrates with Jira to verify ticket existence and ensure the requester
is the assignee of the ticket. It also uses Slack for communication and notifications
throughout the process.
"""
Expand All @@ -25,7 +26,7 @@
from pathlib import Path

import autokitteh
from autokitteh.atlassian import jira_client, get_base_url
from autokitteh.atlassian import get_base_url, jira_client
from autokitteh.slack import slack_client
from requests.exceptions import HTTPError

Expand Down
45 changes: 23 additions & 22 deletions categorize_emails/program.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,31 @@
"""
This program demonstrates a real-life workflow that integrates Gmail, ChatGPT, and Slack.
"""A real-life workflow that integrates Gmail, ChatGPT, and Slack:
Workflow:
1. Trigger: Detect a new email in Gmail.
2. Categorize: Use ChatGPT to read and categorize the email (e.g., technical work, marketing, sales).
2. Categorize: Use ChatGPT to read and categorize the email
(e.g., technical work, marketing, sales).
3. Notify: Send a message to the corresponding Slack channel based on the category.
4. Label: Add a label to the email in Gmail.
"""

import base64
from datetime import datetime, timezone
from datetime import datetime, UTC
import os
import time

import autokitteh
from autokitteh import google, openai, slack
from autokitteh.google import gmail_client
from autokitteh.openai import openai_client
from autokitteh.slack import slack_client


POLL_INTERVAL = float(os.getenv("POLL_INTERVAL"))
SLACK_CHANNELS = ["demos", "engineering", "ui"]


gmail_client = google.gmail_client("my_gmail").users()
slack_client = slack.slack_client("my_slack")
gmail = gmail_client("my_gmail").users()
slack = slack_client("my_slack")
processed_message_ids = set()
start_time = datetime.now(timezone.utc).timestamp()
start_time = datetime.now(UTC).timestamp()


def on_http_get(event):
Expand All @@ -46,7 +47,7 @@ def _poll_inbox():


def _process_email(message_id: str, start_time: datetime):
message = gmail_client.messages().get(userId="me", id=message_id).execute()
message = gmail.messages().get(userId="me", id=message_id).execute()
email_timestamp = float(message["internalDate"]) / 1000

if email_timestamp < start_time:
Expand All @@ -64,15 +65,15 @@ def _process_email(message_id: str, start_time: datetime):
print("Could not categorize email.")
return

slack_client.chat_postMessage(channel=channel, text=email_content)
slack.chat_postMessage(channel=channel, text=email_content)

# Add label to email
label_id = _get_label_id(channel) or _create_label(channel)
if not label_id:
return

body = {"addLabelIds": [label_id]}
gmail_client.messages().modify(userId="me", id=message_id, body=body).execute()
gmail.messages().modify(userId="me", id=message_id, body=body).execute()


def _parse_email(message: dict):
Expand All @@ -95,12 +96,12 @@ def _create_label(label_name: str) -> str:
"messageListVisibility": "show",
"name": label_name,
}
created_label = gmail_client.labels().create(userId="me", body=label).execute()
created_label = gmail.labels().create(userId="me", body=label).execute()
return created_label.get("id", None)


def _get_label_id(label_name: str) -> str:
labels_response = gmail_client.labels().list(userId="me").execute()
labels_response = gmail.labels().list(userId="me").execute()
labels = labels_response.get("labels", [])
for label in labels:
if label["name"] == label_name:
Expand All @@ -110,7 +111,7 @@ def _get_label_id(label_name: str) -> str:

def get_new_inbox_messages():
query = "in:inbox -in:drafts"
return gmail_client.messages().list(userId="me", q=query, maxResults=10).execute()
return gmail.messages().list(userId="me", q=query, maxResults=10).execute()


@autokitteh.activity
Expand All @@ -121,19 +122,19 @@ def _categorize_email(email_content: str) -> str:
The name of the Slack channel to send a message to as a string.
If the channel is not in the provided list, returns None.
"""
client = openai.openai_client("my_chatgpt")
client = openai_client("my_chatgpt")
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{
"role": "user",
"content": f"""Categorize the following email based on its
topic and suggest a channel to post it in from the
provided list. The output should be one of the provided
channels and nothing else.
Email Content: {email_content} Channels: {SLACK_CHANNELS}
Output example: {SLACK_CHANNELS[0]}""",
"content": (
"Categorize the following email based on its topic and suggest a "
"channel to post it in from the provided list. The output should "
"be one of the channels in {SLACK_CHANNELS} and nothing else, "
"for example: {SLACK_CHANNELS[0]}\n\nEmail content: {email_content}"
),
},
],
)
Expand Down
6 changes: 3 additions & 3 deletions data_pipeline/pipeline.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
"""Parse GPX files when uploaded to an S3 bucket, and insert the data into a SQLite database."""
"""Parse GPX files when uploaded to an S3 bucket, and insert into a SQLite database."""

from contextlib import closing
from io import BytesIO
import json
import os
import sqlite3
import xml.etree.ElementTree as xml
import xml.etree.ElementTree as Xml

import autokitteh
from autokitteh.aws import boto3_client
Expand Down Expand Up @@ -64,7 +64,7 @@ def insert_records(db_dsn, records):
@autokitteh.activity
def parse_gpx(track_id, data):
io = BytesIO(data)
root = xml.parse(io).getroot()
root = Xml.parse(io).getroot()
return [
{
"track_id": track_id,
Expand Down
5 changes: 1 addition & 4 deletions discord_to_spreadsheet/program.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""This program logs Discord message events and the author's username
into a Google Sheets document.
"""
"""Log Discord message events and the author's username into a Google Sheet."""

import os

Expand All @@ -15,7 +13,6 @@

def on_discord_message(event):
values = [[event.data["author"]["username"], event.data["content"]]]

sheet.append(
spreadsheetId=SPREADSHEET_ID,
range=RANGE_NAME,
Expand Down
23 changes: 15 additions & 8 deletions github_actions/program.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
"""This program provides functions to handle GitHub workflows that interact across multiple repositories.
It defines triggers that automatically start workflows in specific repositories when workflows in other
repositories are completed.
"""Handle GitHub workflows that interact across multiple repositories.
This program defines triggers that automatically start workflows in specific
repositories when workflows in other repositories are completed.
This program supports several types of triggers:
1. Cross-repo trigger: Initiates a workflow in repository B when a workflow in repository A completes.
2. Fan-out trigger: Initiates workflows in repositories B and C upon the completion of a workflow in repository A.
3. OR trigger: Initiates a workflow in repository C if a workflow in either repository A or B completes.
4. Fan-in trigger: Initiates a workflow in repository C only when workflows in both repositories A and B complete.
1. Cross-repo trigger: Initiates a workflow in repository B when a workflow in
repository A completes.
2. Fan-out trigger: Initiates workflows in repositories B and C upon the
completion of a workflow in repository A.
3. OR trigger: Initiates a workflow in repository C if a workflow in either
repository A or B completes.
4. Fan-in trigger: Initiates a workflow in repository C only when workflows in
both repositories A and B complete.
"""

import os

import autokitteh
from autokitteh.github import github_client


REPO_A = os.getenv("REPO_A")
REPO_B = os.getenv("REPO_B")
REPO_C = os.getenv("REPO_C")
Expand All @@ -24,7 +31,7 @@


def on_cross_repo(_):
"""Cross-repo trigger (completion of workflow in repo A triggers workflow in repo B)."""
"""Cross-repo trigger (workflow completion in repo A triggers workflow in B)."""
subscribe_to_event([REPO_A])
trigger_workflow(REPO_B, B_WORKFLOW_FILE)

Expand Down
3 changes: 2 additions & 1 deletion google_cal_to_asana/program.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
"""This program creates a new Asana task when a new event is created in Google Calendar."""
"""Create a new Asana task when a new event is created in Google Calendar."""

import os

import asana
from asana.rest import ApiException
from autokitteh.asana import asana_client


ASANA_PROJECT_GID = os.getenv("ASANA_PROJECT_GID")

api_client = asana_client("asana_conn")
Expand Down
9 changes: 5 additions & 4 deletions hackernews/program.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
"""Monitor Hacker News for new articles on a specific topic, and post updates to a Slack channel."""
"""Monitor Hacker News for new articles on a specific topic, post updates to Slack."""

import os
import requests
import time
import urllib.parse

from autokitteh.slack import slack_client
import requests


API_URL = "http://hn.algolia.com/api/v1/search_by_date?tags=story&page=0&query="
Expand All @@ -16,6 +16,7 @@

def on_slack_command(event):
"""Workflow's entry-point.
Extracts a topic from a Slack command, monitors for new articles,
and posts updates to `SLACK_CHANNEL`.
"""
Expand All @@ -27,8 +28,8 @@ def on_slack_command(event):
current_articles = set()
fetch_articles(topic, current_articles)

# NOTE: For low-traffic topics, it might take a while for new articles to be published,
# so users may experience delays in receiving notifications.
# NOTE: For low-traffic topics, it might take a while for new articles to
# be published, so users may experience delays in receiving notifications.
while True:
all_articles = set(current_articles)
fetch_articles(topic, all_articles)
Expand Down
5 changes: 2 additions & 3 deletions jira_google_calendar/assignee_from_schedule/program.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""
This program assigns Atlassian Jira issues based on a shared Google Calendar.
"""This program assigns Atlassian Jira issues based on a shared Google Calendar.
The shared Google Calendar defines a 27/4 on-call rotation.
How to create it: https://support.google.com/calendar/answer/37095
Expand All @@ -9,7 +8,7 @@
- Description: their Atlassian account ID
"""

from datetime import UTC, datetime, timedelta
from datetime import datetime, timedelta, UTC
import os

import autokitteh
Expand Down
3 changes: 1 addition & 2 deletions jira_google_calendar/deadline_to_event/program.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""
This program receives Jira events and creates Google Calendar events.
"""This program receives Jira events and creates Google Calendar events.
Scenario:
Initiating a procedure that requires collaboration and coordination,
Expand Down
6 changes: 3 additions & 3 deletions purrr/data_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,15 @@
def cache_github_reference(slack_user_id: str, github_ref: str) -> None:
"""Map a Slack user ID to a GitHub user reference/name, for a day.
This helps reduce the amount of GitHub and Slack lookup API calls, to avoid throttling.
This helps reduce the amount of lookup API calls, to avoid throttling.
"""
return # TODO: Implement this function.


def cached_github_reference(slack_user_id: str) -> str:
"""Return the GitHub user reference/name mapped to a Slack user ID, or "" if not cached yet.
"""Return the GitHub user reference/name mapped to a Slack user ID, or "".
This helps reduce the amount of GitHub and Slack lookup API calls, to avoid throttling.
This helps reduce the amount of lookup API calls, to avoid throttling.
"""
return "" # TODO: Implement this function.

Expand Down
3 changes: 2 additions & 1 deletion purrr/github_pr.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ def _parse_github_pr_event(data) -> None:
case "unassigned":
_on_pr_unassigned(data)

# The title or body of a pull request was edited, or the base branch was changed.
# The title or body of a pull request was edited,
# or the base branch was changed.
case "edited":
_on_pr_edited(data)
# A pull request's head branch was updated.
Expand Down
Loading

0 comments on commit ad2817d

Please sign in to comment.