Exemple #1
0
 def __init__(self, bot, update, user_data):
     self.bot = bot
     self.update = update
     self.user_data = user_data
     self.bot_constants = BotConstants()
     self.bot_variables = BotVariables()
     self.query = self.update.callback_query
     self.chosen_option = self.query.data
     self.chat_id = self.query.message.chat_id
     self.message_id = self.query.message.message_id
     self.telegram_username = self.query.message.chat.username
     self.strava_telegram_webhooks_resource = StravaTelegramWebhooksResource(
     )
     self.approve_payment_config = {
         "bot": {},
         "challenges": {
             "cadence90": {
                 "odd": {
                     "column_name": "odd_challenges"
                 },
                 "even": {
                     "column_name": "even_challenges"
                 }
             }
         }
     }
Exemple #2
0
 def __init__(self, bot, update, args):
     self.bot = bot
     self.update = update
     self.args = args
     self.bot_constants = BotConstants()
     self.bot_variables = BotVariables()
     self.strava_telegram_webhooks_resource = StravaTelegramWebhooksResource(
     )
Exemple #3
0
class HandleRegistration:

    def __init__(self, bot, update, user_data):
        self.bot = bot
        self.update = update
        self.user_data = user_data
        self.bot_variables = BotVariables()
        self.bot_constants = BotConstants()
        self.telegram_user_first_name = self.update.message.from_user.first_name
        self.telegram_username = self.update.message.from_user.username
        self.command = self.update.message.text
        self.chat_id = update.message.chat_id
        self.strava_telegram_webhooks_resource = StravaTelegramWebhooksResource()

    def next_command(self):
        if self.telegram_username:
            message = "I see that your Telegram username is: `{telegram_username}`\n\nFollow the below steps to signup:".format(
                telegram_username=self.telegram_username)
            self.strava_telegram_webhooks_resource.send_message(message)
            self.auth_and_reg()
        else:
            message = "Looks like you haven't set your Telegram username yet. Follow the above steps and click /next to continue or message {admin_user_name} for additional help.".format(
                admin_user_name=self.bot_variables.admin_user_name)
            self.update.message.reply_text(message, parse_mode="Markdown", disable_web_page_preview=True)
            self.strava_telegram_webhooks_resource.send_message(message)

    def auth_and_reg(self):
        photo_path = "scripts/commands/help/registration/strava_app_auth.PNG"
        caption = "Open the following link and login to your Strava account and click on Authorize.\n\n{registration_url}".format(
            registration_url=self.bot_variables.registration_url)
        self.bot.send_photo(chat_id=self.chat_id, photo=open(photo_path, 'rb'), caption=caption)
        photo_path = "scripts/commands/help/registration/telegram_reg.png"
        caption = "Once you Authorize, enter your Telegram username:\n\n{telegram_username}\n\nand click on Submit.\n\nOnce done, come back to this chat and click /next to continue.".format(
            telegram_username=self.telegram_username)
        self.bot.send_photo(chat_id=self.chat_id, photo=open(photo_path, 'rb'), caption=caption)
        self.strava_telegram_webhooks_resource.send_message(
            "Sent Authorize and Registration screenshots to the user.")

    def registration(self):
        message = "Hi {first_name}, Welcome to Cadence90 Bot! I will help you out in signing up for the bot.\n\n".format(
            first_name=self.telegram_user_first_name)
        if self.telegram_username:
            message += "I see that your Telegram username is: `{telegram_username}`\n\nFollow the below steps to signup:".format(
                telegram_username=self.telegram_username)
            self.update.message.reply_text(message, parse_mode="Markdown", disable_web_page_preview=True)
            self.strava_telegram_webhooks_resource.send_message(message)
            self.auth_and_reg()
        else:
            message += "You haven't set your username in Telegram yet which is required to signup for the bot. Let me show you how. Choose the type of device you are using:"
            self.update.message.reply_text(message, disable_web_page_preview=True,
                                           reply_markup=self.bot_constants.KEYBOARD_HELP_REGISTRATION)
            self.strava_telegram_webhooks_resource.send_message(message)

    def main(self):
        if self.command == "/next":
            self.next_command()
        else:
            self.registration()
Exemple #4
0
 def __init__(self, bot, update, user_data):
     self.bot = bot
     self.update = update
     self.user_data = user_data
     self.bot_variables = BotVariables()
     self.bot_constants = BotConstants()
     self.telegram_user_first_name = self.update.message.from_user.first_name
     self.telegram_username = self.update.message.from_user.username
     self.command = self.update.message.text
     self.chat_id = update.message.chat_id
     self.strava_telegram_webhooks_resource = StravaTelegramWebhooksResource()
 def __init__(self, bot, update, user_data, chosen_option):
     self.bot = bot
     self.update = update
     self.user_data = user_data
     self.bot_constants = BotConstants()
     self.query = self.update.callback_query
     self.chosen_option = chosen_option
     self.chat_id = self.query.message.chat_id
     self.message_id = self.query.message.message_id
     self.strava_telegram_webhooks_resource = StravaTelegramWebhooksResource(
     )
Exemple #6
0
class ApprovePayment:
    def __init__(self, bot, update, user_data):
        self.bot = bot
        self.update = update
        self.user_data = user_data
        self.bot_constants = BotConstants()
        self.bot_variables = BotVariables()
        self.query = self.update.callback_query
        self.chosen_option = self.query.data
        self.chat_id = self.query.message.chat_id
        self.message_id = self.query.message.message_id
        self.telegram_username = self.query.message.chat.username
        self.strava_telegram_webhooks_resource = StravaTelegramWebhooksResource(
        )
        self.approve_payment_config = {
            "bot": {},
            "challenges": {
                "cadence90": {
                    "odd": {
                        "column_name": "odd_challenges"
                    },
                    "even": {
                        "column_name": "even_challenges"
                    }
                }
            }
        }

    def process(self):
        approved_payment_details = (self.chosen_option.split("pa_",
                                                             1)[1]).split("_")
        category = approved_payment_details[0]
        company = approved_payment_details[1]
        month = approved_payment_details[2]
        athlete_id = approved_payment_details[3]
        if self.strava_telegram_webhooks_resource.approve_payment_for_challenge(
                self.approve_payment_config[category][company][month]
            ['column_name'], athlete_id):
            message = "Approved payment for [{athlete_id}](https://www.strava.com/athletes/{athlete_id}).".format(
                athlete_id=athlete_id)
            self.strava_telegram_webhooks_resource.update_challenges_stats(
                athlete_id)
        else:
            message = "Failed to approve payment for [{athlete_id}](https://www.strava.com/athletes/{athlete_id}).".format(
                athlete_id=athlete_id)
        logging.info(message)
        self.bot.edit_message_text(text=message,
                                   chat_id=self.chat_id,
                                   message_id=self.message_id,
                                   parse_mode='Markdown')
Exemple #7
0
 def __init__(self, bot, update, user_data):
     self.bot = bot
     self.update = update
     self.user_data = user_data
     self.bot_variables = BotVariables()
     self.bot_constants = BotConstants()
     self.telegram_user_first_name = self.update.message.from_user.first_name
     self.strava_telegram_webhooks_resource = StravaTelegramWebhooksResource(
     )
     self.aes_cipher = AESCipher(self.bot_variables.crypt_key_length,
                                 self.bot_variables.crypt_key)
     self.telegram_username = self.update.message.from_user.username
     self.chat_id = self.update.message.chat_id
     self.athlete_details = None
     self.registration = HandleRegistration(self.bot, self.update,
                                            self.user_data)
class AutoUpdateIndoorRide:
    def __init__(self, bot, update, user_data, chosen_option):
        self.bot = bot
        self.update = update
        self.user_data = user_data
        self.bot_constants = BotConstants()
        self.query = self.update.callback_query
        self.chosen_option = chosen_option
        self.chat_id = self.query.message.chat_id
        self.message_id = self.query.message.message_id
        self.strava_telegram_webhooks_resource = StravaTelegramWebhooksResource(
        )

    def auto_update_indoor_ride_disable(self):
        self.strava_telegram_webhooks_resource.disable_auto_update_indoor_ride(
            athlete_id=self.user_data['auto_update_indoor_ride']['athlete_id'])
        self.user_data.clear()
        message = self.bot_constants.MESSAGE_UPDATE_INDOOR_RIDE_DISABLED
        self.bot.edit_message_text(text=message,
                                   chat_id=self.chat_id,
                                   message_id=self.message_id)
        self.strava_telegram_webhooks_resource.send_message(message)

    def auto_update_indoor_ride_ignore(self):
        self.user_data.clear()
        message = self.bot_constants.MESSAGE_UPDATE_INDOOR_RIDE_DISABLE_CANCEL
        self.bot.edit_message_text(text=message,
                                   chat_id=self.chat_id,
                                   message_id=self.message_id)
        self.strava_telegram_webhooks_resource.send_message(message)

    def auto_update_indoor_ride_name_indoor_ride(self):
        self.user_data['auto_update_indoor_ride'].update(
            {'name': 'Indoor Ride'})
        self.get_bikes()

    def auto_update_indoor_ride_name_indoor_cycling(self):
        self.user_data['auto_update_indoor_ride'].update(
            {'name': 'Indoor Cycling'})
        self.get_bikes()

    def auto_update_indoor_ride_name_automatic(self):
        self.user_data['auto_update_indoor_ride'].update({'name': 'Automatic'})
        self.get_bikes()

    def auto_update_indoor_ride_name_skip(self):
        self.user_data['auto_update_indoor_ride'].update({'name': None})
        self.get_bikes()

    def get_bikes(self):
        bikes = self.strava_telegram_webhooks_resource.get_bikes_list(
            self.user_data['auto_update_indoor_ride']['athlete_token'])
        if len(bikes) > 0:
            bikes_list = []
            for sl_no in bikes:
                bikes_list += [
                    InlineKeyboardButton(
                        text=sl_no,
                        callback_data=
                        "auto_update_indoor_ride_gear_id_{gear_id}".format(
                            gear_id=bikes[sl_no]['bike_id']))
                ]
            keyboard_bikes = InlineKeyboardMarkup(inline_keyboard=[bikes_list])
            list_bikes = ""
            for sl_no in bikes:
                list_bikes += "{sl_no}. {bike_name}\n".format(
                    sl_no=sl_no, bike_name=bikes[sl_no]['bike_name'])
            self.user_data['auto_update_indoor_ride'].update(
                {'gear_id': bikes})
            self.bot.send_message(text=list_bikes, chat_id=self.chat_id)
            self.strava_telegram_webhooks_resource.send_message(list_bikes)
            message = self.bot_constants.MESSAGE_AUTO_UPDATE_INDOOR_RIDE_CHOOSE_BIKE
            self.bot.edit_message_text(text=message,
                                       chat_id=self.chat_id,
                                       message_id=self.message_id,
                                       reply_markup=keyboard_bikes)
        else:
            self.user_data['auto_update_indoor_ride'].update({'gear_id': None})
            self.auto_update_indoor_ride_setup_confirmation()

    def auto_update_indoor_ride_setup_confirmation(self):
        found = True
        if not self.user_data['auto_update_indoor_ride']['name']:
            if not self.user_data['auto_update_indoor_ride']['gear_id']:
                found = False
        self.bot.deleteMessage(self.chat_id, self.message_id)
        if found:
            configured_data = ""
            if self.user_data['auto_update_indoor_ride']['name']:
                configured_data += "Activity Name: {activity_name}\n".format(
                    activity_name=self.user_data['auto_update_indoor_ride']
                    ['name'])
            if self.user_data['auto_update_indoor_ride']['gear_id']:
                bike_name = self.strava_telegram_webhooks_resource.get_gear_name(
                    self.user_data['auto_update_indoor_ride']['athlete_token'],
                    self.user_data['auto_update_indoor_ride']['gear_id'])
                configured_data += "Bike: {bike_name}".format(
                    bike_name=bike_name)
            message = self.bot_constants.MESSAGE_AUTO_UPDATE_INDOOR_RIDE_CONFIRMATION.format(
                configuration=configured_data)
            self.bot.send_message(
                text=message,
                chat_id=self.chat_id,
                reply_markup=self.bot_constants.
                KEYBOARD_AUTO_UPDATE_INDOOR_RIDE_CONFIRMATION)
            self.strava_telegram_webhooks_resource.send_message(message)
        else:
            self.user_data.clear()
            message = self.bot_constants.MESSAGE_AUTO_UPDATE_INDOOR_RIDE_INSUFFICIENT_INFORMATION
            self.bot.send_message(text=message, chat_id=self.chat_id)
            self.strava_telegram_webhooks_resource.send_message(message)

    def auto_update_indoor_ride_update_confirm_yes(self):
        update_indoor_ride_data = dict()
        if 'name' in self.user_data['auto_update_indoor_ride']:
            update_indoor_ride_data.update(
                {'name': self.user_data['auto_update_indoor_ride']['name']})
        if 'gear_id' in self.user_data['auto_update_indoor_ride']:
            update_indoor_ride_data.update({
                'gear_id':
                self.user_data['auto_update_indoor_ride']['gear_id']
            })

        self.strava_telegram_webhooks_resource.database_write(
            self.bot_constants.QUERY_UPDATE_INDOOR_RIDE_ENABLE.format(
                update_indoor_ride_data=ujson.dumps(update_indoor_ride_data),
                chat_id=self.chat_id,
                athlete_id=self.user_data['auto_update_indoor_ride']
                ['athlete_id']))

        self.user_data.clear()
        message = self.bot_constants.MESSAGE_AUTO_UPDATE_INDOOR_RIDE_ENABLED
        self.bot.edit_message_text(text=message,
                                   chat_id=self.chat_id,
                                   message_id=self.message_id)
        self.strava_telegram_webhooks_resource.send_message(message)

    def auto_update_indoor_ride_confirm_no(self):
        self.user_data.clear()
        message = self.bot_constants.MESSAGE_AUTO_UPDATE_INDOOR_RIDE_CANCELLED
        self.bot.edit_message_text(text=message,
                                   chat_id=self.chat_id,
                                   message_id=self.message_id)
        self.strava_telegram_webhooks_resource.send_message(message)

    def exit_button(self):
        self.user_data.clear()
        message = self.bot_constants.MESSAGE_EXIT_BUTTON
        self.bot.edit_message_text(text=message,
                                   chat_id=self.chat_id,
                                   message_id=self.message_id)
        self.strava_telegram_webhooks_resource.send_message(message)

    def process(self):
        if 'auto_update_indoor_ride_gear_id_' in self.chosen_option:
            gear_id = self.chosen_option.split(
                "auto_update_indoor_ride_gear_id_")[1]
            self.user_data['auto_update_indoor_ride']['gear_id'] = gear_id
            self.chosen_option = "auto_update_indoor_ride_setup_confirmation"

        options = defaultdict(
            lambda: self.exit_button, {
                'auto_update_indoor_ride_disable':
                self.auto_update_indoor_ride_disable,
                'auto_update_indoor_ride_ignore':
                self.auto_update_indoor_ride_ignore,
                'auto_update_indoor_ride_name_indoor_ride':
                self.auto_update_indoor_ride_name_indoor_ride,
                'auto_update_indoor_ride_name_indoor_cycling':
                self.auto_update_indoor_ride_name_indoor_cycling,
                'auto_update_indoor_ride_name_automatic':
                self.auto_update_indoor_ride_name_automatic,
                'auto_update_indoor_ride_name_skip':
                self.auto_update_indoor_ride_name_skip,
                'auto_update_indoor_ride_setup_confirmation':
                self.auto_update_indoor_ride_setup_confirmation,
                'auto_update_indoor_ride_update_confirm_yes':
                self.auto_update_indoor_ride_update_confirm_yes,
                'auto_update_indoor_ride_confirm_no':
                self.auto_update_indoor_ride_confirm_no
            })

        options[self.chosen_option]()
Exemple #9
0
 def __init__(self, bot, update):
     self.bot = bot
     self.update = update
     self.operations = Operations()
     self.strava_telegram_webhooks_resource = StravaTelegramWebhooksResource(
     )
Exemple #10
0
class Challenges2020:
    def __init__(self, bot, update):
        self.bot = bot
        self.update = update
        self.operations = Operations()
        self.strava_telegram_webhooks_resource = StravaTelegramWebhooksResource(
        )

    def get_strava_data(self, athlete_id):
        return self.strava_telegram_webhooks_resource.get_athlete_stats_by_athlete_id(
            athlete_id)

    def cs_vs_sa(self):
        stats_cr = self.get_strava_data(877837)
        stats_sa = self.get_strava_data(5577083)

        cr_at_distance = round(
            self.operations.meters_to_kilometers(
                float(stats_cr['ride_at_distance'])), 2)
        sa_at_distance = round(
            self.operations.meters_to_kilometers(
                float(stats_sa['ride_at_distance'])), 2)

        cr_ytd_distance = round(
            self.operations.meters_to_kilometers(
                float(stats_cr['ride_ytd_distance'])), 2)
        sa_ytd_distance = round(
            self.operations.meters_to_kilometers(
                float(stats_sa['ride_ytd_distance'])), 2)

        cr_at_hundreds = int(stats_cr['ride_at_hundred'])
        sa_at_hundreds = int(stats_sa['ride_at_hundred'])

        message = "*Chethan Ram vs Satish Addanki*\n\n\n"

        if cr_at_distance > sa_at_distance:
            at_name = "Chethan Ram"
            at_distance = cr_at_distance - sa_at_distance
        else:
            at_name = "Satish Addanki"
            at_distance = sa_at_distance - cr_at_distance

        at_distance = "{0:.2f}".format(round(at_distance, 2))

        if cr_ytd_distance > sa_ytd_distance:
            ytd_name = "Chethan Ram"
            ytd_distance = cr_ytd_distance - sa_ytd_distance
        else:
            ytd_name = "Satish Addanki"
            ytd_distance = sa_ytd_distance - cr_ytd_distance

        ytd_distance = "{0:.2f}".format(round(ytd_distance, 2))

        if cr_at_hundreds > sa_at_hundreds:
            name = "Chethan Ram"
            hundreds = cr_at_hundreds - sa_at_hundreds
        else:
            name = "Satish Addanki"
            hundreds = sa_at_hundreds - cr_at_hundreds

        message += "_Distance All Time_: {at_name} leads by {at_distance} km\n\n".format(
            at_name=at_name, at_distance=at_distance)
        message += "_Distance Year to Date_: {ytd_name} leads by {ytd_distance} km\n\n".format(
            ytd_name=ytd_name, ytd_distance=ytd_distance)
        message += "_Hundreds_: {name} leads by {hundreds} hundreds\n\n\n".format(
            name=name, hundreds=hundreds)

        message += "*Chethan Ram*:\n\nDistance All Time: {cr_at_distance} km\nDistance Year to Date: {cr_ytd_distance} km\nTotal Hundreds: {cr_at_hundreds}\n\n".format(
            cr_at_distance=cr_at_distance,
            cr_ytd_distance=cr_ytd_distance,
            cr_at_hundreds=cr_at_hundreds)
        message += "*Satish Addankni*:\n\nDistance All Time: {sa_at_distance} km\nDistance Year to Date: {sa_ytd_distance} km\nTotal Hundreds: {sa_at_hundreds}\n\n".format(
            sa_at_distance=sa_at_distance,
            sa_ytd_distance=sa_ytd_distance,
            sa_at_hundreds=sa_at_hundreds)

        return message

    def main(self):
        message = self.cs_vs_sa()
        self.update.message.reply_text(message, parse_mode="Markdown")
        self.strava_telegram_webhooks_resource.send_message(message)
Exemple #11
0
 def __init__(self):
     self.bot_variables = BotVariables()
     self.strava_telegram_webhooks_resource = StravaTelegramWebhooksResource(
     )
Exemple #12
0
class HandleCommandArgs:
    def __init__(self, bot, update, args):
        self.bot = bot
        self.update = update
        self.args = args
        self.bot_constants = BotConstants()
        self.bot_variables = BotVariables()
        self.strava_telegram_webhooks_resource = StravaTelegramWebhooksResource(
        )

    def default(self):
        pass

    def token_command(self):
        if len(self.args) == 1:
            athlete_id = self.args[0]
            athlete_details = self.strava_telegram_webhooks_resource.get_athlete(
                athlete_id)
            if athlete_details:
                athlete_token = athlete_details['athlete_token']
                message = "Token for {athlete_id}: `{athlete_token}`".format(
                    athlete_id=athlete_id, athlete_token=athlete_token)
            else:
                message = "Athlete ID {athlete_id} not found.".format(
                    athlete_id=athlete_id)
            self.update.message.reply_text(message,
                                           parse_mode="Markdown",
                                           disable_web_page_preview=True)
            self.strava_telegram_webhooks_resource.send_message(message)
        else:
            logging.warning("More than 1 arguments passed for /token. Args %s",
                            self.args)

    def activate_athlete_command(self):
        if len(self.args) == 1:
            athlete_id = self.args[0]
            if self.strava_telegram_webhooks_resource.activate_flag_athlete(
                    athlete_id=athlete_id):
                message = "Successfully activated {athlete_id}.".format(
                    athlete_id=athlete_id)
            else:
                message = "Failed to activate {athlete_id}.".format(
                    athlete_id=athlete_id)
            self.update.message.reply_text(message,
                                           parse_mode="Markdown",
                                           disable_web_page_preview=True)
            self.strava_telegram_webhooks_resource.send_message(message)
        else:
            logging.warning(
                "More than 1 arguments passed for /activate. Args %s",
                self.args)

    def deactivate_athlete_command(self):
        if len(self.args) == 1:
            athlete_id = self.args[0]
            if self.strava_telegram_webhooks_resource.deactivate_flag_athlete(
                    athlete_id=athlete_id):
                message = "Successfully deactivated {athlete_id}.".format(
                    athlete_id=athlete_id)
            else:
                message = "Failed to deactivate {athlete_id}.".format(
                    athlete_id=athlete_id)
            self.update.message.reply_text(message,
                                           parse_mode="Markdown",
                                           disable_web_page_preview=True)
            self.strava_telegram_webhooks_resource.send_message(message)
        else:
            logging.warning(
                "More than 1 arguments passed for /deactivate. Args %s",
                self.args)

    def update_stats_command(self):
        if len(self.args) == 1:
            athlete_id = self.args[0]
            if self.strava_telegram_webhooks_resource.update_stats(athlete_id):
                message = "Updating stats for {}..".format(athlete_id)
            else:
                message = "Failed to trigger update stats for {}".format(
                    athlete_id)
            self.update.message.reply_text(message,
                                           parse_mode="Markdown",
                                           disable_web_page_preview=True)
            self.strava_telegram_webhooks_resource.send_message(message)
        else:
            logging.warning(
                "More than 1 arguments passed for /deactivate. Args %s",
                self.args)

    def challenges_refresh_stats_command(self):
        if len(self.args) == 1:
            athlete_id = self.args[0]
            message = self.bot_constants.MESSAGE_UPDATE_STATS_CHALLENGES_FAILED
            if self.strava_telegram_webhooks_resource.update_challenges_stats(
                    athlete_id):
                message = self.bot_constants.MESSAGE_UPDATE_STATS_CHALLENGES_SUCCESS
            self.update.message.reply_text(message,
                                           parse_mode="Markdown",
                                           disable_web_page_preview=True)
            self.strava_telegram_webhooks_resource.send_message(message)
        else:
            logging.warning(
                "More than 1 arguments passed for /deactivate. Args %s",
                self.args)

    def challenges_deauth_command(self):
        if len(self.args) == 1:
            athlete_id = self.args[0]
            if self.strava_telegram_webhooks_resource.challenges_deauth_athlete(
                    athlete_id):
                message = "Successfully deauthorised {athlete_id} from challenges".format(
                    athlete_id=athlete_id)
            else:
                message = "Failed to deauthorise {athlete_id} from challenges".format(
                    athlete_id=athlete_id)
            self.update.message.reply_text(message,
                                           parse_mode="Markdown",
                                           disable_web_page_preview=True)
            self.strava_telegram_webhooks_resource.send_message(message)
        else:
            logging.warning(
                "More than 1 arguments passed for /deactivate. Args %s",
                self.args)

    def process(self):
        command = self.update.message.text.split(' ', 1)[0]

        options = defaultdict(
            lambda: self.default, {
                '/token': self.token_command,
                '/activate': self.activate_athlete_command,
                '/deactivate': self.deactivate_athlete_command,
                '/update': self.update_stats_command,
                '/challenges_refresh_stats':
                self.challenges_refresh_stats_command,
                '/challenges_deauth': self.challenges_deauth_command
            })

        options[command]()
Exemple #13
0
class HandleCommands:
    def __init__(self, bot, update, user_data):
        self.bot = bot
        self.update = update
        self.user_data = user_data
        self.bot_variables = BotVariables()
        self.bot_constants = BotConstants()
        self.telegram_user_first_name = self.update.message.from_user.first_name
        self.strava_telegram_webhooks_resource = StravaTelegramWebhooksResource(
        )
        self.aes_cipher = AESCipher(self.bot_variables.crypt_key_length,
                                    self.bot_variables.crypt_key)
        self.telegram_username = self.update.message.from_user.username
        self.chat_id = self.update.message.chat_id
        self.athlete_details = None
        self.registration = HandleRegistration(self.bot, self.update,
                                               self.user_data)

    def update_user_chat_id(self):
        if not self.athlete_details['chat_id'] or int(
                self.athlete_details['chat_id']) != int(self.chat_id):
            self.strava_telegram_webhooks_resource.update_chat_id(
                chat_id=self.chat_id,
                athlete_id=self.athlete_details['athlete_id'])

    def stats_command(self):
        self.user_data.clear()
        self.update_user_chat_id()
        stats = ProcessStats(self.update)
        stats.process()

    def refresh_command(self):
        self.user_data.clear()
        self.update_user_chat_id()
        message = self.bot_constants.MESSAGE_UPDATE_STATS_FAILED.format(
            first_name=self.telegram_user_first_name)
        if self.strava_telegram_webhooks_resource.update_stats(
                self.athlete_details['athlete_id']):
            message = self.bot_constants.MESSAGE_UPDATE_STATS_STARTED.format(
                first_name=self.telegram_user_first_name)
        self.update.message.reply_text(message,
                                       parse_mode="Markdown",
                                       disable_web_page_preview=True)
        self.strava_telegram_webhooks_resource.send_message(message)

    def refresh_all_stats_command(self):
        self.user_data.clear()
        message = self.bot_constants.MESSAGE_UPDATE_STATS_FAILED.format(
            first_name=self.telegram_user_first_name)
        if self.strava_telegram_webhooks_resource.update_all_stats():
            message = self.bot_constants.MESSAGE_UPDATE_STATS_STARTED_ALL.format(
                first_name=self.telegram_user_first_name)
        self.update.message.reply_text(message,
                                       parse_mode="Markdown",
                                       disable_web_page_preview=True)
        self.strava_telegram_webhooks_resource.send_message(message)

    def challenges_refresh_all_stats_command(self):
        self.user_data.clear()
        message = self.bot_constants.MESSAGE_UPDATE_STATS_CHALLENGES_FAILED.format(
            first_name=self.telegram_user_first_name)
        if self.strava_telegram_webhooks_resource.update_challenges_all_stats(
        ):
            message = self.bot_constants.MESSAGE_UPDATE_STATS_CHALLENGES_STARTED.format(
                first_name=self.telegram_user_first_name)
        self.update.message.reply_text(message,
                                       parse_mode="Markdown",
                                       disable_web_page_preview=True)
        self.strava_telegram_webhooks_resource.send_message(message)

    def all_athletes_command(self):
        self.user_data.clear()
        message = self.bot_constants.MESSAGE_FETCHING_REGISTERED_ATHLETES.format(
            first_name=self.telegram_user_first_name)
        self.update.message.reply_text(message,
                                       parse_mode="Markdown",
                                       disable_web_page_preview=True)
        self.strava_telegram_webhooks_resource.send_message(message)
        all_athletes = self.strava_telegram_webhooks_resource.database_read_all(
            self.bot_constants.QUERY_GET_ATHLETES)
        sl_no = 0
        messages = list()
        names = "*List of registered athletes:*\n\n"
        for athlete in all_athletes:
            sl_no += 1
            names += "{sl_no}. [{name}](https://www.strava.com/athletes/{athlete_id})\n".format(
                sl_no=sl_no, name=athlete[0], athlete_id=athlete[1])
            if sl_no % 25 == 0:
                messages.append(names)
                names = "*List of registered athletes:*\n\n"
        messages.append(names)
        for name in messages:
            if name != "*List of registered athletes:*\n\n":
                self.update.message.reply_text(name,
                                               parse_mode="Markdown",
                                               disable_web_page_preview=True)
                self.strava_telegram_webhooks_resource.send_message(name)

    def challenges_even_athletes(self):
        self.user_data.clear()
        message = self.bot_constants.MESSAGE_FETCHING_REGISTERED_ATHLETES_EVEN_CHALLENGES.format(
            first_name=self.telegram_user_first_name)
        self.update.message.reply_text(message,
                                       parse_mode="Markdown",
                                       disable_web_page_preview=True)
        self.strava_telegram_webhooks_resource.send_message(message)
        results = self.strava_telegram_webhooks_resource.get_even_challenges_athletes(
        )
        for result in results:
            self.update.message.reply_text(result,
                                           parse_mode="Markdown",
                                           disable_web_page_preview=True)
            self.strava_telegram_webhooks_resource.send_message(result)

    def challenges_odd_athletes(self):
        self.user_data.clear()
        message = self.bot_constants.MESSAGE_FETCHING_REGISTERED_ATHLETES_ODD_CHALLENGES.format(
            first_name=self.telegram_user_first_name)
        self.update.message.reply_text(message,
                                       parse_mode="Markdown",
                                       disable_web_page_preview=True)
        self.strava_telegram_webhooks_resource.send_message(message)
        results = self.strava_telegram_webhooks_resource.get_odd_challenges_athletes(
        )
        for result in results:
            self.update.message.reply_text(result,
                                           parse_mode="Markdown",
                                           disable_web_page_preview=True)
            self.strava_telegram_webhooks_resource.send_message(result)

    def activity_summary_command(self):
        self.user_data.clear()
        self.user_data['ride_summary'] = {
            'athlete_id': self.athlete_details['athlete_id']
        }
        if self.athlete_details['enable_activity_summary']:
            message = self.bot_constants.MESSAGE_ACTIVITY_SUMMARY_SHOULD_DISABLE.format(
                first_name=self.telegram_user_first_name)
            reply_markup = self.bot_constants.KEYBOARD_ACTIVITY_SUMMARY_DISABLE_CONFIRMATION

        else:
            message = self.bot_constants.MESSAGE_ACTIVITY_SUMMARY_CONFIRMATION.format(
                first_name=self.telegram_user_first_name)
            reply_markup = self.bot_constants.KEYBOARD_ENABLE_ACTIVITY_SUMMARY_CONFIRMATION

        self.update.message.reply_text(message, reply_markup=reply_markup)
        self.strava_telegram_webhooks_resource.send_message(message)

    def auto_update_indoor_ride_command(self):
        self.user_data.clear()
        self.user_data['auto_update_indoor_ride'] = {
            'athlete_id': self.athlete_details['athlete_id'],
            'athlete_token': self.athlete_details['athlete_token']
        }
        if self.athlete_details['update_indoor_ride']:
            configured_data = ""
            if self.athlete_details['update_indoor_ride_data']['name']:
                configured_data += "\nActivity Name: {activity_name}".format(
                    activity_name=self.
                    athlete_details['update_indoor_ride_data']['name'])
            if self.athlete_details['update_indoor_ride_data']['gear_id']:
                bike_name = self.strava_telegram_webhooks_resource.get_gear_name(
                    self.athlete_details['athlete_token'],
                    self.athlete_details['update_indoor_ride_data']['gear_id'])
                configured_data += "\nBike: {bike_name}".format(
                    bike_name=bike_name)

            message = self.bot_constants.MESSAGE_SHOULD_UPDATE_INDOOR_RIDE_DISABLE.format(
                first_name=self.telegram_user_first_name,
                configuration=configured_data)
            reply_markup = self.bot_constants.KEYBOARD_AUTO_UPDATE_INDOOR_RIDE_DISABLE_PROMPT
        else:
            message = self.bot_constants.MESSAGE_UPDATE_INDOOR_RIDE_CHOOSE_ACTIVITY_NAME.format(
                first_name=self.telegram_user_first_name)
            reply_markup = self.bot_constants.KEYBOARD_AUTO_UPDATE_INDOOR_RIDE_NAME

        self.update.message.reply_text(message, reply_markup=reply_markup)
        self.strava_telegram_webhooks_resource.send_message(message)

    def challenges_hits_reset(self):
        self.user_data.clear()
        result = self.strava_telegram_webhooks_resource.challenges_hits_reset()
        if result:
            message = self.bot_constants.MESSAGE_CHALLENGES_HITS_RESET_SUCCESS.format(
                first_name=self.telegram_user_first_name)
        else:
            message = self.bot_constants.MESSAGE_CHALLENGES_HITS_RESET_FAIL.format(
                first_name=self.telegram_user_first_name)
        self.update.message.reply_text(message,
                                       parse_mode="Markdown",
                                       disable_web_page_preview=True)
        self.strava_telegram_webhooks_resource.send_message(message)

    def help_command(self):
        self.user_data.clear()
        self.update_user_chat_id()
        message = self.bot_constants.MESSAGE_HELP_COMMANDS
        self.update.message.reply_text(message)
        self.strava_telegram_webhooks_resource.send_message(
            "Sent help commands.")

    def cancel_command(self):
        self.user_data.clear()
        message = self.bot_constants.MESSAGE_CANCEL_CURRENT_OPERATION
        self.update.message.reply_text(message)
        self.strava_telegram_webhooks_resource.send_message(message)

    def process(self):
        self.bot.send_chat_action(chat_id=self.chat_id,
                                  action=telegram.ChatAction.TYPING)
        self.athlete_details = self.strava_telegram_webhooks_resource.get_athlete_by_telegram_username(
            self.telegram_username)
        if self.athlete_details:
            command = self.update.message.text
            options = defaultdict(
                lambda: self.help_command, {
                    '/start': self.help_command,
                    '/next': self.help_command,
                    '/stats': self.stats_command,
                    '/refresh_stats': self.refresh_command,
                    '/auto_update_indoor_ride':
                    self.auto_update_indoor_ride_command,
                    '/cancel': self.cancel_command,
                    '/refresh_all_stats': self.refresh_all_stats_command,
                    '/all_athletes': self.all_athletes_command,
                    '/challenges_even_athletes': self.challenges_even_athletes,
                    '/challenges_odd_athletes': self.challenges_odd_athletes,
                    '/challenges_refresh_all_stats':
                    self.challenges_refresh_all_stats_command,
                    '/challenges_hits_reset': self.challenges_hits_reset,
                    '/activity_summary': self.activity_summary_command,
                    '/help': self.help_command
                })
            options[command]()
        else:
            self.registration.main()
Exemple #14
0
class Stats:
    def __init__(self, bot, update, user_data):
        self.bot = bot
        self.update = update
        self.user_data = user_data
        self.bot_constants = BotConstants()
        self.query = self.update.callback_query
        self.chosen_option = self.query.data
        self.chat_id = self.query.message.chat_id
        self.message_id = self.query.message.message_id
        self.telegram_username = self.query.message.chat.username
        self.strava_telegram_webhooks_resource = StravaTelegramWebhooksResource(
        )
        self.iron_cache_resource = IronCacheResource()

    def get_strava_data(self):
        strava_data = self.iron_cache_resource.get_cache(
            "stats", self.telegram_username)
        if not strava_data:
            logging.warning(
                "Failed to fetch from cache! Falling back to database..")
            strava_data = self.strava_telegram_webhooks_resource.get_athlete_stats(
                self.telegram_username)
            self.iron_cache_resource.put_cache("stats", self.telegram_username,
                                               strava_data)

        return strava_data

    def stats_ride_button(self):
        message = self.bot_constants.MESSAGE_STATS_SUB_KEYBOARD_MENU
        self.bot.edit_message_text(
            text=message,
            chat_id=self.chat_id,
            message_id=self.message_id,
            reply_markup=self.bot_constants.KEYBOARD_STATS_RIDE_KEYBOARD_MENU)

    def stats_ride_all_time_button(self):
        format_stats = FormatStats(self.get_strava_data())
        message = format_stats.ride_stats("All Time Stats", "at")
        self.bot.edit_message_text(text=message,
                                   chat_id=self.chat_id,
                                   message_id=self.message_id,
                                   parse_mode="Markdown",
                                   disable_web_page_preview=True)
        self.strava_telegram_webhooks_resource.send_message(message)
        message = self.bot_constants.MESSAGE_STATS_MAIN_KEYBOARD_MENU
        self.bot.send_message(
            text=message,
            chat_id=self.chat_id,
            reply_markup=self.bot_constants.KEYBOARD_STATS_MAIN_KEYBOARD_MENU)

    def stats_ride_ytd_button(self):
        format_stats = FormatStats(self.get_strava_data())
        message = format_stats.ride_stats("Year to Date Stats", "ytd")
        self.bot.edit_message_text(text=message,
                                   chat_id=self.chat_id,
                                   message_id=self.message_id,
                                   parse_mode="Markdown",
                                   disable_web_page_preview=True)
        self.strava_telegram_webhooks_resource.send_message(message)
        message = self.bot_constants.MESSAGE_STATS_MAIN_KEYBOARD_MENU
        self.bot.send_message(
            text=message,
            chat_id=self.chat_id,
            reply_markup=self.bot_constants.KEYBOARD_STATS_MAIN_KEYBOARD_MENU)

    def stats_ride_py_button(self):
        format_stats = FormatStats(self.get_strava_data())
        message = format_stats.ride_stats("Previous Year Stats", "py")
        self.bot.edit_message_text(text=message,
                                   chat_id=self.chat_id,
                                   message_id=self.message_id,
                                   parse_mode="Markdown",
                                   disable_web_page_preview=True)
        self.strava_telegram_webhooks_resource.send_message(message)
        message = self.bot_constants.MESSAGE_STATS_MAIN_KEYBOARD_MENU
        self.bot.send_message(
            text=message,
            chat_id=self.chat_id,
            reply_markup=self.bot_constants.KEYBOARD_STATS_MAIN_KEYBOARD_MENU)

    def stats_ride_cm_button(self):
        format_stats = FormatStats(self.get_strava_data())
        message = format_stats.ride_stats("Current Month Stats", "cm")
        self.bot.edit_message_text(text=message,
                                   chat_id=self.chat_id,
                                   message_id=self.message_id,
                                   parse_mode="Markdown",
                                   disable_web_page_preview=True)
        self.strava_telegram_webhooks_resource.send_message(message)
        message = self.bot_constants.MESSAGE_STATS_MAIN_KEYBOARD_MENU
        self.bot.send_message(
            text=message,
            chat_id=self.chat_id,
            reply_markup=self.bot_constants.KEYBOARD_STATS_MAIN_KEYBOARD_MENU)

    def stats_ride_pm_button(self):
        format_stats = FormatStats(self.get_strava_data())
        message = format_stats.ride_stats("Previous Month Stats", "pm")
        self.bot.edit_message_text(text=message,
                                   chat_id=self.chat_id,
                                   message_id=self.message_id,
                                   parse_mode="Markdown",
                                   disable_web_page_preview=True)
        self.strava_telegram_webhooks_resource.send_message(message)
        message = self.bot_constants.MESSAGE_STATS_MAIN_KEYBOARD_MENU
        self.bot.send_message(
            text=message,
            chat_id=self.chat_id,
            reply_markup=self.bot_constants.KEYBOARD_STATS_MAIN_KEYBOARD_MENU)

    def stats_run_button(self):
        message = self.bot_constants.MESSAGE_STATS_SUB_KEYBOARD_MENU
        self.bot.edit_message_text(
            text=message,
            chat_id=self.chat_id,
            message_id=self.message_id,
            reply_markup=self.bot_constants.KEYBOARD_STATS_RUN_KEYBOARD_MENU)

    def stats_run_all_time_button(self):
        format_stats = FormatStats(self.get_strava_data())
        message = format_stats.run_stats("All Time Stats", "at")
        self.bot.edit_message_text(text=message,
                                   chat_id=self.chat_id,
                                   message_id=self.message_id,
                                   parse_mode="Markdown",
                                   disable_web_page_preview=True)
        self.strava_telegram_webhooks_resource.send_message(message)
        message = self.bot_constants.MESSAGE_STATS_MAIN_KEYBOARD_MENU
        self.bot.send_message(
            text=message,
            chat_id=self.chat_id,
            reply_markup=self.bot_constants.KEYBOARD_STATS_MAIN_KEYBOARD_MENU)

    def stats_run_ytd_button(self):
        format_stats = FormatStats(self.get_strava_data())
        message = format_stats.run_stats("Year to Date Stats", "ytd")
        self.bot.edit_message_text(text=message,
                                   chat_id=self.chat_id,
                                   message_id=self.message_id,
                                   parse_mode="Markdown",
                                   disable_web_page_preview=True)
        self.strava_telegram_webhooks_resource.send_message(message)
        message = self.bot_constants.MESSAGE_STATS_MAIN_KEYBOARD_MENU
        self.bot.send_message(
            text=message,
            chat_id=self.chat_id,
            reply_markup=self.bot_constants.KEYBOARD_STATS_MAIN_KEYBOARD_MENU)

    def stats_run_py_button(self):
        format_stats = FormatStats(self.get_strava_data())
        message = format_stats.run_stats("Previous Year Stats", "py")
        self.bot.edit_message_text(text=message,
                                   chat_id=self.chat_id,
                                   message_id=self.message_id,
                                   parse_mode="Markdown",
                                   disable_web_page_preview=True)
        self.strava_telegram_webhooks_resource.send_message(message)
        message = self.bot_constants.MESSAGE_STATS_MAIN_KEYBOARD_MENU
        self.bot.send_message(
            text=message,
            chat_id=self.chat_id,
            reply_markup=self.bot_constants.KEYBOARD_STATS_MAIN_KEYBOARD_MENU)

    def stats_run_cm_button(self):
        format_stats = FormatStats(self.get_strava_data())
        message = format_stats.run_stats("Current Month Stats", "cm")
        self.bot.edit_message_text(text=message,
                                   chat_id=self.chat_id,
                                   message_id=self.message_id,
                                   parse_mode="Markdown",
                                   disable_web_page_preview=True)
        self.strava_telegram_webhooks_resource.send_message(message)
        message = self.bot_constants.MESSAGE_STATS_MAIN_KEYBOARD_MENU
        self.bot.send_message(
            text=message,
            chat_id=self.chat_id,
            reply_markup=self.bot_constants.KEYBOARD_STATS_MAIN_KEYBOARD_MENU)

    def stats_run_pm_button(self):
        format_stats = FormatStats(self.get_strava_data())
        message = format_stats.run_stats("Previous Month", "pm")
        self.bot.edit_message_text(text=message,
                                   chat_id=self.chat_id,
                                   message_id=self.message_id,
                                   parse_mode="Markdown",
                                   disable_web_page_preview=True)
        self.strava_telegram_webhooks_resource.send_message(message)
        message = self.bot_constants.MESSAGE_STATS_MAIN_KEYBOARD_MENU
        self.bot.send_message(
            text=message,
            chat_id=self.chat_id,
            reply_markup=self.bot_constants.KEYBOARD_STATS_MAIN_KEYBOARD_MENU)

    def stats_swim_button(self):
        message = self.bot_constants.MESSAGE_STATS_SUB_KEYBOARD_MENU
        self.bot.edit_message_text(
            text=message,
            chat_id=self.chat_id,
            message_id=self.message_id,
            reply_markup=self.bot_constants.KEYBOARD_STATS_SWIM_KEYBOARD_MENU)

    def stats_swim_all_time_button(self):
        format_stats = FormatStats(self.get_strava_data())
        message = format_stats.swim_stats("All Time Stats", "at")
        self.bot.edit_message_text(text=message,
                                   chat_id=self.chat_id,
                                   message_id=self.message_id,
                                   parse_mode="Markdown",
                                   disable_web_page_preview=True)
        self.strava_telegram_webhooks_resource.send_message(message)
        message = self.bot_constants.MESSAGE_STATS_MAIN_KEYBOARD_MENU
        self.bot.send_message(
            text=message,
            chat_id=self.chat_id,
            reply_markup=self.bot_constants.KEYBOARD_STATS_MAIN_KEYBOARD_MENU)

    def stats_swim_ytd_button(self):
        format_stats = FormatStats(self.get_strava_data())
        message = format_stats.swim_stats("Year to Date Stats", "ytd")
        self.bot.edit_message_text(text=message,
                                   chat_id=self.chat_id,
                                   message_id=self.message_id,
                                   parse_mode="Markdown",
                                   disable_web_page_preview=True)
        self.strava_telegram_webhooks_resource.send_message(message)
        message = self.bot_constants.MESSAGE_STATS_MAIN_KEYBOARD_MENU
        self.bot.send_message(
            text=message,
            chat_id=self.chat_id,
            reply_markup=self.bot_constants.KEYBOARD_STATS_MAIN_KEYBOARD_MENU)

    def stats_swim_py_button(self):
        format_stats = FormatStats(self.get_strava_data())
        message = format_stats.swim_stats("Previous Year Stats", "py")
        self.bot.edit_message_text(text=message,
                                   chat_id=self.chat_id,
                                   message_id=self.message_id,
                                   parse_mode="Markdown",
                                   disable_web_page_preview=True)
        self.strava_telegram_webhooks_resource.send_message(message)
        message = self.bot_constants.MESSAGE_STATS_MAIN_KEYBOARD_MENU
        self.bot.send_message(
            text=message,
            chat_id=self.chat_id,
            reply_markup=self.bot_constants.KEYBOARD_STATS_MAIN_KEYBOARD_MENU)

    def stats_swim_cm_button(self):
        format_stats = FormatStats(self.get_strava_data())
        message = format_stats.swim_stats("Current Month Stats", "cm")
        self.bot.edit_message_text(text=message,
                                   chat_id=self.chat_id,
                                   message_id=self.message_id,
                                   parse_mode="Markdown",
                                   disable_web_page_preview=True)
        self.strava_telegram_webhooks_resource.send_message(message)
        message = self.bot_constants.MESSAGE_STATS_MAIN_KEYBOARD_MENU
        self.bot.send_message(
            text=message,
            chat_id=self.chat_id,
            reply_markup=self.bot_constants.KEYBOARD_STATS_MAIN_KEYBOARD_MENU)

    def stats_swim_pm_button(self):
        format_stats = FormatStats(self.get_strava_data())
        message = format_stats.swim_stats("Previous Month Stats", "pm")
        self.bot.edit_message_text(text=message,
                                   chat_id=self.chat_id,
                                   message_id=self.message_id,
                                   parse_mode="Markdown",
                                   disable_web_page_preview=True)
        self.strava_telegram_webhooks_resource.send_message(message)
        message = self.bot_constants.MESSAGE_STATS_MAIN_KEYBOARD_MENU
        self.bot.send_message(
            text=message,
            chat_id=self.chat_id,
            reply_markup=self.bot_constants.KEYBOARD_STATS_MAIN_KEYBOARD_MENU)

    def back_button(self):
        message = self.bot_constants.MESSAGE_STATS_MAIN_KEYBOARD_MENU
        self.bot.edit_message_text(
            text=message,
            chat_id=self.chat_id,
            message_id=self.message_id,
            reply_markup=self.bot_constants.KEYBOARD_STATS_MAIN_KEYBOARD_MENU)

    def exit_button(self):
        self.user_data.clear()
        message = self.bot_constants.MESSAGE_EXIT_BUTTON
        self.bot.edit_message_text(text=message,
                                   chat_id=self.chat_id,
                                   message_id=self.message_id)
        self.strava_telegram_webhooks_resource.send_message(message)

    def process(self):
        options = defaultdict(
            lambda: self.exit_button, {
                'stats_ride': self.stats_ride_button,
                'stats_ride_all_time': self.stats_ride_all_time_button,
                'stats_ride_ytd': self.stats_ride_ytd_button,
                'stats_ride_py': self.stats_ride_py_button,
                'stats_ride_cm': self.stats_ride_cm_button,
                'stats_ride_pm': self.stats_ride_pm_button,
                'stats_run': self.stats_run_button,
                'stats_run_all_time': self.stats_run_all_time_button,
                'stats_run_ytd': self.stats_run_ytd_button,
                'stats_run_py': self.stats_run_py_button,
                'stats_run_cm': self.stats_run_cm_button,
                'stats_run_pm': self.stats_run_pm_button,
                'stats_swim': self.stats_swim_button,
                'stats_swim_all_time': self.stats_swim_all_time_button,
                'stats_swim_ytd': self.stats_swim_ytd_button,
                'stats_swim_py': self.stats_swim_py_button,
                'stats_swim_cm': self.stats_swim_cm_button,
                'stats_swim_pm': self.stats_swim_pm_button,
                'stats_back': self.back_button,
                'stats_exit': self.exit_button
            })

        options[self.chosen_option]()
class ActivitySummary:
    def __init__(self, bot, update, user_data):
        self.bot = bot
        self.update = update
        self.user_data = user_data
        self.bot_constants = BotConstants()
        self.query = self.update.callback_query
        self.chosen_option = self.query.data
        self.chat_id = self.query.message.chat_id
        self.message_id = self.query.message.message_id
        self.telegram_username = self.query.message.chat.username
        self.strava_telegram_webhooks_resource = StravaTelegramWebhooksResource(
        )

    def activity_summary_enable_button(self):
        if self.strava_telegram_webhooks_resource.enable_activity_summary(
                chat_id=self.chat_id,
                athlete_id=self.user_data['ride_summary']['athlete_id']):
            self.user_data.clear()
            message = self.bot_constants.MESSAGE_ACTIVITY_SUMMARY_ENABLED
            self.bot.edit_message_text(text=message,
                                       chat_id=self.chat_id,
                                       message_id=self.message_id)
            self.strava_telegram_webhooks_resource.send_message(message)

    def activity_summary_disable_button(self):
        self.strava_telegram_webhooks_resource.disable_activity_summary(
            athlete_id=self.user_data['ride_summary']['athlete_id'])
        self.user_data.clear()
        message = self.bot_constants.MESSAGE_ACTIVITY_SUMMARY_DISABLED
        self.bot.edit_message_text(text=message,
                                   chat_id=self.chat_id,
                                   message_id=self.message_id)
        self.strava_telegram_webhooks_resource.send_message(message)

    def activity_summary_ignore_button(self):
        self.user_data.clear()
        message = self.bot_constants.MESSAGE_ACTIVITY_SUMMARY_IGNORE
        self.bot.edit_message_text(text=message,
                                   chat_id=self.chat_id,
                                   message_id=self.message_id)
        self.strava_telegram_webhooks_resource.send_message(message)

    def activity_summary_disable_ignore_button(self):
        self.user_data.clear()
        message = self.bot_constants.MESSAGE_ACTIVITY_SUMMARY_DISABLE_IGNORE
        self.bot.edit_message_text(text=message,
                                   chat_id=self.chat_id,
                                   message_id=self.message_id)
        self.strava_telegram_webhooks_resource.send_message(message)

    def exit_button(self):
        self.user_data.clear()
        message = self.bot_constants.MESSAGE_EXIT_BUTTON
        self.bot.edit_message_text(text=message,
                                   chat_id=self.chat_id,
                                   message_id=self.message_id)
        self.strava_telegram_webhooks_resource.send_message(message)

    def process(self):
        options = defaultdict(
            lambda: self.exit_button, {
                'activity_summary_enable':
                self.activity_summary_enable_button,
                'activity_summary_ignore':
                self.activity_summary_ignore_button,
                'activity_summary_disable':
                self.activity_summary_disable_button,
                'activity_summary_disable_ignore':
                self.activity_summary_disable_ignore_button
            })

        options[self.chosen_option]()
class BotHelp:
    def __init__(self, bot, update, user_data):
        self.bot = bot
        self.update = update
        self.user_data = user_data
        self.bot_constants = BotConstants()
        self.bot_variables = BotVariables()
        self.query = self.update.callback_query
        self.chosen_option = self.query.data
        self.chat_id = self.query.message.chat_id
        self.message_id = self.query.message.message_id
        self.telegram_username = self.query.message.chat.username
        self.strava_telegram_webhooks_resource = StravaTelegramWebhooksResource(
        )

    def help_exit_button(self):
        self.user_data.clear()
        message = self.bot_constants.MESSAGE_HELP_EXIT
        self.bot.edit_message_text(text=message,
                                   chat_id=self.chat_id,
                                   message_id=self.message_id)
        self.strava_telegram_webhooks_resource.send_message(message)

    def help_registration_ios_button(self):
        self.user_data.clear()
        photo_path = 'scripts/commands/help/username/ios.jpeg'
        caption = "Go back to your Telegram's main screen -> Settings -> Click on your profile -> Username"
        self.bot.edit_message_text(text="Find the below screenshot:",
                                   chat_id=self.chat_id,
                                   message_id=self.message_id)
        self.bot.send_photo(chat_id=self.chat_id,
                            photo=open(photo_path, 'rb'),
                            caption=caption)
        message = "Once you set your Telegram username, come back to this chat and click /next to continue."
        self.bot.send_message(text=message,
                              chat_id=self.chat_id,
                              parse_mode="Markdown")
        self.strava_telegram_webhooks_resource.send_message(
            "Sent iOS screenshot to the user.")

    def help_registration_android_button(self):
        self.user_data.clear()
        photo_path = 'scripts/commands/help/username/android.jpeg'
        caption = "Go back to your Telegram's main screen -> Settings -> Username"
        self.bot.edit_message_text(text="Find the below screenshot:",
                                   chat_id=self.chat_id,
                                   message_id=self.message_id)
        self.bot.send_photo(chat_id=self.chat_id,
                            photo=open(photo_path, 'rb'),
                            caption=caption)
        message = "Once you set your Telegram username, come back to this chat and click /next to continue."
        self.bot.send_message(text=message,
                              chat_id=self.chat_id,
                              parse_mode="Markdown")
        self.strava_telegram_webhooks_resource.send_message(
            "Sent Android screenshot to the user.")

    def process(self):
        options = defaultdict(
            lambda: self.help_exit_button, {
                'help_registration_ios': self.help_registration_ios_button,
                'help_registration_android':
                self.help_registration_android_button,
                'help_exit': self.help_exit_button,
            })

        options[self.chosen_option]()
Exemple #17
0
class StravaTelegramBot:
    def __init__(self):
        self.bot_variables = BotVariables()
        self.strava_telegram_webhooks_resource = StravaTelegramWebhooksResource(
        )

    @staticmethod
    def error(update, context):
        logger.error('Update %s caused error %s', update, context.error)

    def handle_commands(self, update: Update, context: CallbackContext):
        try:
            commands = HandleCommands(context.bot, update, context.user_data)
            commands.process()
        except Exception:
            message = "Something went wrong. Exception: {exception}".format(
                exception=traceback.format_exc())
            logging.error(message)
            self.strava_telegram_webhooks_resource.send_message(message)

    def handle_buttons(self, update: Update, context: CallbackContext):
        try:
            buttons = HandleButtons(context.bot, update, context.user_data)
            buttons.process()
        except Exception:
            message = "Something went wrong. Exception: {exception}".format(
                exception=traceback.format_exc())
            logging.error(message)
            self.strava_telegram_webhooks_resource.send_message(message)

    def handle_command_args(self, update: Update, context: CallbackContext):
        try:
            if len(context.args) > 0:
                command_args = HandleCommandArgs(context.bot, update,
                                                 context.args)
                command_args.process()
            else:
                logging.warning("No arguments passed.")
        except Exception:
            message = "Something went wrong. Exception: {exception}".format(
                exception=traceback.format_exc())
            logging.error(message)
            self.strava_telegram_webhooks_resource.send_message(message)

    def main(self):
        updater = Updater(self.bot_variables.telegram_bot_token,
                          use_context=True,
                          workers=16)
        dispatcher_handler = updater.dispatcher

        dispatcher_handler.add_handler(
            CommandHandler("start", self.handle_commands, pass_user_data=True))
        dispatcher_handler.add_handler(
            CommandHandler("next", self.handle_commands, pass_user_data=True))
        dispatcher_handler.add_handler(
            CommandHandler("stats", self.handle_commands, pass_user_data=True))
        dispatcher_handler.add_handler(
            CommandHandler("refresh_stats",
                           self.handle_commands,
                           pass_user_data=True))
        dispatcher_handler.add_handler(
            CommandHandler("challenges_refresh_stats",
                           self.handle_command_args,
                           pass_args=True))
        dispatcher_handler.add_handler(
            CommandHandler("challenges_deauth",
                           self.handle_command_args,
                           pass_args=True))
        dispatcher_handler.add_handler(
            CommandHandler(
                "challenges_refresh_all_stats",
                self.handle_commands,
                pass_user_data=True,
                filters=Filters.user(username=self.bot_variables.admins)))
        dispatcher_handler.add_handler(
            CommandHandler("auto_update_indoor_ride",
                           self.handle_commands,
                           pass_user_data=True))
        dispatcher_handler.add_handler(
            CommandHandler("cancel", self.handle_commands,
                           pass_user_data=True))
        dispatcher_handler.add_handler(
            CommandHandler(
                "all_athletes",
                self.handle_commands,
                pass_user_data=True,
                filters=Filters.user(username=self.bot_variables.admins)))
        dispatcher_handler.add_handler(
            CommandHandler(
                "challenges_even_athletes",
                self.handle_commands,
                pass_user_data=True,
                filters=Filters.user(username=self.bot_variables.admins)))
        dispatcher_handler.add_handler(
            CommandHandler(
                "challenges_odd_athletes",
                self.handle_commands,
                pass_user_data=True,
                filters=Filters.user(username=self.bot_variables.admins)))
        dispatcher_handler.add_handler(
            CommandHandler(
                "challenges_hits_reset",
                self.handle_commands,
                pass_user_data=True,
                filters=Filters.user(username=self.bot_variables.admins)))
        dispatcher_handler.add_handler(
            CommandHandler(
                "refresh_all_stats",
                self.handle_commands,
                pass_user_data=True,
                filters=Filters.user(username=self.bot_variables.admins)))
        dispatcher_handler.add_handler(
            CommandHandler("activity_summary",
                           self.handle_commands,
                           pass_user_data=True))
        dispatcher_handler.add_handler(
            CommandHandler("help", self.handle_commands, pass_user_data=True))
        dispatcher_handler.add_handler(
            CommandHandler(
                "token",
                self.handle_command_args,
                pass_args=True,
                filters=Filters.user(username=self.bot_variables.admins)))
        dispatcher_handler.add_handler(
            CommandHandler(
                "activate",
                self.handle_command_args,
                pass_args=True,
                filters=Filters.user(username=self.bot_variables.admins)))
        dispatcher_handler.add_handler(
            CommandHandler(
                "deactivate",
                self.handle_command_args,
                pass_args=True,
                filters=Filters.user(username=self.bot_variables.admins)))
        dispatcher_handler.add_handler(
            CommandHandler(
                "update",
                self.handle_command_args,
                pass_args=True,
                filters=Filters.user(username=self.bot_variables.admins)))
        dispatcher_handler.add_handler(
            CallbackQueryHandler(self.handle_buttons, pass_user_data=True))

        dispatcher_handler.add_error_handler(self.error)

        updater.start_webhook(listen="0.0.0.0",
                              port=self.bot_variables.port,
                              url_path=self.bot_variables.telegram_bot_token)

        updater.bot.setWebhook("{app_name}/{telegram_bot_token}".format(
            app_name=self.bot_variables.app_name,
            telegram_bot_token=self.bot_variables.telegram_bot_token))
        updater.idle()