File: Currency.py

package info (click to toggle)
supybot 0.80.1-3
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 3,196 kB
  • ctags: 6,555
  • sloc: python: 43,960; makefile: 25
file content (144 lines) | stat: -rw-r--r-- 5,802 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
###
# Copyright (c) 2004, James Vega
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#   * Redistributions of source code must retain the above copyright notice,
#     this list of conditions, and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright notice,
#     this list of conditions, and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#   * Neither the name of the author of this software nor the name of
#     contributors to this software may be used to endorse or promote products
#     derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###

"""
Provides commands which interface with various websites to perform currency
conversions.
"""

import supybot

__revision__ = "$Id: Currency.py,v 1.13 2004/12/16 07:57:06 jemfinch Exp $"
__author__ = supybot.authors.jamessan

import re

import supybot.conf as conf
import supybot.utils as utils
from supybot.commands import *
import supybot.ircutils as ircutils
import supybot.registry as registry
import supybot.webutils as webutils
import supybot.callbacks as callbacks

class CurrencyCommand(registry.String):
    def setValue(self, s):
        m = Currency.currencyCommands
        if s not in m:
            raise registry.InvalidRegistryValue,\
                  'Command must be one of %s.' % utils.commaAndify(m)
        else:
            method = getattr(Currency, s)
            Currency.convert.im_func.__doc__ = method.__doc__
        registry.String.setValue(self, s)

class Currency(callbacks.Privmsg):
    currencyCommands = ['xe', 'yahoo']
    threaded = True

    _symbolError = 'Currency must be denoted by its three-letter symbol.'
    def convert(self, irc, msg, args):
        # This specifically does not have a docstring.
        channel = None
        if irc.isChannel(msg.args[0]):
            channel = msg.args[0]
        realCommandName = self.registryValue('command', channel)
        realCommand = getattr(self, realCommandName)
        realCommand(irc, msg, args)

    _xeCurrError = re.compile(r'The following error occurred:<BR><BR>\s+'
                              r'(.*)</body>', re.I | re.S)
    _xeConvert = re.compile(r'<TD[^>]+><FONT[^>]+>\s+([\d.]+\s+\w{3}\s+='
                            r'\s+[\d.]+\s+\w{3})', re.I | re.S)
    def xe(self, irc, msg, args, number, curr1, curr2):
        """[<number>] <currency1> [to] <currency2>

        Converts from <currency1> to <currency2>.  If number isn't given, it
        defaults to 1.
        """
        if len(curr1) != 3 and len(curr2) != 3:
            irc.error(self._symbolError)
            return
        url = 'http://www.xe.com/ucc/convert.cgi?Amount=%s&From=%s&To=%s'
        try:
            text = webutils.getUrl(url % (number, curr1, curr2))
        except webutils.WebError, e:
            irc.error(str(e))
            return
        err = self._xeCurrError.search(text)
        if err is not None:
            irc.error('You used an incorrect currency symbol.')
            return
        conv = self._xeConvert.search(text)
        if conv is not None:
            resp = conv.group(1).split()
            resp[0] = str(float(resp[0]) * number)
            if resp[0].endswith('.0'):
                resp[0] = '%s.00' % resp[0][:-2]
            resp[3] = str(float(resp[3]) * number)
            irc.reply(' '.join(resp))
            return
        else:
            irc.error('XE must\'ve changed the format of their site.')
            return
    xe = wrap(xe, [optional('float', 1.0), 'lowered', 'to', 'lowered'])

    def yahoo(self, irc, msg, args, number, curr1, curr2):
        """[<number>] <currency1> to <currency2>

        Converts from <currency1> to <currency2>.  If number isn't given, it
        defaults to 1.
        """
        if len(curr1) != 3 and len(curr2) != 3:
            irc.error(self._symbolError)
            return
        url = r'http://finance.yahoo.com/d/quotes.csv?'\
              r's=%s%s=X&f=sl1d1t1ba&e=.csv' % (curr1, curr2)
        try:
            text = webutils.getUrl(url)
        except webutils.WebError, e:
            irc.error(str(e))
            return
        if 'N/A' in text:
            irc.error('You used an incorrect currency symbol.')
            return
        conv = text.split(',')[1]
        conv = number * float(conv)
        irc.reply('%.2f %s = %.2f %s' % (number, curr1, conv, curr2))
    yahoo = wrap(yahoo, [optional('float', 1.0), 'lowered', 'to', 'lowered'])

conf.registerPlugin('Currency')
conf.registerChannelValue(conf.supybot.plugins.Currency, 'command',
    CurrencyCommand('yahoo', """Sets the default command to use when retrieving
    the currency conversion.  Command must be one of %s.""" %
    utils.commaAndify(Currency.currencyCommands, And='or')))

Class = Currency

# vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78: