def handler_acceptrep(cli, msg):
    if isauthed(str(msg.from_user.id)):
        if len(msg.command) == 2:
            tag = msg.command[1]
            chat = Redis.hget('reportedfrom:global', tag).decode('utf-8')
            user = get_user_name(
                Redis.hget('reportedby:global', tag).decode('utf-8'))
            bot.send_message(chat_id=chat, text=ntf_accepted.format(user, tag))
            rmsnippet(tag, bot_master)
            rmreport(tag)
    else:
        msg.reply('Insufficiant permission')
def handler_addadmin(cli, msg):
    if str(msg.from_user.id) == bot_master:
        if len(msg.command) > 1:
            users = []
            for user in msg.command[1:]:
                Redis.sadd(f'botadmin:{bot_name}', user)

            delmsg(
                msg.reply(f'Done! These users are now privileged:\n{users}'))

    else:
        delmsg(msg.reply('Insufficient permission'))

    delmsg(msg, 0)
def isauthed(user: str, tag: str = '', adminonly: bool = False) -> bool:
    '''
	Determines if the user is able to do something, e.g. to edit a snippet or to delete a snippet.  
	Only the user who created the snippet, bot admins and bot master (see config.py) can do such an operation.

	Params:
	
	- `tag` : the tag needed to be authenticated.
	- `user` : the user who takes the action.
	- `adminonly` : `bool` , if the action is admin only, then set this to True.

	Return:  
	`True` if the user is qualified or
	`False` if the user is not qualified.
	'''
    qualified = [bot_master]
    # Get bot admins
    _ = Redis.smembers(f'botadmin:{bot_name}')
    for a in _:
        qualified.append(a.decode('utf-8'))

    # Get the credit of the tag
    if tag:
        credit = getsnippet(tag)[2]
        qualified.append(credit)

    return user in qualified
def rmreport(tag):
    """
	Remove a recorded report.
	This is not related to tag itself, whether the snippet was deleted or not.
	"""
    Redis.srem('reported:global', tag)
    Redis.hdel('repreason:global', tag)
    Redis.hdel('reportedby:global', tag)
    Redis.hdel('reportedfrom:global', tag)
def iscreatedby(credit: str, tag: str) -> bool:
    """
	Determines if the `tag` is created by user `credit`.
	Just simply calling Redis method.

	Return `True` or `False` .
	"""
    return Redis.hexists(CREATEDBY.format(credit), tag)
def getsnippet(tag: str) -> Snippet:
    """
	Get everything of the given tag, if exists.

	Returns: `list`
	- `[0]` : `str`, command snippet itself.
	- `[1]` : `str`, the description.
	- `[2]` : `str`, the credit.

	Raises: `TagNotFound` if the tag is not exist in the database.
	"""
    if not Redis.sismember(TAGS_GBL, tag):
        raise TagNotFound
    desc = Redis.hget(DESC_GBL, tag).decode('utf-8')
    command = Redis.hget(CMDS_GBL, tag).decode('utf-8')
    credit = Redis.hget(CRDT_GBL, tag).decode('utf-8')
    return (command, desc, credit)
def addreport(tag: str, reason: str, user: str, chat: str) -> None:
    """
	Record a abuse report.
	Will be removed after being processed.
	"""
    if not tagexists(tag):
        raise TagNotFound

    Redis.sadd('reported:global', tag)
    Redis.hset('repreason:global', tag, reason)
    Redis.hset('reportedby:global', tag, user)
    Redis.hset('reportedfrom:global', tag, chat)
def setsnippet(tag: str, desc: str, command: str, credit: str) -> None:
    """
	To add or set a command into the database.
	Params:
	- `tag` : `str` , unique tag of the command
	- `desc` : `str` , description of the command
	- `command` : `str` , the command itself
	- `credit` : `str` , ident of the user who add the command

	Returns: `None`
	"""
    if tagexists(tag):
        raise TagAlreadyExists

    Redis.sadd(TAGS_GBL, tag)
    Redis.hset(CMDS_GBL, tag, command)
    Redis.hset(DESC_GBL, tag, desc)
    Redis.hset(CRDT_GBL, tag, credit)
    Redis.sadd(CREATEDBY.format(credit), tag)
def handler_listadmins(cli, msg):
    if isauthed(str(msg.from_user.id)):
        admins = []
        for i in Redis.smembers(f'botadmin:{bot_name}'):
            admins.append(i.decode('utf-8'))
        delmsg(msg.reply(f'List of bot admins:\n{admins}'), 30)

    else:
        delmsg(msg.reply('Insufficient permission'))
    delmsg(msg, 0)
Beispiel #10
0
def tagsingroup(group: str) -> List[Tags]:
    """
	Get all tags belongs to the group.

	Returns:

	- `['', []]` if the group is not exist, there's a chance that the group was emptied.
	- `[str, list[str]]` the first string is the description of the group, the latter is a list of the tags in the given group.

	Raises: None
	"""
    result = ['', []]
    res = Redis.smembers(f'taggroup:global:{group}')
    if res:
        result[0] = Redis.hget('g_description:global', group)
        for e in res:
            result[1].append(e.decode('utf-8'))

    return result
Beispiel #11
0
def editsnippet(tag: str, edit: str, content: str, user: str) -> None:
    '''
	Edit a snippet. Which to edit depends on the selection.
	
	Params:

	- `tag` : `str` , the tag to edit.
	- `edit` : `str` - `desc` or `snippet` , to choose what to edit.
	- `content` : `str` , the content to be replaced.
	- `user` : `str` , the user who takes action.
	'''
    if not tagexists:
        raise TagNotFound
    if not isauthed(user, tag=tag):
        raise TagNotOwned

    if edit == 'desc':
        Redis.hset(DESC_GBL, tag, content)
    elif edit == 'snippet':
        Redis.hset(CMDS_GBL, tag, content)
    else:
        raise Exception(err_invalid_edit)
Beispiel #12
0
def handler_reportsnippet(cli, msg):
    if len(msg.command) > 2:
        lines = msg.text.split('\n')
        if len(lines) > 1:
            try:
                tag = msg.command[1]
                reason = '\n'.join(lines[1:])
                user = str(msg.from_user.id)
                chat = str(msg.chat.id)
                addreport(tag=tag, reason=reason, user=user, chat=chat)
                Redis.hset('username', user, msg.from_user.first_name)
                sendmaster(
                    f'New Report: \nTag: {getsnippet_f(tag)}\nReported by {get_user_name(user)}\nReason: {reason}'
                )
                delmsg(msg.reply(ntf_ticket_sent))
            except Exception as e:
                delmsg(msg.reply(e))
                return
        else:
            delmsg(msg.reply(help_text_report))
    else:
        delmsg(msg.reply(help_text_report))
    delmsg(msg, 0)
Beispiel #13
0
def handler_addsnippet(cli: Client, msg: Message) -> None:
    if len(msg.command) > 2:
        lines = msg.text.split('\n')
        if len(lines) >= 3:
            try:
                tag = msg.command[1]
                desc = lines[1]
                commands = '\n'.join(lines[2:])
                credit = str(msg.from_user.id)
                setsnippet(tag, desc, commands, credit)
                Redis.hset('username', credit, msg.from_user.first_name)
                delmsg(
                    msg.reply(
                        f'Done, the snippet was successfully added:\n{getsnippet_f(tag)}'
                    ), 30)
                sendmaster(f'New Tag:\n{getsnippet_f(tag)}')
            except Exception as e:
                delmsg(msg.reply(e))
                return
        else:
            delmsg(msg.reply(help_text_addsnipppet))
    else:
        delmsg(msg.reply(help_text_addsnipppet))
    delmsg(msg, 0)
Beispiel #14
0
def listtags(query: str, count: int = 10) -> List[str]:
    """
	List all tags matches the pattern.

	Returns:

	- `[]` if no tags was found
	- `list[str]` the list of the tags matched the query pattern

	Raises: None
	"""
    result = []
    res = Redis.sscan('tags:global', match=f'*{query}*')[1]
    if res:
        for e in res:
            result.append(e.decode('utf-8'))

    return result
Beispiel #15
0
def listgrps(query: str, count: int = 20) -> List[str]:
    """
	List all tags matches the pattern.
	Params:

	- `query`: `str` , query string
	- `count`: `str` , counts of the given results.

	Returns:

	- `[]` if no tags was found
	- `list[str]` the list of the groups matched the query pattern

	Raises: None
	"""
    result = []
    res = Redis.sscan('taggroups:global', match=f'*{query}*', count=count)[1]
    if res[1]:
        for e in res[1]:
            result.append(e.decode('utf-8'))

    return res
Beispiel #16
0
def put_user_name(ident: str, name: str) -> str:
    Redis.hset('username', ident, name)
Beispiel #17
0
def grouplength(group):
    return Redis.scard(f'taggroups:global:{group}')
Beispiel #18
0
def rmsnippet(tag: str, user: str) -> None:
    """
	To remove a command into the database.
	Params:
	- `tag` : `str` , unique tag of the command to be removed
	- `user` : `str` , the user who takes the action, for verification use.

	Returns: `None`
	Raises:
	
	- `TagNotFound` if tag is not found.
	- `TagNotOwned` if tag is not owned by the user.
	"""
    if not tagexists(tag):
        raise TagNotFound

    if not isauthed(user, tag):
        raise TagNotOwned

    credit = Redis.hget(CRDT_GBL, tag).decode('utf-8')
    Redis.srem(TAGS_GBL, tag)
    Redis.hdel(CMDS_GBL, tag)
    Redis.hdel(DESC_GBL, tag)
    Redis.srem(CREATEDBY.format(credit), tag)
    Redis.hdel(CRDT_GBL, tag)
Beispiel #19
0
def get_user_name(ident: str) -> str:
    return Redis.hget('username', ident).decode('utf-8')
Beispiel #20
0
def tagexists(tag: str) -> bool:
    return Redis.sismember(TAGS_GBL, tag)