Merge pull request 'redis-support' (#2) from redis-support into main

Reviewed-on: #2
This commit is contained in:
Benjamyn Love 2023-10-15 04:45:30 -04:00
commit 18ac61e210
6 changed files with 134 additions and 9 deletions

View File

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

11
Pipfile.lock generated
View File

@ -1,7 +1,7 @@
{
"_meta": {
"hash": {
"sha256": "c15a725d7a97c336acc3f1198bfbdd80a2360883990bd018c6482960d2606860"
"sha256": "c5a98719dfb37b2da391fbbb06f7dce1c8be9b79d9b4be7b4b365ac786e53ecb"
},
"pipfile-spec": 6,
"requires": {
@ -534,6 +534,15 @@
"markers": "python_version >= '3.7'",
"version": "==1.1.0"
},
"redis": {
"hashes": [
"sha256:0dab495cd5753069d3bc650a0dde8a8f9edde16fc5691b689a566eda58100d0f",
"sha256:ed4802971884ae19d640775ba3b03aa2e7bd5e8fb8dfaed2decce4d0fc48391f"
],
"index": "pypi",
"markers": "python_version >= '3.7'",
"version": "==5.0.1"
},
"slack-bolt": {
"hashes": [
"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 {"status": 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
import libs.block_utils as block_utils
import libs.benv
from libs import http
import redis.asyncio as redis
libs.benv.load_env()
logging.basicConfig(level=logging.DEBUG)
logging.basicConfig(level=logging.INFO)
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
auto_react_lookup = {
@ -24,14 +29,52 @@ auto_react_lookup = {
"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)
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(user_id) 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"]["profile"]["first_name"],
"lastname": user_info["user"]["profile"]["last_name"],
"email": f"{user_info['user']['profile']['display_name_normalized']}@nexigen.digital",
"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")
async def reaction_add(body, logger, ack, say, client):
await ack()
@ -45,6 +88,8 @@ async def reaction_add(body, logger, ack, say, client):
reactions = await client.reactions_get(
channel=event["item"]["channel"], timestamp=event["item"]["ts"]
)
# for reaction in reactions.data["message"]["reactions"]:
# if reaction["name"] == "clown_face":
# if (
@ -63,14 +108,17 @@ async def reaction_del(body, logger, ack):
await ack()
@app.event(event="message")
async def handle_message_events(body, say, ack, logger, client, message, response):
# logger.info(body)
pprint(body)
event = body.get("event", {})
channel_id = event.get("channel")
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
if user_id in auto_react_lookup.keys():
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")
pprint(environ)
# if text == "!milk":
# await ack()
# members = await client.conversations_members(channel=channel_id)

34
testing_libs.py Normal file
View File

@ -0,0 +1,34 @@
from libs import http
import asyncio
user_requester = http.users.UserRequests("https://priceybot.au", "API_KEY")
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()