Ejemplo n.º 1
0
def process_question_spreadsheet_link_step(message):
    try:
        if not util.is_url(message.text):
            new_message = bot.send_message(message.chat.id, 'Некорректная ссылка')
            bot.register_next_step_handler(new_message, create_lab(new_message))
        else:
            chat_id = message.chat.id
            lab_id = lab_repository.create_lab()
            lab = Lab(lab_id)
            labs[chat_id] = lab
            spreadsheet_id = util.extract_google_spreadsheet_id(message.text)
            sheet_info = spreadsheetApi.spreadsheets().get(spreadsheetId=spreadsheet_id).execute()["sheets"][0][
                "properties"]
            sheet = spreadsheetApi.spreadsheets().values().get(spreadsheetId=spreadsheet_id,
                                                               range=sheet_info["title"]).execute()["values"]
            for i in range(len(sheet)):
                question_id = question_repository.create_question(lab_id, sheet[i][0], len(sheet[i]) != 1)
                for j in range(1, len(sheet[i])):
                    answer_option_repository.create_answer(question_id, sheet[i][j])

            new_message = bot.send_message(message.chat.id,
                                           'Ссылка на Google Disk папку для ответов. Папка должна быть доступна для '
                                           'всех у кого есть ссылка. Ссылка вида: '
                                           'https://drive.google.com/drive/folders/1BqyY_KkwdK2lcxxGKinq5bKYYbJ75klv'
                                           '?usp=sharing')
            bot.register_next_step_handler(new_message, process_answer_spreadsheet_link_step)
    except Exception as e:
        bot.register_next_step_handler(message, create_lab(message))
Ejemplo n.º 2
0
 def collect_urls(cls, data):
     """
         This Method will collect all the urls from given string
     """
     urls = []
     for string in data:
         if util.is_url(string):
             urls.append(string)
     return cls.test_urls_against_api(urls)
Ejemplo n.º 3
0
def resolve_config(
        config_str: Optional[str]) -> Dict[str, Optional[Dict[str, Any]]]:
    """ resolves if config arg is a registry entry, a url, or a file, folder, or loads from defaults if None"""
    start_t = time.time()
    if config_str is None:
        config = load_config_from_local_path()
    elif config_str in RULES_REGISTRY:
        config = download_config(RULES_REGISTRY[config_str])
    elif is_url(config_str):
        config = download_config(config_str)
    else:
        config = load_config_from_local_path(config_str)
    if config:
        debug_print(f"loaded {len(config)} configs in {time.time() - start_t}")
    return config
Ejemplo n.º 4
0
 async def convert(self, ctx: DiscordContext, argument):
     if is_url(argument) and self.ignore_urls:
         return self.many and [] or None
     if self.many:
         pool_names = argument.split()
     else:
         pool_names = [argument]
     if self.avail_only:
         obj = ctx.user_data.available_pools
     elif self.moderated_only:
         obj = ctx.user_data.moderated_pools
     else:
         obj = MemeImagePool.objects
     pools = obj.filter(name__in=pool_names)
     if len(pools) == 0:
         raise BadArgument("no matching pools found!")
     return self.many and pools or pools[0]
Ejemplo n.º 5
0
def save_output(output_str: str,
                output_data: Dict[str, Any],
                json: bool = False):
    if is_url(output_str):
        post_output(output_str, output_data)
    else:
        if Path(output_str).is_absolute():
            save_path = Path(output_str)
        else:
            base_path = config_resolver.get_base_path()
            save_path = base_path.joinpath(output_str)
        # create the folders if not exists
        save_path.parent.mkdir(parents=True, exist_ok=True)
        with save_path.open(mode="w") as fout:
            if json:
                fout.write(build_output_json(output_data))
            else:
                fout.write("\n".join(
                    build_normal_output(output_data, color_output=False)))
Ejemplo n.º 6
0
 async def from_message(cls, msg: Message, attachments_only=False, just_one=False):
     images = {}
     for attachment in msg.attachments:
         images[attachment.proxy_url] = attachment.filename
     if not attachments_only:
         for embed in msg.embeds:
             if embed.image != discord.Embed.Empty and embed.image.url != discord.Embed.Empty:
                 images[embed.image.url] = None
             elif embed.thumbnail != discord.Embed.Empty and embed.thumbnail.url != discord.Embed.Empty:
                 images[embed.thumbnail.url] = None
         for url in msg.content.split(' '):
             url = url.strip('<>')
             if is_url(url):
                 images[url] = None
     actual_images = []
     async with aiohttp.ClientSession() as http_ses:
         for url, filename in images.items():
             try:
                 r = await http_ses.head(url, headers=headers)
             except (ValueError, aiohttp.ClientError):
                 continue
             contenttype = r.headers.get('content-type')
             contentlength = r.headers.get('content-length')
             if contenttype and 'image' in contenttype and contentlength and int(contentlength) <= settings.MEEM_MAX_SRCIMG_SIZE:
                 actual_images.append(cls(url, filename or struuid4()))
                 if just_one and len(actual_images) == 1:
                     return actual_images[0]
     if not attachments_only and len(actual_images) == 0:  # get last image from channel
         try:
             channel_data = DiscordChannel.objects.get(channel_id=msg.channel.id)
             if channel_data.recent_image:
                 actual_images.append(cls(channel_data.recent_image, struuid4()))
         except DiscordChannel.DoesNotExist:
             pass
     if just_one:
         return len(actual_images) > 0 and actual_images[0] or None
     else:
         return actual_images
Ejemplo n.º 7
0
def process_answer_spreadsheet_link_step(message):
    try:
        if not util.is_url(message.text):
            new_message = bot.send_message(message.chat.id, 'Некорректная ссылка')
            bot.register_next_step_handler(new_message, process_answer_spreadsheet_link_step)
        else:
            chat_id = message.chat.id
            lab = labs[chat_id]
            spreadsheet = {
                'properties': {
                    'title': "Ответы " + str(lab.lab_id)
                }
            }
            new_spreadsheet_id = \
                spreadsheetApi.spreadsheets().create(body=spreadsheet, fields='spreadsheetId').execute()[
                    "spreadsheetId"]

            lab_repository.set_answer_spreadsheet_link(lab.lab_id, new_spreadsheet_id)

            permission = {
                'type': 'anyone',
                'role': 'writer',
            }
            driveApi.permissions().create(fileId=new_spreadsheet_id, body=permission, fields='id').execute()

            folder_id = util.extract_google_disc_folder(message.text)
            file = driveApi.files().get(fileId=new_spreadsheet_id, fields='parents').execute()
            driveApi.files().update(fileId=new_spreadsheet_id, addParents=folder_id,
                                    removeParents=",".join(file.get('parents')), fields='id, parents').execute()
            markup = types.ReplyKeyboardMarkup()
            markup.add(types.KeyboardButton("Создать лабораторную работу"))
            markup.add(types.KeyboardButton("Пройти лабораторную работу"))
            bot.send_message(message.chat.id, "Лабораторная работа создана, ID: " + str(lab.lab_id),
                             reply_markup=markup)
    except Exception as e:
        bot.register_next_step_handler(message, create_lab(message))