def get_user(cls, telegram_id): sqlquery = 'SELECT * FROM USERS WHERE TELEGRAM_ID=\'{}\''.format(hashea(telegram_id)) logger(sqlquery) result = select(sqlquery, True) if result: return cls.parse(result) return None
def do_telegram_callback_query(telegram, payload): """ The callback query :param telegram Telegram: The telegram object :param payload dict: The payload """ member = payload['callback_query']['from'] message_id = payload['callback_query']['message']['message_id'] chat_id = payload['callback_query']['message']['chat']['id'] result, member_id = payload['callback_query']['data'].split('|') logger(f"Result: {result}, Id: {member_id}") if int(member_id) == int(member['id']): user = User.get_user(member['id']) if not user: user = User.insert_user(member) if user is not None and user.get_timestamp() > 0: user.set_timestamp(0) user.set_is_bot(result == 'ko') user.save() logger(f"Chat id: {chat_id}, Message id: {message_id}") telegram.delete_message(chat_id, message_id) if result == 'ko': telegram.kick_chat_member(chat_id, member['id']) insert_into_influxdb(result == 'ko')
def unban(cls, user_id): sqlquery = 'UPDATE USERS SET IS_BOT = ?, TIMESTAMP = 0 WHERE TELEGRAM_ID = ?' logger(sqlquery) data = (HUMAN, hashea(user_id)) logger(data) execute(sqlquery, data) return cls.get_user(user_id)
def insert_into_influxdb(bot): data = '{} value=1'.format('bot' if bot else 'human') url = 'https://influxdb.territoriolinux.es/write?db=telegraf' headers = {'Content-type': 'application/octet-stream'} try: res = requests.post(url=url, data=data, headers=headers) except Exception: logger('Can\'t write in inbluxdb')
def insert_user(cls, member, chat_id, is_bot=False): sqlquery = 'INSERT INTO USERS (TELEGRAM_ID, TIMESTAMP, IS_BOT) VALUES(?, ?, ?)' logger(sqlquery) if is_bot or member['is_bot']: is_bot = BOT else: is_bot = HUMAN data = (hashea(member['id']), int(time.time()), is_bot) execute(sqlquery, data) return cls.get_user(member['id'])
def get_bots(cls, telegram_id=None): bots = [] sqlquery = 'SELECT * FROM USERS WHERE (TIMESTAMP > 0 OR IS_BOT = 0)' if telegram_id: sqlquery += ' AND TELEGRAM_ID = \'{}\''.format(hashea(telegram_id)) logger(sqlquery) result = select(sqlquery) if result: for item in result: bots.append(cls.parse(item)) return bots
def wait_for_new_user(member, chat_id, result): time.sleep(int(os.environ['COURTESY_TIME'])) user = User.get_user(member['id']) logger(user) logger(json.dumps(result)) if user.get_timestamp() > 0: user.set_timestamp(0) user.set_is_bot(True) user.save() telegram = Telegram(os.environ['TELEGRAM_API_TOKEN']) telegram.kick_chat_member(chat_id, member['id']) telegram.delete_message(chat_id, result['result']['message_id']) insert_into_influxdb(True)
def get_webhook(webhook): """ Webhook :param webhook str: the webhook """ logger(webhook) if not os.getenv('WEBHOOK') or os.getenv('WEBHOOK') != webhook: return 'KO', 404 try: if request.method == 'GET' or not request.json: return 'OK', 200 except Exception as exception: logger(exception, True) return 'OK', 200 telegram = Telegram(os.environ['TELEGRAM_API_TOKEN']) logger(request.json) payload = request.json if 'message' in payload and 'new_chat_member' in payload['message']: logger('New member') member = payload['message']['new_chat_member'] chat_id = payload['message']['chat']['id'] user = User.get_user(member['id']) if user: do_kick_user(telegram, user, member, chat_id) else: do_query_user(telegram, member, chat_id) elif 'callback_query' in payload: do_telegram_callback_query(telegram, payload) elif 'message' in payload: do_telegram_mesage(telegram, payload) return 'OK', 201
def insert_into_influxdb(bot): """ Insert data into influxdb """ url = os.getenv('INFLUXDB_URL') if url: item = 'bot' if bot else 'human' data = f"{item} value=1" headers = {'Content-type': 'application/octet-stream'} try: requests.post(url=url, data=data, headers=headers) except Exception as exception: logger(f"Can\'t write in inbluxdb ({exception})", True)
def do_kick_user(telegram, user, member, chat_id): """ Kick an user :param telegram Telegram: Telegram obkect :param user User: an user :param member dict: Member :param chat_id str: chat id """ logger(user) delta = int(time.time()) - int(user.get_timestamp()) if (user.get_timestamp() > 0 and delta > int(os.getenv('COURTESY_TIME', '120'))) \ or user.get_is_bot(): user.set_timestamp(0) user.set_is_bot(True) user.save() telegram.kick_chat_member(chat_id, member['id']) insert_into_influxdb(True)
def wait_for_new_user(member, chat_id, result): """ Wait for the answer of the new user :param member dict: Them member :param chat_id str: The chat id :param result str: The result """ time.sleep(float(os.getenv('COURTESY_TIME', '120'))) user = User.get_user(member['id']) logger(user) logger(json.dumps(result)) if user is not None and user.get_timestamp() > 0: user.set_timestamp(0) user.set_is_bot(True) user.save() telegram = Telegram(os.environ['TELEGRAM_API_TOKEN']) telegram.kick_chat_member(chat_id, member['id']) telegram.delete_message(chat_id, result['result']['message_id']) insert_into_influxdb(True)
def save(self): sqlquery = 'UPDATE USERS SET TIMESTAMP=?, IS_BOT=? WHERE TELEGRAM_ID=?' logger(sqlquery) data = (self._timestamp, self._is_bot, self._telegram_id) execute(sqlquery, data)
def get_webhook(webhook): logger(webhook) if os.environ['WEBHOOK'] != webhook: return 'KO', 404 try: if request.method == 'GET' or not request.json: return 'OK', 200 except Exception: return 'OK', 200 telegram = Telegram(os.environ['TELEGRAM_API_TOKEN']) logger(request.json) payload = request.json if 'message' in payload and 'new_chat_member' in payload['message']: logger('New member') member = payload['message']['new_chat_member'] chat_id = payload['message']['chat']['id'] user = User.get_user(member['id']) if user: logger(user) delta = int(time.time()) - int(user.get_timestamp()) if (user.get_timestamp() > 0 and delta > int(os.environ['COURTESY_TIME'])) \ or user.get_is_bot(): user.set_timestamp(0) user.set_is_bot(True) user.save() telegram.kick_chat_member(chat_id, member['id']) insert_into_influxdb(True) else: User.insert_user(member, chat_id) rows = [] buttons = [] buttons.append({ 'text': '🐸', 'callback_data': 'ko|{}'.format(member['id']) }) buttons.append({ 'text': '🤖', 'callback_data': 'ko|{}'.format(member['id']) }) buttons.append({ 'text': '🐵', 'callback_data': 'ko|{}'.format(member['id']) }) buttons.append({ 'text': '🐱', 'callback_data': 'ko|{}'.format(member['id']) }) random.shuffle(buttons) rows.append(buttons) buttons = [] buttons.append({ 'text': '🐼', 'callback_data': 'ko|{}'.format(member['id']) }) buttons.append({ 'text': '🦝', 'callback_data': 'ko|{}'.format(member['id']) }) buttons.append({ 'text': '🐧', 'callback_data': 'ok|{}'.format(member['id']) }) buttons.append({ 'text': '🐮', 'callback_data': 'ko|{}'.format(member['id']) }) random.shuffle(buttons) rows.append(buttons) random.shuffle(rows) inline_keyboard = {'inline_keyboard': rows} mention = "<a href=\"tg://user?id={}\">{}</a>".format( member['id'], member['first_name'] if member['first_name'] else 'amig@') result = telegram.send_message( chat_id, 'Hola {}, selecciona el pingüino, en menos de {} segundos'. format(mention, os.environ['COURTESY_TIME']), json.dumps(inline_keyboard)) t1 = threading.Thread(target=wait_for_new_user, args=(member, chat_id, result)) t1.start() elif 'callback_query' in payload: member = payload['callback_query']['from'] message_id = payload['callback_query']['message']['message_id'] chat_id = payload['callback_query']['message']['chat']['id'] result, member_id = payload['callback_query']['data'].split('|') logger('Result: {}, Id: {}'.format(result, member_id)) if int(member_id) == int(member['id']): user = User.get_user(member['id']) if not user: user = User.insert_user(member, chat_id) if user and user.get_timestamp() > 0: user.set_timestamp(0) user.set_is_bot(result == 'ko') user.save() logger('Chat id: {}, Message id: {}'.format( chat_id, message_id)) telegram.delete_message(chat_id, message_id) if result == 'ko': telegram.kick_chat_member(chat_id, member['id']) insert_into_influxdb(result == 'ko') elif 'message' in payload: from_id = payload['message']['from']['id'] chat_id = payload['message']['chat']['id'] message_id = payload['message']['message_id'] if User.get_bots(from_id): telegram.delete_message(chat_id, message_id) return 'OK', 201