示例#1
0
def bot_command_raid(bot_command_params: str, chat_id: int):

    try:

        if not re.match('^\d+$', bot_command_params):
            return msg.send_message('That is not a valid raid id.', chat_id,
                                    None)

        raid_id = int(bot_command_params)
        raid_detail = raid.get_raid_by_id(raid_id)
        if not raid_detail:
            return msg.send_message('That is not a valid raid id.', chat_id,
                                    None)

        tracked_data = msg.decode_http_response_as_dict(
            msg.send_message(raid.format_raid_message(raid_detail), chat_id,
                             'MarkdownV2', True))

        # Only track messages for raids that have not completed
        if raid_detail['completed'] == 0:
            raid.insert_message_tracking(bot_command_params,
                                         tracked_data['result']['chat']['id'],
                                         tracked_data['result']['message_id'])

        return

    except Exception as e:
        raise
示例#2
0
def bot_command_location(message_id, chat_id, raid_id, from_id, from_username,
                         location_param):

    location = string.capwords(location_param[:50].strip())
    response = raid.update_raid_location(raid_id, from_id, location)

    if response.get('success'):
        leave_comment_and_update_messages(
            message_id, raid_id, from_username,
            'Updated the raid location to {0}'.format(location_param))
        return msg.send_message(response.get('success'), chat_id, None)

    else:
        return msg.send_message('ERROR: {0}'.format(response.get('error')),
                                chat_id, None)
示例#3
0
def bot_command_team(command_params, chat_id, from_id, from_username):

    if not re.match('^valor|mystic|instinct$', command_params, re.IGNORECASE):
        return msg.send_message(
            'тЪая╕П Invalid team name provided. Please specify either Valor, Mystic or Instinct.',
            chat_id)

    try:
        if raid.update_team(from_id, from_username, command_params):
            return msg.send_message(
                'ЁЯСН Thanks {0}, I have set your team to {1}.'.format(
                    from_username, command_params.title()), chat_id)

    except Exception as e:
        raise
示例#4
0
def bot_command_cancel(message_id, chat_id, raid_id, from_id):

    response = raid.cancel_raid(raid_id, from_id)

    if response.get('success'):
        formatted_message = raid.format_raid_message(
            raid.get_raid_by_id(raid_id))
        tracking = raid.get_message_tracking_by_id(raid_id)
        for t in tracking:
            msg.edit_message(t.get('chat_id'), t.get('message_id'),
                             formatted_message, 'MarkdownV2', True)

        return msg.send_message('Raid Cancelled.', chat_id, None)

    else:
        return msg.send_message('ERROR: {0}'.format(response.get('error')),
                                chat_id, None)
示例#5
0
def bot_command_raid(command_params, chat_id):

    if not re.match('^\d+$', command_params):
        return msg.send_message('тЪая╕П That is not a valid raid id.', chat_id)

    raid_detail = raid.get_raid_by_id(command_params)
    if not raid_detail:
        return msg.send_message('тЪая╕П That is not a valid raid id.', chat_id)

    tracked_message = msg.send_message(raid.format_raid_message(raid_detail),
                                       chat_id, 'MarkdownV2', True)

    # Only track messages for raids that have not completed
    if raid_detail['completed'] == 0:
        tracked_data = json.loads(tracked_message.data.decode("utf-8"))
        raid.insert_message_tracking(command_params,
                                     tracked_data['result']['chat']['id'],
                                     tracked_data['result']['message_id'])
示例#6
0
def bot_command_nickname(command_params, chat_id, from_id, from_username):

    if not re.match('^[A-Za-z0-9]{5,32}$', command_params):
        return msg.send_message(
            'тЪая╕П Invalid nickname provided. Please try again.', chat_id)

    try:
        if raid.update_nickname(from_id, from_username, command_params):
            return msg.send_message(
                'ЁЯСН Thanks {0}, I have set your nickname to {1}.'.format(
                    from_username, command_params), chat_id)

    except pymysql.err.IntegrityError as pe:
        return msg.send_message(
            'тЪая╕П Sorry, your nickname has already been claimed.', chat_id)

    except Exception as e:
        raise
示例#7
0
def bot_command_level(command_params, chat_id, from_id, from_username):

    if not str(command_params).isdigit():
        return msg.send_message(
            'тЪая╕П Invalid level provided. Please try again.', chat_id)
    else:
        level = int(command_params)
        if not 1 <= level <= 40:
            return msg.send_message('тЪая╕П Level must be between 1 and 40.',
                                    chat_id)

        try:
            if raid.update_level(from_id, from_username, level):
                return msg.send_message(
                    'ЁЯСН Thanks {0}, I have set your level to {1}.'.format(
                        from_username, level), chat_id)

        except Exception as e:
            raise
示例#8
0
def bot_command_time(message_id, chat_id, raid_id, from_id, from_username,
                     time_param):

    if not re.match('^([01]?[0-9]|2[0-3]):[0-5][0-9]$', time_param):
        return msg.send_message(
            'ERROR: Please supply the time in the format: hh:mm', chat_id,
            None)

    else:
        response = raid.update_raid_time(raid_id, from_id, time_param)

        if response.get('success'):
            leave_comment_and_update_messages(
                message_id, raid_id, from_username,
                'Updated the raid time to {0}'.format(time_param))
            return msg.send_message(response.get('success'), chat_id, None)

        else:
            return msg.send_message('ERROR: {0}'.format(response.get('error')),
                                    chat_id, None)
示例#9
0
def callback_query_handler(callback_query: dict):
    
    try:
        
        # Check all mandatory fields exist in the callback_query message
        if not (all(x in callback_query for x in ['id', 'from', 'message', 'data'])):
            return
        
        callback_query_id      = callback_query['id']
        callback_query_from    = callback_query['from']
        callback_query_message = callback_query['message']
        callback_query_data    = callback_query['data']
        
        # Validate callback_query_data is a digit
        if not callback_query_data.isdigit():
            return msg.send_message('Received invalid callback_query_data: {0}'.format(callback_query_data), ADMIN_CHAT_ID)
        
        user_id = callback_query_from['id']
        chat_id = callback_query_message['chat']['id']
        msg_txt = callback_query_message["text"].split(';')[0]
        
        if re.match('^Raid\s(\d)+$', msg_txt):
            raid_id = msg_txt.split(' ')[1]
            
            if raid.join_raid(callback_query_from, raid_id, callback_query_data):
                formatted_message = raid.format_raid_message(raid.get_raid_by_id(raid_id))
                tracking = raid.get_message_tracking_by_id(raid_id)
                for t in tracking:
                    msg.edit_message(t.get('chat_id'), t.get('message_id'), formatted_message, 'MarkdownV2', True)
        
        else:
            return msg.send_message('An unrecognised callback query was received: {0}'.format(callback_query), ADMIN_CHAT_ID)
    
    except Exception as e: raise
    
    finally:
        return msg.answer_callback_query(callback_query_id)
示例#10
0
def bot_command_newraid(raid_params, chat_id, from_id, from_username):

    raid_info = raid.create_raid(raid_params, chat_id, from_id, from_username)

    if raid_info.get('error'):
        return msg.send_message(
            'тЪая╕П Invalid newraid command received: {0}\n{1}'.format(
                raid_params, raid_info.get('error')), chat_id)

    bot_command_raid(str(raid_info.get('raid_id')), chat_id)

    # If the newraid request originates from a chat with a channel link then cross post the raid message to the channel
    if CHAT_CHANNEL_LINKS.get(str(chat_id)):
        bot_command_raid(str(raid_info.get('raid_id')),
                         CHAT_CHANNEL_LINKS[str(chat_id)])
示例#11
0
def channel_post_handler(channel_post: dict):

    try:

        # Do not respond to unsupported events
        if (any(x in channel_post for x in UNSUPPORTED_EVENTS)) or not (any(
                x in channel_post for x in SUPPORTED_EVENTS)):
            return

        message_id = channel_post['message_id']
        chat = channel_post['chat']
        channel_id = int(chat['id'])

        # Is the channel authorised?
        if not channel_id in AUTHORISED_CHATS:
            msg.send_message(
                'Bot found in unauthorised channel:\n{0}'.format(channel_post),
                ADMIN_CHAT_ID)
            msg.send_message('Bot not authorised for this channel.',
                             channel_id)
            return

        # Do not respond to chats with no text content
        if not 'text' in channel_post:
            return

        text = channel_post['text']

        # Finally, only respond to bot commands
        if not text.startswith('/'):
            return

        # Get the bot command and check the command is supported
        bot_command = text[1:].split(' ')[0].strip()
        bot_command_params = text[1:].replace(bot_command, '').strip()

        if not any(x == bot_command for x in SUPPORTED_COMMANDS):
            return

        if bot_command == 'raid':
            return bot_command_raid(bot_command_params, channel_id)

        msg.send_message(
            'Unhandled bot command received in channel_post_handler:\n{0}'.
            format(channel_post), ADMIN_CHAT_ID)

        return

    except Exception as e:
        raise
示例#12
0
def lambda_handler(event, context):

    try:

        # If admin tracking is on, send the event to the admin telegram chat
        if os.environ['ADMIN_TRACKING'] == 'On':
            msg.send_message('ADMIN TRACKING: {0}'.format(event),
                             ADMIN_CHAT_ID)

        # Has the trigger originated from EventBridge
        if event.get('resources'):
            if 'wokemon-garbage-collection' in event['resources'][0]:
                return gc.garbage_collection()

        # Has the trigger originated from SQS
        if event.get('Records'):
            event = event['Records'][0]
            sqs_message_id = event['messageId']

        body = json.loads(event['body'])

        # Echo the event body so it appears in CloudWatch Logs
        print(json.dumps(body))

        if 'callback_query' in body:
            return cbk.callback_query_handler(body['callback_query'])

        if 'channel_post' in body:
            return chnl.channel_post_handler(body['channel_post'])

        if 'edited_message' in body:
            return

        if 'message' in body:

            message = body['message']

            # Do not respond to unsupported events
            UNSUPPORTED_EVENTS = [
                'photo', 'document', 'voice', 'audio', 'forward_from',
                'edited_message', 'new_chat_participant',
                'left_chat_participant'
            ]
            if (any(x in message for x in UNSUPPORTED_EVENTS)):
                return

            if 'reply_to_message' in message:
                return reply.reply_to_message_handler(message)

            if 'text' in message:
                message_id = message['message_id']
                text = message['text'].strip()
                chat = message['chat']
                chat_id = chat['id']

                if 'from' in message:
                    from_obj = message['from']
                    from_id = from_obj['id']
                    from_username = raid.get_username(from_obj)
                else:
                    msg.send_message(
                        'Received a message with no from: {0}'.format(body),
                        ADMIN_CHAT_ID)
                    return

                if re.match('^/[a-z0-9]+($|\s)', text):

                    bot_command = re.match('^/[a-z0-9]+($|\s)',
                                           text)[0].strip()
                    bot_command_params = text.replace(bot_command, '').strip()

                    if bot_command == '/newraid':
                        bot_command_newraid(bot_command_params, chat_id,
                                            from_id, from_username)
                        msg.delete_message(chat_id, message_id)

                    elif bot_command == '/raid':
                        bot_command_raid(bot_command_params, chat_id)
                        msg.delete_message(chat_id, message_id)

                    elif bot_command == '/nickname':
                        bot_command_nickname(bot_command_params, chat_id,
                                             from_id, from_username)
                        msg.delete_message(chat_id, message_id)

                    elif bot_command == '/level':
                        bot_command_level(bot_command_params, chat_id, from_id,
                                          from_username)
                        msg.delete_message(chat_id, message_id)

                    elif bot_command == '/team':
                        bot_command_team(bot_command_params, chat_id, from_id,
                                         from_username)
                        msg.delete_message(chat_id, message_id)

                    else:
                        return

                return

        msg.send_message(
            'Unrecognised event received with body: {0}'.format(body),
            ADMIN_CHAT_ID)

    except pymysql.err.ProgrammingError as pe:
        msg.send_message(
            'A database error of type {0} has occured: {1}'.format(
                type(pe), pe.args), ADMIN_CHAT_ID)
        msg.send_message(
            '*\[ERROR\]* A database error has occured\. Please try again in a few minutes\.',
            chat_id, 'MarkdownV2')

    except Exception as e:
        msg.send_message(
            'An unhandled error of type {0} has occured: {1}\n\n{2}'.format(
                type(e), e.args, event), ADMIN_CHAT_ID)
        msg.send_message(
            '*\[ERROR\]* An unhandled error has occured\. Please try again in a few minutes\.',
            chat_id, 'MarkdownV2')

    finally:
        return {'statusCode': 200, 'body': json.dumps('Success.')}