Advertisement
ADevingFre

Untitled

Aug 13th, 2022 (edited)
1,107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.33 KB | Source Code | 0 0
  1. from CONSTANTS import * # Seperate File
  2. from re import compile
  3. import psycopg2 # used for the database
  4. import discord
  5.  
  6. words = "|".join(SWEAR_WORDS)
  7. bad_words = compile(fr"(?P<words>{words})")
  8. mention = compile(r"<@(?P<id>\d+)>|(?P<name>.+)#(?P<discrim>\d{4})")
  9.  
  10. TABLE = "full_user_to_word_count"
  11. conn = psycopg2.connect(DATABASE_URL)
  12.  
  13. intents = discord.Intents.default()
  14. intents.members = True  # Needed to get the id of a user with only the username and discriminator
  15. client = discord.Client(intents=intents)
  16.  
  17.  
  18. def setup():
  19.     # This is a heavy command that updates the database to use added words in SWEAR_WORDS
  20.     with conn.cursor() as cur:
  21.         for word in SWEAR_WORDS:    
  22.             if not word.strip():
  23.                 continue
  24.             cur.execute(f'ALTER TABLE {TABLE} ADD COLUMN IF NOT EXISTS {word} INTEGER DEFAULT 0;')
  25.         conn.commit()
  26.  
  27.  
  28. def update_or_write(id, word):
  29.     id = str(id)
  30.     with conn.cursor() as cur:
  31.         cur.execute(f"SELECT {word} FROM {TABLE} WHERE id=%(id)s;", {"id": id})
  32.         try:
  33.             res = cur.fetchall()[0][0] or 0
  34.         except IndexError:
  35.             res = 0
  36.         cur.execute(f"INSERT INTO {TABLE} (id) SELECT %(id)s WHERE NOT EXISTS (SELECT 1 FROM {TABLE} WHERE id=%(id)s);", {"id": id})
  37.         cur.execute(f"UPDATE {TABLE} SET {word}={res+1} WHERE id=%(id)s;", {"id": id})
  38.         conn.commit()
  39.  
  40.  
  41. async def get_from_id(id, username=None):
  42.     if username is None:    # username is used to address the user in the return msg (aesthetic)
  43.         user = await client.fetch_user(id)
  44.         username = user.display_name
  45.        
  46.     with conn.cursor() as cur:
  47.         cur.execute(f"SELECT * FROM {TABLE} WHERE id=%(id)s", {"id": str(id)})
  48.         try:
  49.             res = cur.fetchall()[0]
  50.         except IndexError:
  51.             res = cur.fetchall()
  52.  
  53.     msg = f"Profanity Count of **{username}**:\n"
  54.     x = "\n".join(f"**{SWEAR_WORDS[i].title()}**: \t{count}" for i, count in enumerate(res[1:]) if count)
  55.     if not x:
  56.         return f"Wow, I have never detected **{username}** swearing!"
  57.     msg += x + "\n"
  58.     rows = len([i for i in res if i]) - 2
  59.     if rows < 3:
  60.         msg += f"*Wow, **{username}** must be a great person!*"
  61.     elif rows < 7:
  62.         msg += "*About average I would say*"
  63.     elif rows < 10:
  64.         msg += "*Ok getting out of hand now*"
  65.     elif rows < 15:
  66.         msg += "*DUDE STOP THIS ISNT A COD LOBBY*"
  67.     else:
  68.         msg += "*I have no words*"
  69.     return msg
  70.  
  71.  
  72. async def get_from_username(username, discriminator):
  73.     response = discord.utils.get(client.get_all_members(), name=username, discriminator=discriminator)
  74.     if response is None:
  75.         return f"I don't know **{username}** :("
  76.     return await get_from_id(response.id)
  77.  
  78.  
  79. @client.event
  80. async def on_ready():
  81.     print("Started!")
  82.     if input("Set Up? "):
  83.         setup()
  84.         print("Set Up!")
  85.  
  86.  
  87. @client.event
  88. async def on_message(message):
  89.     txt: str = message.content
  90.     send = message.channel.send
  91.     auth: discord.member.Member = message.author
  92.  
  93.     for word in bad_words.findall(f"{txt}"):
  94.         update_or_write(auth.id, word)
  95.  
  96.     if not txt.startswith("s!") or auth == client.user:
  97.         return
  98.  
  99.     txt = txt.lstrip("s!").lstrip()
  100.     command = ""
  101.     for i in txt:
  102.         if i in " \t\r":
  103.             break
  104.         command = f"{command}{i}"
  105.     txt = txt.removeprefix(command).strip()
  106.  
  107.     match command:
  108.         case "get_from_user":
  109.             m = mention.fullmatch(txt)
  110.             if m is not None:
  111.                 id = m['id']
  112.                 name = m['name']
  113.                 discrim = m['discrim']
  114.                 print(id, name, discrim)
  115.                 if id is not None:
  116.                     await send(await get_from_id(id))
  117.                 elif None in [name, discrim]:
  118.                     await send("Invalid Name!")
  119.                 else:
  120.                     await send(await get_from_username(name, discrim))
  121.             elif txt in SELF_REFERENCE:
  122.                 await send(await get_from_id(auth.id, username="you"))
  123.             else:
  124.                 await send("Invalid User!")
  125.         case "help":
  126.             await send("1. **s! get_from_user [username#0000/userid]**: Get Profanity Count of a user")
  127.         case _:
  128.             await send(f"Command not recognized: {command}")
  129.  
  130.  
  131. client.run(TOKEN)
  132.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement