Skip to content

Commit

Permalink
Merge pull request #1 from LarynQi/cb
Browse files Browse the repository at this point in the history
[cb] archive sp22, fa22; init sp23
  • Loading branch information
LarynQi authored Jan 18, 2023
2 parents e6e8e46 + 86f31ed commit 07a59cf
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 140 deletions.
98 changes: 34 additions & 64 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,6 @@
from slack_bolt import App, Say
from slack_bolt.adapter.flask import SlackRequestHandler

# from slack_bolt.oauth.oauth_settings import OAuthSettings
# from slack_sdk.oauth.installation_store import FileInstallationStore
# from slack_sdk.oauth.state_store import FileOAuthStateStore

# from utils import init_db, read_db, write_db, email_db, setup_db, insert_db

from utils import read_db, write_db, read_prev, write_prev, DATABASES, DB_NAME
from dotenv import load_dotenv
from pymongo import MongoClient
Expand All @@ -25,46 +19,19 @@

app = Flask(__name__)

# init_db()
# caught, score, spot, images = read_db()

db_client = MongoClient(f'mongodb+srv://{os.environ.get("DB_USER")}:{os.environ.get("PASSWORD")}@cluster0.xzki5.mongodb.net/codespotting?retryWrites=true&w=majority')


# caught, spot, images = read_db(db_client)

# print(caught, spot, images)

token = os.environ.get("CLIENT_TOKEN")
client = WebClient(token=token)
SPOT_WORDS = ["spot", "spotted", "spotting", "codespot", "codespotted", "codespotting"]
USER_PATTERN = r"<@[a-zA-Z0-9]+>"

# prev = [None, None]
# prev = read_prev(db_client)

# https://slack.dev/bolt-python/concepts#authenticating-oauth
# oauth_settings = OAuthSettings(
# client_id=os.environ["SLACK_CLIENT_ID"],
# client_secret=os.environ["SLACK_CLIENT_SECRET"],
# scopes=["channels:read", "groups:read", "chat:write"],
# installation_store=FileInstallationStore(base_dir="./data"),
# state_store=FileOAuthStateStore(expiration_seconds=600, base_dir="./data"),
# )

bolt_app = App(token=token, signing_secret=os.environ.get("SIGNING_SECRET"))
# bolt_app = App(token=token, signing_secret=os.environ.get("SIGNING_SECRET"), oauth_settings=oauth_settings)

handler = SlackRequestHandler(bolt_app)

# @app.route("/slack/oauth_redirect", methods=["GET"])
# def handle_oauth():
# return handler.handle(request)

# @app.route("/slack/install")
# def handle_install():
# return handler.handle(request)

@app.route("/slack/events", methods=["POST"])
def handle_events():
return handler.handle(request)
Expand Down Expand Up @@ -94,8 +61,6 @@ def log_spot(event, say):
prev[0] = spotter
prev[1] = 1
write_prev(db_client, prev)
# write_db(caught, score, spot, images)
# print(caught, spot, images)
write_db(db_client, caught, spot, images)
response = client.reactions_add(channel=event['channel'], name="white_check_mark", timestamp=event['ts'])

Expand All @@ -110,10 +75,9 @@ def scoreboard(event, say, prefix="", db_name=DB_NAME):
except:
n = 5
scoreboard = sorted(spot.items(), key=lambda p: p[1], reverse=True)[:n]
message = "Spotboard:\n"
message = prefix + "Spotboard:\n"
for i in range(len(scoreboard)):
curr = scoreboard[i]
# message += f"{i + 1}. <@{curr[0]}> - {curr[1]}\n"
message += f"{i + 1}. {get_display_name(curr[0])} - {curr[1]}\n"
say(message)

Expand All @@ -124,6 +88,20 @@ def scoreboard(event, say, prefix="", db_name=DB_NAME):
def fa21_scoreboard(event, say):
scoreboard(event, say, prefix="fa21-", db_name=DATABASES['fa21'])

@bolt_app.message("sp22-scoreboard")
@bolt_app.message("sp22-spotboard")
@bolt_app.message("sp22-Scoreboard")
@bolt_app.message("sp22-Spotboard")
def sp22_scoreboard(event, say):
scoreboard(event, say, prefix="sp22-", db_name=DATABASES['sp22'])

@bolt_app.message("fa22-scoreboard")
@bolt_app.message("fa22-spotboard")
@bolt_app.message("fa22-Scoreboard")
@bolt_app.message("fa22-Spotboard")
def fa22_scoreboard(event, say):
scoreboard(event, say, prefix="fa22-", db_name=DATABASES['fa22'])

@bolt_app.message("scoreboard")
@bolt_app.message("spotboard")
@bolt_app.message("Scoreboard")
Expand All @@ -139,7 +117,7 @@ def caughtboard(event, say, prefix="", db_name=DB_NAME):
except:
n = 5
caughtboard = sorted(caught.items(), key=lambda p: p[1], reverse=True)[:n]
message = "Caughtboard:\n"
message = prefix + "Caughtboard:\n"
for i in range(len(caughtboard)):
curr = caughtboard[i]
message += f"{i + 1}. {get_display_name(curr[0][2:-1])} - {curr[1]}\n"
Expand All @@ -150,6 +128,16 @@ def caughtboard(event, say, prefix="", db_name=DB_NAME):
def fa21_caughtboard(event, say):
caughtboard(event, say, prefix="fa21-", db_name=DATABASES['fa21'])

@bolt_app.message("sp22-caughtboard")
@bolt_app.message("sp22-Caughtboard")
def sp22_caughtboard(event, say):
caughtboard(event, say, prefix="sp22-", db_name=DATABASES['sp22'])

@bolt_app.message("fa22-caughtboard")
@bolt_app.message("fa22-Caughtboard")
def fa22_caughtboard(event, say):
caughtboard(event, say, prefix="fa22-", db_name=DATABASES['fa22'])

@bolt_app.message("caughtboard")
@bolt_app.message("Caughtboard")
def curr_caughtboard(event, say):
Expand Down Expand Up @@ -177,43 +165,25 @@ def pics(event, say, db_name=DB_NAME):
def fa21_pics(event, say):
pics(event, say, db_name=DATABASES['fa21'])

@bolt_app.message("sp22-pics")
def sp22_pics(event, say):
pics(event, say, db_name=DATABASES['sp22'])

@bolt_app.message("fa22-pics")
def fa22_pics(event, say):
pics(event, say, db_name=DATABASES['fa22'])

# https://slack.dev/bolt-python/concepts
@bolt_app.message("pics")
def curr_pics(event, say):
pics(event, say)


def get_display_name(user):
try:
profile = bolt_app.client.users_profile_get(user=user)['profile']
return profile['display_name'] or profile['real_name']
except:
print("couldn't find: ", user)

@bolt_app.event("file_shared")
@bolt_app.event("message")
def ignore():
pass

# https://stackoverflow.com/questions/21214270/how-to-schedule-a-function-to-run-every-hour-on-flask

# import time
# import atexit
# from apscheduler.schedulers.background import BackgroundScheduler

# scheduler = BackgroundScheduler()
# scheduler.add_job(func=email_db, trigger="interval", seconds=30)

# from flask_apscheduler import APScheduler

# scheduler = APScheduler()
# scheduler.init_app(app)
# scheduler.start()
# scheduler.add_job(func=email_db, trigger="interval", minutes=30, id='0')


if __name__ == '__main__':
# scheduler.start()
# atexit.register(lambda: scheduler.shutdown())
app.run(threaded=True, port=5000)
# bolt_app.start(5000)
80 changes: 4 additions & 76 deletions utils.py
Original file line number Diff line number Diff line change
@@ -1,85 +1,13 @@
import json
import os
import mimetypes
import smtplib, ssl

from email.mime.multipart import MIMEMultipart
from email.message import EmailMessage

import requests

caught, score, spot, images = {}, {}, {}, {}

DATABASES = {
'fa21': 'spottings',
'sp22': 'sp22-spottings'
'sp22': 'sp22-spottings',
'fa22': 'cb-fa22-spottings',
'sp23': 'cb-sp23-spottings'
}

DB_NAME = DATABASES['sp22']

# DB_PATH = "db/"
# DB = {
# "caughtboard.json": caught,
# "scoreboard.json": score,
# "spotboard.json": spot,
# "images.json": images
# }

# def init_db():
# try:
# os.mkdir(DB_PATH[:-1])
# except:
# return
# for disk in DB:
# with open(DB_PATH + disk, 'w') as f:
# json.dump({}, f, indent=4)

# def read_db():
# for disk, memory in DB.items():
# with open(DB_PATH + disk, 'r') as f:
# memory.update(json.load(f))
# return caught, score, spot, images

# def write_db(*args):
# for data, disk in zip(args, DB):
# with open(DB_PATH + disk, 'w') as f:
# json.dump(data, f, indent=4)

# # https://betterprogramming.pub/how-to-send-emails-with-attachments-using-python-dd37c4b6a7fd
# def email_db():
# # port = 465 # For SSL
# port = int(os.environ.get("SMTP_PORT")) # For TLS
# password = os.environ.get("PASSWORD")

# # Create a secure SSL context
# context = ssl.create_default_context()

# with smtplib.SMTP(os.environ.get("SMTP_ADDRESS"), port) as smtp:
# smtp.ehlo()
# smtp.starttls(context=context)
# smtp.ehlo()
# sender = os.environ.get("SENDER_ADDRESS")
# smtp.login(sender, password)

# message = EmailMessage()
# message["Subject"] = "cbspotbot data"
# message["From"] = sender
# message["To"] = os.environ.get("RECEIVER_ADDRESS")

# for filename in DB:
# path = f'{DB_PATH}{filename}'

# # Guess the content type based on the file's extension.
# ctype, encoding = mimetypes.guess_type(path)
# if ctype is None or encoding is not None:
# ctype = 'application/octet-stream'
# maintype, subtype = ctype.split('/', 1)

# with open(path, 'rb') as fp:
# message.add_attachment(fp.read(), maintype=maintype, subtype=subtype,
# filename=filename)
# smtp.send_message(message)

DB_NAME = DATABASES['sp23']

def read_db(client, db_name=DB_NAME):
db = client.get_database(db_name)
Expand Down

0 comments on commit 07a59cf

Please sign in to comment.