예제 #1
0
파일: safety.py 프로젝트: sopel-irc/sopel
def toggle_safety(bot: SopelWrapper, trigger: Trigger):
    """Set safety setting for channel."""
    if not trigger.admin and bot.channels[trigger.sender].privileges[
            trigger.nick] < plugin.OP:
        bot.reply('Only channel operators can change safety settings')
        return

    new_mode = None
    if trigger.group(2):
        new_mode = trigger.group(2).lower()

    if not new_mode or (new_mode != "default"
                        and new_mode not in SAFETY_MODES):
        bot.reply(
            "Current mode: {}. Available modes: {}, or default ({})".format(
                bot.db.get_channel_value(
                    trigger.sender,
                    "safety",
                    "default",
                ),
                ", ".join(SAFETY_MODES),
                bot.settings.safety.default_mode,
            ))
        return

    if new_mode == "default":
        bot.db.delete_channel_value(trigger.sender, "safety")
    else:
        bot.db.set_channel_value(trigger.sender, "safety", new_mode)
    bot.say('Safety is now set to "%s" for this channel' % new_mode)
예제 #2
0
def get_weather(bot: SopelWrapper, trigger: Trigger) -> None:
    """
    Gets the weather at a given location and returns the first result
    """
    location_lookup_args = trigger.group(2)
    if location_lookup_args is None:

        location_lookup_args = bot.db.get_nick_value(trigger.nick, 'place_id')
        if not location_lookup_args:
            bot.reply("I don't know where you live. "
                      "Give me a location, like {pfx}{command} London, "
                      "or tell me where you live by saying {pfx}setlocation "
                      "London, for example.".format(
                          command=trigger.group(1),
                          pfx=bot.config.core.help_prefix))
            return plugin.NOLIMIT

    api = get_owm_api(bot)
    location = parse_location_args(location_lookup_args)
    message = get_weather_message(api, location)
    bot.reply(message)
예제 #3
0
def url_unban(bot: SopelWrapper, trigger: Trigger):
    """Allow a URL for auto title.

    Use ``urlpallow`` to allow a pattern instead of a URL.
    """
    url = trigger.group(2)

    if not url:
        bot.reply('This command requires a URL to allow.')
        return

    if trigger.group(1) in ['urlpallow', 'urlpunban']:
        # validate regex pattern
        try:
            re.compile(url)
        except re.error as err:
            bot.reply('Invalid regex pattern: %s' % err)
            return
    else:
        # escape the URL to ensure a valid pattern
        url = re.escape(url)

    patterns = bot.settings.url.exclude

    if url not in patterns:
        bot.reply('This URL was not excluded from auto title.')
        return

    # update settings
    patterns.remove(url)
    bot.settings.url.exclude = patterns  # set the config option
    bot.settings.save()
    LOGGER.info('%s allowed the URL pattern "%s"', trigger.nick, url)

    # re-compile
    bot.memory['url_exclude'] = [re.compile(s) for s in patterns]

    # tell the user
    bot.reply('This URL is not excluded from auto title anymore.')
예제 #4
0
파일: safety.py 프로젝트: sopel-irc/sopel
def vt_command(bot: SopelWrapper, trigger: Trigger):
    """Look up VT results on demand."""
    if not bot.settings.safety.vt_api_key:
        bot.reply("Sorry, I don't have a VirusTotal API key configured.")
        return

    url = trigger.group(2)
    safe_url = safeify_url(url)

    result = virustotal_lookup(bot, url, max_cache_age=timedelta(minutes=1))
    if not result:
        bot.reply("Sorry, an error occurred while looking that up.")
        return

    analysis = result["virustotal_data"]["last_analysis_stats"]

    result_types = {
        "malicious": colors.RED,
        "suspicious": colors.YELLOW,
        "harmless": colors.GREEN,
        "undetected": colors.GREY,
    }
    result_strs = []
    for result_type, result_color in result_types.items():
        if analysis[result_type] == 0:
            result_strs.append("0 " + result_type)
        else:
            result_strs.append(
                bold(
                    color(
                        str(analysis[result_type]) + " " + result_type,
                        result_color)))
    results_str = ", ".join(result_strs)

    vt_scan_time = datetime.fromtimestamp(
        result["virustotal_data"]["last_analysis_date"],
        timezone.utc,
    )
    bot.reply("Results: {} at {} for {}".format(
        results_str,
        tools.time.format_time(
            bot.db,
            bot.config,
            nick=trigger.nick,
            channel=trigger.sender,
            time=vt_scan_time,
        ),
        safe_url,
    ))
예제 #5
0
def title_command(bot: SopelWrapper, trigger: Trigger):
    """
    Show the title or URL information for the given URL, or the last URL seen
    in this channel.
    """
    result_count = 0

    if not trigger.group(2):
        if trigger.sender not in bot.memory['last_seen_url']:
            return
        urls = [bot.memory["last_seen_url"][trigger.sender]]
    else:
        # needs to be a list so len() can be checked later
        urls = list(web.search_urls(trigger))

    for url, title, domain, tinyurl, dispatched in process_urls(
            bot, trigger, urls, requested=True):
        if dispatched:
            result_count += 1
            continue
        message = "%s | %s" % (title, domain)
        if tinyurl:
            message += ' ( %s )' % tinyurl
        bot.reply(message)
        bot.memory['last_seen_url'][trigger.sender] = url
        result_count += 1

    expected_count = len(urls)
    if result_count < expected_count:
        if expected_count == 1:
            bot.reply(
                "Sorry, fetching that title failed. Make sure the site is working."
            )
        elif result_count == 0:
            bot.reply("Sorry, I couldn't fetch titles for any of those.")
        else:
            bot.reply(
                "I couldn't get all of the titles, but I fetched what I could!"
            )