Ejemplo n.º 1
0
 def add(self, fairy):
     """Add a cute little helper."""
     if isinstance(fairy, core.Session):
         self.fairies.append(fairy)
     else:
         self.fairies.append(
             core.Session(fairy,
                          log_usage=not self.threaded,
                          proxied=self.proxied))
Ejemplo n.º 2
0
def clear_history(message: types.Message):
    """Controller to clear any questions of the current user"""
    uid: str = message.chat.id
    s: core.Session = sessions_dict.pop(uid, None)
    # If this user has yet to pass any questions
    if not s:
        s = core.Session(uid)
    s.delete_user_history()
    bot.send_message(uid, get_locale(s.language, config.CLEARED_MSG))
Ejemplo n.º 3
0
def new_question(message: types.Message):
    """Controller to start adding a question to the DB"""
    uid: str = message.chat.id
    s: core.Session = sessions_dict.pop(uid, None)
    if not s:
        s = core.Session(uid)
        s.is_game_mode_edit = True
        sessions_dict.update({uid: s})
    # TODO: Find out way to generate message outside of Model
    bot.send_message(uid,
                     get_locale(s.language, s.fill_question(None, first=True)))
Ejemplo n.º 4
0
def repost(token):
    """Repost w***e."""
    log = logging.getLogger()
    w***e = core.Session(token)

    def reshare(post):
        """Repost an album and share the post."""
        post['description'] = clean(post['description'])

        def clean_image(image, _, success, album):
            """Clean up description and edit first image."""
            image['description'] = clean(image['description'])
            if success == 0:
                desc = image.get('description') or ''
                desc += CFG.get('description').format(**album)
                image['description'] = desc.strip()
            return image

        album = w***e.upload_album(post, [clean_image])
        if not album:
            return False
        data = core.copy_keys(post, 'title', 'topic')
        if post['tags']:
            tags = [tag['name'] for tag in post['tags']]
            data['tags'] = ','.join(tags[:5])  # Imgur only allows 5 tags
        log.info('Sharing album %s to the gallery as %s', album, data['title'])
        req = w***e.post('gallery/album/%s' % album, data=data)
        return req['success']

    page = random.randint(CFG.getint('page min', 100), CFG.getint('page min', 1000))
    log.info('Fetching gallery from %d days ago', page)
    req = w***e.get('gallery/hot/viral/%d' % page)
    if not req['success']:
        log.critical('Failed to get gallery page %d, aborting.', page)
        return
    gallery = req['data']
    gallery.sort(key=lambda post: post['points'], reverse=True)

    fails = 0
    for post in gallery:
        if post['ups'] < post['downs'] * CFG.getfloat('vote ratio', 10):
            continue
        if not post['is_album'] or post['is_ad']:
            continue
        if not post['tags']:
            continue
        if reshare(post):
            break
        fails += 1
        if fails >= CFG['w***e'].getint('max attempts', 3):
            break
Ejemplo n.º 5
0
def change_language(message: types.Message):
    """Controller to change the bot language"""
    uid: str = message.chat.id
    s: core.Session = sessions_dict.pop(uid, None)
    if not s:
        s = core.Session(uid)
    # Set Language change game mode even though REPEATing is allowed
    s.is_game_mode_lang = True
    sessions_dict.update({uid: s})
    bot.send_message(
        chat_id=s.uid,
        text=get_locale(s.language, config.ASK_LANGUAGE_MSG),
        reply_markup=generate_markup(LANGUAGES),
    )
Ejemplo n.º 6
0
def show_question(message: types.Message):
    """Controller to start the game session"""
    uid: str = message.chat.id
    s = core.Session(uid)
    s.start()
    # If there are no more questions to ask
    if s.game_over:
        bot.send_message(uid, get_locale(s.language, config.CONGRATS_MSG))
        return None
    # Send message with generated keyboard
    bot.send_message(
        chat_id=s.uid,
        text=s.ticket.question,
        reply_markup=generate_markup(s.ticket.answers),
    )
    # Use UserID as key for the dictionary added to global sessions list
    sessions_dict.update({uid: s})
Ejemplo n.º 7
0
def get_reply(message: types.Message):
    """Controller to handle the response typed by the user"""
    uid: str = message.chat.id
    s: core.Session = sessions_dict.pop(uid, None)
    reply = message.text
    # If there is no session existing in the global list
    if not s:
        s = core.Session(uid)
        bot.send_message(uid, get_locale(s.language, config.WELCOME_MSG))
        return None
    # Game mode - Language switching
    if s.is_game_mode_lang:
        # TODO: Verify the reply by linking possible answers in dict
        s.update_language(reply)
        return bot.send_message(
            uid, get_locale(s.language, config.LANGUAGE_CHANGED_MSG))
    # Game mode - Adding question
    if s.is_game_mode_edit:
        msg = s.fill_question(reply)
        # In case fill_question loop isn't over we commit back session
        if msg:
            bot.send_message(uid, get_locale(s.language, msg))
            return sessions_dict.update({uid: s})
        return bot.send_message(uid, get_locale(s.language,
                                                config.WELCOME_MSG))
    # Game mode - Verification of replied asnwer
    s.finish(reply)
    # If the given response is correct
    if s.is_matched:
        bot.reply_to(
            message=message,
            text=get_locale(s.language, config.RIGHT_MSG),
            reply_markup=types.ReplyKeyboardRemove(),
        )
        return None
    else:
        bot.reply_to(
            message=message,
            text=get_locale(s.language, config.WRONG_MSG),
            reply_markup=types.ReplyKeyboardRemove(),
        )
        # If it's allowed to try answering the same question
        if REPEAT:
            return sessions_dict.update({uid: s})
        return None
Ejemplo n.º 8
0
 def __init__(self, tokens=None, proxied=True, threaded=False):
     """Initialize with tokens."""
     self.fairies = []
     self.proxied = proxied
     self.threaded = threaded
     self.executor = None
     self.futures = []
     if threaded:
         self.executor = concurrent.futures.ThreadPoolExecutor()
     if isinstance(tokens, str) and os.path.exists(tokens):
         with open(tokens, 'r') as tokens_file:
             tokens = json.load(tokens_file)
     if isinstance(tokens, dict):
         tokens = list(tokens.values())
     if isinstance(tokens, list):
         for token in tokens:
             self.fairies.append(
                 core.Session(token,
                              log_usage=not threaded,
                              proxied=proxied))
     log.info('Initialized swarm with %d fairies', len(self.fairies))
Ejemplo n.º 9
0
            categories[category] = color
    # fill in non-existent entries with randomly generated colors
    for category in config["categories"]:
        if category not in config["gui"]["category_colors"]:
            rgb_color = tuple(random.randint(0, 255) for i in range(0, 3))
            hex_color = '#%02x%02x%02x' % (*rgb_color, )
            categories[category] = hex_color

    cache = {"index": index, "categories": categories}
    return cache


def editconfig(section, key, value):
    with open("config.json", "r") as f:
        conf_file = json.load(f)

    if section == "color":
        # convert QColor to HEX
        hex_color = value.name()
        conf_file["gui"]["category_colors"][key] = hex_color
    else:
        msg = "invalid configuration modifier was called"
        raise UiRuntimeError(msg)


def sess():
    return _sess


_sess = core.Session()