Update slackbot.py

This commit is contained in:
Benjamyn Love 2023-10-29 20:05:49 -04:00
parent df091d80ca
commit 62351658f8

View File

@ -1,200 +1,201 @@
import logging import logging
import asyncio import asyncio
import aiomysql import aiomysql
import random import random
from os import environ from os import environ
from pprint import pprint from pprint import pprint
from slack_bolt.async_app import AsyncApp 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 from libs import http
import redis.asyncio as redis import redis.asyncio as redis
libs.benv.load_env() libs.benv.load_env()
logging.basicConfig(level=logging.INFO) logging.basicConfig(level=logging.INFO)
redis_client = redis.Redis() redis_client = redis.Redis()
user_manager = http.users.UserRequests(environ["API_URL"], environ["API_BOT_TOKEN"]) 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 = {
"U02GTCPB2CB": {"text": "glass_of_milk", "chance": -1}, # agoodlet "U02GTCPB2CB": {"text": "glass_of_milk", "chance": -1}, # agoodlet
"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
} "U05ERL0PSBY": {"text": "gif", "chance": 3} # mginger
}
app = AsyncApp(
token=environ.get("SLACK_BOT_TOKEN"), app = AsyncApp(
signing_secret=environ.get("SLACK_SIGNING_SECRET"), 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 def check_user_registration(user_id: str, client) -> bool:
async with r.pipeline(transaction=True) as pipe: r = await redis.from_url("redis://localhost")
user_exists = await pipe.get(user_id).execute() async with r.pipeline(transaction=True) as pipe:
if user_exists[0] is None: user_exists = await pipe.get(user_id).execute()
if await check_user_exists(user_id) is True: if user_exists[0] is None:
await pipe.set(user_id, 1) if await check_user_exists(user_id) is True:
return True await pipe.set(user_id, 1)
else: return True
user_created = await register_user(user_id, client) else:
if user_created is True: user_created = await register_user(user_id, client)
await pipe.set(user_id, 1).execute() if user_created is True:
return user_created await pipe.set(user_id, 1).execute()
else: return user_created
return True else:
return True
async def check_user_exists(user_id: str):
response = await user_manager.getUser(user_id) async def check_user_exists(user_id: str):
return response["status"] 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 async def register_user(user_id: str, client):
user_info = await client.users_info(user=user_id) # lookup the user_id to get account info
new_user_data = { user_info = await client.users_info(user=user_id)
"firstname": user_info["user"]["profile"]["first_name"], new_user_data = {
"lastname": user_info["user"]["profile"]["last_name"], "firstname": user_info["user"]["profile"]["first_name"],
"email": f"{user_info['user']['profile']['display_name_normalized']}@nexigen.digital", "lastname": user_info["user"]["profile"]["last_name"],
"uuid": user_info["user"]["id"], "email": f"{user_info['user']['profile']['display_name_normalized']}@nexigen.digital",
"profile": user_info["user"]["profile"]["image_512"], "uuid": user_info["user"]["id"],
} "profile": user_info["user"]["profile"]["image_512"],
response = await user_manager.registerUser(new_user_data) }
return response["status"] response = await user_manager.registerUser(new_user_data)
return response["status"]
@app.event("reaction_added")
async def reaction_add(body, logger, ack, say, client): @app.event("reaction_added")
await ack() async def reaction_add(body, logger, ack, say, client):
event = body.get("event") await ack()
user = event.get("item_user") event = body.get("event")
channel_id = event.get("channel") user = event.get("item_user")
reaction = event.get("reaction") channel_id = event.get("channel")
if ( reaction = event.get("reaction")
user == "U05ES1730UE" and event["reaction"] == "clown_face" if (
): # If pricey gets clown reacted user == "U05ES1730UE" and event["reaction"] == "clown_face"
reactions = await client.reactions_get( ): # If pricey gets clown reacted
channel=event["item"]["channel"], timestamp=event["item"]["ts"] 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": # for reaction in reactions.data["message"]["reactions"]:
# if ( # if reaction["name"] == "clown_face":
# int(reaction["count"]) >= 3 # if (
# and messages_already_reacted.get(event["item"]["ts"], False) # int(reaction["count"]) >= 3
# is False # and messages_already_reacted.get(event["item"]["ts"], False)
# ): # is False
# messages_already_reacted[event["item"]["ts"]] = True # ):
# await say( # messages_already_reacted[event["item"]["ts"]] = True
# f"Pricey has been clown reacted {reaction['count']} times on a recent post" # await say(
# ) # f"Pricey has been clown reacted {reaction['count']} times on a recent post"
# )
@app.event("reaction_removed")
async def reaction_del(body, logger, ack): @app.event("reaction_removed")
await ack() 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): @app.event(event="message")
# logger.info(body) async def handle_message_events(body, say, ack, logger, client, message, response):
# logger.info(body)
pprint(body)
event = body.get("event", {}) pprint(body)
channel_id = event.get("channel") event = body.get("event", {})
user_id = event.get("user") channel_id = event.get("channel")
await ack() user_id = event.get("user")
await check_user_registration(user_id, client) 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(): # Check user is the milk man and then add a milk react
rand_num = random.randrange(0, 6) if user_id in auto_react_lookup.keys():
print(rand_num) rand_num = random.randrange(0, 6)
if rand_num > auto_react_lookup[user_id]["chance"]: print(rand_num)
await client.reactions_add( if rand_num > auto_react_lookup[user_id]["chance"]:
channel=channel_id, await client.reactions_add(
name=auto_react_lookup[user_id]["text"], channel=channel_id,
timestamp=message["ts"], name=auto_react_lookup[user_id]["text"],
) timestamp=message["ts"],
)
text = event.get("text")
if text == "x": text = event.get("text")
await say("hi") if text == "x":
pprint(environ) await say("hi")
pprint(environ)
# if text == "!milk":
# await ack() # if text == "!milk":
# members = await client.conversations_members(channel=channel_id) # await ack()
# members = members["members"] # members = await client.conversations_members(channel=channel_id)
# member_data = await client.users_info(user=members[0]) # members = members["members"]
# await client.reactions_add( # member_data = await client.users_info(user=members[0])
# channel=channel_id, name="glass_of_milk", timestamp=message["ts"] # await client.reactions_add(
# ) # channel=channel_id, name="glass_of_milk", timestamp=message["ts"]
# pprint(member_data.data) # )
# await say("test") # pprint(member_data.data)
# if text == "vader": # await say("test")
# await ack() # if text == "vader":
# blocks = await block_utils.image_block( # await ack()
# "https://benjamyn.love/vader.gif", "I fixed it mother bitch" # blocks = await block_utils.image_block(
# ) # "https://benjamyn.love/vader.gif", "I fixed it mother bitch"
# await say(blocks=blocks) # )
# await say(blocks=blocks)
# if text == "test image action":
# await ack() # if text == "test image action":
# blocks = await block_utils.image_block( # await ack()
# "https://benjamyn.love/topright.png", "Top right buddy" # blocks = await block_utils.image_block(
# ) # "https://benjamyn.love/topright.png", "Top right buddy"
# await say(blocks=blocks) # )
# await say(blocks=blocks)
# if text == "gimmie":
# pool = await aiomysql.create_pool( # if text == "gimmie":
# host=environ.get("MYSQL_HOST"), # pool = await aiomysql.create_pool(
# port=int(environ.get("MYSQL_PORT")), # host=environ.get("MYSQL_HOST"),
# user=environ.get("MYSQL_USER"), # port=int(environ.get("MYSQL_PORT")),
# password=environ.get("MYSQL_PASS"), # user=environ.get("MYSQL_USER"),
# db=environ.get("MYSQL_DB"), # password=environ.get("MYSQL_PASS"),
# loop=asyncio.get_event_loop(), # db=environ.get("MYSQL_DB"),
# ) # loop=asyncio.get_event_loop(),
# )
# async with pool.acquire() as conn:
# async with conn.cursor() as cur: # async with pool.acquire() as conn:
# await cur.execute( # async with conn.cursor() as cur:
# "select quote from tblQuotes order by rand() limit 1;" # await cur.execute(
# ) # "select quote from tblQuotes order by rand() limit 1;"
# (r,) = await cur.fetchone() # )
# await say(text=r.decode()) # (r,) = await cur.fetchone()
# pool.close() # await say(text=r.decode())
# await pool.wait_closed() # pool.close()
# await ack() # await pool.wait_closed()
# await ack()
@app.command(command="/socialcredit")
async def handle_social_credit(body, client, say, logger, ack): @app.command(command="/socialcredit")
await ack() async def handle_social_credit(body, client, say, logger, ack):
user_id = body.get("user_id") await ack()
await say(f"This feature is under development") user_id = body.get("user_id")
await say(f"This feature is under development")
@app.command(command="/test")
async def handle_test_command(body, say, ack, respond, context, logger): @app.command(command="/test")
logger.info(body) async def handle_test_command(body, say, ack, respond, context, logger):
await ack() logger.info(body)
await say("Responding to slash commands") await ack()
await say("Responding to slash commands")
if __name__ == "__main__":
app.start(5000) if __name__ == "__main__":
app.start(5000)