Skip to content

Commit

Permalink
Merge pull request CloudBotIRC#218 from linuxdaemon/gonzobot+tellinpu…
Browse files Browse the repository at this point in the history
…t-actions

Refactor tell plugin
  • Loading branch information
linuxdaemon authored Jan 22, 2019
2 parents 2f561f2 + 0db26a3 commit a5da089
Showing 1 changed file with 144 additions and 5 deletions.
149 changes: 144 additions & 5 deletions plugins/tell.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import asyncio
from collections import defaultdict
from datetime import datetime

from sqlalchemy import Table, Column, String, Boolean, DateTime
from sqlalchemy import Table, Column, String, Boolean, DateTime, PrimaryKeyConstraint
from sqlalchemy.sql import select

from cloudbot import hook
from cloudbot.event import EventType
from cloudbot.util import timeformat, database
from cloudbot.util import timeformat, database, web
from cloudbot.util.formatting import gen_markdown_table

table = Table(
'tells',
Expand All @@ -19,6 +22,18 @@
Column('time_read', DateTime)
)

ignore_table = Table(
'tell_ignores',
database.metadata,
Column('conn', String),
Column('target', String),
Column('setter', String),
Column('set_at', DateTime),
PrimaryKeyConstraint('conn', 'target'),
)

ignore_cache = defaultdict(set)


@hook.on_start
def load_cache(db):
Expand All @@ -33,7 +48,70 @@ def load_cache(db):
tell_cache.append((conn, target))


@hook.on_start
def load_ignores(db):
"""
:type db: sqlalchemy.orm.Session
"""
ignore_cache.clear()
for row in db.execute(ignore_table.select()):
ignore_cache[row['conn']].add(row['target'].lower())


def is_ignored(conn, target):
"""
:type conn: cloudbot.client.Client
:type target: str
:rtype: bool
"""
return target.lower() in ignore_cache[conn.name.lower()]


def add_ignore(db, conn, setter, target, now=None):
"""
:type db: sqlalchemy.orm.Session
:type conn: cloudbot.client.Client
:type setter: str
:type target: str
:type now: datetime
"""
if now is None:
now = datetime.now()

db.execute(ignore_table.insert().values(conn=conn.name.lower(), setter=setter, set_at=now, target=target.lower()))
db.commit()
load_ignores(db)


def del_ignore(db, conn, target):
"""
:type db: sqlalchemy.orm.Session
:type conn: cloudbot.client.Client
:type target: str
"""
db.execute(
ignore_table.delete().where(ignore_table.c.conn == conn.name.lower())
.where(ignore_table.c.target == target.lower())
)
db.commit()
load_ignores(db)


def list_ignores(db, conn):
"""
:type db: sqlalchemy.orm.Session
:type conn: cloudbot.client.Client
"""
for row in db.execute(ignore_table.select().where(ignore_table.c.conn == conn.name.lower())):
yield (row['conn'], row['target'], row['setter'], row['set_at'].ctime())


def get_unread(db, server, target):
"""
:type db: sqlalchemy.orm.Session
:type server: str
:type target: str
"""
query = select([table.c.sender, table.c.message, table.c.time_sent]) \
.where(table.c.connection == server.lower()) \
.where(table.c.target == target.lower()) \
Expand Down Expand Up @@ -94,7 +172,7 @@ def tell_check(conn, nick):
return True


@hook.event(EventType.message, singlethread=True)
@hook.event([EventType.message, EventType.action], singlethread=True)
def tellinput(event, conn, db, nick, notice):
"""
:type event: cloudbot.event.Event
Expand Down Expand Up @@ -148,8 +226,7 @@ def showtells(nick, notice, db, conn):
def tell_cmd(text, nick, db, notice, conn, notice_doc, is_nick_valid):
"""<nick> <message> - Relay <message> to <nick> when <nick> is around."""
query = text.split(' ', 1)
if query[0].lower() == "paradox":
return "Paradox doesn't want to hear from me. Just send him a fucking message."

if len(query) != 2:
notice_doc()
return
Expand All @@ -158,6 +235,10 @@ def tell_cmd(text, nick, db, notice, conn, notice_doc, is_nick_valid):
message = query[1].strip()
sender = nick

if is_ignored(conn, target):
notice("You may not send a tell to that user.")
return

if target.lower() == sender.lower():
notice("Have you looked in a mirror lately?")
return
Expand All @@ -172,3 +253,61 @@ def tell_cmd(text, nick, db, notice, conn, notice_doc, is_nick_valid):

add_tell(db, conn.name, sender, target.lower(), message)
notice("Your message has been saved, and {} will be notified once they are active.".format(target))


def check_permissions(event, *perms):
return any(event.has_permission(perm) for perm in perms)


@hook.command("tellignore", autohelp=False)
def tell_ignore(conn, db, text, nick, event):
"""[nick] - Disallow tells being sent to [nick]"""
is_self = False
if not text or text.casefold() == nick.casefold():
text = nick
is_self = True
elif not check_permissions(event, 'botcontrol', 'ignore'):
event.notice("Sorry, you are not allowed to use this command.")
return None

target = text.split()[0]
if is_ignored(conn, target):
return "{} already on the tell ignore list and will not receive tells.".format(
"You are" if is_self else "{!r} is".format(target)
)

add_ignore(db, conn, nick, target)
return "{} now on the tell ignore list and will no longer receive tells.".format(
"You are" if is_self else "{!r} is".format(target)
)


@hook.command("tellunignore", autohelp=False)
def tell_unignore(conn, db, text, event, nick):
"""[nick] - Removes [nick] from the tellignore list"""
is_self = False
if not text or text.casefold() == nick.casefold():
text = nick
is_self = True
elif not check_permissions(event, 'botcontrol', 'ignore'):
event.notice("Sorry, you are not allowed to use this command.")
return None

target = text.split()[0]
if not is_ignored(conn, target):
return "{} already not on the tell ignore list and will receive tells.".format(
"You are" if is_self else "{!r} is".format(target)
)

del_ignore(db, conn, target)
return "{} now no longer on the tell ignore list and will receive tells.".format(
"You are" if is_self else "{!r} is".format(target)
)


@hook.command("listtellignores", permissions=["botcontrol", "ignore"])
def tell_list_ignores(conn, db):
"""- Returns the current list of people who are not able to recieve tells"""
ignores = list(list_ignores(db, conn))
md = gen_markdown_table(["Connection", "Target", "Setter", "Set At"], ignores)
return web.paste(md, 'md', 'hastebin')

0 comments on commit a5da089

Please sign in to comment.