コード例 #1
0
def print_weather(bot, trigger):
    location = trigger.group(2)
    if not location:
        state = db.SopelDB(bot.config)
        fmi_last_location = state.get_nick_value(trigger.nick,
                                                 'fmi_last_location')
        if fmi_last_location:
            location = fmi_last_location
        else:
            location = "Espoo"
    else:
        state = db.SopelDB(bot.config)
        state.set_nick_value(trigger.nick, 'fmi_last_location', location)

    weather = get_fmi_data(location)
    weather['timestamp'] = weather['timestamp'].strftime('%H:%M')
    weather['winddirection'] = weather['winddirection']
    weather['visibility'] = weather['visibility'] / 1000
    weather['weather'] = WEATHERCODE_MAP[weather['weather']]
    weather['forecastweather'] = WEATHERCODE_MAP[weather['forecastweather']]
    try:
        weather['windfrom'] = DIRECTION_MAP[int(
            (weather['winddirection'] + 22.5) / 45) % 8]
    except Exception:
        weather['windfrom'] = ""

    msg = "{place} {temperature}°C ({timestamp}), {weather}. Ilmankosteus {rh:.0f} %, sademäärä (<1h): {rainfall} mm. Tuulee {windspeed} m/s {windfrom} ({winddirection:.0f}°). Näkyvyys {visibility:.0f} km, pilvisyys {clouds:.0f}/8. Lumensyvyys {snow:.0f} cm. Huomispäiväksi luvattu {forecasttemp:.1f}°C, {forecastweather}.".format(
        **weather)
    bot.say(msg)
コード例 #2
0
ファイル: spotify.py プロジェクト: janihy/dsg
def refresh_spotify_token(bot, nick, spotify):
    client_id = bot.config.spotify.client_id
    client_secret = bot.config.spotify.client_secret
    headers = {
        'Authorization':
        'Basic ' + b64encode(
            f'{client_id}:{client_secret}'.encode('utf-8')).decode('utf-8')
    }
    payload = {
        'grant_type': 'refresh_token',
        'refresh_token': spotify.get('refresh_token')
    }
    response = requests.post(SPOTIFY_TOKEN_ENDPOINT,
                             headers=headers,
                             data=payload)

    if response.status_code == 200:
        response = response.json()
        spotify.update({
            'access_token':
            response.get('access_token'),
            'expires_at':
            (datetime.now() +
             timedelta(seconds=response.get('expires_in'))).isoformat()
        })

        state = db.SopelDB(bot.config)
        state.set_nick_value(nick, 'spotify', spotify)

        return spotify
    else:
        bot.say('refresh token puuttuu tai jotain :-(')
コード例 #3
0
ファイル: spotify.py プロジェクト: janihy/dsg
def spotify_np(bot, trigger):
    client_id = bot.config.spotify.client_id
    state = db.SopelDB(bot.config)
    nick = trigger.group(1) or trigger.nick
    spotify = state.get_nick_value(nick, 'spotify')
    if not spotify:
        # user hasn't gone through the authentication flow, let's send
        # a link to the authenticator
        if nick == trigger.nick:
            bot.reply('Laitoin sulle msg.')
            bot.say(SPOTIFY_AUTH_ENDPOINT.format(client_id=client_id), nick)
        else:
            bot.say(
                f'{nick} on varmaan joku köyhä jolla ei oo varaa spotifyyn :/')
    else:
        # the user has already registered and everything should be fine
        np = get_now_playing(bot, nick, spotify)
        bot.say(format_song_output(nick, np))
コード例 #4
0
ファイル: spotify.py プロジェクト: janihy/dsg
def spotify_authenticate(bot, trigger):
    # we'll follow the Authorization Code flow from Spotify docs:
    # https://developer.spotify.com/documentation/general/guides/authorization-guide/

    authcode = trigger.group(1)
    client_id = bot.config.spotify.client_id
    client_secret = bot.config.spotify.client_secret

    headers = {
        'Authorization':
        'Basic ' + b64encode(
            f'{client_id}:{client_secret}'.encode('utf-8')).decode('utf-8')
    }
    payload = {
        'grant_type': 'authorization_code',
        'code': authcode,
        'redirect_uri': 'https://dsg.fi/bot-callback/'
    }
    res = requests.post(SPOTIFY_TOKEN_ENDPOINT, headers=headers, data=payload)

    if res.status_code == 200:
        state = db.SopelDB(bot.config)
        response = json.loads(res.text)

        spotify = {
            'access_token':
            response.get('access_token'),
            'expires_at':
            (datetime.now() +
             timedelta(seconds=response.get('expires_in'))).isoformat(),
            'refresh_token':
            response.get('refresh_token')
        }
        state.set_nick_value(trigger.nick, 'spotify', spotify)
        bot.say('5/5')
    else:
        bot.say('Nyt meni joku perseelleen vituiks :-(')
コード例 #5
0
ファイル: bot.py プロジェクト: sopel-irc/sopel
    def __init__(self, config, daemon=False):
        super().__init__(config)
        self._daemon = daemon  # Used for iPython. TODO something saner here
        self._running_triggers = []
        self._running_triggers_lock = threading.Lock()
        self._plugins: Dict[str, Any] = {}
        self._rules_manager = plugin_rules.Manager()
        self._scheduler = plugin_jobs.Scheduler(self)

        self._url_callbacks = tools.SopelMemory()
        """Tracking of manually registered URL callbacks.

        Should be manipulated only by use of :meth:`register_url_callback` and
        :meth:`unregister_url_callback` methods, which are deprecated.

        Remove in Sopel 9, along with the above related methods.
        """

        self._times = {}
        """
        A dictionary mapping lowercased nicks to dictionaries which map
        function names to the time which they were last used by that nick.
        """

        self.server_capabilities = {}
        """A dict mapping supported IRCv3 capabilities to their options.

        For example, if the server specifies the capability ``sasl=EXTERNAL``,
        it will be here as ``{"sasl": "EXTERNAL"}``. Capabilities specified
        without any options will have ``None`` as the value.

        For servers that do not support IRCv3, this will be an empty set.
        """

        self.modeparser = modes.ModeParser()
        """A mode parser used to parse ``MODE`` messages and modestrings."""

        self.channels = tools.SopelIdentifierMemory(
            identifier_factory=self.make_identifier, )
        """A map of the channels that Sopel is in.

        The keys are :class:`~sopel.tools.identifiers.Identifier`\\s of the
        channel names, and map to :class:`~sopel.tools.target.Channel` objects
        which contain the users in the channel and their permissions.
        """

        self.users = tools.SopelIdentifierMemory(
            identifier_factory=self.make_identifier, )
        """A map of the users that Sopel is aware of.

        The keys are :class:`~sopel.tools.identifiers.Identifier`\\s of the
        nicknames, and map to :class:`~sopel.tools.target.User` instances. In
        order for Sopel to be aware of a user, it must share at least one
        mutual channel.
        """

        self.db = db.SopelDB(config, identifier_factory=self.make_identifier)
        """The bot's database, as a :class:`sopel.db.SopelDB` instance."""

        self.memory = tools.SopelMemory()
        """
        A thread-safe dict for storage of runtime data to be shared between
        plugins. See :class:`sopel.tools.memories.SopelMemory`.
        """

        self.shutdown_methods = []
        """List of methods to call on shutdown."""
コード例 #6
0
ファイル: spotify.py プロジェクト: janihy/dsg
def spotify_forget(bot, trigger):
    state = db.SopelDB(bot.config)
    state.delete_nick_value(trigger.nick, 'spotify')
コード例 #7
0
ファイル: spotify.py プロジェクト: janihy/dsg
def spotify_debug(bot, trigger):
    state = db.SopelDB(bot.config)
    spotify = state.get_nick_value(trigger.nick, 'spotify')
    bot.reply(json.dumps(spotify))