Script: triggerreply.py

Automatically replies over specified triggers.
Author: Vlad Stoica — Version: 0.4.4 — License: GPL3
For WeeChat ≥ 0.4.0, requires: sqlite3.
Tags: reply, py2, py3
Added: 2015-03-22 — Updated: 2022-07-07

Download GitHub Repository

  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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
"""
Copyright (c) 2014-2018 by Vlad Stoica <stoica.vl@gmail.com>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

History
-------
01-05-2014 - Vlad Stoica
Uses a sqlite3 database to store triggers with the replies, has the
ability to ignore channels.
16-08-2015 - Vlad Stoica
Fixed a bug where replies couldn't have `:' in them.
15-02-2018 - Vlad Stoica
Added regex support in triggers, and edited syntax of adding triggers.
The command is now 'add "trigger" "reply"'. Quote marks can be escaped
in triggers or replies by prefixing them with a backslash ('\'). For
example, 'add "\"picture\"" "say \"cheese\"!"' is a valid command and
will reply with 'say "cheese"!' whenever it finds '"picture"' sent.
29-04-2020 - Fisher
Some new functions:
      - multiple matches ("match1|match2|match3" etc)
      - random selected multiple replites ("reply1|reply2|reply3" etc)
      - can ignore nicks (and ignore itself) for example bots
      - matches now case insensitive
      - utf-8 added
      - cooldown (max. n replies in t time)
      - random delay, so more human-like
      - even more randomness: can specify randomness of the reply/replies group.
2020-09-05 - new function - actions
2021-05-06 - Sébastien Helleu <flashcode@flashtux.org>
Add compatibility with WeeChat >= 3.2 (XDG directories).

2022-07-22 - Nils Görs (libera.#weechat)
      - fix bug: https://github.com/weechat/scripts/issues/459
      - add autocompletion
      - add option for sqlite3 filename
      - help text will be displayed using /help command

Bugs: not that i'm aware of.
"""

try:
    import weechat
    import sqlite3
    import re
    import random
    import sys
except ImportError:
    raise ImportError("Failed importing weechat, sqlite3, re or random")
import os

SCRIPT_NAME = "triggerreply"
SCRIPT_AUTHOR = "Vlad Stoica <stoica.vl@gmail.com>"
SCRIPT_VERSION = "0.4.4"
SCRIPT_LICENSE = "GPL3"
SCRIPT_DESC = "Auto replies when someone sends a specified trigger. Now with 100% more regex!"
pcooldown  = 1
""" This is all I need so far :) """
colorcodes = { "^Cb":"\x02","^CR":"\x0F","^Ci":"\x1D" }

def cooldown_timer_cb(data, remaining_calls):
    global pcooldown
    if ( pcooldown > 0 ):
         pcooldown -= 1
    return weechat.WEECHAT_RC_OK

def print_help():
    weechat.prnt('','%s%s %s %s' % (weechat.prefix('error'),SCRIPT_NAME,': see /help',SCRIPT_NAME))
    return weechat.WEECHAT_RC_OK

def debug(mlevel, message):
    if int(weechat.config_get_plugin('debug')) >= int(mlevel):
       weechat.prnt("", "DEBUG: %s" % message)

def create_db(delete=False):
    debug(3, "Creating basic database.")
    """ create the sqlite database """
    if delete:
        os.remove(db_file)
    temp_con = sqlite3.connect(db_file)
    cur = temp_con.cursor()
    cur.execute("CREATE TABLE triggers(id INTEGER PRIMARY KEY, trig VARCHAR, reply VARCHAR, prob INTEGER);")
    cur.execute("INSERT INTO triggers(trig, reply, prob) VALUES ('trigge.rs', 'Automatic reply', '1');")
    cur.execute("CREATE TABLE banchans(id INTEGER PRIMARY KEY, ignored VARCHAR);")
    cur.execute("INSERT INTO banchans(ignored) VALUES ('rizon.#help');")
    cur.execute("CREATE TABLE ignorenicks(id INTEGER PRIMARY KEY, ignored VARCHAR);")
    cur.execute("INSERT INTO ignorenicks(ignored) VALUES ('dumanet.#DumaNet.Neo');")
    temp_con.commit()
    cur.close()



def check_db():
    temp_con = sqlite3.connect(db_file)
    cur = temp_con.cursor()

    try:
        """ Try to add record enchated with probability """
        cur.execute("INSERT INTO triggers(trig, reply, prob) VALUES (?,?,?)", ('JJORAIGPADMLOLYUGSBZ',"",1))
    except:
        """ If it fails, hope the best and assume it is just an older schema """
        cur.execute("ALTER TABLE triggers ADD COLUMN prob INTEGER")

    """ Clean up the mess """
    cur.execute("DELETE FROM triggers WHERE trig='JJORAIGPADMLOLYUGSBZ'")
    temp_con.commit()
    cur.close()



def search_trig_cb(data, buf, date, tags, displayed, highlight, prefix, message):
    """ function for parsing sent messages """
    global pcooldown

    """ Prevent infinite loop/flood, no more messages than n (approx 3) in 300 secs """
    if ( pcooldown > 300 ): return weechat.WEECHAT_RC_OK

    """ Save some CPU cycles """
    if (prefix == '-->' or prefix == '<--' or prefix == '--' or prefix == ' *' or prefix == ""): return weechat.WEECHAT_RC_OK

    bufname = weechat.buffer_get_string(buf, "name")

    if bufname == 'weechat': return weechat.WEECHAT_RC_OK

    """ Ignore myself """
    mynick =  weechat.buffer_get_string(buf, "localvar_nick")
    if re.search('[@+~]?' + mynick, prefix):
        """ weechat.prnt("", "Ignored myself.") """
        return weechat.WEECHAT_RC_OK


    database = sqlite3.connect(db_file)
    cursor = database.cursor()
    pure = weechat.string_remove_color(message,"")

    debug(1, "Nick in question:'%s" % bufname + '.' + prefix.translate(None,'@+~') + "'")

    for row in cursor.execute("SELECT ignored from ignorenicks;"):
        if re.search(row[0], bufname + '.' + prefix.translate(None,'@+~')):
            """ weechat.prnt("", "Nick ignored: %s" % row[0]) """
            return weechat.WEECHAT_RC_OK

    for row in cursor.execute("SELECT ignored from banchans;"):
        if  bufname == row[0]:
            return weechat.WEECHAT_RC_OK

    for row in cursor.execute("SELECT * FROM triggers"):
        delay = random.randint(4,9)

        pattern = row[1].encode('utf8')
        pattern = pattern.replace("%N", mynick)
        replydata = row[2].encode('utf8')
        prob = int(row[3])

        for ccode, chex in list(colorcodes.items()):
            replydata = replydata.replace(ccode,chex)

        try:
            nick = re.sub('^[+%@]','', prefix)
            debug(2, "prefix: %s, mynick: %s, nick: %s, pattern: %s, prob: %s, pure: %s" % (prefix, mynick, nick, pattern, str(prob), pure))

            r = re.compile(pattern,re.I | re.U)

            if r.search(pure) is not None:
                weechat.prnt("", "Matched")

                """ Meh, not really sure how random it is, but probably good enough """
                if ( prob > 1 and random.randint(1,prob) == 1):
                    debug(1, "Randomly ignored.")
                    return weechat.WEECHAT_RC_OK

                weechat.prnt("", "Match: %s" % r.search(pure).group(0))
                myreply = "n/a"
                if prob < 0:
                    """ -1 means this is action, not saying """
                    delay = 0
                    debug(1,"Command mode triggered.")
                    infolist = weechat.infolist_get("irc_nick", "", bufname.replace(".",","))
                    while weechat.infolist_next(infolist):
                       _nick = weechat.infolist_string(infolist, 'name')
                       if _nick == nick:
                          hostinfo = weechat.infolist_string(infolist,'host')
                          break
                    mask = hostinfo.split('@')[1]
                    weechat.prnt("", "mask: %s" % mask)
                    weechat.infolist_free(infolist)

                    for myreply in replydata.split('|'):
                        myreply = myreply.replace("%n", nick)
                        myreply = myreply.replace("%N", mynick)
                        myreply = myreply.replace("%m", mask)
                        myreply = myreply.replace("%c", bufname.split(".")[1])
                        weechat.prnt("", "Command: %s" % myreply)
                        if delay > 0:
                            weechat.command(buf, "/wait %s %s" % (delay, myreply))
                        else:
                            weechat.command(buf, "%s" % myreply)
                        delay++2

                    return weechat.WEECHAT_RC_OK

                myreply = random.choice(replydata.split('|'))
                myreply = myreply.replace("%n", nick)
                weechat.prnt("", "reply: %s" % myreply)
                weechat.prnt("", "%s triggered." % pattern)
                weechat.command(buf, "/wait %s /say %s" % (delay, myreply))
                pcooldown += 100
        except:
            weechat.prnt("", "NOMatch")
            if pattern == pure:
                weechat.command(buf, "/wait %s /say %s" % (delay, myreply))
                pcooldown += 120

    return weechat.WEECHAT_RC_OK


def command_input_callback(data, buffer, argv):
    """ function called when `/triggerreply args' is run """
    database = sqlite3.connect(db_file)
    cursor = database.cursor()
    command = argv.split()

    if len(command) == 0:
        return weechat.WEECHAT_RC_ERROR

    if command[0] == "list":
        weechat.prnt("", "List of triggers with replies:")
        for row in cursor.execute("SELECT * FROM triggers;"):
            weechat.prnt("", (str(row[0]) + ". " + str(row[1]) + " -> " + str(row[2]) + "  [Prob: " + str(row[3]) + "]"))
#            weechat.prnt("", str(row[0]) + ". " + row[1].encode('utf8') + " -> " + row[2].encode('utf8') + "  [Prob: " + str(row[3]) + "]")

        weechat.prnt("", "\nList of ignored channels:")
        for row in cursor.execute("SELECT ignored FROM banchans;"):
            weechat.prnt("", row[0])

        weechat.prnt("", "\nList of ignored nicks:")
        for row in cursor.execute("SELECT ignored FROM ignorenicks;"):
            weechat.prnt("", str(row[0]))

    elif command[0] == "add":
        if len(argv) == len(command[0]):
            print_help()
            return weechat.WEECHAT_RC_ERROR

        if argv.count('"') < 4:
            print_help()
            return weechat.WEECHAT_RC_ERROR

        pos = []
        for k, v in enumerate(argv):
            if v == '"' and argv[k - 1] != '\\':
                pos.append(k)

        if (len(pos) != 6 and len(pos) != 4):
            print_help()
            return weechat.WEECHAT_RC_ERROR

        trigger = argv[pos[0] + 1:pos[1]].replace('\\"', '"')
        reply = argv[pos[2] + 1:pos[3]].replace('\\"', '"')

        prob = 1
        if (len(pos) == 6):
            prob = int(argv[pos[4] + 1:pos[5]])

        try:
            cursor.execute("INSERT INTO triggers(trig, reply, prob) VALUES (?,?,?)", (trigger, reply, prob))
#            cursor.execute("INSERT INTO triggers(trig, reply, prob) VALUES (?,?,?)", (trigger.encode('utf8'), reply.encode('utf8'), prob))
#            cursor.execute("INSERT INTO triggers(trig, reply, prob) VALUES (?,?,?)", (trigger.decode('utf8'), reply.decode('utf8'), prob))
        except:
            print_help()
            weechat.prnt("", "DB Insert error.")
            return weechat.WEECHAT_RC_ERROR

        database.commit()
        weechat.prnt("", "Trigger added successfully!")
    elif command[0] == "remove":
        if len(argv) == len(command[0]):
            print_help()
            return weechat.WEECHAT_RC_ERROR

        try:
            cursor.execute("DELETE FROM triggers WHERE id = ?", (argv[7:],))
        except:
            print_help()
            return weechat.WEECHAT_RC_ERROR

        database.commit()
        weechat.prnt("", "Trigger successfully removed.")
    elif command[0] == "ignore":
        if len(argv) == len(command[0]):
            print_help()
            return weechat.WEECHAT_RC_ERROR

        try:
            cursor.execute("INSERT INTO banchans(ignored) VALUES (?)", (command[1],))
        except:
            print_help()
            return weechat.WEECHAT_RC_ERROR

        database.commit()
        weechat.prnt("", "Channel successfully added to ignore list!")
    elif command[0] == "parse":
        if len(argv) == len(command[0]):
            print_help()
            return weechat.WEECHAT_RC_ERROR

        try:
            cursor.execute("DELETE FROM banchans WHERE ignored = ?", (command[1],))
        except:
            print_help()
            return weechat.WEECHAT_RC_ERROR

        database.commit()
        weechat.prnt("", "Channnel being watched again.")

    elif command[0] == "ignorenick":
        if len(argv) == len(command[0]):
            print_help()
            return weechat.WEECHAT_RC_ERROR

        try:
            cursor.execute("INSERT INTO ignorenicks(ignored) VALUES (?)", (command[1],))
        except:
            print_help()
            return weechat.WEECHAT_RC_ERROR

        database.commit()
        weechat.prnt("", "Nick successfully added to ignore list!")
    elif command[0] == "watchnick":
        if len(argv) == len(command[0]):
            print_help()
            return weechat.WEECHAT_RC_ERROR

        try:
            cursor.execute("DELETE FROM ignorenicks WHERE ignored = ?", (command[1],))
        except:
            print_help()
            return weechat.WEECHAT_RC_ERROR

        database.commit()
        weechat.prnt("", "Nick successfully removed from ignored.")

    return weechat.WEECHAT_RC_OK


if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE, SCRIPT_DESC, "", ""):
    options = {
        'directory': 'data',
    }

    if weechat.config_get_plugin('database') == "":
        weechat.config_set_plugin('database', "%h/trigge.rs")
        db_file = weechat.string_eval_path_home("%h/trigge.rs", {}, {}, options)
    else:
       db_file = weechat.string_eval_path_home(weechat.config_get_plugin('database'), {}, {}, options)

    if weechat.config_get_plugin('debug') == "":
        weechat.config_set_plugin('debug', "0")

    random.seed()

    if not os.path.isfile(db_file):
        create_db()

    check_db()

    weechat.hook_print("", "", "", 1, "search_trig_cb", "")
    weechat.hook_command(SCRIPT_NAME, SCRIPT_DESC, 'Triggerreply (trigge.rs) script. Automatically replies over specified triggers.\n'
'Usage: /triggerreply [list | add | remove | ignore | parse] ARGUMENTS\n\n'
'Commands:\n'
'    list   - lists the triggers with replies, and ignored channels\n'
'    add    - three arguments: "trigger", "reply" and probability\n'
'           - adds a trigger with the specified reply and probability\n'
'           - probability 1 = 1/1 (100%), 5 = 1/5 (20 %) - optional, default is 1 (100%)\n'
'           - negative probability means action, see examples\n'
'           - %n in the reply will be replaced by the nick of the matching line\n'
'           - %N replaced by "my" nick\n'
'           - %m replaced by host and mask *!*@\n'
'           - %c replaced by channel name\n\n'
'    remove - one argument: "trigger"\n'
'           - remove a trigger\n'
'    ignore - one argument: "server.#channel"\n'
'           - ignores a particular channel from a server\n'
'    parse  - one argument: "server.#channel"\n'
'           - removes a channel from ignored list\n'
'ignorenick - one argument: "server.#channel.Nick"\n'
'           - ignores a particular nick from a server.#channel\n'
'watchnick  - one argument: "server.#channel.Nick"\n'
'           - removes a nick from ignored list\n\n'
'Examples:\n'
'    /triggerreply add "^H(i|ello|ey)[ .!]*" "Hey there!|Hi matey|Aloha!" "1"\n'
'    /triggerreply add "lol" "not funny tho" "5"\n'
'    /triggerreply remove 2\n'
'    /triggerreply ignore rizon.#help\n'
'    /triggerreply parse rizon.#help\n'
'    /triggerreply ignore rizon.#help.\n'
'    /triggerreply ignorenick rizon.#help.Bot\n'
'    /triggerreply watchnick rizon.#help.Bot\n\n'
'Auto greetings:\n'
'/triggerreply add "(hi|hello|hey|howdy)[,: ]+%N" "Hi, %n.|Hello, %n." "1"\n'
'/triggerreply add "%N[,: ]+(hi|hello|hey|howdy)" "Hi, %n.|Helllo, %n." "1"\n\n\n'
'Kick on adult content. Probability -1 means the strings between | are command executed in order:\n'
'/triggerreply add "https?://(www\.)?pornhub\.com|https?://(www\.)?xhamster\.com" "/msg chanserv op %c %N|/kick %n No adult content here, bye|/ban *!*@%m|/msg chanserv deop %c %N" "-1"', "", "list||add||remove||ignore||parse||ignorenick||watchnick",
                         "command_input_callback", "")

    """ fire every sec """
    hook = weechat.hook_timer(1000, 0, 0, "cooldown_timer_cb", "")