Added redis cache and user registration system

This commit is contained in:
Benjamyn Love 2023-10-15 18:54:25 +11:00
parent 391687bc15
commit 4efb02784c
6 changed files with 135 additions and 8 deletions

View File

@ -10,6 +10,7 @@ aiomysql = "*"
uvicorn = "*" uvicorn = "*"
gunicorn = "*" gunicorn = "*"
flask = "*" flask = "*"
redis = "*"
[dev-packages] [dev-packages]

11
Pipfile.lock generated
View File

@ -1,7 +1,7 @@
{ {
"_meta": { "_meta": {
"hash": { "hash": {
"sha256": "c15a725d7a97c336acc3f1198bfbdd80a2360883990bd018c6482960d2606860" "sha256": "c5a98719dfb37b2da391fbbb06f7dce1c8be9b79d9b4be7b4b365ac786e53ecb"
}, },
"pipfile-spec": 6, "pipfile-spec": 6,
"requires": { "requires": {
@ -534,6 +534,15 @@
"markers": "python_version >= '3.7'", "markers": "python_version >= '3.7'",
"version": "==1.1.0" "version": "==1.1.0"
}, },
"redis": {
"hashes": [
"sha256:0dab495cd5753069d3bc650a0dde8a8f9edde16fc5691b689a566eda58100d0f",
"sha256:ed4802971884ae19d640775ba3b03aa2e7bd5e8fb8dfaed2decce4d0fc48391f"
],
"index": "pypi",
"markers": "python_version >= '3.7'",
"version": "==5.0.1"
},
"slack-bolt": { "slack-bolt": {
"hashes": [ "hashes": [
"sha256:43b121acf78440303ce5129e53be36bdfe5d926a193daef7daf2860688e65dd3", "sha256:43b121acf78440303ce5129e53be36bdfe5d926a193daef7daf2860688e65dd3",

1
libs/http/__init__.py Normal file
View File

@ -0,0 +1 @@
from . import users

31
libs/http/users.py Normal file
View File

@ -0,0 +1,31 @@
import aiohttp
class UserRequests:
def __init__(self, API_URL, BOT_TOKEN):
self.API_URL = API_URL
self.headers = {"Content-Type": "application/json", "X-BOTAUTH": BOT_TOKEN}
async def getUser(self, user_id):
async with aiohttp.ClientSession(self.API_URL, headers=self.headers) as session:
# Make sure we have a good connection
async with session.head("/") as alive:
if alive.status != 200:
return None
async with session.get(f"/api/user/{user_id}") as data:
response = await data.json()
return response
async def registerUser(self, user_data: dict):
async with aiohttp.ClientSession(self.API_URL, headers=self.headers) as session:
# Make sure we have a good connection
async with session.head("/") as alive:
if alive.status != 200:
return None
async with session.post("/api/user/register", json=user_data) as data:
if data.status != 200:
return False
response = await data.json()
return response

View File

@ -8,11 +8,16 @@ from slack_bolt.async_app import AsyncApp
from slack_bolt.adapter.asgi.async_handler import AsyncSlackRequestHandler from slack_bolt.adapter.asgi.async_handler import AsyncSlackRequestHandler
import libs.block_utils as block_utils import libs.block_utils as block_utils
import libs.benv import libs.benv
from libs import http
import redis.asyncio as redis
libs.benv.load_env() libs.benv.load_env()
logging.basicConfig(level=logging.DEBUG) logging.basicConfig(level=logging.DEBUG)
redis_client = redis.Redis()
user_manager = http.users.UserRequests(environ["API_URL"], environ["API_BOT_TOKEN"])
# Dataset for automatic reactions, the lower the chance the more often it triggers # Dataset for automatic reactions, the lower the chance the more often it triggers
auto_react_lookup = { auto_react_lookup = {
@ -20,18 +25,56 @@ auto_react_lookup = {
"U05ES1730UE": {"text": "clown_face", "chance": 3}, # mprice "U05ES1730UE": {"text": "clown_face", "chance": 3}, # mprice
"U05FN1F9ZCG": {"text": "frannodders", "chance": 4}, # blove "U05FN1F9ZCG": {"text": "frannodders", "chance": 4}, # blove
"U05EY6DQR9R": {"text": "kekw", "chance": 4}, # jfox "U05EY6DQR9R": {"text": "kekw", "chance": 4}, # jfox
"U05ERL26A3G": {"text": "jacoborg", "chance": 3},# jborg "U05ERL26A3G": {"text": "jacoborg", "chance": 3}, # jborg
"U05F0NWDH9S": {"text": "usb-c", "chance": 3}, #jjennings "U05F0NWDH9S": {"text": "usb-c", "chance": 3}, # jjennings
} }
app = AsyncApp(token=environ.get("SLACK_BOT_TOKEN"), signing_secret=environ.get('SLACK_SIGNING_SECRET')) app = AsyncApp(
token=environ.get("SLACK_BOT_TOKEN"),
signing_secret=environ.get("SLACK_SIGNING_SECRET"),
)
api = AsyncSlackRequestHandler(app) api = AsyncSlackRequestHandler(app)
messages_already_reacted = {} messages_already_reacted = {}
async def check_user_registration(user_id: str, client) -> bool:
r = await redis.from_url("redis://localhost")
async with r.pipeline(transaction=True) as pipe:
user_exists = await pipe.get(user_id).execute()
if user_exists[0] is None:
if check_user_exists() is True:
await pipe.set(user_id, 1)
return True
else:
user_created = await register_user(user_id, client)
if user_created is True:
await pipe.set(user_id, 1)
return user_created
else:
return True
async def check_user_exists(user_id: str):
response = await user_manager.getUser(user_id)
return response["status"]
async def register_user(user_id: str, client):
# lookup the user_id to get account info
user_info = await client.users_info(user=user_id)
new_user_data = {
"firstname": user_info["user"]["real_name"].split()[0],
"lastname": user_info["user"]["real_name"].split()[1],
"email": user_info["user"]["profile"]["email"],
"uuid": user_info["user"]["id"],
"profile": user_info["user"]["profile"]["image_512"],
}
response = await user_manager.registerUser(new_user_data)
return response["status"]
@app.event("reaction_added") @app.event("reaction_added")
async def reaction_add(body, logger, ack, say, client): async def reaction_add(body, logger, ack, say, client):
await ack() await ack()
@ -45,6 +88,8 @@ async def reaction_add(body, logger, ack, say, client):
reactions = await client.reactions_get( reactions = await client.reactions_get(
channel=event["item"]["channel"], timestamp=event["item"]["ts"] channel=event["item"]["channel"], timestamp=event["item"]["ts"]
) )
# for reaction in reactions.data["message"]["reactions"]: # for reaction in reactions.data["message"]["reactions"]:
# if reaction["name"] == "clown_face": # if reaction["name"] == "clown_face":
# if ( # if (
@ -63,14 +108,17 @@ async def reaction_del(body, logger, ack):
await ack() await ack()
@app.event(event="message") @app.event(event="message")
async def handle_message_events(body, say, ack, logger, client, message, response): async def handle_message_events(body, say, ack, logger, client, message, response):
# logger.info(body) # logger.info(body)
pprint(body) pprint(body)
event = body.get("event", {}) event = body.get("event", {})
channel_id = event.get("channel") channel_id = event.get("channel")
user_id = event.get("user") user_id = event.get("user")
await ack()
await check_user_registration(user_id, client)
# Check user is the milk man and then add a milk react # Check user is the milk man and then add a milk react
if user_id in auto_react_lookup.keys(): if user_id in auto_react_lookup.keys():
rand_num = random.randrange(0, 6) rand_num = random.randrange(0, 6)
@ -87,6 +135,7 @@ async def handle_message_events(body, say, ack, logger, client, message, respons
await say("hi") await say("hi")
pprint(environ) pprint(environ)
# if text == "!milk": # if text == "!milk":
# await ack() # await ack()
# members = await client.conversations_members(channel=channel_id) # members = await client.conversations_members(channel=channel_id)
@ -95,8 +144,8 @@ async def handle_message_events(body, say, ack, logger, client, message, respons
# await client.reactions_add( # await client.reactions_add(
# channel=channel_id, name="glass_of_milk", timestamp=message["ts"] # channel=channel_id, name="glass_of_milk", timestamp=message["ts"]
# ) # )
# pprint(member_data.data) # pprint(member_data.data)
# await say("test") # await say("test")
# if text == "vader": # if text == "vader":
# await ack() # await ack()
# blocks = await block_utils.image_block( # blocks = await block_utils.image_block(

36
testing_libs.py Normal file
View File

@ -0,0 +1,36 @@
from libs import http
import asyncio
user_requester = http.users.UserRequests(
"https://priceybot.au", "jkcGd6r6zJrd05RnKnU3pWm7xlo6enBj"
)
async def getUser(user_id):
data = await user_requester.getUser(user_id)
print(data)
async def registerUser(user_data):
response = await user_requester.registerUser(user_data)
print(response)
loop = asyncio.get_event_loop()
data = {
"firstname": "Test2",
"lastname": "User2",
"email": "test@benjamyn.love2",
"uuid": "U1111112",
"profile": "https://benjamyn.love/PriceyBot.png",
}
tasks = [
loop.create_task(getUser("U05FN1F9ZCG")),
loop.create_task(registerUser(data)),
]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()