source: trunk/amazonbot/amazonbot.py @ 14

Revision 14, 10.0 KB checked in by atzm, 18 years ago (diff)
Line 
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
11import sys
12import time
13import shlex
14import random
15import getopt
16
17import MeCab
18import nkf
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):
36        """リストから重耇を取り陀く (順番が狂うので泚意)
37        """
38        return list(set(sequence))
39
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
54def mecab_parse(text):
55        """MeCab を䜿っお圢態玠解析し固有名詞ず䞀般名詞だけを抜出する
56        """
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):
62                                res.append(unicoding(word))
63                return res
64
65        text = ununicoding(text, 'utf-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):
78        """アマゟンボットのベヌスクラス
79        単䜓では受け取ったメッセヌゞの圢態玠解析ず名詞抜出たでしかやらない
80        サブクラスで process_keyword を実装しお Amazon ぞク゚リを投げるべし
81
82        サブクラスには onmsg_HOGEHOGE(self, conn, ev, to, args) メ゜ッドを䜜るこずでコマンド远加可胜
83        コマンド曞匏は !HOGEHOGE arg [, arg2, ...] ずなる
84        ヘルプはメ゜ッドに docstring を曞けば OK
85        """
86        def __init__(self):
87                _server = [(config.get('irc', 'server'), config.get('irc', 'port', 'int'))]
88                _nick = config.get('bot', 'nick')
89
90                self._prev_time = time.time()
91                self._silent = False
92                SingleServerIRCBot.__init__(self, _server, _nick, _nick)
93
94        def start(self):
95                try:
96                        SingleServerIRCBot.start(self)
97                except KeyboardInterrupt:
98                        self.die(ununicoding(config.get('bot', 'bye')))
99
100        def on_welcome(self, c, e):
101                c.join(config.get('irc', 'channel'))
102                if __debug__:
103                        print >> sys.stderr, 'DEBUG> Joined %s' % config.get('irc', 'channel')
104
105        def on_nicknameinuse(self, c, e):
106                c.nick(c.get_nickname() + '_')
107
108        def on_privmsg(self, c, e):
109                return self.on_pubmsg(c, e, to=nm_to_n(e.source()))
110
111        def on_pubmsg(self, c, e, to=config.get('irc', 'channel')):
112                msg = unicoding(e.arguments()[0])
113
114                if __debug__:
115                        print >> sys.stderr, 'DEBUG> pubmsg incoming "%s", reply to %s' % (ununicoding(msg, 'euc-jp'), to)
116
117                if msg[0] == '!':
118                        words = shlex.split(ununicoding(msg, 'utf-8')[1:])
119                        method = getattr(self, 'onmsg_%s' % words[0], lambda *arg: False)
120                        return method(c, e, to, words[1:]) # words[0] == command name
121
122                _current_time = time.time()
123                if _current_time < self._prev_time + config.get('bot', 'freq', 'int'):
124                        if __debug__:
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)
128                        return False
129                self._prev_time = _current_time
130
131                self.silence(msg, c, e, to)
132                if self._silent:
133                        return False
134
135                nominals = mecab_parse(msg)
136                if not nominals:
137                        if __debug__:
138                                print >> sys.stderr, "DEBUG> Couldn't find nominal words"
139                        return False
140
141                title, url = self.process_keyword(' '.join(nominals))
142                if title and url:
143                        content = unicoding(config.get('bot', 'content'))
144                        try:
145                                message = ununicoding(': '.join([content, title, url]))
146                        except UnicodeError, err:
147                                # なぜかたたに unicode オブゞェクトを iso-2022-jp で゚ンコヌドできない
148                                if __debug__:
149                                        print >> sys.stderr, 'DEBUG> %s' % str(err)
150                                return False
151
152                        c.notice(to, message)
153                        return True
154                return False
155
156        ACTIVE_PATTERN = re.compile(unicoding(config.get('bot', 'active_pattern')))
157        SILENT_PATTERN = re.compile(unicoding(config.get('bot', 'silent_pattern')))
158        def silence(self, msg, c, e, to):
159                active = self.ACTIVE_PATTERN.search(msg)
160                silent = self.SILENT_PATTERN.search(msg)
161                if __debug__:
162                        print >> sys.stderr, 'DEBUG> ACT_PATT: %s, SIL_PATT: %s' % (str(active), str(silent))
163
164                if active:
165                        self._silent = False
166                        c.notice(to, ununicoding(config.get('bot', 'thanks')))
167                elif silent:
168                        self._silent = True
169                        c.notice(to, ununicoding(config.get('bot', 'sorry')))
170
171        def process_keyword(self, keyword):
172                return [None, None]
173
174class AmazonBot(AmazonBotBase):
175        """アマゟンボットの実装クラス
176        process_keyword メ゜ッドで Amazon ぞク゚リを投げお結果を返す
177        """
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
193        def __init__(self):
194                AmazonBotBase.__init__(self)
195
196        def get_version(self):
197                return 'AmazonBot by %s, based on python-irclib' % __author__
198
199        def onmsg_isbn(self, c, e, to, args):
200                """Syntax: !isbn <ISBN number>
201                """
202                return self.onmsg_asin(c, e, to, args)
203        def onmsg_asin(self, c, e, to, args):
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:
212                        c.notice(to, ununicoding(config.get('bot', 'no_products')))
213                        if __debug__:
214                                print >> sys.stderr, 'DEBUG> Caught AmazonError in onmsg_asin: %s' % str(err)
215                        return False
216                except IndexError, err:
217                        c.notice(to, 'Please specify an argument.')
218                        return False
219
220                return self._process_onmsg(c, e, to, data)
221
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, ...]
225                """
226                if __debug__:
227                        print >> sys.stderr, 'DEBUG> in keyword command: %s' % str(args)
228
229                try:
230                        options, rest = getopt.getopt(args, 't:h', ['type=', 'help'])
231                except getopt.GetoptError, err:
232                        if __debug__:
233                                print >> sys.stderr, 'DEBUG> Caught GetoptError in onmsg_keyword: %s' % str(err)
234                        return False
235
236                keyword = ' '.join(rest).strip()
237                product_line = 'books-jp'
238                for opt, val in options:
239                        if opt in ['-t', '--type']:
240                                if val not in self._AVAIL_PRODUCT_LINES.keys():
241                                        c.notice(to, 'Type "%s" is not available.' % val)
242                                        return False
243
244                                product_line = val
245                                break
246
247                        elif opt in ['-h', '--help']:
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
255                                return True
256
257                if not keyword:
258                        c.notice(to, 'Please specify keywords.')
259                        return False
260
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:
268                        c.notice(to, ununicoding(config.get('bot', 'no_products')))
269                        if __debug__:
270                                print >> sys.stderr, 'DEBUG> Caught AmazonError in onmsg_amazon: %s' % str(err)
271                        return False
272
273                return self._process_onmsg(c, e, to, data)
274
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)
281
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):
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)
309                c.notice(to, '%(title)s: %(url)s' % locals())
310
311                return True
312
313        def process_keyword(self, keyword):
314                keyword = ununicoding(keyword, 'utf-8')
315                if __debug__:
316                        print >> sys.stderr, 'DEBUG> KEYWORD: %s' % ununicoding(keyword, 'euc-jp')
317
318                try:
319                        data = my_amazon.searchByBlended(keyword)
320                        if type(data.ProductLine) is not type([]):
321                                data.ProductLine = [data.ProductLine]
322                except my_amazon.AmazonError, err:
323                        if __debug__:
324                                print >> sys.stderr, 'DEBUG> Caught AmazonError: %s' % str(err)
325                        return [None, None]
326
327                product_line = random.choice(data.ProductLine)
328                detail = random.choice(product_line.ProductInfo.Details)
329
330                url = unicoding(getattr(detail, 'URL', None))
331                product_name = unicoding(getattr(detail, 'ProductName', None))
332
333                return [product_name, url]
334
335if __name__ == '__main__':
336        bot = AmazonBot()
337        bot.start()
338        print '> Bye ;)'
Note: See TracBrowser for help on using the repository browser.