source: trunk/amazonbot/amazonbot.py @ 14

Revision 14, 10.0 KB checked in by atzm, 18 years ago (diff)
RevLine 
[8]1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4__version__ = '$Revision$'
5__author__ = 'Atzm WATANABE <sitosito@p.chan.ne.jp>'
6__date__ = '$Date$'
7__copyright__ = 'Copyright(C) 2006 Atzm WATANABE, all rights reserved.'
8__license__ = 'Python'
9
10import re
[9]11import sys
[10]12import time
[12]13import shlex
[8]14import random
[12]15import getopt
16
[8]17import MeCab
[10]18import nkf
[8]19
20from ircbot import SingleServerIRCBot
21from irclib import nm_to_n
22
23import config
24config.init()
25
26import my_amazon
27my_amazon.setLocale(config.get('amazon', 'locale'))
28my_amazon.setLicense(config.get('amazon', 'access_key'))
29
30try:
31        set, frozenset
32except NameError:
33        from sets import Set as set, ImmutableSet as frozenset
34
35def uniq(sequence):
[10]36        """リストから重耇を取り陀く (順番が狂うので泚意)
37        """
[8]38        return list(set(sequence))
39
[10]40def unicoding(text):
41        """text を匷制的に unicode オブゞェクトに倉換
42        """
43        if type(text) is unicode:
44                return text
45        return unicode(nkf.nkf('-w', text), 'utf-8')
46
47def 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)
53
[8]54def mecab_parse(text):
[10]55        """MeCab を䜿っお圢態玠解析し固有名詞ず䞀般名詞だけを抜出する
56        """
[8]57        def choice_nominal(wlist):
58                res = []
59                for word, wtype in wlist:
60                        wtypes = wtype.split('-')
61                        if '固有名詞' in wtypes or ('名詞' in wtypes and '䞀般' in wtypes):
[10]62                                res.append(unicoding(word))
[8]63                return res
64
[10]65        text = ununicoding(text, 'utf-8')
[8]66        result = []
67        tag = MeCab.Tagger('-Ochasen')
68        for line in tag.parse(text).split('\n'):
69                if not line or line == 'EOS':
70                        break
71                words = line.split()
72                result.append((words[0], words[-1])) # word, word-type
73
74        result = uniq(choice_nominal(result))
75        return result
76
77class AmazonBotBase(SingleServerIRCBot):
[10]78        """アマゟンボットのベヌスクラス
[12]79        単䜓では受け取ったメッセヌゞの圢態玠解析ず名詞抜出たでしかやらない
[10]80        サブクラスで process_keyword を実装しお Amazon ぞク゚リを投げるべし
[12]81
[14]82        サブクラスには onmsg_HOGEHOGE(self, conn, ev, to, args) メ゜ッドを䜜るこずでコマンド远加可胜
[12]83        コマンド曞匏は !HOGEHOGE arg [, arg2, ...] ずなる
[14]84        ヘルプはメ゜ッドに docstring を曞けば OK
[10]85        """
[8]86        def __init__(self):
87                _server = [(config.get('irc', 'server'), config.get('irc', 'port', 'int'))]
88                _nick = config.get('bot', 'nick')
89
[10]90                self._prev_time = time.time()
[8]91                self._silent = False
92                SingleServerIRCBot.__init__(self, _server, _nick, _nick)
93
[10]94        def start(self):
95                try:
96                        SingleServerIRCBot.start(self)
97                except KeyboardInterrupt:
98                        self.die(ununicoding(config.get('bot', 'bye')))
[8]99
100        def on_welcome(self, c, e):
101                c.join(config.get('irc', 'channel'))
102                if __debug__:
[10]103                        print >> sys.stderr, 'DEBUG> Joined %s' % config.get('irc', 'channel')
[8]104
105        def on_nicknameinuse(self, c, e):
106                c.nick(c.get_nickname() + '_')
107
108        def on_privmsg(self, c, e):
[14]109                return self.on_pubmsg(c, e, to=nm_to_n(e.source()))
[8]110
[14]111        def on_pubmsg(self, c, e, to=config.get('irc', 'channel')):
[12]112                msg = unicoding(e.arguments()[0])
[14]113
114                if __debug__:
115                        print >> sys.stderr, 'DEBUG> pubmsg incoming "%s", reply to %s' % (ununicoding(msg, 'euc-jp'), to)
116
[12]117                if msg[0] == '!':
118                        words = shlex.split(ununicoding(msg, 'utf-8')[1:])
119                        method = getattr(self, 'onmsg_%s' % words[0], lambda *arg: False)
[14]120                        return method(c, e, to, words[1:]) # words[0] == command name
[12]121
[11]122                _current_time = time.time()
123                if _current_time < self._prev_time + config.get('bot', 'freq', 'int'):
[9]124                        if __debug__:
[14]125                                prev = time.strftime('%H:%M:%S', time.localtime(self._prev_time))
126                                go = time.strftime('%H:%M:%S', time.localtime(self._prev_time + config.get('bot', 'freq', 'int')))
127                                print >> sys.stderr, 'DEBUG> Not expired: prev time is %s, be expired at: %s' % (prev, go)
[9]128                        return False
[11]129                self._prev_time = _current_time
[10]130
[14]131                self.silence(msg, c, e, to)
[8]132                if self._silent:
133                        return False
134
[10]135                nominals = mecab_parse(msg)
[8]136                if not nominals:
[10]137                        if __debug__:
138                                print >> sys.stderr, "DEBUG> Couldn't find nominal words"
[8]139                        return False
140
141                title, url = self.process_keyword(' '.join(nominals))
142                if title and url:
[10]143                        content = unicoding(config.get('bot', 'content'))
[9]144                        try:
[10]145                                message = ununicoding(': '.join([content, title, url]))
[12]146                        except UnicodeError, err:
[11]147                                # なぜかたたに unicode オブゞェクトを iso-2022-jp で゚ンコヌドできない
148                                if __debug__:
[12]149                                        print >> sys.stderr, 'DEBUG> %s' % str(err)
[9]150                                return False
151
[14]152                        c.notice(to, message)
[8]153                        return True
154                return False
155
[10]156        ACTIVE_PATTERN = re.compile(unicoding(config.get('bot', 'active_pattern')))
157        SILENT_PATTERN = re.compile(unicoding(config.get('bot', 'silent_pattern')))
[14]158        def silence(self, msg, c, e, to):
[10]159                active = self.ACTIVE_PATTERN.search(msg)
160                silent = self.SILENT_PATTERN.search(msg)
[9]161                if __debug__:
[10]162                        print >> sys.stderr, 'DEBUG> ACT_PATT: %s, SIL_PATT: %s' % (str(active), str(silent))
[9]163
164                if active:
[8]165                        self._silent = False
[14]166                        c.notice(to, ununicoding(config.get('bot', 'thanks')))
[9]167                elif silent:
[8]168                        self._silent = True
[14]169                        c.notice(to, ununicoding(config.get('bot', 'sorry')))
[8]170
171        def process_keyword(self, keyword):
172                return [None, None]
173
174class AmazonBot(AmazonBotBase):
[10]175        """アマゟンボットの実装クラス
176        process_keyword メ゜ッドで Amazon ぞク゚リを投げお結果を返す
177        """
[14]178        _AVAIL_PRODUCT_LINES = {
179                'books-jp': '(和曞, default)',
180                'books-us': '(掋曞)',
181                'music-jp': '(ポピュラヌ音楜)',
182                'classical-jp': '(クラシック音楜)',
183                'dvd-jp': '(DVD)',
184                'vhs-jp': '(ビデオ)',
185                'electronics-jp': '(゚レクトロニクス)',
186                'kitchen-jp': '(ホヌムキッチン)',
187                'software-jp': '(゜フトりェア)',
188                'videogames-jp': '(ゲヌム)',
189                'magazines-jp': '(雑誌)',
190                'toys-jp': '(おもちゃホビヌ)',
191        }
192
[8]193        def __init__(self):
194                AmazonBotBase.__init__(self)
195
[10]196        def get_version(self):
197                return 'AmazonBot by %s, based on python-irclib' % __author__
198
[14]199        def onmsg_isbn(self, c, e, to, args):
[12]200                """Syntax: !isbn <ISBN number>
201                """
[14]202                return self.onmsg_asin(c, e, to, args)
203        def onmsg_asin(self, c, e, to, args):
[12]204                """Syntax: !asin <ASIN number>
205                """
206                if __debug__:
207                        print >> sys.stderr, 'DEBUG> in asin command: %s' % str(args)
208
209                try:
210                        data = my_amazon.searchByASIN(args[0])
211                except my_amazon.AmazonError, err:
[14]212                        c.notice(to, ununicoding(config.get('bot', 'no_products')))
[12]213                        if __debug__:
214                                print >> sys.stderr, 'DEBUG> Caught AmazonError in onmsg_asin: %s' % str(err)
215                        return False
[14]216                except IndexError, err:
217                        c.notice(to, 'Please specify an argument.')
218                        return False
[12]219
[14]220                return self._process_onmsg(c, e, to, data)
[12]221
[14]222        def onmsg_k(self, c, e, to, args): return self.onmsg_keyword(c, e, to, args)
223        def onmsg_keyword(self, c, e, to, args):
224                """Syntax: !keyword [-h] [-t type] <keyword1> [, keyword2, ...]
[12]225                """
226                if __debug__:
[14]227                        print >> sys.stderr, 'DEBUG> in keyword command: %s' % str(args)
[12]228
229                try:
230                        options, rest = getopt.getopt(args, 't:h', ['type=', 'help'])
231                except getopt.GetoptError, err:
232                        if __debug__:
[14]233                                print >> sys.stderr, 'DEBUG> Caught GetoptError in onmsg_keyword: %s' % str(err)
[12]234                        return False
235
[14]236                keyword = ' '.join(rest).strip()
[12]237                product_line = 'books-jp'
238                for opt, val in options:
239                        if opt in ['-t', '--type']:
[14]240                                if val not in self._AVAIL_PRODUCT_LINES.keys():
241                                        c.notice(to, 'Type "%s" is not available.' % val)
242                                        return False
243
[12]244                                product_line = val
245                                break
[14]246
[12]247                        elif opt in ['-h', '--help']:
[14]248                                _from = nm_to_n(e.source()) # ログを流しおしたうのでヘルプは盎接送信元ぞ
249                                c.notice(_from, ununicoding('Available types:'))
250
251                                for key, val in self._AVAIL_PRODUCT_LINES.iteritems():
252                                        time.sleep(1) # XXX: 連続投皿するず匟かれるこずがあるので暫定察凊
253                                        c.notice(_from, ununicoding(' * %s: %s' % (key, val)))
254
[12]255                                return True
256
[14]257                if not keyword:
258                        c.notice(to, 'Please specify keywords.')
259                        return False
260
[12]261                if __debug__:
262                        fmt = 'DEBUG> keyword="%s", product_line=%s'
263                        print >> sys.stderr, fmt % (ununicoding(keyword, 'euc-jp'), product_line)
264
265                try:
266                        data = my_amazon.searchByKeyword(keyword, product_line=product_line)
267                except my_amazon.AmazonError, err:
[14]268                        c.notice(to, ununicoding(config.get('bot', 'no_products')))
[12]269                        if __debug__:
270                                print >> sys.stderr, 'DEBUG> Caught AmazonError in onmsg_amazon: %s' % str(err)
271                        return False
272
[14]273                return self._process_onmsg(c, e, to, data)
[12]274
[14]275        def onmsg_h(self, c, e, to, args): return self.onmsg_help(c, e, to, args)
276        def onmsg_help(self, c, e, to, args):
277                """Syntax: !help
278                """
279                if __debug__:
280                        print >> sys.stderr, 'DEBUG> in help command: %s' % str(args)
[12]281
[14]282                _from = nm_to_n(e.source()) # ログを流しおしたうのでヘルプは盎接送信元ぞ
283                docs = []
284                for key in dir(self):
285                        val = getattr(self, key, '')
286                        if __debug__:
287                                print >> sys.stderr, 'DEBUG> key=%s, val=%s' % (key, ununicoding(str(val), 'euc-jp'))
288
289                        if key[:6] != 'onmsg_':
290                                continue
291
292                        doc = val.__doc__
293                        if doc:
294                                doc = doc.strip()
295                                if not doc:
296                                        continue
297                                time.sleep(1) # XXX: 連続投皿するず匟かれるっぜいので暫定察凊
298                                c.notice(_from, doc)
299
300                return True
301
302        def _process_onmsg(self, c, e, to, data):
[12]303                if type(data.Details) is not list:
304                        data.Details = [data.Details]
305
306                detail = random.choice(data.Details)
307                title = ununicoding(detail.ProductName)
308                url = ununicoding(detail.URL)
[14]309                c.notice(to, '%(title)s: %(url)s' % locals())
[12]310
311                return True
312
[8]313        def process_keyword(self, keyword):
[10]314                keyword = ununicoding(keyword, 'utf-8')
315                if __debug__:
316                        print >> sys.stderr, 'DEBUG> KEYWORD: %s' % ununicoding(keyword, 'euc-jp')
317
[8]318                try:
319                        data = my_amazon.searchByBlended(keyword)
320                        if type(data.ProductLine) is not type([]):
321                                data.ProductLine = [data.ProductLine]
[12]322                except my_amazon.AmazonError, err:
[10]323                        if __debug__:
[12]324                                print >> sys.stderr, 'DEBUG> Caught AmazonError: %s' % str(err)
[8]325                        return [None, None]
326
327                product_line = random.choice(data.ProductLine)
328                detail = random.choice(product_line.ProductInfo.Details)
329
[10]330                url = unicoding(getattr(detail, 'URL', None))
331                product_name = unicoding(getattr(detail, 'ProductName', None))
[8]332
333                return [product_name, url]
334
335if __name__ == '__main__':
336        bot = AmazonBot()
337        bot.start()
[14]338        print '> Bye ;)'
Note: See TracBrowser for help on using the repository browser.