[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 | |
---|
| 10 | import re |
---|
[9] | 11 | import sys |
---|
[10] | 12 | import time |
---|
[12] | 13 | import shlex |
---|
[8] | 14 | import random |
---|
[12] | 15 | import getopt |
---|
| 16 | |
---|
[8] | 17 | import MeCab |
---|
[10] | 18 | import nkf |
---|
[8] | 19 | |
---|
| 20 | from ircbot import SingleServerIRCBot |
---|
| 21 | from irclib import nm_to_n |
---|
| 22 | |
---|
| 23 | import config |
---|
| 24 | config.init() |
---|
| 25 | |
---|
| 26 | import my_amazon |
---|
| 27 | my_amazon.setLocale(config.get('amazon', 'locale')) |
---|
| 28 | my_amazon.setLicense(config.get('amazon', 'access_key')) |
---|
| 29 | |
---|
| 30 | try: |
---|
| 31 | set, frozenset |
---|
| 32 | except NameError: |
---|
| 33 | from sets import Set as set, ImmutableSet as frozenset |
---|
| 34 | |
---|
| 35 | def uniq(sequence): |
---|
[10] | 36 | """ãªã¹ãããéè€ãåãé€ã (é çªãçãã®ã§æ³šæ) |
---|
| 37 | """ |
---|
[8] | 38 | return list(set(sequence)) |
---|
| 39 | |
---|
[10] | 40 | def 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 | |
---|
| 47 | def 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] | 54 | def 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 | |
---|
| 77 | class 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 | |
---|
[15] | 90 | self._prev_time = time.time() - config.get('bot', 'freq', 'int') |
---|
[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__: |
---|
[15] | 115 | print >> sys.stderr, 'DEBUG> pubmsg incoming "%s", should be reply to %s' % (ununicoding(msg, 'euc-jp'), to) |
---|
[14] | 116 | |
---|
[12] | 117 | if msg[0] == '!': |
---|
| 118 | words = shlex.split(ununicoding(msg, 'utf-8')[1:]) |
---|
[16] | 119 | if not words: |
---|
| 120 | return False |
---|
[12] | 121 | method = getattr(self, 'onmsg_%s' % words[0], lambda *arg: False) |
---|
[14] | 122 | return method(c, e, to, words[1:]) # words[0] == command name |
---|
[12] | 123 | |
---|
[11] | 124 | _current_time = time.time() |
---|
| 125 | if _current_time < self._prev_time + config.get('bot', 'freq', 'int'): |
---|
[9] | 126 | if __debug__: |
---|
[15] | 127 | cur = time.strftime('%H:%M:%S', time.localtime(_current_time)) |
---|
[14] | 128 | go = time.strftime('%H:%M:%S', time.localtime(self._prev_time + config.get('bot', 'freq', 'int'))) |
---|
[15] | 129 | print >> sys.stderr, 'DEBUG> Not expired: now %s, be expired at: %s' % (cur, go) |
---|
[9] | 130 | return False |
---|
[11] | 131 | self._prev_time = _current_time |
---|
[10] | 132 | |
---|
[14] | 133 | self.silence(msg, c, e, to) |
---|
[8] | 134 | if self._silent: |
---|
| 135 | return False |
---|
| 136 | |
---|
[10] | 137 | nominals = mecab_parse(msg) |
---|
[8] | 138 | if not nominals: |
---|
[10] | 139 | if __debug__: |
---|
| 140 | print >> sys.stderr, "DEBUG> Couldn't find nominal words" |
---|
[8] | 141 | return False |
---|
| 142 | |
---|
| 143 | title, url = self.process_keyword(' '.join(nominals)) |
---|
| 144 | if title and url: |
---|
[10] | 145 | content = unicoding(config.get('bot', 'content')) |
---|
[9] | 146 | try: |
---|
[10] | 147 | message = ununicoding(': '.join([content, title, url])) |
---|
[12] | 148 | except UnicodeError, err: |
---|
[11] | 149 | # ãªããããŸã« unicode ãªããžã§ã¯ãã iso-2022-jp ã§ãšã³ã³ãŒãã§ããªã |
---|
| 150 | if __debug__: |
---|
[12] | 151 | print >> sys.stderr, 'DEBUG> %s' % str(err) |
---|
[9] | 152 | return False |
---|
| 153 | |
---|
[14] | 154 | c.notice(to, message) |
---|
[8] | 155 | return True |
---|
| 156 | return False |
---|
| 157 | |
---|
[10] | 158 | ACTIVE_PATTERN = re.compile(unicoding(config.get('bot', 'active_pattern'))) |
---|
| 159 | SILENT_PATTERN = re.compile(unicoding(config.get('bot', 'silent_pattern'))) |
---|
[14] | 160 | def silence(self, msg, c, e, to): |
---|
[10] | 161 | active = self.ACTIVE_PATTERN.search(msg) |
---|
| 162 | silent = self.SILENT_PATTERN.search(msg) |
---|
[9] | 163 | if __debug__: |
---|
[10] | 164 | print >> sys.stderr, 'DEBUG> ACT_PATT: %s, SIL_PATT: %s' % (str(active), str(silent)) |
---|
[9] | 165 | |
---|
| 166 | if active: |
---|
[8] | 167 | self._silent = False |
---|
[14] | 168 | c.notice(to, ununicoding(config.get('bot', 'thanks'))) |
---|
[9] | 169 | elif silent: |
---|
[8] | 170 | self._silent = True |
---|
[14] | 171 | c.notice(to, ununicoding(config.get('bot', 'sorry'))) |
---|
[8] | 172 | |
---|
| 173 | def process_keyword(self, keyword): |
---|
| 174 | return [None, None] |
---|
| 175 | |
---|
| 176 | class AmazonBot(AmazonBotBase): |
---|
[10] | 177 | """ã¢ããŸã³ãããã®å®è£
ã¯ã©ã¹ |
---|
| 178 | process_keyword ã¡ãœãã㧠Amazon ãžã¯ãšãªãæããŠçµæãè¿ã |
---|
| 179 | """ |
---|
[14] | 180 | _AVAIL_PRODUCT_LINES = { |
---|
| 181 | 'books-jp': '(åæž, default)', |
---|
| 182 | 'books-us': '(æŽæž)', |
---|
| 183 | 'music-jp': '(ããã¥ã©ãŒé³æ¥œ)', |
---|
| 184 | 'classical-jp': '(ã¯ã©ã·ãã¯é³æ¥œ)', |
---|
| 185 | 'dvd-jp': '(DVD)', |
---|
| 186 | 'vhs-jp': '(ãããª)', |
---|
| 187 | 'electronics-jp': '(ãšã¬ã¯ãããã¯ã¹)', |
---|
| 188 | 'kitchen-jp': '(ããŒã ïŒãããã³)', |
---|
| 189 | 'software-jp': '(ãœãããŠã§ã¢)', |
---|
| 190 | 'videogames-jp': '(ã²ãŒã )', |
---|
| 191 | 'magazines-jp': '(éèª)', |
---|
| 192 | 'toys-jp': '(ããã¡ãïŒãããŒ)', |
---|
| 193 | } |
---|
| 194 | |
---|
[8] | 195 | def __init__(self): |
---|
| 196 | AmazonBotBase.__init__(self) |
---|
| 197 | |
---|
[10] | 198 | def get_version(self): |
---|
| 199 | return 'AmazonBot by %s, based on python-irclib' % __author__ |
---|
| 200 | |
---|
[14] | 201 | def onmsg_isbn(self, c, e, to, args): |
---|
[12] | 202 | """Syntax: !isbn <ISBN number> |
---|
| 203 | """ |
---|
[14] | 204 | return self.onmsg_asin(c, e, to, args) |
---|
| 205 | def onmsg_asin(self, c, e, to, args): |
---|
[12] | 206 | """Syntax: !asin <ASIN number> |
---|
| 207 | """ |
---|
| 208 | if __debug__: |
---|
| 209 | print >> sys.stderr, 'DEBUG> in asin command: %s' % str(args) |
---|
| 210 | |
---|
| 211 | try: |
---|
| 212 | data = my_amazon.searchByASIN(args[0]) |
---|
| 213 | except my_amazon.AmazonError, err: |
---|
[14] | 214 | c.notice(to, ununicoding(config.get('bot', 'no_products'))) |
---|
[12] | 215 | if __debug__: |
---|
| 216 | print >> sys.stderr, 'DEBUG> Caught AmazonError in onmsg_asin: %s' % str(err) |
---|
| 217 | return False |
---|
[14] | 218 | except IndexError, err: |
---|
| 219 | c.notice(to, 'Please specify an argument.') |
---|
| 220 | return False |
---|
[12] | 221 | |
---|
[14] | 222 | return self._process_onmsg(c, e, to, data) |
---|
[12] | 223 | |
---|
[14] | 224 | def onmsg_k(self, c, e, to, args): return self.onmsg_keyword(c, e, to, args) |
---|
| 225 | def onmsg_keyword(self, c, e, to, args): |
---|
| 226 | """Syntax: !keyword [-h] [-t type] <keyword1> [, keyword2, ...] |
---|
[12] | 227 | """ |
---|
| 228 | if __debug__: |
---|
[14] | 229 | print >> sys.stderr, 'DEBUG> in keyword command: %s' % str(args) |
---|
[12] | 230 | |
---|
| 231 | try: |
---|
| 232 | options, rest = getopt.getopt(args, 't:h', ['type=', 'help']) |
---|
| 233 | except getopt.GetoptError, err: |
---|
| 234 | if __debug__: |
---|
[14] | 235 | print >> sys.stderr, 'DEBUG> Caught GetoptError in onmsg_keyword: %s' % str(err) |
---|
[12] | 236 | return False |
---|
| 237 | |
---|
[14] | 238 | keyword = ' '.join(rest).strip() |
---|
[12] | 239 | product_line = 'books-jp' |
---|
| 240 | for opt, val in options: |
---|
| 241 | if opt in ['-t', '--type']: |
---|
[14] | 242 | if val not in self._AVAIL_PRODUCT_LINES.keys(): |
---|
| 243 | c.notice(to, 'Type "%s" is not available.' % val) |
---|
| 244 | return False |
---|
| 245 | |
---|
[12] | 246 | product_line = val |
---|
| 247 | break |
---|
[14] | 248 | |
---|
[12] | 249 | elif opt in ['-h', '--help']: |
---|
[14] | 250 | _from = nm_to_n(e.source()) # ãã°ãæµããŠããŸãã®ã§ãã«ãã¯çŽæ¥éä¿¡å
ãž |
---|
| 251 | c.notice(_from, ununicoding('Available types:')) |
---|
| 252 | |
---|
| 253 | for key, val in self._AVAIL_PRODUCT_LINES.iteritems(): |
---|
| 254 | time.sleep(1) # XXX: é£ç¶æçš¿ãããšåŒŸãããããšãããã®ã§æ«å®å¯ŸåŠ |
---|
| 255 | c.notice(_from, ununicoding(' * %s: %s' % (key, val))) |
---|
| 256 | |
---|
[12] | 257 | return True |
---|
| 258 | |
---|
[14] | 259 | if not keyword: |
---|
| 260 | c.notice(to, 'Please specify keywords.') |
---|
| 261 | return False |
---|
| 262 | |
---|
[12] | 263 | if __debug__: |
---|
| 264 | fmt = 'DEBUG> keyword="%s", product_line=%s' |
---|
| 265 | print >> sys.stderr, fmt % (ununicoding(keyword, 'euc-jp'), product_line) |
---|
| 266 | |
---|
| 267 | try: |
---|
| 268 | data = my_amazon.searchByKeyword(keyword, product_line=product_line) |
---|
| 269 | except my_amazon.AmazonError, err: |
---|
[14] | 270 | c.notice(to, ununicoding(config.get('bot', 'no_products'))) |
---|
[12] | 271 | if __debug__: |
---|
| 272 | print >> sys.stderr, 'DEBUG> Caught AmazonError in onmsg_amazon: %s' % str(err) |
---|
| 273 | return False |
---|
| 274 | |
---|
[14] | 275 | return self._process_onmsg(c, e, to, data) |
---|
[12] | 276 | |
---|
[14] | 277 | def onmsg_h(self, c, e, to, args): return self.onmsg_help(c, e, to, args) |
---|
| 278 | def onmsg_help(self, c, e, to, args): |
---|
| 279 | """Syntax: !help |
---|
| 280 | """ |
---|
| 281 | if __debug__: |
---|
| 282 | print >> sys.stderr, 'DEBUG> in help command: %s' % str(args) |
---|
[12] | 283 | |
---|
[14] | 284 | _from = nm_to_n(e.source()) # ãã°ãæµããŠããŸãã®ã§ãã«ãã¯çŽæ¥éä¿¡å
ãž |
---|
| 285 | docs = [] |
---|
| 286 | for key in dir(self): |
---|
| 287 | val = getattr(self, key, '') |
---|
| 288 | if __debug__: |
---|
| 289 | print >> sys.stderr, 'DEBUG> key=%s, val=%s' % (key, ununicoding(str(val), 'euc-jp')) |
---|
| 290 | |
---|
| 291 | if key[:6] != 'onmsg_': |
---|
| 292 | continue |
---|
| 293 | |
---|
| 294 | doc = val.__doc__ |
---|
| 295 | if doc: |
---|
| 296 | doc = doc.strip() |
---|
| 297 | if not doc: |
---|
| 298 | continue |
---|
| 299 | time.sleep(1) # XXX: é£ç¶æçš¿ãããšåŒŸãããã£ãœãã®ã§æ«å®å¯ŸåŠ |
---|
| 300 | c.notice(_from, doc) |
---|
| 301 | |
---|
| 302 | return True |
---|
| 303 | |
---|
| 304 | def _process_onmsg(self, c, e, to, data): |
---|
[12] | 305 | if type(data.Details) is not list: |
---|
| 306 | data.Details = [data.Details] |
---|
| 307 | |
---|
| 308 | detail = random.choice(data.Details) |
---|
| 309 | title = ununicoding(detail.ProductName) |
---|
| 310 | url = ununicoding(detail.URL) |
---|
[14] | 311 | c.notice(to, '%(title)s: %(url)s' % locals()) |
---|
[12] | 312 | |
---|
| 313 | return True |
---|
| 314 | |
---|
[8] | 315 | def process_keyword(self, keyword): |
---|
[10] | 316 | keyword = ununicoding(keyword, 'utf-8') |
---|
| 317 | if __debug__: |
---|
| 318 | print >> sys.stderr, 'DEBUG> KEYWORD: %s' % ununicoding(keyword, 'euc-jp') |
---|
| 319 | |
---|
[8] | 320 | try: |
---|
| 321 | data = my_amazon.searchByBlended(keyword) |
---|
| 322 | if type(data.ProductLine) is not type([]): |
---|
| 323 | data.ProductLine = [data.ProductLine] |
---|
[12] | 324 | except my_amazon.AmazonError, err: |
---|
[10] | 325 | if __debug__: |
---|
[12] | 326 | print >> sys.stderr, 'DEBUG> Caught AmazonError: %s' % str(err) |
---|
[8] | 327 | return [None, None] |
---|
| 328 | |
---|
| 329 | product_line = random.choice(data.ProductLine) |
---|
| 330 | detail = random.choice(product_line.ProductInfo.Details) |
---|
| 331 | |
---|
[10] | 332 | url = unicoding(getattr(detail, 'URL', None)) |
---|
| 333 | product_name = unicoding(getattr(detail, 'ProductName', None)) |
---|
[8] | 334 | |
---|
| 335 | return [product_name, url] |
---|
| 336 | |
---|
| 337 | if __name__ == '__main__': |
---|
| 338 | bot = AmazonBot() |
---|
| 339 | bot.start() |
---|
[14] | 340 | print '> Bye ;)' |
---|