Source

DailyPromptBot / minibot / events.py

   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
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# The Daily Prompt Mini-Bot - A Shut Up and Write Project
# Author: Marc-Alexandre Chan <laogeodritt at arenthil.net>
#-------------------------------------------------------------------------------
#
# Copyright (c) 2012 Marc-Alexandre Chan. Licensed under the GNU GPL version 3
#
# 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/>.
#
#-------------------------------------------------------------------------------

""" Events and commands used by the Minibot event scheduler. """

from minibot.errors import * # Bah!
from minibot.db import Prompt, User, SuggestionThread
from minibot.util import DateParseMixin, MarkdownMixin, DataFormatMixin,\
    classname, get_reddit_url

import praw.objects

from sqlalchemy.sql import desc

from datetime import datetime, timedelta, time as dt_time, date as dt_date
from datetime import timedelta
from calendar import timegm
from urlparse import urlparse
from time     import strftime, localtime, gmtime
import re

# TODO: Organise these events into files/modules

# this is in all superscript (renders equiv. small text) ^(syntax is like this)
_BOT_MSG = ("_Having a problem with DailyPromptBot? Want to comment? You can "
"contact [Laogeodritt](http://www.reddit.com/u/Laogeodritt) or leave us a note "
"on our [issue tracker](https://bitbucket.org/Laogeodritt/dailypromptbot/issues)._"
"\n\n"
"_Would you like to help us improve DailyPromptBot? He's open-source! Here's "
"the [DailyPromptBot repository](https://bitbucket.org/Laogeodritt/dailypromptbot). "
"Feel free to fork him and make a pull request with your changes!_")


class CommandBase(object):
    """ Abstract base class for command events (single-shot events).

    Defaults:
        * ``start_time`` = 0 (immediately)
        * ``duration`` = 0
        * ``interval`` = 0

        """
    start_time = 0 # execute ASAP by default
    duration = 0
    interval = 0
    def start(self): raise NotImplementedError()
    def run(self): pass
    def end(self): raise NotImplementedError()


class CheckMessageEvent(object):
    """ Event to check for new private messages, check whether the command is
    valid and from an authorised user, and queues commands to execute.

    Defaults:
        * ``start_time`` = 0
        * ``duration`` = -1
        * ``interval`` = 60
        * ``priority`` = 90

    """
    required_res = ['reddit', 'approved', 'config.minibot', 'logger']
    start_time = 0
    duration = -1
    interval = 60
    priority = 90

    def __init__(self):
        pass

    def start(self):
        self.reddit = self.res['reddit']
        self.users = self.res['approved']
        self.msg_chunk = self.res['config.minibot'].msg_chunk
        self.log = self.res['logger']

        self.run() # start processing on first execution

    def run(self):
        for msg in self.reddit.user.get_unread(limit=self.msg_chunk):
            try:
                self._process_message(msg)
            except (CommandParseError, CommandNameError,
                    CommandParameterError, MissingParameterError) as e:
                self.log.info("%s: %s", classname(self), e.args[0])

                self.log.info("%s: Replying to invalid command PM from %s (%s)",
                    classname(self), msg.author.name, msg.id)
                err_cmd = SendErrorMessageCommand.command_parameter(e, msg)
                self.owner.queue_event(err_cmd)

                msg.mark_as_read()
            except BadCommandError: # bad message, ignore it
                # if bad PM, log; but don't care about replies/comments
                if msg.subreddit is None:
                    self.log.info(
                        "%s: Ignoring bad private message from %s (%s)",
                        classname(self), msg.author.name, msg.id)
                msg.mark_as_read()

    def end(self):
        pass

    def _process_message(self, msg):
        """ Process a message. May throw CommandParseError, CommandNameError,
        CommandParameterError, MissingParameterError, BadCommandError. """
        if not self._is_valid_message(msg):
            raise BadCommandError('CheckMessageEvent: bad command message', msg)
        # raises CommandParseError
        msg_data = self._parse_message(msg)

        if not self._is_msg_queued(msg, msg_data):
            # build event obj. raises CommandNameError/CommandParameterError
            # or MissingParameterError
            msg_command = self._make_command(msg, msg_data)
            # queue the event in the scheduler
            self.owner.queue_event(msg_command)

    def _is_valid_message(self, msg):
        """ Check whether message source is appropriate for a command message
        (is a PM sent to the bot (not modmail) from an approved user). """
        return (msg.subreddit is None and
                msg.dest == self.reddit.user.name and
                msg.author.name.lower() in self.users)

    # command message parsing variables
    PARSE_FIELD = 0
    PARSE_TEXT = 1
    PARSE_ERROR = -1
    # dict of command_name : command_object - assigned at the end of the file
    cmd_actions = dict()

    def _parse_message(self, msg):
        """ Parse a message's body text for a bot command. Returns a dict
        containing the entries:

        * 'action' = action name (e.g. add, delete, list)
        * name = value (for parameters)
        * 'text' = text block (if available)

        No validation of the data is performed.

        """
        self.log.debug('%s: Parsing message %s from %s.',
            classname(self), msg.id, msg.author.name)
        msg_data = {}
        text_data = []

        # set up parsing line-by-line
        lineno = 0
        lines = msg.body.splitlines()
        state = self.PARSE_FIELD

        for line in lines:
            if state == self.PARSE_ERROR:
                break

            elif state == self.PARSE_FIELD:
                line = line.strip() # ignore whitespace around line

                # if not blank, parse as field
                if line:
                    try:
                        field_data = self._parse_field(line)
                        msg_data[field_data[0].lower()] = field_data[1]
                    except CommandParseError as e:
                        # if first line and is the action name, ignore
                        if not msg_data and line == msg.subject.strip().lower():
                            continue
                        # otherwise it's a parse error
                        raise CommandParseError(
                            'Parse error in {info}: {error}'.format(\
                            info=self._exc_msg_data(msg), error=str(e)))
                # else if blank line, denotes the start of text data
                else:
                    state = self.PARSE_TEXT

            elif state == self.PARSE_TEXT:
                text_data.append(line)

        # get the command from the subject field
        # done at end to overwrite any (erroneous) action field in body
        msg_data['action'] = msg.subject.strip().lower()

        if text_data:
            msg_data['text'] = '\n'.join(text_data)

        return msg_data

    def _parse_field(self, line):
        """ Parse a message line as a field. Returns a (fieldname, fieldval)
        pair. Whitespace is stripped from each value. If the line is an invalid
        parameter/field line, throws CommandParseError. """
        eq_pos  = line.find('=')
        col_pos = line.find(':')

        if eq_pos >= 0 and col_pos >= 0: # both are present - take first occurr.
            sep_pos = min(eq_pos, col_pos)
        else: # one isn't present - take the one that is present
            sep_pos = max(eq_pos, col_pos)

        field_data = (line[0:sep_pos].strip(), line[sep_pos+1:].strip())

        # check for valid data extracted
        if not field_data[0]:
            raise CommandParseError(
                    ''.join(["No parameter name in line: \"", line, "\""]))
        elif sep_pos == -1:
            raise CommandParseError(
                    ''.join(["No parameter value in line: \"", line, "\""]))

        self.log.debug('%s: Parsed argument line: %s = %s',
            classname(self), field_data[0], field_data[1])

        return field_data

    def _is_msg_queued(self, msg, data):
        """ Check whether an event is already queued in the event scheduler
        for this message. Returns a boolean. """
        if data['action'] in self.cmd_actions.keys():
            CommandClass = self.cmd_actions[data.get('action')]
            for ev in self.owner.get_events(CommandClass):
                if ev.msg.id == msg.id:
                    return True
            return False
        else:
            raise CommandNameError(
                    ''.join(["Unknown command '", data['action'], "' in ",
                             self._exc_msg_data(msg)]))

    def _make_command(self, msg, data):
        """ Build a bot command object from ``_parse_message()``'s message
        data. If the command name is invalid, raises a CommandNameError. If the
        command parameters are invalid or incomplete, raises a
        CommandParametersError (from the command constructor). """
        self.log.info('%s: message %s: building command: %s',
            classname(self), msg.id,
            '; '.join(['='.join([x, y]) for x, y in data.iteritems()]))
        if data.has_key('action') and data['action'] in self.cmd_actions.keys():
            CommandClass = self.cmd_actions[data.pop('action')]
            cmd_obj = CommandClass(msg, **data)
            cmd_obj.start_time = 0
        else:
            raise CommandNameError(
                    ''.join(["Unknown command '", data['action'], "' in ",
                             self._exc_msg_data(msg)]))
        return cmd_obj

    def handle_exception(self, e):
        # expected recoverable exceptions are handled in the code
        # and Reddit errors are handled by the scheduler
        return self.owner.EXC_UNHANDLED

    def __repr__(self):
        return ''.join(['<', classname(self), '>'])

    def _exc_msg_data(self, msg):
        """ Return info string on a message for use in exceptions. """
        return 'message "{subject}" from {author} at {time}'.format(
            subject=msg.subject, author=msg.author.name,
            time=strftime('%Y-%m-%d %H:%M:%S UTC', gmtime(msg.created_utc)))


class CheckPostQueueEvent(object):
    """ Event to check the current prompt queue for the next post.

    Defaults:
        * ``start_time`` = 0
        * ``duration`` = -1
        * ``interval`` = 60
        * ``priority`` = 80

    """
    required_res = ['dbsession', 'config.minibot', 'logger']
    start_time = 0
    interval = 60
    duration = -1
    priority = 80

    def __init__(self):
        pass

    def start(self):
        self.log = self.res['logger']

        self.run()
        return

    def run(self):
        """ Check for prompts in the queue to be posted before 5*``queue_rate``
        seconds from now (limit entries to the value of ``queue_rate`` in
        seconds). If any are found, they are queued in the event scheduler for
        posting. """
        self.queue_rate = self.res['config.minibot'].queue_rate
        self.db = self.res['dbsession'] # might be updated by the scheduler
        dt_limit = datetime.utcnow() + timedelta(seconds=5*self.queue_rate)

        queued_ids = [ev.post_id for ev in
                      self.owner.get_events(PostPromptCommand)]

        for id_, utc_post in self.db.query(Prompt.id, Prompt.post_time).\
                filter(Prompt.post_time <= dt_limit).\
                filter(Prompt.status == Prompt.STATUS_QUEUED).\
                order_by(Prompt.post_time)[0:int(self.queue_rate)]:
            if id_ not in queued_ids:
                self.log.info("%s: Queuing prompt %d at %s",
                    classname(self), id_,
                    utc_post.strftime("%Y-%m-%d %H:%M:%S UTC"))
                new_cmd = PostPromptCommand(id_, utc_post)
                self.owner.queue_event(new_cmd)
        self.db.close()

    def end(self):
        self.db.close()

    def handle_exception(self, e):
        if isinstance(e, SQLAlchemyError) or\
             isinstance(e, DBAPIError):
            self.res['dbsession'].rollback()
            self.res['dbsession'].close()
            self.delay = 5
            return self.owner.EXC_HANDLED_RETRY
        return self.owner.EXC_UNHANDLED

    def __repr__(self):
        return ''.join(['<', classname(self), '>'])


class CheckSuggestionQueueEvent(object):
    """ Event to check the current suggestion thread queue for the next post.

    Defaults:
        * ``start_time`` = 0
        * ``duration`` = -1
        * ``interval`` = 60
        * ``priority`` = 75

    """
    required_res = ['dbsession', 'config.minibot', 'logger']
    start_time = 0
    interval = 60
    duration = -1
    priority = 75

    def __init__(self):
        pass

    def start(self):
        self.log = self.res['logger']

        self.run()
        return

    def run(self):
        """ Check for threads in the queue to be posted before 5*``queue_rate``
        seconds from now (limit entries to the value of ``queue_rate`` in
        seconds). If any are found, they are queued in the event scheduler for
        posting. """
        self.db = self.res['dbsession'] # might be updated by the scheduler
        self.queue_rate = self.res['config.minibot'].queue_rate
        dt_limit = datetime.utcnow() + timedelta(seconds=5*self.queue_rate)

        queued_ids = [ev.post_id for ev in
                        self.owner.get_events(PostSuggestionThreadCommand)]

        for id_, utc_post in\
                self.db.query(SuggestionThread.id, SuggestionThread.time).\
                filter(SuggestionThread.time <= dt_limit).\
                filter(SuggestionThread.status==SuggestionThread.STATUS_QUEUED).\
                order_by(SuggestionThread.time)[0:int(self.queue_rate)]:
            if id_ not in queued_ids:
                self.log.info("%s: Queuing thread %d at %s", classname(self),
                id_, utc_post.strftime("%Y-%m-%d %H:%M:%S UTC"))
                new_cmd = PostSuggestionThreadCommand(id_, utc_post)
                self.owner.queue_event(new_cmd)
        self.db.close()

    def end(self):
        self.db.close()

    def handle_exception(self, e):
        if isinstance(e, SQLAlchemyError) or\
             isinstance(e, DBAPIError):
            self.res['dbsession'].rollback()
            self.res['dbsession'].close()
            self.delay = 5
            return self.owner.EXC_HANDLED_RETRY
        return self.owner.EXC_UNHANDLED

    def __repr__(self):
        return ''.join(['<', classname(self), '>'])


class SuggestionThreadQueueMaintainer(DateParseMixin):
    """ Skeleton event for the Minibot form of the bot. This event checks
    whether next week's suggestion thread is already queued, and if not,
    queues one the specified weekday at the specified time (both in the
    configuration).

    Defaults:
        * ``start_time`` = 0 (immediately)
        * ``duration`` = -1
        * ``interval`` = 300
        * ``priority`` = 100

        """
    required_res = ['reddit', 'dbsession', 'config.minibot', 'logger']
    start_time = 0
    duration = -1
    interval = 300
    priority = 100

    def __init__(self):
        pass

    def start(self):
        self.log = self.res['logger']
        self.run()

    def run(self):
        reddit = self.res['reddit']
        db     = self.res['dbsession']

        # target day configuration
        post_time = self._parse_datetime(
            time_str=self.res['config.minibot'].suggestions_time)
        post_day = self.res['config.minibot'].suggestions_day

        # current date
        lo_dt_now = datetime.now()
        lo_today = lo_dt_now.weekday()

        # calculate next thread's date + start/end times for that day
        delta_next = timedelta(days=(post_day - lo_today) % 7)
        day_next = lo_dt_now.date() + delta_next
        utc_dt_next = self._utctime(datetime.combine(day_next, dt_time(0,0,0)))
        utc_dt_next_end = utc_dt_next + timedelta(days=1)

        # find any thread on the next post date
        self.log.debug("%s: Checking %s to %s", classname(self),
            utc_dt_next.strftime("%Y-%m-%d %H:%M:%S UTC"),
            utc_dt_next_end.strftime("%Y-%m-%d %H:%M:%S UTC"))
        num_threads = db.query(SuggestionThread).\
                    filter(SuggestionThread.time >= utc_dt_next).\
                    filter(SuggestionThread.time <  utc_dt_next_end).\
                    count()

        # if no thread is found on that day, queue one up
        if num_threads == 0:
            utc_post_dt = self._utctime(datetime.combine(day_next, post_time))
            new_thread = SuggestionThread(utc_post_dt)
            db.add(new_thread)
            self.log.info("%s: Added thread for %s to database",
            classname(self), utc_post_dt.strftime("%Y-%m-%d %H:%M:%S UTC"))
            self.log.debug("%s: %s", classname(self), repr(new_thread))
            db.commit()
        else: # if a thread is found on that day, no action to take
            pass

        db.close()

    def end(self):
        self.res['dbsession'].close()

    def handle_exception(self, e):
        self.res['dbsession'].rollback()
        if isinstance(e, SQLAlchemyError) or\
             isinstance(e, DBAPIError):
            self.res['dbsession'].rollback()
            self.res['dbsession'].close()
            self.delay = 5
            return self.owner.EXC_HANDLED_RETRY
        return self.owner.EXC_UNHANDLED

    def __repr__(self):
        return ''.join(['<', classname(self), '>'])


class PromptCommandBase(CommandBase, DataFormatMixin, DateParseMixin):
    """ Command to process the insertion or modification of a prompt in queue.

    Defaults:
        * ``start_time`` = 0 (immediately)
        * ``duration`` = 0
        * ``interval`` = 0
        * ``priority`` = 50

    """
    required_res = ['reddit', 'dbsession', 'config.minibot', 'logger']
    start_time = 0 # execute ASAP
    priority = 50

    PARAMS = ['title', 'text', 'user', 'submission', 'date', 'time']

    def __init__(self, msg, **kwargs):
        """ Constructor. Keyword arguments are strings defined as per the
        `CheckCommandSpec` class documentation; the text block is expected as
        a 'text' argument. Throws MissingParameterError or CommandParameterError
        on missing or invalid parameters (respectively). """

        self.msg = msg
        self.raw_params = kwargs.copy()
        self.params = dict()
        self._check_param_fields()

    def __repr__(self):
        """ Return a string representing this object. """
        return '<{cls}: message {id_} ({author}), {args}>'.format(
                cls=classname(self), id_=self.msg.id,
                author=self.msg.author.name, args=self.raw_params)

    def _check_param_fields(self):
        """ Check that the parameter fields passed are valid and that all
        required parameters are included. Child classes may override this method
        and call PromptCommandBase's method if they need to include additional
        criteria. Returns True if params are valid, or raises a
        CommandParameterError on errors. """
        input_params = list(self.raw_params.keys())
        unknown_params = list()
        for param in input_params:
            if param not in self.PARAMS:
                # remember param, in single quote marks
                unknown_params.append(''.join(["'", param, "'"]))

        if unknown_params:
            if len(unknown_params) == 1:
                text = "Unknown parameter: {params}"
            else:
                text = "Unknown parameters: {params}"
            raise CommandParameterError(
                text.format(params=', '.join(unknown_params)))

        return True

    def _parse_params(self):
        """ Parse params. Stores a dict ``params`` containing parsed parameters
        with defaults set. Parameters: title, text, user, r_user_id,
        r_source_url, r_approver_id, post_time
        """
        # lazy shorthands 'p' and 'raw'
        raw = self.raw_params
        self.params = p = dict()

        # resources
        reddit = self.res['reddit']

        # store params
        p['title'] = raw.get('title', None)
        p['text'] = raw.get('text', None)

        # post time
        p['post_time'] = self.__parse_param_post_time(
                            raw.get('date', None), raw.get('time', None))

        # submitter (user)
        tmp_user = raw.get('user', None)
        if tmp_user:
            try:
                p['r_user_id'] = reddit.get_redditor(tmp_user).id
                p['user'] = tmp_user
            except HTTPError, AttributeError:
                raise CommandParameterError(
                    ''.join(["Unknown Reddit user: '", tmp_user, "'."]))
        else:
            p['user'] = None
            p['r_user_id'] = None

        # source url - check for reddit domain
        tmp_submission = raw.get('submission', None)
        if tmp_submission:
            source_url_parsed = urlparse(tmp_submission)
            domain = source_url_parsed.netloc
            if domain == reddit.config.domain or\
               domain == reddit.config.domain.replace('www.', '') or\
               domain == reddit.config._short_domain.replace('http://', '').\
                            replace('https://', ''):
                p['r_source_url'] = tmp_submission
            else:
                raise CommandParameterError(''.join(
                    ["Invalid domain on source URL: '", self.submission, "'."]))
        else:
            p['r_source_url'] = None

        # approver
        p['r_approver_id'] = self.msg.author.id

    def __parse_param_post_time(self, datestr, timestr):
        """ Parse date/time params. Returns post time UTC (with default values
        set if params not specified). """
        # parse the input parameters
        if hasattr(datestr, 'strip'): datestr = datestr.strip()
        if hasattr(timestr, 'strip'): timestr = timestr.strip()
        param_datetime = self._parse_datetime(datestr, timestr)

        # determine which defaults to use
        use_default_date = (datestr is None)
        use_default_time = (timestr is None)

        # determine final datetime object
        if use_default_date and use_default_time:
            localtime = datetime.combine(
                            self._get_autodate(), self._get_autotime())
        elif use_default_date:
            # in this case, param_datetime is a dt_time object instead
            localtime = datetime.combine(
                            self._get_autodate(), param_datetime)
        elif use_default_time:
            localtime = datetime.combine(
                            param_datetime.date(), self._get_autotime())
        else:
            localtime = param_datetime

        return self._utctime(localtime)

    def _make_approver_user(self, r_approver_id, approver_name):
        """ If the approver isn't in the User database, make an entry for the
        approver. The action is NOT committed in the DB session. """
        db = self.res['dbsession']
        hash_opts = {'globsalt' : self.res['config.minibot'].hash_salt,
                     'rounds' : self.res['config.minibot'].hash_rounds}

        if not db.query(User).filter(User.r_id==r_approver_id).count():
            self.res['logger'].info(
                "%s: User %s (%s) not found. Adding to database `user` table.",
                classname(self), approver_name, r_approver_id)
            new_user = User(r_approver_id, approver_name, **hash_opts)
            db.add(new_user) # set as unregistered by default
        else:
            self.res['logger'].debug(
                "%s: User %s (%s) found in database `user` table.",
                classname(self), approver_name, r_approver_id)

    def start(self):
        raise NotImplementedError("PromptCommandBase.start()")

    def run(self):
        """ To be implemented by derived class. Should probably call
        self._parse_params() and self._make_approver_user() at some point. """
        raise NotImplementedError("PromptCommandBase.run()")

    def end(self):
        # close off the session
        self.res['dbsession'].close()
        del self.res['dbsession']

    def handle_exception(self, e):
        # sends an error message, marks msg as read and does NOT requeue
        if isinstance(e, CommandParameterError):
            err_cmd = SendErrorMessageCommand.command_parameter(e, self.msg)
            self.owner.queue_event(err_cmd)
            self.msg.mark_as_read()
            self.res['dbsession'].rollback()
            return self.owner.EXC_HANDLED_FINAL
        elif isinstance(e, SQLAlchemyError) or\
             isinstance(e, DBAPIError):
            self.res['dbsession'].rollback()
            self.delay = 5
            return self.owner.EXC_HANDLED_RETRY
        else:
            self.res['dbsession'].rollback()
            return self.owner.EXC_UNHANDLED

    def _get_autodate(self):
        """ Determine the default date for a new prompt. This is the nearest
        future date that does not already have a prompt queued. Datetimes are
        considered in local time, not UTC."""
        db = self.res['dbsession']
        a_day = timedelta(days=1)
        # get today, local time
        current_date = datetime.now().date()
        # iterate queued prompts for the future
        for q_time in db.query(Prompt.post_time).\
                      filter(Prompt.status == Prompt.STATUS_QUEUED).\
                      filter(Prompt.post_time >= datetime.utcnow()).\
                      order_by(Prompt.post_time):
            q_local_date = self._localtime(q_time[0]).date()
            if current_date == q_local_date:
                current_date += a_day
            elif current_date < q_local_date:
                break
            else:
                continue
        self.res['logger'].debug("%s: Nearest unqueued date found: %s.",
            classname(self), current_date.strftime('%Y-%m-%d'))
        return current_date

    def _get_autotime(self):
        """ Determine the default time for a new prompt. This is set in the
        config.minibot resource. """
        default_time_str = self.res['config.minibot'].default_time
        return self._parse_datetime(default_time_str)


class AddPromptCommand(PromptCommandBase):
    """ Command to add a prompt to the queue.

    Defaults:
        * ``start_time`` = 0 (immediately)
        * ``duration`` = 0
        * ``interval`` = 0
        * ``priority`` =48

    """
    priority = 48
    def __init__(self, msg, **kwargs):
        """ Constructor. Keyword arguments are strings defined as per the
        `CheckCommandSpec` class documentation; the text block is expected as
        a 'text' argument. Throws MissingParameterError or CommandParameterError
        on missing or invalid parameters (respectively). """
        self.added = False
        self.times_delayed = 0
        PromptCommandBase.__init__(self, msg, **kwargs)

    def _check_param_fields(self):
        """ Overriden from PromptCommandBase. """
        if not self.raw_params.get('text', None):
            raise MissingParameterError(
                "The required text block parameter is missing.")
        return PromptCommandBase._check_param_fields(self)

    def start(self):
        self.log = self.res['logger']
        self._parse_params()
        self.run()

    def run(self):
        if not self.added:
            self._run_db()
        self._run_reddit()

    def _run_db(self):
        """ Add the prompt to the DB. Sets self.prompt to the newly-created
        prompt. """
        # shorthand
        p = self.params
        db = self.res['dbsession']

        # guard against re-adding prompt to DB if Reddit errors occur and the
        # event is requeued
        # first check User table for approver
        self._make_approver_user(p['r_approver_id'], self.msg.author.name)

        # now make new prompt entry in queue
        self.prompt = new_prompt = Prompt(
                            p['title'], p['text'], p['r_approver_id'],
                            datetime.utcfromtimestamp(self.msg.created_utc),
                            user=p['user'], user_id=p['r_user_id'],
                            source_url=p['r_source_url'])
        new_prompt.queue(p['post_time']) # already in UTC
        db.add(new_prompt)
        db.commit()
        self.added = True

        self.log.info("%s: Added prompt '%s' (%d) to database queue.",
            classname(self), p['title'], new_prompt.id)
        self.log.debug("%s: %s", classname(self), repr(new_prompt))

        db.close()

    def _run_reddit(self):
        self.msg.mark_as_read()
        self.log.debug("%s: Marked message %s as read.",
            classname(self), self.msg.name)

        reply_topic = "Prompt added"
        reply_text  = ''.join([
                        u"Your prompt has been added.\n\n",
                        self._format_prompt(self.prompt)])
        self.owner.queue_event(
            SendReplyCommand(self.msg, reply_topic, reply_text))


class RemovePromptCommand(CommandBase, DataFormatMixin):
    """ Command to remove a prompt from the queue.

    Defaults:
        * ``start_time`` = 0 (immediately)
        * ``duration`` = 0
        * ``interval`` = 0
        * ``priority`` = 50

    """
    required_res = ['dbsession', 'logger']
    start_time = 0 # execute ASAP
    priority=50

    def __init__(self, msg, **kwargs):
        """ Constructor. Keyword arguments are strings defined as per the
        `CheckCommandSpec` class documentation; the text block is expected as
        a 'text' argument. Throws MissingParameterError or CommandParameterError
        on missing or invalid parameters (respectively). """
        self.msg = msg

        # required params
        try:
            id_ = kwargs.pop('id')
            self.id  = int(id_, 10)
        except KeyError:
            raise MissingParameterError(
                "The required 'id' parameter is missing.")
        except ValueError, TypeError:
            raise CommandParameterError(
                ''.join(["The 'id' parameter is not valid: '", id_, "'."]))

        # if parameters left over, they're not valid
        if len(kwargs):
            if len(kwargs) == 1:
                raise CommandParameterError(
                    "Unknown parameter: " + kwargs.keys()[0])
            else:
                raise CommandParameterError(
                    "Unknown parameters: " + ', '.join(kwargs.keys()))

    def start(self):
        self.run()

    def run(self):
        self._run_db()
        self._run_reddit()

    def _run_db(self):
        """ Remove the prompt from the DB. Sets self.prompt to the deleted
        prompt object. """
        db = self.res['dbsession']
        log = self.res['logger']

        self.prompt = db.query(Prompt).filter(Prompt.id==self.id).first()
        if self.prompt is None:
            raise CommandParameterError(
                ''.join(["Prompt ", self.id, " not found."]))
        self.prompt.reject()
        db.commit()

        log.info("%s: Removed prompt '%s' (%d) from database queue.",
                 classname(self), self.prompt.title, self.prompt.id)

        db.close()

    def _run_reddit(self):
        log = self.res['logger']

        self.msg.mark_as_read()
        log.debug("%s: Marked message %s as read.",
                  classname(self), self.msg.name)

        reply_title = "Prompt deleted"
        reply_text = u"Prompt {id_:d} has been deleted.\n\n{prompt}".\
            format(id_=self.prompt.id, prompt=self._format_prompt(self.prompt))
        self.owner.queue_event(
            SendReplyCommand(self.msg, reply_title, reply_text))

    def end(self):
        self.res['dbsession'].close()
        del self.res['dbsession']

    def __repr__(self):
        return "<{cls}: message={msg_id} ({author}), id={p_id}>".format(
                cls=classname(self), msg_id=self.msg.id,
                author=self.msg.author.name, p_id=self.id)


class UpdatePromptCommand(PromptCommandBase):
    """ Command to remove a prompt from the queue.

    Defaults:
        * ``start_time`` = 0 (immediately)
        * ``duration`` = 0
        * ``interval`` = 0
        * ``priority`` = 49

    """
    priority = 49

    def __init__(self, msg, **kwargs):
        """ Constructor. Keyword arguments are strings defined as per the
        `CheckCommandSpec` class documentation; the text block is expected as
        a 'text' argument. Throws MissingParameterError or CommandParameterError
        on missing or invalid parameters (respectively). """
        self.updated = False
        # add the 'id' param to the allowed params
        self.PARAMS = list(self.PARAMS)
        self.PARAMS.append('id')
        PromptCommandBase.__init__(self, msg, **kwargs)

    def _check_param_fields(self):
        """ Overriden from PromptCommandBase. """
        # required id param
        if self.raw_params.get('id', None) is None:
            raise MissingParameterError(
                "The required 'id' parameter is missing.")
        return PromptCommandBase._check_param_fields(self)

    def start(self):
        # resources
        self.log = self.res['logger']

        # process params
        self._parse_params()

        self.run()

    def _parse_params(self):
        """ Overriden from PromptCommandBase. Sets self.prompt to the
        minibot.db.Prompt object to update. """
        db = self.res['dbsession']

        # id parameter - we need to retrieve it now for datetime preprocessing
        try:
            prompt_id = int(self.raw_params.get('id'), 10)
        except ValueError, TypeError:
            raise CommandParameterError(
                "The 'id' parameter is not valid: '{}'.".format(str_id))

        # retrieve prompt to update and check it
        self.prompt = db.query(Prompt).filter(Prompt.id==prompt_id).first()
        if self.prompt is None:
            raise CommandParameterError(
                "Prompt {:d} not found.".format(prompt_id))
        if self.prompt.status == Prompt.STATUS_POSTED:
            raise CommandParameterError(
                "Prompt {:d} is already posted.".format(prompt_id))
        elif self.prompt.status == Prompt.STATUS_REJECTED:
            raise CommandParameterError(
                "Prompt {:d} is marked as deleted.".format(prompt_id))

        # pre-process datetime raw params
        # so we patch raw_params to change parent._parse_params() bhav
        # _parse_params() original bhav: absent = default value; '' = invalid.
        if self.raw_params.get('date', None) is None: # absent = no change
            # works because DateParseMixin._parse_datetime accepts object
            self.raw_params['date'] = self.prompt.post_time.date()
        elif not self.raw_params.get('date', None): # '' = default value
            self.raw_params['date'] = None

        if self.raw_params.get('time', None) is None: # absent = no change
            # works because DateParseMixin._parse_datetime accepts object
            self.raw_params['time'] = self.prompt.post_time.time()
        elif not self.raw_params.get('time', None): # '' = default value
            self.raw_params['time'] = None

        # call parent
        PromptCommandBase._parse_params(self)

        # set the ID parameter to the params dict
        self.params['id'] = prompt_id

    def run(self):
        if not self.updated:
            # update in database
            self._run_db()
            # remove the prompt from the scheduler queue, if applicable
            self._check_event_queue()
        # send reddit confirmation
        self._run_reddit()

    def _run_db(self):
        """ Update the prompt in the DB. Relies on the prompt object having been
        retrieved and assigned to self.prompt."""
        # shorthand
        db = self.res['dbsession']
        p = self.params
        prompt = self.prompt

        # first check User table for approver
        self._make_approver_user(p['r_approver_id'], self.msg.author.name)

        # now update prompt in database (retrieved in start())
        if p['title'] is not None:
            prompt.title = p['title']
        if p['text'] is not None:
            prompt.text = p['text']

        prompt.queue(p['post_time'])

        if p['user'] is not None:
            prompt.user = p['user']
            prompt.r_user_id = p['r_user_id']

        if p['r_source_url'] is not None:
            prompt.r_source_url = p['r_source_url']

        # update approver - replace as if old queued prompt is replaced
        prompt.r_approver_id = self.msg.author.id

        # update the submit time - treat as if old queued prompt is replaced
        prompt.submit_time = datetime.utcfromtimestamp(self.msg.created_utc)

        # finalise
        db.commit()
        self.updated = True
        self.log.info(
            "%s: Updated prompt '%s' (%d) in database queue.",
            classname(self), p['title'], prompt.id)
        self.log.debug("%s: %s", classname(self), repr(prompt))
        db.close()

    def _run_reddit(self):
        prompt = self.prompt

        # take care of things reddit-side
        self.msg.mark_as_read()
        self.log.debug("%s: Marked message %s as read.",
                    classname(self), self.msg.name)

        reply_title = "Prompt updated"
        reply_text = u"Prompt {id_:d} has been updated.\n\n{prompt}".\
            format(id_=prompt.id, prompt=self._format_prompt(prompt))
        self.owner.queue_event(
            SendReplyCommand(self.msg, reply_title, reply_text))

    def _check_event_queue(self):
        """ Check whether a prompt add event for this prompt is in the
        scheduler. If so, remove it. """
        for ev in self.owner.get_events(PostPromptCommand):
            if ev.post_id == self.params['id']:
                self.owner.remove_event(ev)


class SendMessageCommand(CommandBase):
    """ Command to send a private message to a user.

    Defaults:
        * ``start_time`` = 0 (immediately)
        * ``duration`` = 0
        * ``interval`` = 0
        * ``priority`` = 60

    """
    required_res = ['reddit', 'logger']
    start_time = 0
    priority = 60

    def __init__(self, user, title, text):
        """ Constructor. Throws MissingParameterError or CommandParameterError
        on missing or invalid parameters (respectively). """
        self.user = user
        self.title = title
        self.text = text

        if not user:
            raise MissingParameterError('Cannot send message without recipient.')
        if not title:
            raise MissingParameterError('Cannot send message without subject.')
        if not text:
            raise MissingParameterError('Cannot send message without body text.')

    def start(self):
        self.log = self.res['logger']
        self.res['reddit'].compose_message(self.user, self.title, self.text)
        self.log.info("%s: Sent PM titled '%s' to %s.", classname(self),
            self.title, self.user)

    def run(self):
        pass

    def end(self):
        pass

    def handle_exception(self, e):
        return self.owner.EXC_UNHANDLED

    def __repr__(self):
        if len(self.text) > 127:
            excerpt = self.text[0:125] + '...'
        else:
            excerpt = self.text
        return "<{cls}: to={to}, title='{title}', message='{msg}'>".format(
            cls=classname(self), to=self.user, title=self.title, msg=excerpt)


class SendReplyCommand(CommandBase):
    """ Command to send a private message reply to a user and then mark the
    original message read.

    Defaults:
        * ``start_time`` = 0 (immediately)
        * ``duration`` = 0
        * ``interval`` = 0
        * ``priority`` = 60

    """
    required_res = ['reddit', 'logger']
    start_time = 0 # execute ASAP
    priority = 60

    def __init__(self, source_msg, subject, text):
        """ Constructor. Throws MissingParameterError or CommandParameterError
        on missing or invalid parameters (respectively). Note that subject is
        unused for replies. """
        self.msg = source_msg
        self.title = subject
        self.text = text

    def start(self):
        self.log = self.res['logger']

        try:
            self.msg.reply(self.text)
            self.msg.mark_as_read()
        except AttributeError as e:
            raise CommandParameterError('Invalid parent message object')

        self.log.info("%s: Sent Reddit reply to %s from %s.", classname(self),
            self.msg.author.name, self.res['reddit'].user.name)

    def run(self):
        pass

    def end(self):
        pass

    def handle_exception(self, e):
        if isinstance(e, CommandParameterError):
            return self.owner.EXC_HANDLED_FINAL
        return self.owner.EXC_UNHANDLED

    def __repr__(self):
        if len(self.text) > 127:
            excerpt = self.text[0:125] + '...'
        else:
            excerpt = self.text
        return "<{cls}: msgid={id_}, to={to}, title='{title}', message='{msg}'>".\
            format(cls=classname(self), id_=self.msg.id,
            to=self.msg.author.name, title=self.title, msg=excerpt)


class SendErrorMessageCommand(SendReplyCommand):
    """ Command to send an error message to a user.

    Defaults:
        * ``start_time`` = 0 (immediately)
        * ``duration`` = 0
        * ``interval`` = 0
        * ``priority`` = 60

    """
    start_time = 0 # execute ASAP
    priority = 60

    def __init__(self, source_msg, subject, text):
        """ Constructor. Throws MissingParameterError or CommandParameterError
        on missing or invalid parameters (respectively). Note that subject is
        unused for replies. """
        full_text = ''.join(["An error occurred: ", text])
        SendReplyCommand.__init__(self, source_msg, subject, full_text)

    @classmethod
    def command_parameter(cls, exc_obj, source_msg):
        """ Construct a SendErrorMessageCommand for a CommandParameterError.
        """
        subject = "Invalid Command Parameter"
        body = ("Sorry, there was a problem with the command you "
                   "sent me. I couldn't understand one of the parameters in "
                   "your command. The error that occurred is:\n\n{error}").\
                   format(error=exc_obj.args[0])
        return SendReplyCommand(source_msg, subject, body)


class ListPromptsCommand(CommandBase, DataFormatMixin):
    # MarkdownMixin, DateParseMixing via DataFormatMixin
    """ Command to send a list of prompts to a user via PM.

    Defaults:
        * ``start_time`` = 0 (immediately)
        * ``duration`` = 0
        * ``interval`` = 0
        * ``priority`` = 60

    """

    MAX_ENTRIES = 30
    start_time = 0 # execute ASAP
    priority = 60
    required_res = ['reddit', 'dbsession', 'logger']

    def __init__(self, msg, **kwargs):
        """ Constructor. Keyword arguments are strings defined as per the
        `CheckCommandSpec` class documentation; the text block is expected as
        a 'text' argument. Throws MissingParameterError or CommandParameterError
        on missing or invalid parameters (respectively). """

        self.msg = msg

        s_ids = kwargs.pop('id', None)
        s_past = kwargs.pop('past', None)
        s_start_date = kwargs.pop('start_date', None)
        s_end_date = kwargs.pop('end_date', None)
        s_user = kwargs.pop('user', None)
        s_approver = kwargs.pop('approver', None)
        s_short_entry = kwargs.pop('short_entry', None)
        s_by_id = kwargs.pop('by_id', None)
        s_limit = kwargs.pop('limit', None)

        # if parameters left over, they're not valid
        if len(kwargs):
            if len(kwargs) == 1:
                raise CommandParameterError(
                    "Unknown parameter: " + kwargs.keys()[0])
            else:
                raise CommandParameterError(
                    "Unknown parameters: " + ', '.join(kwargs.keys()))

        self.ids = None

        if s_ids is not None:
            list_s_id = s_ids.replace(',', ' ').split()
            self.ids = []
            try:
                for s_id in list_s_id:
                    self.ids.append(int(s_id, 10))
            except ValueError:
                raise CommandParameterError(
                    ''.join(["Invalid 'id' value: '", s_ids, "'."]))

        if not self.ids: # if id not specified or empty
            self.ids = None
            self.past = (s_past.lower() == 'true') if\
                    s_past is not None else False
            self.start_date = self._parse_datetime(s_start_date) if\
                    s_start_date is not None else None
            self.end_date = self._parse_datetime(s_end_date) if\
                    s_end_date is not None else None
            self.user = s_user
            self.approver = s_approver

        self.short_entry = (s_short_entry.lower() == 'true') if\
                s_short_entry else True
        self.by_id = (s_by_id.lower() == 'true') if\
                s_by_id else False

        if s_limit is not None:
            try:
                par_limit = int(s_limit, 10)
            except ValueError:
                raise CommandParameterError("Invalid 'limit' value: " + s_limit)
        else:
            par_limit = self.MAX_ENTRIES
        # bracket 'limit' to between 1 and self.MAX_ENTRIES
        self.limit = max(1, min(self.MAX_ENTRIES, par_limit))

    def start(self):
        self.run()

    def run(self):
        self.log = self.res['logger']
        query = self._run_query()

        self.msg.reply(self._build_prompt_list(query))
        self.log.info("%s: Sent prompt listing by PM to %s.",
            classname(self), self.msg.author.name)

        self.msg.mark_as_read()
        self.log.debug("%s: Marked message %s as read.",
            classname(self), self.msg.name)
        self.res['dbsession'].close()

    def _run_query(self):
        """ Return a Query object for the query configured. """
        query = self.res['dbsession'].query(Prompt)

        if self.ids:
            query = query.filter(Prompt.id.in_(self.ids))
        else:
            if not self.past:
                query = query.filter(Prompt.post_time >= datetime.utcnow())
            if self.start_date is not None:
                query = query.filter(Prompt.post_time >= self.start_date)
            if self.end_date is not None: # up to the end of the end date
                query = query.filter(
                    Prompt.post_time < self.end_date + timedelta(days=1))
            if self.user is not None:
                query = query.filter(Prompt.user == self.user)
            if self.approver is not None:
                query = query.join(User).filter(User.uname == self.approver)

        if not self.by_id:
            query = query.order_by(Prompt.post_time)
        else:
            query = query.order_by(Prompt.id)
        return query

    def _build_prompt_list(self, query):
        """ Return a string containing the prompt listing. """
        prompt_listing = [self._header_prompt(self.short_entry)]
        prompt_ids = []
        has_prompt = False

        for prompt in query[0:self.limit]:
            has_prompt = True
            prompt_listing.append(self._format_prompt(prompt, self.short_entry))
            prompt_ids.append(prompt.id)

        if has_prompt:
            self.log.debug("%s: Found prompts: %s", classname(self),
                ', '.join(['{:d}'.format(i) for i in prompt_ids]))
        else:
            self.log.debug("%s: No prompts found.", classname(self))
            prompt_listing = ["No results found."]

        if self.short_entry: # no newlines between entries
            return u''.join(prompt_listing)
        else: # long list = newlines between entries
            return u'\n'.join(prompt_listing)

    def end(self):
        self.res['dbsession'].close()
        del self.res['dbsession']

    def handle_exception(self, e):
        self.res['dbsession'].rollback()
        return self.owner.EXC_UNHANDLED

    def _format_url(self, post_id):
        """ Overrides ``DataFormatMixin._format_url()``. """
        return get_reddit_url(post_id, self.res['reddit'])

    def __repr__(self):
        """ Return a string representing this object. """
        display = [('short_entry', self.short_entry),
                   ('by_id',       self.by_id),
                   ('limit',       self.limit)]
        if self.ids:
            criteria = [('ids', self.ids)]
        else:
            criteria = [('past', self.past)]
            if self.start_date is not None:
                criteria.append(('start_date', self.start_date))
            if self.end_date is not None:
                criteria.append(('end_date', self.end_date))
            if self.user is not None:
                criteria.append(('user', self.user))
            if self.approver is not None:
                criteria.append(('approver', self.approver))
        return ('<{cls}: message {id_} ({author}), display: {{{disp_args}}}, '
                'criteria: {{{criteria}}}>').format(
                cls=classname(self), id_=self.msg.id, author=self.msg.author.name,
                disp_args=', '.join(['{}: {}'.format(x, repr(y))
                            for x, y in display]),
                criteria=', '.join(['{}: {}'.format(x, repr(y))
                            for x, y in criteria]))


class SendHelpMessageCommand(SendReplyCommand):
    """ Command to send a help message.

    Defaults:
        * ``start_time`` = 0 (immediately)
        * ``duration`` = 0
        * ``interval`` = 0
        * ``priority`` = 60

    """

    MAX_RETRY = 5

    def __init__(self, msg, **kwargs):
        """ Constructor. Keyword arguments are strings defined as per the
        `CheckCommandSpec` class documentation; the text block is expected as
        a 'text' argument. Throws MissingParameterError or CommandParameterError
        on missing or invalid parameters (respectively). """
        self.msg = msg
        self.tries = 0

    def start(self):
        self.tries += 1 # retries related to exceptions being thrown
        if self.tries <= self.MAX_RETRY:
            self.log = self.res['logger']
            with open('minibot/commands.txt') as help_file:
                self.msg.reply(help_file.read())
            self.log.info("%s: Sent help message to %s",
                classname(self), self.msg.author.name)
        else:
            self.msg.reply("Can't open help file!")
            self.log.info("%s: Can't open help file: %s: %s",
                classname(self), classname(e), e.args[0])
        self.msg.mark_as_read() # on error, reply() raises exc; won't reach this

    def run(self):
        pass

    def end(self):
        pass

    def handle_exception(self, e):
        if isinstance(e, IOError) or isinstance(e, OSError):
            if self.tries <= self.MAX_RETRY:
                self.delay = 5
                return self.owner.EXC_HANDLED_RETRY
            else:
                return self.owner.EXC_HANDLED_FINAL
        return self.owner.EXC_UNHANDLED

    def __repr__(self):
        return "<{cls}: to={to}>".format(
                cls=classname(self), to=self.msg.author.name)


class PostPromptCommand(CommandBase, DataFormatMixin):
    # indirectly inherits: DateParseMixin, MarkdownMixin
    """ Command to post the next prompt.

    Defaults:
        * ``start_time`` = post_time (init parameter, assumed UTC)
        * ``duration`` = 0
        * ``interval`` = 0
        * ``priority`` = 55

    """
    TITLE_PRETEXT  = u"The Daily Prompt for {date_}"
    BODY_PRETEXT   = u"Writing prompt for {date_}."
    SUBMITTER_TEXT = u"Originally suggested by {user}{permalink}."
    SOURCE_ONLY_TEXT = u"Originally suggested at [permalink]({permalink})."
    APPROVER_TEXT  = u"Selected by {approver}."
    required_res = ['reddit', 'dbsession', 'config.reddit', 'logger']
    priority = 55

    def __init__(self, post_id, utc_post_time):
        """ Constructor. post_id should be an integer (minibot.db.Prompt value),
        post_time should be a datetime object (naive, in UTC). Throws
        MissingParameterError or CommandParameterError on missing or invalid
        parameters (respectively).
        """
        self.__data = [post_id, utc_post_time]
        self.start_time = timegm(utc_post_time.utctimetuple())
        self._str_date = self._localtime(utc_post_time).strftime('%d %B %Y')

    @property
    def post_id(self):
        return self.__data[0]

    @property
    def post_time(self):
        """ Return the UTC post time. """
        return self.__data[1]

    def start(self):
        self.run()

    def run(self):
        target = self.res['config.reddit'].target
        reddit = self.res['reddit']
        db = self.res['dbsession']
        self.log = self.res['logger']

        prompt = self.prompt = db.query(Prompt).get(self.post_id)
        if prompt is None:
            raise CommandParameterError(
                ''.join(["Prompt ", self.id, " not found."]))

        r_sub = reddit.submit(target, self._get_title(), self._get_text())
        prompt.set_posted(r_sub.id, r_sub.created_utc)
        self.log.info("%s: Posted prompt %d to /r/%s", classname(self),
            prompt.id, target)
        db.commit()

    def end(self):
        self.res['dbsession'].close()
        del self.res['dbsession']

    def handle_exception(self, e):
        if isinstance(e, SQLAlchemyError) or isinstance(e, DBAPIError):
            self.delay = 5
            return self.owner.EXC_HANDLED_RETRY
        return self.owner.EXC_UNHANDLED

    def __repr__(self):
        return "<{cls}: post_id={id_}, post_time={time}>".format(
                cls=classname(self),
                id_=self.post_id,
                time=self.post_time.strftime('%Y-%m-%d %H:%M:%S UTC'))

    def _get_title(self):
        """ Return the submission title for the prompt stored in
        ``self.prompt``. """
        pre_title = self.TITLE_PRETEXT.format(date_=self._str_date)
        if self.prompt.title:
            return ''.join([pre_title, ': ', self.prompt.title])
        else:
            return pre_title

    def _get_text(self):
        """ Return the submission text for the prompt stored in
        ``self.prompt``. """
        text_parts = []

        # body: date text
        text_parts.append(self.BODY_PRETEXT.format(date_=self._str_date))

        # body: original submitter or source URL text
        text_parts.append(u' ')
        if self.prompt.user and self.prompt.r_source_url:
            permalink_str = u''.join([u' (',
                self.md_link(u'permalink', self.prompt.r_source_url), u')'])
            text_parts.append(self.SUBMITTER_TEXT.format(
                user=self.prompt.user, permalink=permalink_str))
        elif self.prompt.user:
            text_parts.append(self.SUBMITTER_TEXT.format(
                user=self.prompt.user, permalink=''))
        elif self.prompt.r_source_url:
            text_parts.append(self.SOURCE_ONLY_TEXT.format(
                permalink=self.prompt.r_source_url))

        # body: approver
        text_parts.append(u' ')
        approver_name = self.prompt.approver.uname
        text_parts.append(self.APPROVER_TEXT.format(approver=self.md_link(
            approver_name,
            get_reddit_url(u'u/' + approver_name, self.res['reddit']))))

        # body: prompt text
        text_parts.append(u'\n\n')
        text_parts.append(self.prompt.text)

        # the bot msg
        text_parts.append(u'\n___\n')
        text_parts.append(_BOT_MSG)

        return u''.join(text_parts)


class PostSuggestionThreadCommand(CommandBase, DateParseMixin, MarkdownMixin):
    """ Command to post a suggestions thread.

    Defaults:
        * ``start_time`` = 0 (immediately)
        * ``duration`` = 0
        * ``interval`` = 0
        * ``priority`` = 56

    """
    TITLE_PRETEXT  = u"The Daily Prompt Suggestions for {date_}"
    BODY_TEXT =(u"This is the prompt suggestion thread for the week of {date_}. "
                u"Post your daily prompt ideas here! Our moderators will pick "
                u"out creative, thought-provoking or challenging prompts "
                u"and queue them up for next week or beyond.\n\n"

                u"We're looking for prompts relating to theme, situations, "
                u"particular character ideas, technical fiction challenges, "
                u"or anything else you can think of in terms of "
                u"fiction-writing prompts!\n\n"

                u"Here are the guidelines for suggestions. We won't consider "
                u"suggestions that don't follow these guidelines.\n\n"

                u"* Suggestions must be top-level comments. In other words: "
                u"reply to this post, not to someone else's comment!\n"

                u"* **One prompt per comment.**\n"

                u"* Give us a title and 1-3 sentences describing or pitching "
                u"your prompt. (If you omit the title, we'll just write one "
                u"for you. No biggie.)\n"

                u"* A few words like \"a love affair\" isn't so much a "
                u"specific _theme_ as it is just a vague subject. Try to avoid "
                u"those—there are more interesting prompts to be found!\n"

                u"\n"

                u"{text}"

                u"Please feel free to repost ideas you submitted in previous "
                u"weeks! We only select seven per week, so unfortunately good "
                u"ideas often don't make the cut in any given week.")

    NAV_MENU = (u"| | | |\n"
                u"| :-: | :-: | :-: |\n"
                u"| « {prev} | .:{cur}:. | {next} » |\n"
                u"| | | |\n")
    priority = 56

    required_res = ['reddit', 'dbsession', 'config.reddit', 'logger']
    def __init__(self, post_id, utc_post_time):
        """ Constructor. post_id should be an integer (minibot.db.Prompt value),
        post_time should be a datetime object (naive, in UTC). Throws
        MissingParameterError or CommandParameterError on missing or invalid
        parameters (respectively).
        """
        self.__data = [post_id, utc_post_time]
        self.start_time = timegm(utc_post_time.utctimetuple())
        self._str_date = self._localtime(utc_post_time).strftime('%d %B %Y')

    @property
    def post_id(self):
        return self.__data[0]

    @property
    def post_time(self):
        """ Return the UTC post time. """
        return self.__data[1]

    def start(self):
        self.run()

    def run(self):
        target = self.res['config.reddit'].target
        reddit = self.res['reddit']
        db = self.res['dbsession']
        self.log = self.res['logger']

        thread = self.thread = db.query(SuggestionThread).get(self.post_id)
        self._find_prev_thread()
        if thread is None:
            raise CommandParameterError(
                ''.join(["Queued suggestion thread ", self.id, " not found."]))

        r_post = reddit.submit(target, self._get_title(), self._get_text())

        thread.set_posted(r_post.id, r_post.created_utc)
        self._archive_older_threads()
        self._add_link_to_last_thread()
        self.log.info("%s: Posted suggestion thread %d to /r/%s",
            classname(self), thread.id, target)
        db.commit()

    def end(self):
        self.res['dbsession'].close()
        del self.res['dbsession']

    def handle_exception(self, e):
        if isinstance(e, SQLAlchemyError) or isinstance(e, DBAPIError):
            self.delay = 5
            return self.owner.EXC_HANDLED_RETRY
        return self.owner.EXC_UNHANDLED

    def __repr__(self):
        return "<{cls}: post_id={id_}, post_time={time}>".format(
                cls=classname(self),
                id_=self.post_id,
                time=self.post_time.strftime('%Y-%m-%d %H:%M:%S UTC'))

    def _get_title(self):
        """ Return the submission title for the thread stored in
        ``self.thread``. """
        pre_title = self.TITLE_PRETEXT.format(date_=self._str_date)
        if self.thread.title:
            return u''.join([pre_title, u': ', self.thread.title])
        else:
            return pre_title

    def _get_text(self):
        """ Return the submission text for the thread stored in
        ``self.thread``. """
        lo_post_date = self._localtime(self.post_time).date()
        prev_date_str = (lo_post_date - timedelta(days=7)).strftime('%d %B %Y')
        curr_date_str = lo_post_date.strftime('%d %B %Y')
        next_date_str = (lo_post_date + timedelta(days=7)).strftime('%d %B %Y')

        if self.prev_thread is not None and\
                self.prev_thread.r_post_id is not None:
            prev_url = get_reddit_url(
                                      self.prev_thread.r_post_id,
                                      self.res['reddit'])
            prev_text = self.md_link(prev_date_str, prev_url)
        else:
            prev_text = u"End of List"

        text = u''.join([
                self.BODY_TEXT.format(
                    date_=self._str_date,
                    text=(self.thread.text+'\n\n') if self.thread.text
                         else u''),
                u'\n\n',
                self.NAV_MENU.format(
                    prev=prev_text,
                    cur=self.md_bold(curr_date_str),
                    next=next_date_str),
                u'\n___\n', _BOT_MSG])
        return text

    def _find_prev_thread(self):
        """ Find the previous week's SuggestionThread. First tries to find a
        SuggestionThread exactly seven days ago, otherwise any SuggestionThread
        in the past seven days. Returns the SuggestionThread object, or None
        if none found. Also stores the result as self.prev_thread. """
        db = self.res['dbsession']
        lo_post_time = self._localtime(self.post_time)

        # all in local time
        lo_today_start = datetime.combine(lo_post_time.date(), dt_time())
        prev_date = lo_post_time.date() - timedelta(days=7)
        prev_date_str = prev_date.strftime('%Y-%m-%d')
        lo_prev_start = datetime.combine(prev_date, dt_time())
        lo_prev_end = datetime.combine(prev_date + timedelta(days=1), dt_time())

        # convert them all to UTC time for database comparisons
        utc_today_start = self._utctime(lo_today_start)
        utc_prev_start  = self._utctime(lo_prev_start)
        utc_prev_end    = self._utctime(lo_prev_end)

        # query thread seven days ago
        thread = db.query(SuggestionThread).\
                    filter(SuggestionThread.time >= utc_prev_start).\
                    filter(SuggestionThread.time < utc_prev_end).\
                    filter(SuggestionThread.status ==
                                            SuggestionThread.STATUS_ACTIVE).\
                    order_by(desc(SuggestionThread.time)).limit(1).first()
        if thread:
            self.log.info("%s: Found previous suggestion thread %d (%s) <%s>",
                    classname(self), thread.id,
                    thread.time.strftime("%Y-%m-%d %H:%M:%S UTC"),
                    get_reddit_url(thread.r_post_id, self.res['reddit']))
            self.prev_thread = thread
            return thread
        else:
            self.log.warn("%s: No previous suggestion thread found on %s. "
                          "Falling back to full week search.",
                          classname(self), prev_date_str)

        # fallback: check threads during the entirety of the past week
        thread = db.query(SuggestionThread).\
                      filter(SuggestionThread.time >= utc_prev_start).\
                      filter(SuggestionThread.time < utc_today_start).\
                      filter(SuggestionThread.status ==
                                            SuggestionThread.STATUS_ACTIVE).\
                      order_by(desc(SuggestionThread.time)).limit(1).first()
        if thread:
            self.log.info("%s: Found previous suggestion thread %d (%s) <%s>",
                    classname(self), thread.id,
                    thread.time.strftime("%Y-%m-%d %H:%M:%S UTC"),
                    get_reddit_url(thread.r_post_id, self.res['reddit']))
            self.prev_thread = thread
            return thread
        else:
            self.log.warn("%s: No previous suggestion thread found in the "
                          "seven days following %s.",
                          classname(self), prev_date_str)
            self.prev_thread = None
            return None

    def _archive_older_threads(self):
        """ Sets all older active threads to archived status in database. Does
        not commit the transaction. """
        db = self.res['dbsession']
        thread_ids = []
        for other_thread in db.query(SuggestionThread).\
                filter(SuggestionThread.id != self.post_id).\
                filter(SuggestionThread.time <= self.thread.time).\
                filter(SuggestionThread.status == self.thread.STATUS_ACTIVE):
            other_thread.set_archived()
            thread_ids.append(other_thread.r_post_id)
        self.log.info("%s: Archived %d other threads: id %s",
            classname(self), len(thread_ids),
            ', '.join(['{}'.format(tid) for tid in thread_ids]))

    def _add_link_to_last_thread(self):
        """ Adds a 'next week's suggestion thread' link to the previous
        suggestion thread. """
        # if _find_prev_thread() hasn't been called, call it
        if not hasattr(self, 'prev_thread'):
            self._find_prev_thread()

        if self.prev_thread is not None: # if one was found
            # set up the find and replace params needed
            # the date fmt inside regex and strftime regex must correspond
            oldlink_re = re.compile(ur'\| \d{1,2} [A-Za-z][a-z]* \d{4} » \|')

            date_str = self._localtime(self.post_time).strftime('%d %B %Y')
            post_url = get_reddit_url(self.thread.r_post_id, self.res['reddit'])
            newlink = u' '.join([u'|', self.md_link(date_str, post_url), u'» |'])

            # get the reddit thread, get the self-text and do the replacement
            r_thread = self.res['reddit'].\
                       get_submission(submission_id=self.prev_thread.r_post_id)

            new_text = oldlink_re.sub(newlink, r_thread.selftext)
            r_thread.edit(new_text)

            self.log.info("%s: Edited navigation link to thread %s in previous "
                "thread %s", classname(self), self.thread.r_post_id,
                self.prev_thread.r_post_id)


CheckMessageEvent.cmd_actions = {'add'    : AddPromptCommand,
                                 'delete' : RemovePromptCommand,
                                 'update' : UpdatePromptCommand,
                                 'list'   : ListPromptsCommand,
                                 'help'   : SendHelpMessageCommand}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.