def accept(msg: catbot.Message):
    operator = bot.get_chat_member(config['group'], msg.from_.id)
    if not (operator.status == 'creator' or operator.status == 'administrator'):
        return

    if msg.reply:
        accepted_id = msg.reply_to_message.from_.id
    else:
        user_input_token = msg.text.split()
        if len(user_input_token) < 2:
            bot.send_message(msg.chat.id, text=config['messages']['general_prompt'], reply_to_message_id=msg.id)
            return
        try:
            accepted_id = int(user_input_token[1])
        except ValueError:
            bot.send_message(msg.chat.id, text=config['messages']['telegram_id_error'], reply_to_message_id=msg.id)
            return

    with t_lock:
        ac_list, rec = bot.secure_record_fetch('ac', list)
        for i in range(len(ac_list)):
            entry = Ac.from_dict(ac_list[i])
            if entry.telegram_id == accepted_id:
                accepted_index = i
                break
        else:
            entry = Ac(accepted_id)
            ac_list.append(entry)
            accepted_index = -1
        entry.refused = False
        ac_list[accepted_index] = entry.to_dict()
        rec['ac'] = ac_list
        json.dump(rec, open(config['record'], 'w', encoding='utf-8'), indent=2, ensure_ascii=False)

    log(config['messages']['accept_log'].format(tg_id=accepted_id, acceptor=html_refer(operator.name)))
def new_member(msg: catbot.ChatMemberUpdate):
    if msg.new_chat_member.status == 'restricted':
        restricted_until = msg.new_chat_member.until_date
        if restricted_until == 0:
            restricted_until = -1  # Restricted by bot, keep entry.restricted_until unchanged later
    elif msg.new_chat_member.status == 'creator' or \
            msg.new_chat_member.status == 'administrator' or \
            msg.new_chat_member.status == 'kicked':
        return
    else:
        restricted_until = 0

    try:
        bot.silence_chat_member(config['group'], msg.new_chat_member.id)
    except catbot.InsufficientRightError:
        bot.send_message(config['group'], text=config['messages']['insufficient_right'])
        return

    with t_lock:
        ac_list, rec = bot.secure_record_fetch('ac', list)
        for i in range(len(ac_list)):
            entry = Ac.from_dict(ac_list[i])
            if entry.telegram_id == msg.new_chat_member.id:
                user_index = i
                break
        else:
            entry = Ac(msg.from_.id)
            ac_list.append(entry)
            user_index = -1

        if restricted_until != -1:
            entry.restricted_until = restricted_until
        ac_list[user_index] = entry.to_dict()
        rec['ac'] = ac_list
        json.dump(rec, open(config['record'], 'w', encoding='utf-8'), indent=2, ensure_ascii=False)

    if entry.confirmed or entry.whitelist_reason:
        lift_restriction_trial(entry, config['group'])
    else:
        with t_lock:
            last_id, rec = bot.secure_record_fetch('last_welcome', int)
            cur = bot.send_message(config['group'],
                                   text=config['messages']['new_member_hint'].format(
                                       tg_id=msg.new_chat_member.id,
                                       tg_name=html_refer(msg.new_chat_member.name)),
                                   parse_mode='HTML')
            rec['last_welcome'] = cur.id
            json.dump(rec, open(config['record'], 'w', encoding='utf-8'), indent=2, ensure_ascii=False)
            try:
                bot.delete_message(config['group'], last_id)
            except catbot.DeleteMessageError:
                pass
def refuse(msg: catbot.Message):
    try:
        operator = bot.get_chat_member(config['group'], msg.from_.id)
    except catbot.UserNotFoundError:
        return
    if not (operator.status == 'creator' or operator.status == 'administrator'):
        return

    if msg.reply:
        refused_id = msg.reply_to_message.from_.id
    else:
        user_input_token = msg.text.split()
        if len(user_input_token) < 2:
            bot.send_message(msg.chat.id, text=config['messages']['general_prompt'], reply_to_message_id=msg.id)
            return
        try:
            refused_id = int(user_input_token[1])
        except ValueError:
            bot.send_message(msg.chat.id, text=config['messages']['telegram_id_error'], reply_to_message_id=msg.id)
            return

    try:
        refused_user = bot.get_chat_member(config['group'], refused_id)
    except catbot.UserNotFoundError:
        restricted_until = 0
    else:
        if refused_user.status == 'restricted':
            restricted_until = refused_user.until_date
            if restricted_until == 0:
                restricted_until = -1
        else:
            restricted_until = 0

    with t_lock:
        ac_list, rec = bot.secure_record_fetch('ac', list)
        for i in range(len(ac_list)):
            entry = Ac.from_dict(ac_list[i])
            if entry.telegram_id == refused_id:
                refused_index = i
                break
        else:
            entry = Ac(refused_id)
            ac_list.append(entry)
            refused_index = -1

        if restricted_until != -1:
            entry.restricted_until = restricted_until
        entry.confirmed = False
        entry.confirming = False
        entry.refused = True
        ac_list[refused_index] = entry.to_dict()
        rec['ac'] = ac_list
        json.dump(rec, open(config['record'], 'w', encoding='utf-8'), indent=2, ensure_ascii=False)

    log(config['messages']['refuse_log'].format(tg_id=refused_id, refuser=html_refer(operator.name)))

    silence_trial(entry)
def add_whitelist(msg: catbot.Message):
    adder = bot.get_chat_member(config['group'], msg.from_.id)
    if not (adder.status == 'creator' or adder.status == 'administrator'):
        return

    user_input_token = msg.text.split()
    if msg.reply:
        whitelist_id = msg.reply_to_message.from_.id
        if len(user_input_token) > 1:
            reason = ' '.join(user_input_token[1:])
        else:
            reason = 'whitelisted'
    else:
        if len(user_input_token) < 2:
            bot.send_message(msg.chat.id, text=config['messages']['add_whitelist_prompt'], reply_to_message_id=msg.id)
            return
        try:
            whitelist_id = int(user_input_token[1])
        except ValueError:
            bot.send_message(msg.chat.id, text=config['messages']['telegram_id_error'], reply_to_message_id=msg.id)
            return
        if len(user_input_token) > 2:
            reason = ' '.join(user_input_token[2:])
        else:
            reason = 'whitelisted'

    with t_lock:
        ac_list, rec = bot.secure_record_fetch('ac', list)
        for i in range(len(ac_list)):
            entry = Ac.from_dict(ac_list[i])
            if entry.telegram_id == whitelist_id:
                entry.whitelist_reason = reason
                ac_list[i] = entry.to_dict()
                break
        else:
            entry = Ac(whitelist_id)
            entry.whitelist_reason = reason
            ac_list.append(entry.to_dict())

        rec['ac'] = ac_list
        json.dump(rec, open(config['record'], 'w', encoding='utf-8'), indent=2, ensure_ascii=False)

    log(config['messages']['add_whitelist_log'].format(adder=html_refer(adder.name), tg_id=whitelist_id, reason=reason))
    bot.send_message(msg.chat.id, text=config['messages']['add_whitelist_succ'].format(tg_id=whitelist_id),
                     reply_to_message_id=msg.id)

    lift_restriction_trial(entry, msg.chat.id)
def whois(msg: catbot.Message):
    user_input_token = msg.text.split()
    if msg.reply:
        whois_id = msg.reply_to_message.from_.id
        whois_mw_id = None
    else:
        if len(user_input_token) == 1:
            bot.send_message(config['group'], text=config['messages']['whois_prompt'], reply_to_message_id=msg.id)
            return

        try:
            whois_id = int(' '.join(user_input_token[1:]))
            whois_mw_id = None
        except ValueError:
            whois_id = 0
            whois_wm_name = '_'.join(user_input_token[1:])
            whois_wm_name = whois_wm_name[0].upper() + whois_wm_name[1:]
            whois_mw_id = get_mw_id(whois_wm_name)
            if whois_mw_id is None:
                bot.send_message(config['group'], text=config['messages']['whois_not_found'],
                                 reply_to_message_id=msg.id)
                return

    with t_lock:
        ac_list, rec = bot.secure_record_fetch('ac', list)
        for i in range(len(ac_list)):
            entry = Ac.from_dict(ac_list[i])
            if (entry.confirmed or entry.whitelist_reason) and (entry.telegram_id == whois_id or
                                                                entry.mw_id == whois_mw_id):
                break
        else:
            bot.send_message(config['group'], text=config['messages']['whois_not_found'], reply_to_message_id=msg.id)
            return

    try:
        whois_member = bot.get_chat_member(config['group'], entry.telegram_id)
        name = html_refer(whois_member.name)
    except catbot.UserNotFoundError:
        name = config['messages']['whois_tg_name_unavailable']
    resp_text = f'{name} ({entry.telegram_id})\n'

    if entry.confirmed:
        wp_username = get_mw_username(entry.mw_id)
        if wp_username is None:
            bot.send_message(config['group'], text=config['messages']['whois_not_found'], reply_to_message_id=msg.id)
            return
        resp_text += config['messages']['whois_has_mw'].format(
            wp_id=html_refer(wp_username),
            ctime=time.strftime('%Y-%m-%d %H:%M', time.gmtime(entry.confirmed_time)),
            site=config['main_site']
        )
    else:
        resp_text += config['messages']['whois_no_mw']
    if entry.whitelist_reason:
        resp_text += config['messages']['whois_whitelisted'].format(reason=entry.whitelist_reason)

    bot.send_message(config['group'], text=resp_text, reply_to_message_id=msg.id, parse_mode='HTML',
                     disable_web_page_preview=True)
def remove_whitelist(msg: catbot.Message):
    try:
        remover = bot.get_chat_member(config['group'], msg.from_.id)
    except catbot.UserNotFoundError:
        return
    if not (remover.status == 'creator' or remover.status == 'administrator'):
        return

    user_input_token = msg.text.split()
    if msg.reply:
        whitelist_id = msg.reply_to_message.from_.id
    else:
        if len(user_input_token) < 2:
            bot.send_message(msg.chat.id, text=config['messages']['general_prompt'], reply_to_message_id=msg.id)
            return
        try:
            whitelist_id = int(user_input_token[1])
        except ValueError:
            bot.send_message(msg.chat.id, text=config['messages']['telegram_id_error'], reply_to_message_id=msg.id)
            return

    try:
        whitelist_user = bot.get_chat_member(config['group'], whitelist_id)
    except catbot.UserNotFoundError:
        restricted_until = 0
    else:
        if whitelist_user.status == 'restricted':
            restricted_until = whitelist_user.until_date
            if restricted_until == 0:
                restricted_until = -1  # Restricted by bot, keep entry.restricted_until unchanged later
        else:
            restricted_until = 0

    with t_lock:
        ac_list, rec = bot.secure_record_fetch('ac', list)
        for i in range(len(ac_list)):
            entry = Ac.from_dict(ac_list[i])
            if entry.telegram_id == whitelist_id and entry.whitelist_reason:
                entry.whitelist_reason = ''
                if restricted_until != -1:
                    entry.restricted_until = restricted_until
                ac_list[i] = entry.to_dict()
                break
        else:
            bot.send_message(msg.chat.id, text=config['messages']['remove_whitelist_not_found'],
                             reply_to_message_id=msg.id)
            return

        rec['ac'] = ac_list
        json.dump(rec, open(config['record'], 'w', encoding='utf-8'), indent=2, ensure_ascii=False)

    log(config['messages']['remove_whitelist_log'].format(remover=html_refer(remover.name), tg_id=whitelist_id))
    bot.send_message(msg.chat.id, text=config['messages']['remove_whitelist_succ'].format(tg_id=whitelist_id),
                     reply_to_message_id=msg.id)

    silence_trial(entry, msg.chat.id)
def confirm_button(query: catbot.CallbackQuery):
    bot.answer_callback_query(callback_query_id=query.id)
    bot.edit_message(query.msg.chat.id, query.msg.id, text=query.msg.html_formatted_text, parse_mode='HTML',
                     disable_web_page_preview=True)
    with t_lock:
        ac_list, rec = bot.secure_record_fetch('ac', list)
        for i in range(len(ac_list)):
            entry = Ac.from_dict(ac_list[i])
            if entry.telegram_id != query.from_.id:
                continue
            if entry.confirmed:
                bot.send_message(query.msg.chat.id, text=config['messages']['confirm_already'].format(
                    wp_name=get_mw_username(entry.mw_id)
                ))
                return
            if entry.confirming:
                entry_index = i
                break
        else:
            bot.send_message(query.msg.chat.id, text=config['messages']['confirm_session_lost'])
            return

        try:
            res = requests.post(config['oauth_query_url'], json={'query_key': config['oauth_query_key'],
                                                                 'telegram_id': str(query.from_.id)})
        except (requests.ConnectTimeout, requests.ConnectionError, requests.HTTPError):
            entry.confirmed = False
        else:
            if res.status_code == 200 and res.json()['ok']:
                entry.mw_id = res.json()['mw_id']
                entry.confirmed = check_eligibility(query, entry.mw_id)
            else:
                entry.confirmed = False
        finally:
            if entry.confirmed:
                entry.confirmed_time = time.time()
            entry.confirming = False

        ac_list[entry_index] = entry.to_dict()
        rec['ac'] = ac_list
        json.dump(rec, open(config['record'], 'w', encoding='utf-8'), indent=2, ensure_ascii=False)

    if entry.confirmed:
        bot.send_message(query.msg.chat.id, text=config['messages']['confirm_complete'])
        lift_restriction_trial(entry)
        log(config['messages']['confirm_log'].format(
            tg_id=entry.telegram_id,
            wp_id=get_mw_username(entry.mw_id),
            site=config['main_site']
        ))
    else:
        bot.send_message(query.msg.chat.id, text=config['messages']['confirm_failed'])
def block_unconfirmed(msg: catbot.Message):
    if hasattr(msg, 'new_chat_members') or hasattr(msg, 'left_chat_member'):
        return
    with t_lock:
        ac_list, rec = bot.secure_record_fetch('ac', list)
        for i, item in enumerate(ac_list):
            entry = Ac.from_dict(item)
            if entry.telegram_id == msg.from_.id and entry.confirmed:
                return
            if entry.telegram_id == msg.from_.id and entry.whitelist_reason:
                return

    try:
        bot.delete_message(config['group'], msg.id)
    except catbot.DeleteMessageError:
        print(f'[Error] Delete message {msg.id} failed.')
示例#9
0
    def listen(self):
        self.conn.listen(1)
        while True:
            print("Espperando ...")
            connection, client = self.conn.accept()
            try:
                print(sys.stderr, 'from ', client)
                while True:
                    data = connection.recv(16)
                    print("recebido %s" % data)
                    Arc = Ac("192.168.0.201", 4998)
                    Arc.open()
                    #if data.isnumeric():
                    print(type(data))
                    Arc.setTemp(int(data))
                    Arc.close()

            finally:
                connection.close()
示例#10
0
	def listen(self):
		self.conn.listen(1)
		while True:
			print("Espperando ...")
			connection,client=self.conn.accept()
			try:
				print (sys.stderr,'from ',client)
				while True:
					data = connection.recv(16)
					print("recebido %s"%data)
					Arc=Ac("192.168.0.201",4998)
					Arc.open()
					#if data.isnumeric():
					print(type(data))
					Arc.setTemp(int(data))
					Arc.close()
				
			finally:
				connection.close()
def deconfirm_button(query: catbot.CallbackQuery):
    bot.answer_callback_query(query.id)
    try:
        user_chat = bot.get_chat_member(config['group'], query.from_.id)
    except catbot.UserNotFoundError:
        restricted_until = 0
    else:
        if user_chat.status == 'restricted':
            restricted_until = user_chat.until_date
            if restricted_until == 0:
                restricted_until = -1  # Restricted by bot, keep entry.restricted_until unchanged later
        else:
            restricted_until = 0

    with t_lock:
        ac_list, rec = bot.secure_record_fetch('ac', list)
        for i in range(len(ac_list)):
            entry = Ac.from_dict(ac_list[i])
            if entry.telegram_id == query.from_.id:
                if entry.confirmed:
                    entry.confirmed = False
                    ac_list[i] = entry.to_dict()
                    if restricted_until != -1:
                        entry.restricted_until = restricted_until
                    break
                else:
                    bot.send_message(query.msg.chat.id, text=config['messages']['deconfirm_not_confirmed'])
                    return
        else:
            bot.send_message(query.msg.chat.id, text=config['messages']['deconfirm_not_confirmed'])
            return

        rec['ac'] = ac_list
        json.dump(rec, open(config['record'], 'w', encoding='utf-8'), indent=2, ensure_ascii=False)

    log(config['messages']['deconfirm_log'].format(tg_id=entry.telegram_id, wp_id=get_mw_username(entry.mw_id),
                                                   site=config['main_site']))
    bot.send_message(query.msg.chat.id, text=config['messages']['deconfirm_succ'])

    silence_trial(entry)
def confirm(msg: catbot.Message):
    with t_lock:
        ac_list, rec = bot.secure_record_fetch('ac', list)

        entry_index = -1
        for i in range(len(ac_list)):
            entry = Ac.from_dict(ac_list[i])
            if entry.telegram_id == msg.from_.id:
                if entry.confirmed:
                    bot.send_message(msg.chat.id, text=config['messages']['confirm_already'].format(
                        wp_name=get_mw_username(entry.mw_id)
                    ))
                    return
                elif entry.confirming:
                    bot.send_message(msg.chat.id, text=config['messages']['confirm_confirming'])
                    return
                elif entry.refused:
                    bot.send_message(msg.chat.id, text=config['messages']['confirm_ineligible'])
                    return
                else:
                    entry_index = i

        else:
            if entry_index == -1:
                entry = Ac(msg.from_.id)
                ac_list.append(entry.to_dict())
            entry = Ac.from_dict(ac_list[entry_index])
            entry.confirming = True
            ac_list[entry_index] = entry.to_dict()

        rec['ac'] = ac_list
        json.dump(rec, open(config['record'], 'w', encoding='utf-8'), indent=2, ensure_ascii=False)

    button = catbot.InlineKeyboardButton(config['messages']['confirm_button'], callback_data=f'confirm')
    keyboard = catbot.InlineKeyboard([[button]])
    bot.send_message(msg.chat.id, text=config['messages']['confirm_wait'].format(
        link=config['oauth_auth_url'].format(telegram_id=msg.from_.id),
    ),
                     parse_mode='HTML', disable_web_page_preview=True, reply_markup=keyboard)
示例#13
0
from ac import Ac
import sys
data=sys.argv[1]
Arc=Ac("192.168.0.201",4998)
Arc.open()
#if data.isnumeric():
print("Temperatura: ",data)
Arc.setTemp(int(data))
Arc.close()