usr bin python encoding utf-8 import weechat import re import psycopg2

  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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
#!/usr/bin/python
# -*- encoding: utf-8 -*-
import weechat
import re
import psycopg2, psycopg2.extensions
import traceback
from random import random, sample
from time import time
from itertools import groupby, ifilter
from locale import getlocale
local_charset = getlocale()[1]
bot_nickname = 'FYHT'
server_name = 'omskirc'
channel_name = '#buktopuha'
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
connection = psycopg2.connect(database = "buktopuha")
connection.set_client_encoding('UNICODE')
def cleanup():
global connection
connection.close()
connection = None
return weechat.PLUGIN_RC_OK
def urlGrabParsemsg(server, command):
# :nick!ident@host PRIVMSG dest :foobarbaz
l = command.split(' ')
mask = l[0][1:]
nick = mask.split("!")[0]
dest = l[2]
message = ' '.join(l[3:])[1:]
###########################################
#nothing, info, message = command.split(":", 2)
#info = info.split(' ')
if dest == weechat.get_info('nick', server):
channel = nick
else:
channel = dest
return (nick, channel, message)
# ERROR: value too long for type character(40)
# CONTEXT: COPY words, line 667658, column word: "японскаянациональнаяодеждасвободногопокроя"
send_queue = []
def flush_queue():
global send_queue
now = time()
local_queue, send_queue = send_queue, []
for do_send, queue in groupby(local_queue, lambda p: p[2] < now):
if do_send:
for func, msg, time_to_send in queue:
if func == 'command':
if weechat.get_plugin_config('debug'):
weechat.prnt((u'>>> ' + msg).encode(local_charset), channel_name, server_name)
else:
weechat.command(msg.encode(local_charset), channel_name, server_name)
elif func == 'prnt':
weechat.prnt(msg.encode(local_charset), channel_name, server_name)
else:
raise NotImplementedError, 'what is %s?' % func
# BUGZZZ: weechat.remove_timer_handler("flush_queue")
else:
send_queue = [i for i in queue]
return weechat.PLUGIN_RC_OK
def drop_queue():
global send_queue
send_queue = []
def enqueue(command, delay = 0):
global send_queue
send_queue.append(('command', command, time() + delay))
# BUGZZZ: weechat.add_timer_handler(1, "flush_queue")
def echo(line, delay = 0):
global send_queue
send_queue.append(('prnt', line, time() + delay))
# BUGZZZ: weechat.add_timer_handler(1, "flush_queue")
def latinize(line):
c = weechat.get_plugin_config('do_latinize')
if c and c[0].lower() == 'y':
cyr2lat = (
(u'е', u'e'),
(u'т', u't'),
(u'о', u'o'),
(u'р', u'p'),
(u'а', u'a'),
# (u'н', u'h'),
(u'к', u'k'),
(u'х', u'x'),
(u'с', u'c'),
# (u'в', u'b'),
(u'м', u'm'),
# (u'и', u'i'),
)
line = line.lower()
for cyr, lat in cyr2lat:
line = line.replace(cyr, lat)
return line
def get_bool(cfgname):
c = weechat.get_plugin_config(cfgname)
return c and c[0].lower() == 'y'
def on_msg(server, args):
global send_queue
nick, chan, message = urlGrabParsemsg(server, args)
message = unicode(message, local_charset)
read_cps = float(weechat.get_plugin_config('read_cps') or 60)
write_cps = float(weechat.get_plugin_config('write_cps') or 9)
max_delay = float(weechat.get_plugin_config('max_delay') or 9)
reply_probability = float(weechat.get_plugin_config('reply_probability') or 0)
shit_probability = float(weechat.get_plugin_config('shit_probability') or 0)
mindspeed_multiplier = float(weechat.get_plugin_config('mindspeed_multiplier') or 3)
if chan == channel_name and server == server_name and nick == bot_nickname:
message = re.sub(ur'\x03(?:[01].|3)?', '', message)
match = re.match(u'(?:Bоnpoс #\d+|Экстра Bоnpoс): (.*) \((\d+) букв\)', message)
if match and random() < reply_probability:
drop_queue()
if len(weechat.get_plugin_config('dump_message')) > 1:
echo(message)
question = match.group(1)
no_of_alphas = int(match.group(2))
words = set([word.lower() for word in re.findall(u'\w+', question, re.UNICODE)])
# echo(u"Quest: [%s]" % ', '.join(words))
# echo(u"Alpha: %i" % no_of_alphas)
try:
ph = ', '.join(('%s', ) * len(words))
cursor = connection.cursor()
start = time()
cursor.execute(
"""SELECT COUNT(definer_id) AS matches, word FROM defs JOIN words ON (term_id = word_id)
WHERE definer_id IN(SELECT word_id FROM words WHERE word IN (""" + ph + """)) AND LENGTH(word) = %s
GROUP BY term_id,word HAVING COUNT(definer_id) > 1 ORDER BY matches DESC LIMIT 10""",
tuple(words) + (no_of_alphas, ))
variants = cursor.fetchall()
end = time()
db_delay = end - start
reply = None
if len(variants) == 1 or len(variants) > 0 and variants[0][0] > variants[1][0]:
reply = latinize(variants[0][1])
if get_bool('dump_variants'):
if len(variants):
for matches, list in groupby(variants, lambda row: row[0]):
list = [row[1].strip() for row in list]
list.sort()
echo(u"%i совпадений: %s" % (matches, u' '.join(list)))
if get_bool('dump_only_match'):
break
elif not variants:
echo(u"Не осилил, тупил %f с" % db_delay)
if random() < shit_probability:
reply = sample((
u'многочлен',
u'треугольник',
u'серпинский',
u'вагина',
u'петрович',
u'октаэдр',
u'пенис'), 1)[0]
if reply:
delay = len(question) / read_cps + mindspeed_multiplier * db_delay + len(reply) / write_cps
delay = min(delay, max_delay + (random() - 0.5))
if get_bool('dump_time'):
echo(u"Нашел ответ за %f c... Задержка ответа - %f c" % (db_delay, delay))
enqueue(reply, delay)
except Exception, e:
traceback.print_exception(None, e, None)
return weechat.PLUGIN_RC_OK
if weechat.register("buktopuha", "0.0", "cleanup", "buktopuha autosolver"):
weechat.add_message_handler("privmsg", "on_msg")
weechat.add_timer_handler(1, "flush_queue")
# vim:set tabstop=4 softtabstop=4 shiftwidth=4:
# vim:set foldmethod=marker foldlevel=32 foldmarker={{{,}}}:
# vim:set expandtab: