예제 #1
0
파일: awdbot.py 프로젝트: yukixz/cqbot
def command(message):
    # Restrict to admin
    if message.qq not in ADMIN:
        return
    # Parse message
    try:
        texts = message.text.split()
        cmd = texts[0]
        qq = texts[1]
        idx = texts[2:]
    except:
        return
    if cmd != '/awd':
        return

    match = CQAt.PATTERN.fullmatch(qq)
    if match and match.group(1):
        qq = match.group(1)
    try:
        idx = list(map(lambda x: int(x), idx))
    except:
        idx = []
    if len(idx) == 0:
        idx = [0]

    items = list(filter(lambda x: x.qq == qq, messages))
    items.reverse()
    for i in idx:
        try:
            item = items[i]
        except:
            continue
        reply(qqbot, message, "[awd] {qq} #{i}\n{text}".format(
                i=i, qq=CQAt(item.qq), text=item.text))
예제 #2
0
def invoke(update, context, _):

    # Ignore unprivileged people
    who = Permissions.e_whois(update)
    if not Permissions.is_user(who):
        return

    # If /help admin was requested
    admin_mods = Permissions.admin_modules()
    if Permissions.is_admin and len(context.args) > 0:
        if context.args[0] == 'admin':
            help_admin(update, admin_mods)
            return

    # Get descriptions of the loaded modules that the user may invoke
    mods = set(Loader.loaded()) & set(Permissions.user_modules(who))
    mods -= set(['start', 'logout'])
    mod_list = list(mods - admin_mods)
    if who != raw_whois(update):
        mod_list.append('logout')
    descs = ['/' + i + ': ' + Permissions.info(i) for i in mod_list]

    # Reply
    if Permissions.is_admin(who):
        descs.insert(0, 'Admin: /help admin for admin modules')
    reply(update, '@' + who + ' may use:' + djoin(descs))
예제 #3
0
파일: poibot.py 프로젝트: wusir2001/dogbot
def repeat(message):
    text = message.text
    sender = message.qq

    # Find & remove matched message from queue.
    msg = None
    for m in queue:
        if m.text == text:
            msg = m
            queue.remove(m)
            break

    # Increase message count
    if msg is None:
        msg = QueueMessage(text)
    msg.senders.add(sender)
    msg.count = len(msg.senders)

    # Push message back to queue
    queue.appendleft(msg)
    if len(queue) > REPEAT_QUEUE_SIZE:
        queue.pop()

    # Repeat message
    if msg.repeated or msg.count < REPEAT_COUNT_MIN:
        return
    if random.randint(1, REPEAT_COUNT_MAX - msg.count + 1) == 1:
        reply(qqbot, message, msg.text)
        msg.repeated = True
        return True
예제 #4
0
파일: db.py 프로젝트: cjbdnet/cyxbs_bot
def query(stu_ids, offset, update):
    reply_arr = []
    stu_ids = filter(lambda x: is_stu_num(x), stu_ids)
    for stu in stu_ids:
        name = get_name_by_stu_num(int(stu)) if update.message.chat.type == 'private' else '***'
        hint = 'hi~ %s 这里是明天的课表' % (name,) if offset == 1 else 'hi~ %s 这里是今天的课表' % (name,)
        reply_arr.append({'stu_num': stu, 'course': get_courses(stu, offset=offset), 'hint': hint})
    reply(update, reply_arr)
예제 #5
0
def invoke(update, context, _):
    usage = 'Usage: /module <command> <args>'
    try:
        fn = cmds[context.args[0]]
        fn(update, context.args[1:])
    except (KeyError, IndexError):
        assert len(cmds.keys()) > 0
        msg = usage + '\nCommands:' + djoin(cmds.keys())
        reply(update, msg)
예제 #6
0
파일: online.py 프로젝트: yuulin/qqbot.py
def command(message):
    if message.qq not in ONLINE.ADMIN:
        return
    if message.text != "/online":
        return
    text = '\n'.join([
        "ONLINE",
        "Last message at {last}.",
    ]).format(tolerance=ONLINE.TOLERANCE, last=ONLINE.last)
    reply(qqbot, message, text)
예제 #7
0
def send_leaderboard(message):
    recip = message['name']
    leaders = read_from_db()
    leaders = ids_to_names(leaders)
    leaders_stats_string = ''
    for leader in leaders:
        leaders_stats_string += '{}: {}\n'.format(leader['name'],
                                                  leader['stars'])
    message = "@{}\nAll time stats:\n{}".format(recip, leaders_stats_string)
    reply(message, bot_id)
예제 #8
0
def unload_module(update, args, *, cmd='unload'):
    try:
        mod = args[0]
        Loader.unload(mod)
        reply(update, mod + ' successfully unloaded')
        return True
    except (AssertionError, IndexError):
        msg = 'Usage: /module ' + cmd + ' <module>'
        msg += '\nLoaded modules:' + djoin(Loader.loaded())
        reply(update, msg)
        return False
예제 #9
0
파일: sudo.py 프로젝트: zwimer/zac-bot-core
def invoke(update, context, _):
    try:
        what = context.args[0]
        fn = Loader.pre_protection_fn(what)
        del context.args[0]
        fn(update, context)
    except AssertionError:
        msg = 'Errpr: No such module.'
        msg += ' Loaded modules are:' + djoin(Loader.loaded())
        reply(update, msg)
    except IndexError:
        reply(update, '/sudo <module> [args...]')
예제 #10
0
파일: kill.py 프로젝트: zwimer/zac-bot-core
def invoke(update, context, _):
    reqs = ['verified']
    try:
        assert reqs == context.args
        reply(update, 'Goodbye')
        logging.warning('Killing bot')
        os.kill(os.getpid(), signal.SIGINT)
        time.sleep(60)
        logging.error('Failed to gracefully kill bot. Killing.')
        os.kill(os.getpid(), signal.SIGINT)
    except AssertionError:
        reply(update, 'Usage: /kill ' + ' '.join(reqs))
예제 #11
0
def invoke(update, *_):
    # raw_user should not be able to log out e_user
    raw_user = raw_whois(update)
    if raw_user == Permissions.e_whois(update):
        raise DispatcherHandlerContinue
    # If invoked by e_user
    try:
        Permissions.remove_user_translation(raw_user)
        reply(update, 'Success')
    except AssertionError as err:
        logging.error(str(err))
        reply(update, 'Error: ' + str(err))
예제 #12
0
파일: mzbot.py 프로젝트: chiwei/mzbot
def validateUSCC(message):
    text = message.text
    dartRe = re.search('^([0-9]|[A-Z]){18}$', text)
    if dartRe != None:
        if validator(text) == True:
            reply(
                qqbot, message,
                "[CQ:at,qq={}]{}".format(message.qq,
                                         '\n统一社会信用代码:' + text + '\n√ 校验正确!√ '))
        else:
            reply(
                qqbot, message, "[CQ:at,qq={}]{}".format(
                    message.qq, '\n统一社会信用代码:' + text + '\n ×不符合编码规则!×'))
예제 #13
0
def explore_tree(update, context, args, cmd, chain):
    try:
        opt = args[0]
        res = cmd[opt]
        chain.append(opt)
        if isinstance(res, dict):
            explore_tree(update, context, args[1:], res, chain)
        else:
            res(update, context, args[1:], chain)
    except (IndexError, KeyError):
        usage = 'usage: /' + mod_name + djoin(chain, ' ')
        usage += ' <arg1> [args...]\nOptions:' + djoin(cmd.keys())
        reply(update, usage)
예제 #14
0
 def packaged_fn(update, context):
     try:
         extra_args = cls._pass[module] if module in cls._pass else None
         install_me(update, context, extra_args)
     except DispatcherHandlerContinue:
         return
     except DispatcherHandlerStop:
         raise
     except Exception as err:
         msg = 'Error invoking ' + module + '.invoke: '
         msg += traceback.format_exc()
         logging.error(msg)
         reply(update, 'Internal error.')
     raise DispatcherHandlerStop()
예제 #15
0
파일: mzbot.py 프로젝트: chiwei/mzbot
def queryOrgByOrgcode(message):
    texts = message.text
    dartRe = re.search('^([0-9]|[A-Z]){9}$', texts)
    if validatorBarcode(texts) == False:
        return
    if dartRe != None:
        result = queryOrgByCode(dartRe.group(0))
        if result != '':
            reply(qqbot, message,
                  "[CQ:at,qq={}]\n{}".format(message.qq, result))
        else:
            reply(
                qqbot, message,
                "[CQ:at,qq={}] 组织机构代码:{}{}".format(message.qq, dartRe.group(0),
                                                   '\n机构库中查不到此单位'))
예제 #16
0
def notify_chat(top_posters):
    if top_posters is None:
        pass
    else:
        members = get_members(group_id, access_token)
        members = [member for member in members if member['user_id'] in top_posters[0]]
        if len(members) == 1:
            member = members[0]
            message = '{} had the top post yesterday with {} likes!'.format(member['nickname'], top_posters[1])
            reply(message, bot_id)
        elif len(members) > 1:
            nicks = [m['nickname'] for m in members]
            nicks = '\n'.join(nicks)
            message = 'These members tied for the top post yesterday with {} likes!\n{}'.format(top_posters[1], nicks)
            reply(message, bot_id)
예제 #17
0
def sms():
	"""Respond to incoming calls with a simple text message."""
	# Fetch the message
	msg = request.form.get('Body')
	sender = request.form.get('From')
	print("reading message")

	# Create reply
	resp = MessagingResponse()
	if msg.lower() == "repeat":
		#fetch last msg
		result = database.fetchQuery(sender)
		result = list(result)
		print(result)
		msg = result[0]["Query"]
		print("Query retrived from database")
	else:
		print("Storing query in database")
		database.insertQuery(msg, sender)
	
	print(msg)
	message_reply, intent_Type = utils.reply(msg, sender)
	if intent_Type == "Map":
		resp.message(message_reply).media("http://www.delhimetrotimes.in/maps/delhi-metro-rail-map.jpg")
	elif intent_Type == "Directory":
		resp.message(message_reply).media("http://www.delhimetrorail.com/otherdocuments/900/directory_24818.pdf")
	else:
		resp.message(message_reply)
	print("replied")
	return str(resp)
예제 #18
0
파일: mzbot.py 프로젝트: chiwei/mzbot
def queryRegioninfoByRegioncode(message):
    texts = message.text
    dartRe = re.search('^\d{9}$', texts)
    if validatorBarcode(texts) == True:
        return
    if dartRe != None:
        result = queryRegionByCode(dartRe.group(0))
        if result != '':
            reply(
                qqbot, message, "[CQ:at,qq={}]{}".format(
                    message.qq,
                    '查询区划代码:' + dartRe.group(0) + '\n反馈结果:\n' + result))
        else:
            reply(
                qqbot, message,
                "[CQ:at,qq={}]区划代码:{}{}".format(message.qq, dartRe.group(0),
                                                '\n该代码未被使用过(区县以上)'))
예제 #19
0
def bantop(message):
    if message.qq not in ADMIN:
        return
    texts = message.text.split()
    if not (len(texts) > 0 and texts[0] == '/bantop'):
        return
    try:
        n = int(texts[1])
    except:
        n = 3
    topN = BanRecord.top(n)
    texts = ["**** 禁言次数排名 ****"]
    for qq, record in topN:
        texts.append("{qq} {count}".format(qq=CQAt(qq), count=record.count))
    text = '\n'.join(texts)
    reply(qqbot, message, text)
    return True
예제 #20
0
def banget(message):
    if message.qq not in ADMIN:
        return
    texts = message.text.split()
    if not (len(texts) > 0 and texts[0] == '/banget'):
        return
    try:
        qq = texts[1]
        qqm = CQAt.PATTERN.fullmatch(qq)
        if qqm and qqm.group(1):
            qq = qqm.group(1)
        record = BanRecord.get(qq)
        reply(
            qqbot, message,
            "Ban count: {qq} {count}".format(qq=CQAt(qq), count=record.count))
    except:
        reply(qqbot, message, "Error parsing command.")
    return True
예제 #21
0
파일: poibot.py 프로젝트: wusir2001/dogbot
def faq(message):
    text = message.text.lower()
    now = time.time()
    for faq in FAQ:
        if not match(text, faq.keywords):
            continue
        if match(text, faq.whitelist):
            return True
        if (now - faq.triggered) < faq.interval:
            return True

        if isinstance(faq.message, list):
            send_text = random.choice(faq.message)
        else:
            send_text = faq.message

        faq.triggered = now
        reply(qqbot, message, send_text)
        return True
예제 #22
0
파일: poibot.py 프로젝트: wusir2001/dogbot
def roll(message):
    texts = message.text.split()
    if not (len(texts) > 0 and texts[0] == '/roll'):
        return
    texts = RE_CQ_SPECIAL.sub('', message.text).split()

    ranges = []
    for text in texts[1:6]:
        # /roll 100
        try:
            n = int(text)
            if ROLL_LOWER <= n <= ROLL_UPPER:
                ranges.append(n)
            else:
                reply(qqbot, message, ROLL_HELP)
                return True
            continue
        except:
            pass
        # /roll 1,20,100
        if ROLL_SEPARATOR in text:
            n = text.split(',')
            ranges.append(n)
            continue
        # else
        break
    if len(ranges) == 0:
        ranges = [100]

    rolls = []
    for n in ranges:
        if isinstance(n, int):
            rolls.append("{}/{}".format(random.randint(1, n), n))
        if isinstance(n, (list, tuple)):
            rolls.append("{}/{}".format(random.choice(n),
                                        ROLL_SEPARATOR.join(n)))
    roll_text = ", ".join(rolls)
    send_text = "[roll] [CQ:at,qq={}]: {}".format(message.qq, roll_text)

    reply(qqbot, message, send_text)
    return True
예제 #23
0
def invoke(update, context, _):
    if 'logout' not in Loader.loaded():
        reply(update, 'Refusing to login, logout module is not loaded')
        return
    try:
        user = Permissions.e_whois(update)
        new_u = context.args[0]
        try:
            Permissions.add_user_translation(user, new_u)
            msg = '@' + user + ' logged in as @' + new_u
            logging.info(msg)
            reply(update, msg)
        except AssertionError as err:
            reply(update, 'Error: ' + str(err))
    except IndexError:
        reply(update, 'usage: /login <user>')
예제 #24
0
def repeat(message):
    text = message.text
    sender = message.qq

    # Find & remove matched message from queue.
    msg = None
    for m in queue:
        if m.text == text:
            msg = m
            queue.remove(m)
            break

    # Increase message count
    if msg is None:
        msg = QueueMessage(text)
    msg.senders.add(sender)
    msg.count = len(msg.senders)

    # Push message back to queue
    queue.appendleft(msg)
    if len(queue) > REPEAT_QUEUE_SIZE:
        queue.pop()

    # Ban4 event
    if msg.repeated and sender not in NOBAN_USERS and rQueue1.next():
        record = BanRecord.get(sender)
        duration = record.multiply * 1
        qqbot.send(GroupBan(message.group, sender, duration * 60))
        record.increase()

    # Repeat message
    if msg.repeated or msg.count < REPEAT_COUNT_MIN:
        return
    if random.randint(1, REPEAT_COUNT_MAX - msg.count + 1) == 1:
        reply(qqbot, message, msg.text)
        msg.repeated = True
        return True
예제 #25
0
def command(message):
    # Restrict to admin
    if message.qq not in ADMIN:
        return
    # Parse message
    try:
        texts = message.text.split()
        cmd = texts[0]
        qq = texts[1]
        idx = texts[2:]
    except:
        return
    if cmd != '/awd':
        return

    match = CQAt.PATTERN.fullmatch(qq)
    if match and match.group(1):
        qq = match.group(1)
    try:
        idx = list(map(lambda x: int(x), idx))
    except:
        idx = []
    if len(idx) == 0:
        idx = [0]

    items = list(filter(lambda x: x.qq == qq, messages))
    items.reverse()
    for i in idx:
        try:
            item = items[i]
        except:
            continue
        reply(
            qqbot, message, "[awd] {qq} #{i}\n{text}".format(i=i,
                                                             qq=CQAt(item.qq),
                                                             text=item.text))
예제 #26
0
 def wrapper(update, context, args, chain):
     try:
         f(update, *args)
         if notify_success:
             reply(update, 'Success')
     except AssertionError as err:
         reply(update, 'Error: ' + str(err))
     except TypeError:
         if fn_usage:
             chain.append(fn_usage)
         reply(update, 'Usage: /' + mod_name + djoin(chain, ' '))
예제 #27
0
def reset_modules(update, _):
    for i in list(Loader.loaded()):
        Loader.unload(i)
    reply(update, 'All modules unloaded. Loading modules.')
    success = []
    for mod in Permissions.modules():
        try:
            Loader.load(mod)
            success.append(mod)
        except ModuleNotFoundError as err:
            reply(update, str(err))
            logging.warning(str(err))
    if len(success) > 0:
        msg = 'Successfully loaded:' + djoin(success)
        reply(update, msg)
예제 #28
0
def load_module(update, args, *, cmd='load'):
    mod = ''
    try:
        mod = args[0]
        Loader.load(mod)
        reply(update, mod + ' successfully loaded')
        return True
    except (AssertionError, IndexError) as e:
        msg = 'Usage: /module ' + cmd + ' <module>'
        unloaded = [
            i for i in Permissions.modules() if i not in Loader.loaded()
        ]
        msg += '\nUnloaded modules:' + djoin(unloaded)
        reply(update, msg)
        return False
    except ModuleNotFoundError as err:
        logging.error('Failed to load module "' + mod + '" with error: ' +
                      str(err))
        reply(update, 'Failed to load module.')
        raise
예제 #29
0
def invoke(updater, *_):
    msg = 'Welcome to zac-bot. '
    msg += 'Invoke /help to see what commands are availabe.'
    reply(updater, msg)
예제 #30
0
def watch_key(message, key):
    utils.reply(message, "start observing key {key}".format(key=key))
    schedule.every(20).seconds.do(lambda: utils.reply(message, kv.eget(key)))
예제 #31
0
def help_admin(update, mods):
    descs = ['/' + i + ': ' + Permissions.info(i) for i in mods]
    reply(update, 'Admin modules:' + djoin(descs))