Changeset 19


Ignore:
Timestamp:
12/27/06 10:03:25 (17 years ago)
Author:
atzm
Message:
  • untabify, and cosmeticize debug messages
File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/amazonbot/amazonbot.py

    r18 r19  
    2121from irclib import nm_to_n 
    2222 
    23 import config 
    24 config.init() 
     23try: 
     24    set, frozenset 
     25except NameError: 
     26    from sets import Set as set, ImmutableSet as frozenset 
     27 
     28 
     29import config; config.init() 
    2530 
    2631import my_amazon 
     
    2833my_amazon.setLicense(config.get('amazon', 'access_key')) 
    2934 
    30 try: 
    31         set, frozenset 
    32 except NameError: 
    33         from sets import Set as set, ImmutableSet as frozenset 
     35 
     36DEBUG_MSG_TO = sys.stderr 
     37 
    3438 
    3539def uniq(sequence): 
    36         """リストから重耇を取り陀く (順番が狂うので泚意) 
    37         """ 
    38         return list(set(sequence)) 
     40    """リストから重耇を取り陀く (順番が狂うので泚意) 
     41    """ 
     42    return list(set(sequence)) 
    3943 
    4044def unicoding(text): 
    41         """text を匷制的に unicode オブゞェクトに倉換 
    42         """ 
    43         if type(text) is unicode: 
    44                 return text 
    45         return unicode(nkf.nkf('-w', text), 'utf-8') 
     45    """text を匷制的に unicode オブゞェクトに倉換 
     46    """ 
     47    if type(text) is unicode: 
     48        return text 
     49    return unicode(nkf.nkf('-w', text), 'utf-8') 
    4650 
    4751def ununicoding(text, encoding='iso-2022-jp'): 
    48         """text を指定された encoding で゚ンコヌドしraw str に匷制倉換 
    49         """ 
    50         if type(text) is not unicode: 
    51                 return unicoding(text).encode(encoding) 
    52         return text.encode(encoding) 
     52    """text を指定された encoding で゚ンコヌドしraw str に匷制倉換 
     53    """ 
     54    if type(text) is not unicode: 
     55        return unicoding(text).encode(encoding) 
     56    return text.encode(encoding) 
    5357 
    5458def mecab_parse(text): 
    55         """MeCab を䜿っお圢æ 
     59    """MeCab を䜿っお圢æ 
    5660‹çŽ è§£æžã—固有名詞ず䞀般名詞だけを抜出する 
    57         """ 
    58         def choice_nominal(wlist): 
    59                 res = [] 
    60                 for word, wtype in wlist: 
    61                         wtypes = wtype.split('-') 
    62                         if '固有名詞' in wtypes or ('名詞' in wtypes and '䞀般' in wtypes): 
    63                                 res.append(unicoding(word)) 
    64                 return res 
    65  
    66         text = ununicoding(text, 'utf-8') 
    67         result = [] 
    68         tag = MeCab.Tagger('-Ochasen') 
    69         for line in tag.parse(text).split('\n'): 
    70                 if not line or line == 'EOS': 
    71                         break 
    72                 words = line.split() 
    73                 result.append((words[0], words[-1])) # word, word-type 
    74  
    75         result = uniq(choice_nominal(result)) 
    76         return result 
     61    """ 
     62    def choice_nominal(wlist): 
     63        res = [] 
     64        for word, wtype in wlist: 
     65            wtypes = wtype.split('-') 
     66            if '固有名詞' in wtypes or ('名詞' in wtypes and '䞀般' in wtypes): 
     67                res.append(unicoding(word)) 
     68        return res 
     69 
     70    text = ununicoding(text, 'utf-8') 
     71    result = [] 
     72    tag = MeCab.Tagger('-Ochasen') 
     73    for line in tag.parse(text).split('\n'): 
     74        if not line or line == 'EOS': 
     75            break 
     76        words = line.split() 
     77        result.append((words[0], words[-1])) # word, word-type 
     78 
     79    result = uniq(choice_nominal(result)) 
     80    return result 
     81 
     82def _debug(fmt, *args): 
     83    if __debug__: 
     84        timeline = time.strftime("%b %d %T", time.localtime()) 
     85        try: 
     86            fmt = ununicoding(fmt, 'euc-jp') 
     87            args = list(args) 
     88            for i in range(len(args)): 
     89                if isinstance(args[i], basestring): 
     90                    args[i] = ununicoding(args[i], 'euc-jp') 
     91 
     92            print >> DEBUG_MSG_TO, '(%s) <DEBUG>' % timeline, 
     93            print >> DEBUG_MSG_TO, fmt % tuple(args) 
     94 
     95        except: 
     96            print >> DEBUG_MSG_TO, '(%s) <DEBUG>' % timeline, 
     97            print >> DEBUG_MSG_TO, '!! debug message print failed !!' 
    7798 
    7899class AmazonBotBase(SingleServerIRCBot): 
    79         """アマゟンボットのベヌスクラス 
    80         単䜓では受け取ったメッセヌゞの圢æ 
     100    """アマゟンボットのベヌスクラス 
     101    単䜓では受け取ったメッセヌゞの圢æ 
    81102‹çŽ è§£æžãšåè©žæŠœå‡ºãŸã§ã—かやらない 
    82         サブクラスで process_keyword を実裠
     103    サブクラスで process_keyword を実裠
    83104しお Amazon ぞク゚リを投げるべし 
    84105 
    85         サブクラスには onmsg_HOGEHOGE(self, conn, ev, to, args) メ゜ッドを䜜るこずでコマンド远加可胜 
    86         コマンド曞匏は !HOGEHOGE arg [, arg2, ...] ずなる 
    87         ヘルプはメ゜ッドに docstring を曞けば OK 
    88         """ 
    89         def __init__(self): 
    90                 _server = [(config.get('irc', 'server'), config.get('irc', 'port', 'int'))] 
    91                 _nick = config.get('bot', 'nick') 
    92  
    93                 self._current_lines = 0 
    94                 self._prev_time = time.time() - config.get('freq', 'timeout', 'int') 
    95                 self._silent = False 
    96                 SingleServerIRCBot.__init__(self, _server, _nick, _nick) 
    97  
    98         def start(self): 
    99                 try: 
    100                         SingleServerIRCBot.start(self) 
    101                 except KeyboardInterrupt: 
    102                         self.die(ununicoding(config.get('bot', 'bye'))) 
    103  
    104         def on_welcome(self, c, e): 
    105                 c.join(config.get('irc', 'channel')) 
    106                 if __debug__: 
    107                         print >> sys.stderr, 'DEBUG> Joined %s' % config.get('irc', 'channel') 
    108  
    109         def on_nicknameinuse(self, c, e): 
    110                 c.nick(c.get_nickname() + '_') 
    111  
    112         def on_privmsg(self, c, e): 
    113                 return self.on_pubmsg(c, e, to=nm_to_n(e.source())) 
    114  
    115         def on_pubmsg(self, c, e, to=config.get('irc', 'channel')): 
    116                 msg = unicoding(e.arguments()[0]) 
    117  
    118                 if __debug__: 
    119                         try: 
    120                                 print >> sys.stderr, 'DEBUG> pubmsg incoming "%s", should be reply to %s' % (ununicoding(msg, 'euc-jp'), to) 
    121                         except: 
    122                                 print >> sys.stderr, 'DEBUG> pubmsg incoming, but could not en/decode message. should be reply to %s' % to 
    123  
    124                 if msg[0] == '!': 
    125                         try: 
    126                                 words = shlex.split(ununicoding(msg, 'utf-8')[1:]) 
    127                         except: 
    128                                 return False 
    129                         if not words: 
    130                                 return False 
    131                         method = getattr(self, 'onmsg_%s' % words[0], lambda *arg: False) 
    132                         return method(c, e, to, words[1:]) # words[0] == command name 
    133  
    134                 # freq_lines 
    135                 self._current_lines += 1 
    136                 _freq_lines = config.get('freq', 'lines', 'int') 
    137                 if _freq_lines: 
    138                         if config.get('freq', 'lines_random', 'boolean'): 
    139                                 _freq_lines = random.randint(int(_freq_lines/2)+1, _freq_lines) 
    140  
    141                         if __debug__: 
    142                                 print >> sys.stderr, 'DEBUG> Line count: now %d, next: %d' % (self._current_lines, _freq_lines) 
    143  
    144                         if self._current_lines < _freq_lines: 
    145                                 return False 
    146                 self._current_lines = 0 
    147  
    148                 # freq 
    149                 _current_time = time.time() 
    150                 if _current_time < self._prev_time + config.get('freq', 'timeout', 'int'): 
    151                         if __debug__: 
    152                                 cur = time.strftime('%H:%M:%S', time.localtime(_current_time)) 
    153                                 go = time.strftime('%H:%M:%S', time.localtime(self._prev_time + config.get('freq', 'timeout', 'int'))) 
    154                                 print >> sys.stderr, 'DEBUG> Not expired: now %s, be expired at: %s' % (cur, go) 
    155                         return False 
    156                 self._prev_time = _current_time 
    157  
    158                 # silence 
    159                 self.silence(msg, c, e, to) 
    160                 if self._silent: 
    161                         return False 
    162  
    163                 nominals = mecab_parse(msg) 
    164                 if not nominals: 
    165                         if __debug__: 
    166                                 print >> sys.stderr, "DEBUG> Couldn't find nominal words" 
    167                         return False 
    168  
    169                 title, url = self.process_keyword(' '.join(nominals)) 
    170                 if title and url: 
    171                         content = unicoding(config.get('bot', 'content')) 
    172                         try: 
    173                                 message = ununicoding(': '.join([content, title, url])) 
    174                         except UnicodeError, err: 
    175                                 # なぜかたたに unicode オブゞェクトを iso-2022-jp で゚ンコヌドできない 
    176                                 if __debug__: 
    177                                         print >> sys.stderr, 'DEBUG> %s' % str(err) 
    178                                 return False 
    179  
    180                         c.notice(to, message) 
    181                         return True 
    182                 return False 
    183  
    184         ACTIVE_PATTERN = re.compile(unicoding(config.get('bot', 'active_pattern'))) 
    185         SILENT_PATTERN = re.compile(unicoding(config.get('bot', 'silent_pattern'))) 
    186         def silence(self, msg, c, e, to): 
    187                 active = self.ACTIVE_PATTERN.search(msg) 
    188                 silent = self.SILENT_PATTERN.search(msg) 
    189                 if __debug__: 
    190                         print >> sys.stderr, 'DEBUG> ACT_PATT: %s, SIL_PATT: %s' % (str(active), str(silent)) 
    191  
    192                 if active: 
    193                         self._silent = False 
    194                         c.notice(to, ununicoding(config.get('bot', 'thanks'))) 
    195                 elif silent: 
    196                         self._silent = True 
    197                         c.notice(to, ununicoding(config.get('bot', 'sorry'))) 
    198  
    199         def process_keyword(self, keyword): 
    200                 return [None, None] 
     106    サブクラスには onmsg_HOGEHOGE(self, conn, ev, to, args) メ゜ッドを䜜るこずでコマンド远加可胜 
     107    コマンド曞匏は !HOGEHOGE arg [, arg2, ...] ずなる 
     108    ヘルプはメ゜ッドに docstring を曞けば OK 
     109    """ 
     110    def __init__(self): 
     111        _server = [(config.get('irc', 'server'), config.get('irc', 'port', 'int'))] 
     112        _nick = config.get('bot', 'nick') 
     113 
     114        self._current_lines = 0 
     115        self._prev_time = time.time() - config.get('freq', 'timeout', 'int') 
     116        self._silent = False 
     117        SingleServerIRCBot.__init__(self, _server, _nick, _nick) 
     118 
     119    def start(self): 
     120        try: 
     121            SingleServerIRCBot.start(self) 
     122        except KeyboardInterrupt: 
     123            self.die(ununicoding(config.get('bot', 'bye'))) 
     124 
     125    def on_welcome(self, c, e): 
     126        c.join(config.get('irc', 'channel')) 
     127        _debug('Joined %s', config.get('irc', 'channel')) 
     128 
     129    def on_nicknameinuse(self, c, e): 
     130        c.nick(c.get_nickname() + '_') 
     131 
     132    def on_privmsg(self, c, e): 
     133        return self.on_pubmsg(c, e, to=nm_to_n(e.source())) 
     134 
     135    def on_pubmsg(self, c, e, to=config.get('irc', 'channel')): 
     136        msg = unicoding(e.arguments()[0]) 
     137        _debug('pubmsg incoming "%s", should be reply to %s', msg, to) 
     138 
     139        if msg[0] == '!': 
     140            try: 
     141                words = shlex.split(ununicoding(msg, 'utf-8')[1:]) 
     142            except: 
     143                return False 
     144            if not words: 
     145                return False 
     146            method = getattr(self, 'onmsg_%s' % words[0], lambda *arg: False) 
     147            return method(c, e, to, words[1:]) # words[0] == command name 
     148 
     149        # freq_lines 
     150        self._current_lines += 1 
     151        _freq_lines = config.get('freq', 'lines', 'int') 
     152        if _freq_lines: 
     153            if config.get('freq', 'lines_random', 'boolean'): 
     154                _freq_lines = random.randint(int(_freq_lines/2)+1, _freq_lines) 
     155 
     156            _debug('Line count: now %d, next: %d', self._current_lines, _freq_lines) 
     157 
     158            if self._current_lines < _freq_lines: 
     159                return False 
     160        self._current_lines = 0 
     161 
     162        # freq 
     163        _current_time = time.time() 
     164        if _current_time < self._prev_time + config.get('freq', 'timeout', 'int'): 
     165            cur = time.strftime('%H:%M:%S', time.localtime(_current_time)) 
     166            go = time.strftime('%H:%M:%S', time.localtime( 
     167                self._prev_time + config.get('freq', 'timeout', 'int'))) 
     168            _debug('Not expired: now %s, be expired at: %s', cur, go) 
     169            return False 
     170        self._prev_time = _current_time 
     171 
     172        # silence 
     173        self.silence(msg, c, e, to) 
     174        if self._silent: 
     175            return False 
     176 
     177        nominals = mecab_parse(msg) 
     178        if not nominals: 
     179            _debug("Couldn't find nominal words") 
     180            return False 
     181 
     182        title, url = self.process_keyword(' '.join(nominals)) 
     183        if title and url: 
     184            content = unicoding(config.get('bot', 'content')) 
     185            try: 
     186                message = ununicoding(': '.join([content, title, url])) 
     187            except UnicodeError, err: 
     188                # なぜかたたに unicode オブゞェクトを iso-2022-jp で゚ンコヌドできない 
     189                _debug('%s', str(err)) 
     190                return False 
     191 
     192            c.notice(to, message) 
     193            return True 
     194        return False 
     195 
     196    ACTIVE_PATTERN = re.compile(unicoding(config.get('bot', 'active_pattern'))) 
     197    SILENT_PATTERN = re.compile(unicoding(config.get('bot', 'silent_pattern'))) 
     198    def silence(self, msg, c, e, to): 
     199        active = self.ACTIVE_PATTERN.search(msg) 
     200        silent = self.SILENT_PATTERN.search(msg) 
     201        _debug('ACT_PATT: %s, SIL_PATT: %s', str(active), str(silent)) 
     202 
     203        if active: 
     204            self._silent = False 
     205            c.notice(to, ununicoding(config.get('bot', 'thanks'))) 
     206        elif silent: 
     207            self._silent = True 
     208            c.notice(to, ununicoding(config.get('bot', 'sorry'))) 
     209 
     210    def process_keyword(self, keyword): 
     211        return [None, None] 
    201212 
    202213class AmazonBot(AmazonBotBase): 
    203         """アマゟンボットの実裠
     214    """アマゟンボットの実裠
    204215クラス 
    205         process_keyword メ゜ッドで Amazon ぞク゚リを投げお結果を返す 
    206         """ 
    207         _AVAIL_PRODUCT_LINES = { 
    208                 'books-jp': '(和曞, default)', 
    209                 'books-us': '(掋曞)', 
    210                 'music-jp': '(ポピュラヌ音楜)', 
    211                 'classical-jp': '(クラシック音楜)', 
    212                 'dvd-jp': '(DVD)', 
    213                 'vhs-jp': '(ビデオ)', 
    214                 'electronics-jp': '(゚レクトロニクス)', 
    215                 'kitchen-jp': '(ホヌムキッチン)', 
    216                 'software-jp': '(゜フトりェア)', 
    217                 'videogames-jp': '(ゲヌム)', 
    218                 'magazines-jp': '(雑誌)', 
    219                 'toys-jp': '(おもちゃホビヌ)', 
    220         } 
    221  
    222         def __init__(self): 
    223                 AmazonBotBase.__init__(self) 
    224  
    225         def get_version(self): 
    226                 return 'AmazonBot by %s, based on python-irclib' % __author__ 
    227  
    228         def onmsg_isbn(self, c, e, to, args): 
    229                 """Syntax: !isbn <ISBN number> 
    230                 """ 
    231                 return self.onmsg_asin(c, e, to, args) 
    232         def onmsg_asin(self, c, e, to, args): 
    233                 """Syntax: !asin <ASIN number> 
    234                 """ 
    235                 if __debug__: 
    236                         print >> sys.stderr, 'DEBUG> in asin command: %s' % str(args) 
    237  
    238                 try: 
    239                         data = my_amazon.searchByASIN(args[0]) 
    240                 except my_amazon.AmazonError, err: 
    241                         c.notice(to, ununicoding(config.get('bot', 'no_products'))) 
    242                         if __debug__: 
    243                                 print >> sys.stderr, 'DEBUG> Caught AmazonError in onmsg_asin: %s' % str(err) 
    244                         return False 
    245                 except IndexError, err: 
    246                         c.notice(to, 'Please specify an argument.') 
    247                         return False 
    248  
    249                 return self._process_onmsg(c, e, to, data) 
    250  
    251         def onmsg_k(self, c, e, to, args): return self.onmsg_keyword(c, e, to, args) 
    252         def onmsg_keyword(self, c, e, to, args): 
    253                 """Syntax: !keyword [-h] [-t type] <keyword1> [, keyword2, ...] 
    254                 """ 
    255                 if __debug__: 
    256                         print >> sys.stderr, 'DEBUG> in keyword command: %s' % str(args) 
    257  
    258                 try: 
    259                         options, rest = getopt.getopt(args, 't:h', ['type=', 'help']) 
    260                 except getopt.GetoptError, err: 
    261                         if __debug__: 
    262                                 print >> sys.stderr, 'DEBUG> Caught GetoptError in onmsg_keyword: %s' % str(err) 
    263                         return False 
    264  
    265                 keyword = ' '.join(rest).strip() 
    266                 product_line = 'books-jp' 
    267                 for opt, val in options: 
    268                         if opt in ['-t', '--type']: 
    269                                 if val not in self._AVAIL_PRODUCT_LINES.keys(): 
    270                                         c.notice(to, 'Type "%s" is not available.' % val) 
    271                                         return False 
    272  
    273                                 product_line = val 
    274                                 break 
    275  
    276                         elif opt in ['-h', '--help']: 
    277                                 _from = nm_to_n(e.source()) # ログを流しおしたうのでヘルプは盎接送信å 
     216    process_keyword メ゜ッドで Amazon ぞク゚リを投げお結果を返す 
     217    """ 
     218    _AVAIL_PRODUCT_LINES = { 
     219        'books-jp': '(和曞, default)', 
     220        'books-us': '(掋曞)', 
     221        'music-jp': '(ポピュラヌ音楜)', 
     222        'classical-jp': '(クラシック音楜)', 
     223        'dvd-jp': '(DVD)', 
     224        'vhs-jp': '(ビデオ)', 
     225        'electronics-jp': '(゚レクトロニクス)', 
     226        'kitchen-jp': '(ホヌムキッチン)', 
     227        'software-jp': '(゜フトりェア)', 
     228        'videogames-jp': '(ゲヌム)', 
     229        'magazines-jp': '(雑誌)', 
     230        'toys-jp': '(おもちゃホビヌ)', 
     231    } 
     232 
     233    def __init__(self): 
     234        AmazonBotBase.__init__(self) 
     235 
     236    def get_version(self): 
     237        return 'AmazonBot by %s, based on python-irclib' % __author__ 
     238 
     239    def onmsg_isbn(self, c, e, to, args): 
     240        """Syntax: !isbn <ISBN number> 
     241        """ 
     242        return self.onmsg_asin(c, e, to, args) 
     243    def onmsg_asin(self, c, e, to, args): 
     244        """Syntax: !asin <ASIN number> 
     245        """ 
     246        _debug('in asin command: %s', str(args)) 
     247 
     248        try: 
     249            data = my_amazon.searchByASIN(args[0]) 
     250        except my_amazon.AmazonError, err: 
     251            c.notice(to, ununicoding(config.get('bot', 'no_products'))) 
     252            _debug('Caught AmazonError in onmsg_asin: %s', str(err)) 
     253            return False 
     254        except IndexError, err: 
     255            c.notice(to, 'Please specify an argument.') 
     256            return False 
     257 
     258        return self._process_onmsg(c, e, to, data) 
     259 
     260    def onmsg_k(self, c, e, to, args): return self.onmsg_keyword(c, e, to, args) 
     261    def onmsg_keyword(self, c, e, to, args): 
     262        """Syntax: !keyword [-h] [-t type] <keyword1> [, keyword2, ...] 
     263        """ 
     264        _debug('in keyword command: %s', str(args)) 
     265 
     266        try: 
     267            options, rest = getopt.getopt(args, 't:h', ['type=', 'help']) 
     268        except getopt.GetoptError, err: 
     269            _debug('Caught GetoptError in onmsg_keyword: %s', str(err)) 
     270            return False 
     271 
     272        keyword = ' '.join(rest).strip() 
     273        product_line = 'books-jp' 
     274        for opt, val in options: 
     275            if opt in ['-t', '--type']: 
     276                if val not in self._AVAIL_PRODUCT_LINES.keys(): 
     277                    c.notice(to, 'Type "%s" is not available.' % val) 
     278                    return False 
     279 
     280                product_line = val 
     281                break 
     282 
     283            elif opt in ['-h', '--help']: 
     284                _from = nm_to_n(e.source()) # ログを流しおしたうのでヘルプは盎接送信å 
    278285ƒãž 
    279                                 c.notice(_from, ununicoding('Available types:')) 
    280  
    281                                 for key, val in self._AVAIL_PRODUCT_LINES.iteritems(): 
    282                                         time.sleep(1) # XXX: 連続投皿するず匟かれるこずがあるので暫定察凊 
    283                                         c.notice(_from, ununicoding(' * %s: %s' % (key, val))) 
    284  
    285                                 return True 
    286  
    287                 if not keyword: 
    288                         c.notice(to, 'Please specify keywords.') 
    289                         return False 
    290  
    291                 if __debug__: 
    292                         fmt = 'DEBUG> keyword="%s", product_line=%s' 
    293                         print >> sys.stderr, fmt % (ununicoding(keyword, 'euc-jp'), product_line) 
    294  
    295                 try: 
    296                         data = my_amazon.searchByKeyword(keyword, product_line=product_line) 
    297                 except my_amazon.AmazonError, err: 
    298                         c.notice(to, ununicoding(config.get('bot', 'no_products'))) 
    299                         if __debug__: 
    300                                 print >> sys.stderr, 'DEBUG> Caught AmazonError in onmsg_amazon: %s' % str(err) 
    301                         return False 
    302  
    303                 return self._process_onmsg(c, e, to, data) 
    304  
    305         def onmsg_h(self, c, e, to, args): return self.onmsg_help(c, e, to, args) 
    306         def onmsg_help(self, c, e, to, args): 
    307                 """Syntax: !help 
    308                 """ 
    309                 if __debug__: 
    310                         print >> sys.stderr, 'DEBUG> in help command: %s' % str(args) 
    311  
    312                 _from = nm_to_n(e.source()) # ログを流しおしたうのでヘルプは盎接送信å 
     286                c.notice(_from, ununicoding('Available types:')) 
     287 
     288                for key, val in self._AVAIL_PRODUCT_LINES.iteritems(): 
     289                    time.sleep(1) # XXX: 連続投皿するず匟かれるこずがあるので暫定察凊 
     290                    c.notice(_from, ununicoding(' * %s: %s' % (key, val))) 
     291 
     292                return True 
     293 
     294        if not keyword: 
     295            c.notice(to, 'Please specify keywords.') 
     296            return False 
     297 
     298        _debug('keyword="%s", product_line=%s', keyword, product_line) 
     299 
     300        try: 
     301            data = my_amazon.searchByKeyword(keyword, product_line=product_line) 
     302        except my_amazon.AmazonError, err: 
     303            c.notice(to, ununicoding(config.get('bot', 'no_products'))) 
     304            _debug('Caught AmazonError in onmsg_amazon: %s', str(err)) 
     305            return False 
     306 
     307        return self._process_onmsg(c, e, to, data) 
     308 
     309    def onmsg_h(self, c, e, to, args): return self.onmsg_help(c, e, to, args) 
     310    def onmsg_help(self, c, e, to, args): 
     311        """Syntax: !help 
     312        """ 
     313        _debug('in help command: %s', str(args)) 
     314 
     315        _from = nm_to_n(e.source()) # ログを流しおしたうのでヘルプは盎接送信å 
    313316ƒãž 
    314                 docs = [] 
    315                 for key in dir(self): 
    316                         val = getattr(self, key, '') 
    317                         if __debug__: 
    318                                 print >> sys.stderr, 'DEBUG> key=%s, val=%s' % (key, ununicoding(str(val), 'euc-jp')) 
    319  
    320                         if key[:6] != 'onmsg_': 
    321                                 continue 
    322  
    323                         doc = val.__doc__ 
    324                         if doc: 
    325                                 doc = doc.strip() 
    326                                 if not doc: 
    327                                         continue 
    328                                 time.sleep(1) # XXX: 連続投皿するず匟かれるっぜいので暫定察凊 
    329                                 c.notice(_from, doc) 
    330  
    331                 return True 
    332  
    333         def _process_onmsg(self, c, e, to, data): 
    334                 if type(data.Details) is not list: 
    335                         data.Details = [data.Details] 
    336  
    337                 detail = random.choice(data.Details) 
    338                 title = ununicoding(detail.ProductName) 
    339                 url = ununicoding(detail.URL) 
    340                 c.notice(to, '%(title)s: %(url)s' % locals()) 
    341  
    342                 return True 
    343  
    344         def process_keyword(self, keyword): 
    345                 keyword = ununicoding(keyword, 'utf-8') 
    346                 if __debug__: 
    347                         print >> sys.stderr, 'DEBUG> KEYWORD: %s' % ununicoding(keyword, 'euc-jp') 
    348  
    349                 try: 
    350                         data = my_amazon.searchByBlended(keyword) 
    351                         if type(data.ProductLine) is not type([]): 
    352                                 data.ProductLine = [data.ProductLine] 
    353                 except my_amazon.AmazonError, err: 
    354                         if __debug__: 
    355                                 print >> sys.stderr, 'DEBUG> Caught AmazonError: %s' % str(err) 
    356                         return [None, None] 
    357  
    358                 product_line = random.choice(data.ProductLine) 
    359                 detail = random.choice(product_line.ProductInfo.Details) 
    360  
    361                 url = unicoding(getattr(detail, 'URL', None)) 
    362                 product_name = unicoding(getattr(detail, 'ProductName', None)) 
    363  
    364                 return [product_name, url] 
     317        docs = [] 
     318        for key in dir(self): 
     319            val = getattr(self, key, '') 
     320            _debug('key=%s, val=%s', key, str(val)) 
     321 
     322            if key[:6] != 'onmsg_': 
     323                continue 
     324 
     325            doc = val.__doc__ 
     326            if doc: 
     327                doc = doc.strip() 
     328                if not doc: 
     329                    continue 
     330                time.sleep(1) # XXX: 連続投皿するず匟かれるっぜいので暫定察凊 
     331                c.notice(_from, doc) 
     332 
     333        return True 
     334 
     335    def _process_onmsg(self, c, e, to, data): 
     336        if type(data.Details) is not list: 
     337            data.Details = [data.Details] 
     338 
     339        detail = random.choice(data.Details) 
     340        title = ununicoding(detail.ProductName) 
     341        url = ununicoding(detail.URL) 
     342        c.notice(to, '%(title)s: %(url)s' % locals()) 
     343 
     344        return True 
     345 
     346    def process_keyword(self, keyword): 
     347        keyword = ununicoding(keyword, 'utf-8') 
     348        _debug('KEYWORD: %s', keyword) 
     349 
     350        try: 
     351            data = my_amazon.searchByBlended(keyword) 
     352            if type(data.ProductLine) is not type([]): 
     353                data.ProductLine = [data.ProductLine] 
     354        except my_amazon.AmazonError, err: 
     355            _debug('Caught AmazonError: %s', str(err)) 
     356            return [None, None] 
     357 
     358        product_line = random.choice(data.ProductLine) 
     359        detail = random.choice(product_line.ProductInfo.Details) 
     360 
     361        url = unicoding(getattr(detail, 'URL', None)) 
     362        product_name = unicoding(getattr(detail, 'ProductName', None)) 
     363 
     364        return [product_name, url] 
    365365 
    366366if __name__ == '__main__': 
    367         bot = AmazonBot() 
    368         bot.start() 
    369         print '> Bye ;)' 
     367    bot = AmazonBot() 
     368    bot.start() 
     369    print '> Bye ;)' 
Note: See TracChangeset for help on using the changeset viewer.