Script: slack.py

Slack.com native client.
Author: Trygve Aaberge — Version: 2.10.2 — License: MIT
For WeeChat ≥ 2.2, requires: python websocket-client.
Tags: slack, py2, py3
Added: 2016-07-31 — Updated: 2024-02-18

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
 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
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
# Copyright (c) 2014-2016 Ryan Huber <rhuber@gmail.com>
# Copyright (c) 2015-2018 Tollef Fog Heen <tfheen@err.no>
# Copyright (c) 2015-2023 Trygve Aaberge <trygveaa@gmail.com>
# Released under the MIT license.

from __future__ import print_function, unicode_literals

from collections import OrderedDict, namedtuple
from datetime import date, datetime, timedelta
from functools import partial, wraps
from io import StringIO
from itertools import chain, count, islice

import copy
import errno
import textwrap
import time
import json
import hashlib
import os
import re
import sys
import traceback
import ssl
import random
import socket
import string

# Prevent websocket from using numpy (it's an optional dependency). We do this
# because numpy causes python (and thus weechat) to crash when it's reloaded.
# See https://github.com/numpy/numpy/issues/11925
sys.modules["numpy"] = None

from websocket import (  # noqa: E402
    ABNF,
    create_connection,
    WebSocketConnectionClosedException,
)

try:
    basestring  # Python 2
    unicode
    str = unicode
except NameError:  # Python 3
    basestring = unicode = str

try:
    from collections.abc import (
        ItemsView,
        Iterable,
        KeysView,
        Mapping,
        Reversible,
        ValuesView,
    )
except ImportError:
    from collections import ItemsView, Iterable, KeysView, Mapping, ValuesView

    Reversible = object

try:
    from urllib.parse import quote, unquote, urlencode
except ImportError:
    from urllib import quote, unquote, urlencode

try:
    JSONDecodeError = json.JSONDecodeError
except AttributeError:
    JSONDecodeError = ValueError

# hack to make tests possible.. better way?
try:
    import weechat
except ImportError:
    pass

SCRIPT_NAME = "slack"
SCRIPT_AUTHOR = "Trygve Aaberge <trygveaa@gmail.com>"
SCRIPT_VERSION = "2.10.2"
SCRIPT_LICENSE = "MIT"
SCRIPT_DESC = "Extends WeeChat for typing notification/search/etc on slack.com"
REPO_URL = "https://github.com/wee-slack/wee-slack"

TYPING_DURATION = 6

RECORD_DIR = "/tmp/weeslack-debug"

SLACK_API_TRANSLATOR = {
    "channel": {
        "history": "conversations.history",
        "join": "conversations.join",
        "leave": "conversations.leave",
        "mark": "conversations.mark",
        "info": "conversations.info",
    },
    "im": {
        "history": "conversations.history",
        "join": "conversations.open",
        "leave": "conversations.close",
        "mark": "conversations.mark",
        "info": "conversations.info",
    },
    "mpim": {
        "history": "conversations.history",
        "join": "conversations.open",
        "leave": "conversations.close",
        "mark": "conversations.mark",
        "info": "conversations.info",
    },
    "group": {
        "history": "conversations.history",
        "join": "conversations.join",
        "leave": "conversations.leave",
        "mark": "conversations.mark",
        "info": "conversations.info",
    },
    "private": {
        "history": "conversations.history",
        "join": "conversations.join",
        "leave": "conversations.leave",
        "mark": "conversations.mark",
        "info": "conversations.info",
    },
    "shared": {
        "history": "conversations.history",
        "join": "conversations.join",
        "leave": "conversations.leave",
        "mark": "conversations.mark",
        "info": "conversations.info",
    },
    "thread": {
        "history": None,
        "join": None,
        "leave": None,
        "mark": "subscriptions.thread.mark",
    },
}

CONFIG_PREFIX = "plugins.var.python." + SCRIPT_NAME

###### Decorators have to be up here


def slack_buffer_or_ignore(f):
    """
    Only run this function if we're in a slack buffer, else ignore
    """

    @wraps(f)
    def wrapper(data, current_buffer, *args, **kwargs):
        if current_buffer not in EVENTROUTER.weechat_controller.buffers:
            return w.WEECHAT_RC_OK
        return f(data, current_buffer, *args, **kwargs)

    return wrapper


def slack_buffer_required(f):
    """
    Only run this function if we're in a slack buffer, else print error
    """

    @wraps(f)
    def wrapper(data, current_buffer, *args, **kwargs):
        if current_buffer not in EVENTROUTER.weechat_controller.buffers:
            command_name = f.__name__.replace("command_", "", 1)
            w.prnt(
                "",
                'slack: command "{}" must be executed on slack buffer'.format(
                    command_name
                ),
            )
            return w.WEECHAT_RC_ERROR
        return f(data, current_buffer, *args, **kwargs)

    return wrapper


def utf8_decode(f):
    """
    Decode all arguments from byte strings to unicode strings. Use this for
    functions called from outside of this script, e.g. callbacks from WeeChat.
    """

    @wraps(f)
    def wrapper(*args, **kwargs):
        return f(*decode_from_utf8(args), **decode_from_utf8(kwargs))

    return wrapper


NICK_GROUP_HERE = "0|Here"
NICK_GROUP_AWAY = "1|Away"
NICK_GROUP_EXTERNAL = "2|External"

sslopt_ca_certs = {}
if hasattr(ssl, "get_default_verify_paths") and callable(ssl.get_default_verify_paths):
    ssl_defaults = ssl.get_default_verify_paths()
    if ssl_defaults.cafile is not None:
        sslopt_ca_certs = {"ca_certs": ssl_defaults.cafile}

EMOJI = {}
EMOJI_WITH_SKIN_TONES_REVERSE = {}

###### Unicode handling


def encode_to_utf8(data):
    if sys.version_info.major > 2:
        return data
    elif isinstance(data, unicode):
        return data.encode("utf-8")
    if isinstance(data, bytes):
        return data
    elif isinstance(data, Mapping):
        return type(data)(map(encode_to_utf8, data.items()))
    elif isinstance(data, Iterable):
        return type(data)(map(encode_to_utf8, data))
    else:
        return data


def decode_from_utf8(data):
    if sys.version_info.major > 2:
        return data
    elif isinstance(data, bytes):
        return data.decode("utf-8")
    if isinstance(data, unicode):
        return data
    elif isinstance(data, Mapping):
        return type(data)(map(decode_from_utf8, data.items()))
    elif isinstance(data, Iterable):
        return type(data)(map(decode_from_utf8, data))
    else:
        return data


class WeechatWrapper(object):
    def __init__(self, wrapped_class):
        self.wrapped_class = wrapped_class

    # Helper method used to encode/decode method calls.
    def wrap_for_utf8(self, method):
        def hooked(*args, **kwargs):
            result = method(*encode_to_utf8(args), **encode_to_utf8(kwargs))
            # Prevent wrapped_class from becoming unwrapped
            if result == self.wrapped_class:
                return self
            return decode_from_utf8(result)

        return hooked

    # Encode and decode everything sent to/received from weechat. We use the
    # unicode type internally in wee-slack, but has to send utf8 to weechat.
    def __getattr__(self, attr):
        orig_attr = self.wrapped_class.__getattribute__(attr)
        if callable(orig_attr):
            return self.wrap_for_utf8(orig_attr)
        else:
            return decode_from_utf8(orig_attr)

    # Ensure all lines sent to weechat specifies a prefix. For lines after the
    # first, we want to disable the prefix, which we do by specifying the same
    # number of spaces, so it aligns correctly.
    def prnt_date_tags(self, buffer, date, tags, message):
        if weechat_version < 0x04000000:
            prefix, _, _ = message.partition("\t")
            prefix = weechat.string_remove_color(encode_to_utf8(prefix), "")
            prefix_spaces = " " * weechat.strlen_screen(prefix)
            message = message.replace("\n", "\n{}\t".format(prefix_spaces))
        return self.wrap_for_utf8(self.wrapped_class.prnt_date_tags)(
            buffer, date, tags, message
        )


class ProxyWrapper(object):
    def __init__(self):
        self.proxy_name = w.config_string(w.config_get("weechat.network.proxy_curl"))
        self.proxy_string = ""
        self.proxy_type = ""
        self.proxy_address = ""
        self.proxy_port = ""
        self.proxy_user = ""
        self.proxy_password = ""
        self.has_proxy = False

        if self.proxy_name:
            self.proxy_string = "weechat.proxy.{}".format(self.proxy_name)
            self.proxy_type = w.config_string(
                w.config_get("{}.type".format(self.proxy_string))
            )
            if self.proxy_type == "http":
                self.proxy_address = w.config_string(
                    w.config_get("{}.address".format(self.proxy_string))
                )
                self.proxy_port = w.config_integer(
                    w.config_get("{}.port".format(self.proxy_string))
                )
                self.proxy_user = w.config_string(
                    w.config_get("{}.username".format(self.proxy_string))
                )
                self.proxy_password = w.config_string(
                    w.config_get("{}.password".format(self.proxy_string))
                )
                self.has_proxy = True
            else:
                w.prnt(
                    "",
                    "\nWarning: weechat.network.proxy_curl is set to {} type (name : {}, conf string : {}). Only HTTP proxy is supported.\n\n".format(
                        self.proxy_type, self.proxy_name, self.proxy_string
                    ),
                )

    def curl(self):
        if not self.has_proxy:
            return ""

        if self.proxy_user and self.proxy_password:
            user = "{}:{}@".format(self.proxy_user, self.proxy_password)
        else:
            user = ""

        if self.proxy_port:
            port = ":{}".format(self.proxy_port)
        else:
            port = ""

        return "-x{}{}{}".format(user, self.proxy_address, port)


class MappingReversible(Mapping, Reversible):
    def keys(self):
        return KeysViewReversible(self)

    def items(self):
        return ItemsViewReversible(self)

    def values(self):
        return ValuesViewReversible(self)


class KeysViewReversible(KeysView, Reversible):
    def __reversed__(self):
        return reversed(self._mapping)


class ItemsViewReversible(ItemsView, Reversible):
    def __reversed__(self):
        for key in reversed(self._mapping):
            yield (key, self._mapping[key])


class ValuesViewReversible(ValuesView, Reversible):
    def __reversed__(self):
        for key in reversed(self._mapping):
            yield self._mapping[key]


##### Helpers


def colorize_string(color, string, reset_color="reset"):
    if color:
        return w.color(color) + string + w.color(reset_color)
    else:
        return string


def print_error(message, buffer="", warning=False):
    prefix = "Warning" if warning else "Error"
    w.prnt(buffer, "{}{}: {}".format(w.prefix("error"), prefix, message))


def print_message_not_found_error(msg_id):
    if msg_id:
        print_error(
            "Invalid id given, must be an existing id or a number greater "
            + "than 0 and less than the number of messages in the channel"
        )
    else:
        print_error("No messages found in channel")


def token_for_print(token):
    return "{}...{}".format(token[:15], token[-10:])


def format_exc_tb():
    return decode_from_utf8(traceback.format_exc())


def format_exc_only():
    etype, value, _ = sys.exc_info()
    return "".join(decode_from_utf8(traceback.format_exception_only(etype, value)))


def url_encode_if_not_encoded(value):
    decoded = unquote(value)
    is_encoded = value != decoded
    if is_encoded:
        return value
    else:
        return quote(value)


def get_localvar_type(slack_type):
    if slack_type in ("im", "mpim"):
        return "private"
    else:
        return "channel"


def get_nick_color(nick):
    return w.info_get("nick_color_name", nick)


def get_thread_color(thread_id):
    if config.color_thread_suffix == "multiple":
        return get_nick_color(thread_id)
    else:
        return config.color_thread_suffix


def sha1_hex(s):
    return str(hashlib.sha1(s.encode("utf-8")).hexdigest())


def get_functions_with_prefix(prefix):
    return {
        name[len(prefix) :]: ref
        for name, ref in globals().items()
        if name.startswith(prefix)
    }


def handle_socket_error(exception, team, caller_name):
    if not (
        isinstance(exception, WebSocketConnectionClosedException)
        or exception.errno in (errno.EPIPE, errno.ECONNRESET, errno.ETIMEDOUT)
    ):
        raise

    w.prnt(
        team.channel_buffer,
        "Lost connection to slack team {} (on {}), reconnecting.".format(
            team.domain, caller_name
        ),
    )
    dbg(
        "Socket failed on {} with exception:\n{}".format(caller_name, format_exc_tb()),
        level=5,
    )
    team.set_disconnected()


MESSAGE_ID_REGEX_STRING = r"(?P<msg_id>\d+|\$[0-9a-fA-F]{3,})"
REACTION_PREFIX_REGEX_STRING = r"{}?(?P<reaction_change>\+|-)".format(
    MESSAGE_ID_REGEX_STRING
)

EMOJI_CHAR_REGEX_STRING = "(?P<emoji_char>[\U00000080-\U0010ffff]+)"
EMOJI_NAME_REGEX_STRING = ":(?P<emoji_name>[a-z0-9_+-]+):"
EMOJI_CHAR_OR_NAME_REGEX_STRING = "({}|{})".format(
    EMOJI_CHAR_REGEX_STRING, EMOJI_NAME_REGEX_STRING
)
EMOJI_NAME_REGEX = re.compile(EMOJI_NAME_REGEX_STRING)
EMOJI_CHAR_OR_NAME_REGEX = re.compile(EMOJI_CHAR_OR_NAME_REGEX_STRING)


def regex_match_to_emoji(match, include_name=False):
    emoji = match.group(1)
    full_match = match.group()
    char = EMOJI.get(emoji, full_match)
    if include_name and char != full_match:
        return "{} ({})".format(char, full_match)
    return char


def replace_string_with_emoji(text):
    if config.render_emoji_as_string == "both":
        return EMOJI_NAME_REGEX.sub(
            partial(regex_match_to_emoji, include_name=True),
            text,
        )
    elif config.render_emoji_as_string:
        return text
    return EMOJI_NAME_REGEX.sub(regex_match_to_emoji, text)


def replace_emoji_with_string(text):
    emoji = None
    key = text
    while emoji is None and len(key):
        emoji = EMOJI_WITH_SKIN_TONES_REVERSE.get(key)
        key = key[:-1]
    return emoji or text


###### New central Event router


class EventRouter(object):
    def __init__(self):
        """
        complete
        Eventrouter is the central hub we use to route:
        1) incoming websocket data
        2) outgoing http requests and incoming replies
        3) local requests
        It has a recorder that, when enabled, logs most events
        to the location specified in RECORD_DIR.
        """
        self.queue = []
        self.slow_queue = []
        self.slow_queue_timer = 0
        self.teams = {}
        self.subteams = {}
        self.context = {}
        self.weechat_controller = WeechatController(self)
        self.previous_buffer = ""
        self.reply_buffer = {}
        self.cmds = get_functions_with_prefix("command_")
        self.proc = get_functions_with_prefix("process_")
        self.handlers = get_functions_with_prefix("handle_")
        self.local_proc = get_functions_with_prefix("local_process_")
        self.shutting_down = False
        self.recording = False
        self.recording_path = "/tmp"
        self.handle_next_hook = None
        self.handle_next_hook_interval = -1

    def record(self):
        """
        complete
        Toggles the event recorder and creates a directory for data if enabled.
        """
        self.recording = not self.recording
        if self.recording:
            if not os.path.exists(RECORD_DIR):
                os.makedirs(RECORD_DIR)

    def record_event(self, message_json, team, file_name_field, subdir=None):
        """
        complete
        Called each time you want to record an event.
        message_json is a json in dict form
        file_name_field is the json key whose value you want to be part of the file name
        """
        now = time.time()

        if team:
            team_subdomain = team.subdomain
        else:
            team_json = message_json.get("team")
            if team_json:
                team_subdomain = team_json.get("domain")
            else:
                team_subdomain = "unknown_team"

        directory = "{}/{}".format(RECORD_DIR, team_subdomain)
        if subdir:
            directory = "{}/{}".format(directory, subdir)
        if not os.path.exists(directory):
            os.makedirs(directory)
        mtype = message_json.get(file_name_field, "unknown")
        f = open("{}/{}-{}.json".format(directory, now, mtype), "w")
        f.write("{}".format(json.dumps(message_json)))
        f.close()

    def store_context(self, data):
        """
        A place to store data and vars needed by callback returns. We need this because
        WeeChat's "callback_data" has a limited size and WeeChat will crash if you exceed
        this size.
        """
        identifier = "".join(
            random.choice(string.ascii_uppercase + string.digits) for _ in range(40)
        )
        self.context[identifier] = data
        dbg("stored context {} {} ".format(identifier, data.url))
        return identifier

    def retrieve_context(self, identifier):
        """
        A place to retrieve data and vars needed by callback returns. We need this because
        WeeChat's "callback_data" has a limited size and WeeChat will crash if you exceed
        this size.
        """
        return self.context.get(identifier)

    def delete_context(self, identifier):
        """
        Requests can span multiple requests, so we may need to delete this as a last step
        """
        if identifier in self.context:
            del self.context[identifier]

    def shutdown(self):
        """
        complete
        This toggles shutdown mode. Shutdown mode tells us not to
        talk to Slack anymore. Without this, typing /quit will trigger
        a race with the buffer close callback and may result in you
        leaving every slack channel.
        """
        self.shutting_down = not self.shutting_down

    def register_team(self, team):
        """
        complete
        Adds a team to the list of known teams for this EventRouter.
        """
        if isinstance(team, SlackTeam):
            self.teams[team.get_team_hash()] = team
        else:
            raise InvalidType(type(team))

    def reconnect_if_disconnected(self):
        for team in self.teams.values():
            time_since_last_ping = time.time() - team.last_ping_time
            time_since_last_pong = time.time() - team.last_pong_time
            if (
                team.connected
                and time_since_last_ping < 5
                and time_since_last_pong > 30
            ):
                w.prnt(
                    team.channel_buffer,
                    "Lost connection to slack team {} (no pong), reconnecting.".format(
                        team.domain
                    ),
                )
                team.set_disconnected()
            if not team.connected:
                team.connect()
                dbg("reconnecting {}".format(team))

    @utf8_decode
    def receive_ws_callback(self, team_hash, fd):
        """
        This is called by the global method of the same name.
        It is triggered when we have incoming data on a websocket,
        which needs to be read. Once it is read, we will ensure
        the data is valid JSON, add metadata, and place it back
        on the queue for processing as JSON.
        """
        team = self.teams[team_hash]
        while True:
            try:
                # Read the data from the websocket associated with this team.
                opcode, data = team.ws.recv_data(control_frame=True)
            except ssl.SSLWantReadError:
                # No more data to read at this time.
                return w.WEECHAT_RC_OK
            except (WebSocketConnectionClosedException, socket.error) as e:
                handle_socket_error(e, team, "receive")
                return w.WEECHAT_RC_OK

            if opcode == ABNF.OPCODE_PONG:
                team.last_pong_time = time.time()
                return w.WEECHAT_RC_OK
            elif opcode != ABNF.OPCODE_TEXT:
                return w.WEECHAT_RC_OK

            message_json = json.loads(data.decode("utf-8"))
            if self.recording:
                self.record_event(message_json, team, "type", "websocket")
            message_json["wee_slack_metadata_team"] = team
            self.receive(message_json)

    def http_check_ratelimited(self, request_metadata, response):
        parts = response.split("\r\n\r\nHTTP/")
        last_header_part, body = parts[-1].split("\r\n\r\n", 1)
        header_lines = last_header_part.split("\r\n")
        http_status = header_lines[0].split(" ")[1]

        if http_status == "429":
            for header in header_lines[1:]:
                name, value = header.split(":", 1)
                if name.lower() == "retry-after":
                    retry_after = int(value.strip())
                    request_metadata.retry_time = time.time() + retry_after
                    return "", "ratelimited"

        return body, ""

    def retry_request(self, request_metadata, data, return_code, err):
        self.reply_buffer.pop(request_metadata.response_id, None)
        self.delete_context(data)
        retry_text = (
            "retrying"
            if request_metadata.should_try()
            else "will not retry after too many failed attempts"
        )
        team = (
            "for team {}".format(request_metadata.team)
            if request_metadata.team
            else "with token {}".format(token_for_print(request_metadata.token))
        )
        w.prnt(
            "",
            (
                "Failed requesting {} {}, {}. "
                + "If this persists, try increasing slack_timeout. Error (code {}): {}"
            ).format(
                request_metadata.request,
                team,
                retry_text,
                return_code,
                err,
            ),
        )
        dbg(
            "{} failed with return_code {} and error {}. stack:\n{}".format(
                request_metadata.request,
                return_code,
                err,
                "".join(traceback.format_stack()),
            ),
            level=5,
        )
        self.receive(request_metadata)

    @utf8_decode
    def receive_httprequest_callback(self, data, command, return_code, out, err):
        """
        complete
        Receives the result of an http request we previously handed
        off to WeeChat (WeeChat bundles libcurl). WeeChat can fragment
        replies, so it buffers them until the reply is complete.
        It is then populated with metadata here so we can identify
        where the request originated and route properly.
        """
        request_metadata = self.retrieve_context(data)
        dbg(
            "RECEIVED CALLBACK with request of {} id of {} and  code {} of length {}".format(
                request_metadata.request,
                request_metadata.response_id,
                return_code,
                len(out),
            )
        )
        if return_code == 0:
            if len(out) > 0:
                if request_metadata.response_id not in self.reply_buffer:
                    self.reply_buffer[request_metadata.response_id] = StringIO()
                self.reply_buffer[request_metadata.response_id].write(out)

                response = self.reply_buffer[request_metadata.response_id].getvalue()
                body, error = self.http_check_ratelimited(request_metadata, response)
                if error:
                    self.retry_request(request_metadata, data, return_code, error)
                else:
                    j = json.loads(body)

                    try:
                        j[
                            "wee_slack_process_method"
                        ] = request_metadata.request_normalized
                        if self.recording:
                            self.record_event(
                                j,
                                request_metadata.team,
                                "wee_slack_process_method",
                                "http",
                            )
                        j["wee_slack_request_metadata"] = request_metadata
                        self.reply_buffer.pop(request_metadata.response_id)
                        self.receive(j)
                        self.delete_context(data)
                    except:
                        dbg("HTTP REQUEST CALLBACK FAILED", True)
            # We got an empty reply and this is weird so just ditch it and retry
            else:
                dbg("length was zero, probably a bug..")
                self.delete_context(data)
                self.receive(request_metadata)
        elif return_code == -1:
            if request_metadata.response_id not in self.reply_buffer:
                self.reply_buffer[request_metadata.response_id] = StringIO()
            self.reply_buffer[request_metadata.response_id].write(out)
        else:
            self.retry_request(request_metadata, data, return_code, err)
        return w.WEECHAT_RC_OK

    def receive(self, dataobj, slow=False):
        """
        Receives a raw object and places it on the queue for
        processing. Object must be known to handle_next or
        be JSON.
        """
        dbg("RECEIVED FROM QUEUE")
        if slow:
            self.slow_queue.append(dataobj)
        else:
            self.queue.append(dataobj)

    def handle_next(self):
        """
        complete
        Main handler of the EventRouter. This is called repeatedly
        via callback to drain events from the queue. It also attaches
        useful metadata and context to events as they are processed.
        """
        wanted_interval = 100
        if len(self.slow_queue) > 0 or len(self.queue) > 0:
            wanted_interval = 10
        if (
            self.handle_next_hook is None
            or wanted_interval != self.handle_next_hook_interval
        ):
            if self.handle_next_hook:
                w.unhook(self.handle_next_hook)
            self.handle_next_hook = w.hook_timer(
                wanted_interval, 0, 0, "handle_next", ""
            )
            self.handle_next_hook_interval = wanted_interval

        if len(self.slow_queue) > 0 and ((self.slow_queue_timer + 1) < time.time()):
            dbg("from slow queue", 0)
            self.queue.append(self.slow_queue.pop())
            self.slow_queue_timer = time.time()
        if len(self.queue) > 0:
            j = self.queue.pop(0)
            # Reply is a special case of a json reply from websocket.
            if isinstance(j, SlackRequest):
                if j.should_try():
                    if j.retry_ready():
                        local_process_async_slack_api_request(j, self)
                    else:
                        self.slow_queue.append(j)
                else:
                    dbg("Max retries for Slackrequest")

            else:
                if "reply_to" in j:
                    dbg("SET FROM REPLY")
                    function_name = "reply"
                elif "type" in j:
                    dbg("SET FROM type")
                    function_name = j["type"]
                elif "wee_slack_process_method" in j:
                    dbg("SET FROM META")
                    function_name = j["wee_slack_process_method"]
                else:
                    dbg("SET FROM NADA")
                    function_name = "unknown"

                request = j.get("wee_slack_request_metadata")
                if request:
                    team = request.team
                    channel = request.channel
                    metadata = request.metadata
                    callback = request.callback
                else:
                    team = j.get("wee_slack_metadata_team")
                    channel = None
                    metadata = {}
                    callback = None

                if team:
                    if "channel" in j:
                        channel_id = (
                            j["channel"]["id"]
                            if isinstance(j["channel"], dict)
                            else j["channel"]
                        )
                        channel = team.channels.get(channel_id, channel)
                    if "user" in j:
                        user_id = (
                            j["user"]["id"]
                            if isinstance(j["user"], dict)
                            else j["user"]
                        )
                        metadata["user"] = team.users.get(user_id)

                dbg("running {}".format(function_name))
                if callable(callback):
                    callback(j, self, team, channel, metadata)
                elif (
                    function_name.startswith("local_")
                    and function_name in self.local_proc
                ):
                    self.local_proc[function_name](j, self, team, channel, metadata)
                elif function_name in self.proc:
                    self.proc[function_name](j, self, team, channel, metadata)
                elif function_name in self.handlers:
                    self.handlers[function_name](j, self, team, channel, metadata)
                else:
                    dbg("Callback not implemented for event: {}".format(function_name))


def handle_next(data, remaining_calls):
    try:
        EVENTROUTER.handle_next()
    except:
        if config.debug_mode:
            traceback.print_exc()
        else:
            pass
    return w.WEECHAT_RC_OK


class WeechatController(object):
    """
    Encapsulates our interaction with WeeChat
    """

    def __init__(self, eventrouter):
        self.eventrouter = eventrouter
        self.buffers = {}
        self.previous_buffer = None

    def iter_buffers(self):
        for b in self.buffers:
            yield (b, self.buffers[b])

    def register_buffer(self, buffer_ptr, channel):
        """
        complete
        Adds a WeeChat buffer to the list of handled buffers for this EventRouter
        """
        if isinstance(buffer_ptr, basestring):
            self.buffers[buffer_ptr] = channel
        else:
            raise InvalidType(type(buffer_ptr))

    def unregister_buffer(self, buffer_ptr, update_remote=False, close_buffer=False):
        """
        complete
        Adds a WeeChat buffer to the list of handled buffers for this EventRouter
        """
        channel = self.buffers.get(buffer_ptr)
        if channel:
            channel.destroy_buffer(update_remote)
            del self.buffers[buffer_ptr]
            if close_buffer:
                w.buffer_close(buffer_ptr)

    def get_channel_from_buffer_ptr(self, buffer_ptr):
        return self.buffers.get(buffer_ptr)

    def get_all(self, buffer_ptr):
        return self.buffers

    def get_previous_buffer_ptr(self):
        return self.previous_buffer

    def set_previous_buffer(self, data):
        self.previous_buffer = data


###### New Local Processors


def local_process_async_slack_api_request(request, event_router):
    """
    complete
    Sends an API request to Slack. You'll need to give this a well formed SlackRequest object.
    DEBUGGING!!! The context here cannot be very large. WeeChat will crash.
    """
    if not event_router.shutting_down:
        weechat_request = "url:{}".format(request.request_string())
        weechat_request += "&nonce={}".format(
            "".join(
                random.choice(string.ascii_uppercase + string.digits) for _ in range(4)
            )
        )
        request.tried()
        options = request.options()
        options["header"] = "1"
        context = event_router.store_context(request)
        w.hook_process_hashtable(
            weechat_request,
            options,
            config.slack_timeout,
            "receive_httprequest_callback",
            context,
        )


###### New Callbacks


@utf8_decode
def ws_ping_cb(data, remaining_calls):
    for team in EVENTROUTER.teams.values():
        if team.ws and team.connected:
            try:
                team.ws.ping()
                team.last_ping_time = time.time()
            except (WebSocketConnectionClosedException, socket.error) as e:
                handle_socket_error(e, team, "ping")
    return w.WEECHAT_RC_OK


@utf8_decode
def reconnect_callback(*args):
    EVENTROUTER.reconnect_if_disconnected()
    return w.WEECHAT_RC_OK


@utf8_decode
def buffer_renamed_cb(data, signal, current_buffer):
    channel = EVENTROUTER.weechat_controller.buffers.get(current_buffer)
    if (
        isinstance(channel, SlackChannelCommon)
        and not channel.buffer_rename_in_progress
    ):
        if w.buffer_get_string(channel.channel_buffer, "old_full_name"):
            channel.label_full_drop_prefix = True
            channel.label_full = w.buffer_get_string(channel.channel_buffer, "name")
        else:
            channel.label_short_drop_prefix = True
            channel.label_short = w.buffer_get_string(
                channel.channel_buffer, "short_name"
            )

        channel.rename()
    return w.WEECHAT_RC_OK


@utf8_decode
def buffer_closing_callback(data, signal, current_buffer):
    """
    Receives a callback from WeeChat when a buffer is being closed.
    """
    EVENTROUTER.weechat_controller.unregister_buffer(current_buffer, True, False)
    return w.WEECHAT_RC_OK


@utf8_decode
def buffer_input_callback(signal, buffer_ptr, data):
    """
    incomplete
    Handles everything a user types in the input bar. In our case
    this includes add/remove reactions, modifying messages, and
    sending messages.
    """
    if weechat_version < 0x2090000:
        data = data.replace("\r", "\n")
    eventrouter = eval(signal)
    channel = eventrouter.weechat_controller.get_channel_from_buffer_ptr(buffer_ptr)
    if not channel:
        return w.WEECHAT_RC_ERROR

    reaction = re.match(
        r"{}{}\s*$".format(
            REACTION_PREFIX_REGEX_STRING, EMOJI_CHAR_OR_NAME_REGEX_STRING
        ),
        data,
    )
    substitute = re.match("{}?s/".format(MESSAGE_ID_REGEX_STRING), data)
    if reaction:
        emoji = reaction.group("emoji_char") or reaction.group("emoji_name")
        if reaction.group("reaction_change") == "+":
            channel.send_add_reaction(reaction.group("msg_id"), emoji)
        elif reaction.group("reaction_change") == "-":
            channel.send_remove_reaction(reaction.group("msg_id"), emoji)
    elif substitute:
        try:
            old, new, flags = re.split(r"(?<!\\)/", data)[1:]
        except ValueError:
            print_error(
                "Incomplete regex for changing a message, "
                "it should be in the form s/old text/new text/"
            )
        else:
            # Replacement string in re.sub() is a string, not a regex, so get
            # rid of escapes.
            new = new.replace(r"\/", "/")
            old = old.replace(r"\/", "/")
            channel.edit_nth_previous_message(
                substitute.group("msg_id"), old, new, flags
            )
    else:
        if data.startswith(("//", " ")):
            data = data[1:]
        channel.send_message(data)
        # this is probably wrong channel.mark_read(update_remote=True, force=True)
    return w.WEECHAT_RC_OK


# Workaround for supporting multiline messages. It intercepts before the input
# callback is called, as this is called with the whole message, while it is
# normally split on newline before being sent to buffer_input_callback.
# WeeChat only splits on newline, so we replace it with carriage return, and
# replace it back in buffer_input_callback.
def input_text_for_buffer_cb(data, modifier, current_buffer, string):
    if current_buffer not in EVENTROUTER.weechat_controller.buffers:
        return string
    return re.sub("\r?\n", "\r", decode_from_utf8(string))


@utf8_decode
def buffer_switch_callback(data, signal, current_buffer):
    """
    Every time we change channels in WeeChat, we call this to:
    1) set read marker 2) determine if we have already populated
    channel history data 3) set presence to active
    """
    prev_buffer_ptr = EVENTROUTER.weechat_controller.get_previous_buffer_ptr()
    # this is to see if we need to gray out things in the buffer list
    prev = EVENTROUTER.weechat_controller.get_channel_from_buffer_ptr(prev_buffer_ptr)
    if prev:
        prev.mark_read()

    new_channel = EVENTROUTER.weechat_controller.get_channel_from_buffer_ptr(
        current_buffer
    )
    if new_channel:
        if not new_channel.got_history or new_channel.history_needs_update:
            new_channel.get_history()
        set_own_presence_active(new_channel.team)

    EVENTROUTER.weechat_controller.set_previous_buffer(current_buffer)
    return w.WEECHAT_RC_OK


@utf8_decode
def buffer_list_update_callback(data, somecount):
    """
    A simple timer-based callback that will update the buffer list
    if needed. We only do this max 1x per second, as otherwise it
    uses a lot of cpu for minimal changes. We use buffer short names
    to indicate typing via "#channel" <-> ">channel" and
    user presence via " name" <-> "+name".
    """

    for buf in EVENTROUTER.weechat_controller.buffers.values():
        buf.refresh()
    return w.WEECHAT_RC_OK


def quit_notification_callback(data, signal, args):
    stop_talking_to_slack()
    return w.WEECHAT_RC_OK


@utf8_decode
def typing_notification_cb(data, signal, current_buffer):
    msg = w.buffer_get_string(current_buffer, "input")
    if len(msg) > 8 and msg[0] != "/":
        global typing_timer
        now = time.time()
        if typing_timer + 4 < now:
            channel = EVENTROUTER.weechat_controller.buffers.get(current_buffer)
            if channel and channel.type != "thread":
                identifier = channel.identifier
                request = {"type": "typing", "channel": identifier}
                channel.team.send_to_websocket(request, expect_reply=False)
                typing_timer = now
    return w.WEECHAT_RC_OK


@utf8_decode
def typing_update_cb(data, remaining_calls):
    w.bar_item_update("slack_typing_notice")
    return w.WEECHAT_RC_OK


@utf8_decode
def slack_never_away_cb(data, remaining_calls):
    if config.never_away:
        for team in EVENTROUTER.teams.values():
            set_own_presence_active(team)
    return w.WEECHAT_RC_OK


@utf8_decode
def typing_bar_item_cb(data, item, current_window, current_buffer, extra_info):
    """
    Privides a bar item indicating who is typing in the current channel AND
    why is typing a DM to you globally.
    """
    typers = []
    current_channel = EVENTROUTER.weechat_controller.buffers.get(current_buffer)

    # first look for people typing in this channel
    if current_channel:
        # this try is mostly becuase server buffers don't implement is_someone_typing
        try:
            if current_channel.type != "im" and current_channel.is_someone_typing():
                typers += current_channel.get_typing_list()
        except:
            pass

    # here is where we notify you that someone is typing in DM
    # regardless of which buffer you are in currently
    for team in EVENTROUTER.teams.values():
        for channel in team.channels.values():
            if channel.type == "im":
                if channel.is_someone_typing():
                    typers.append("D/" + channel.name)

    typing = ", ".join(typers)
    if typing != "":
        typing = colorize_string(config.color_typing_notice, "typing: " + typing)

    return typing


@utf8_decode
def away_bar_item_cb(data, item, current_window, current_buffer, extra_info):
    channel = EVENTROUTER.weechat_controller.buffers.get(current_buffer)
    if not channel:
        return ""

    if channel.team.is_user_present(channel.team.myidentifier):
        return ""
    else:
        away_color = w.config_string(w.config_get("weechat.color.item_away"))
        if channel.team.my_manual_presence == "away":
            return colorize_string(away_color, "manual away")
        else:
            return colorize_string(away_color, "auto away")


@utf8_decode
def channel_completion_cb(data, completion_item, current_buffer, completion):
    """
    Adds all channels on all teams to completion list
    """
    current_channel = EVENTROUTER.weechat_controller.buffers.get(current_buffer)
    should_include_channel = lambda channel: channel.active and channel.type in [
        "channel",
        "group",
        "private",
        "shared",
    ]

    other_teams = [
        team
        for team in EVENTROUTER.teams.values()
        if not current_channel or team != current_channel.team
    ]
    for team in other_teams:
        for channel in team.channels.values():
            if should_include_channel(channel):
                completion_list_add(
                    completion, channel.name, 0, w.WEECHAT_LIST_POS_SORT
                )

    if current_channel:
        for channel in sorted(
            current_channel.team.channels.values(),
            key=lambda channel: channel.name,
            reverse=True,
        ):
            if should_include_channel(channel):
                completion_list_add(
                    completion, channel.name, 0, w.WEECHAT_LIST_POS_BEGINNING
                )

        if should_include_channel(current_channel):
            completion_list_add(
                completion, current_channel.name, 0, w.WEECHAT_LIST_POS_BEGINNING
            )
    return w.WEECHAT_RC_OK


@utf8_decode
def dm_completion_cb(data, completion_item, current_buffer, completion):
    """
    Adds all dms/mpdms on all teams to completion list
    """
    for team in EVENTROUTER.teams.values():
        for channel in team.channels.values():
            if channel.active and channel.type in ["im", "mpim"]:
                completion_list_add(
                    completion, channel.name, 0, w.WEECHAT_LIST_POS_SORT
                )
    return w.WEECHAT_RC_OK


@utf8_decode
def nick_completion_cb(data, completion_item, current_buffer, completion):
    """
    Adds all @-prefixed nicks to completion list
    """
    current_channel = EVENTROUTER.weechat_controller.buffers.get(current_buffer)
    if current_channel is None or current_channel.members is None:
        return w.WEECHAT_RC_OK

    base_command = completion_get_string(completion, "base_command")
    if base_command in ["invite", "msg", "query", "whois"]:
        members = current_channel.team.members
    else:
        members = current_channel.members

    for member in members:
        user = current_channel.team.users.get(member)
        if user and not user.deleted:
            completion_list_add(completion, user.name, 1, w.WEECHAT_LIST_POS_SORT)
            completion_list_add(completion, "@" + user.name, 1, w.WEECHAT_LIST_POS_SORT)
    return w.WEECHAT_RC_OK


@utf8_decode
def emoji_completion_cb(data, completion_item, current_buffer, completion):
    """
    Adds all :-prefixed emoji to completion list
    """
    current_channel = EVENTROUTER.weechat_controller.buffers.get(current_buffer)
    if current_channel is None:
        return w.WEECHAT_RC_OK

    base_word = completion_get_string(completion, "base_word")
    reaction = re.match(REACTION_PREFIX_REGEX_STRING + ":", base_word)
    prefix = reaction.group(0) if reaction else ":"

    for emoji in current_channel.team.emoji_completions:
        completion_list_add(
            completion, prefix + emoji + ":", 0, w.WEECHAT_LIST_POS_SORT
        )
    return w.WEECHAT_RC_OK


@utf8_decode
def thread_completion_cb(data, completion_item, current_buffer, completion):
    """
    Adds all $-prefixed thread ids to completion list
    """
    current_channel = EVENTROUTER.weechat_controller.buffers.get(current_buffer)
    if current_channel is None or not hasattr(current_channel, "hashed_messages"):
        return w.WEECHAT_RC_OK

    threads = (
        x for x in current_channel.hashed_messages.items() if isinstance(x[0], str)
    )
    for thread_id, message_ts in sorted(threads, key=lambda item: item[1]):
        message = current_channel.messages.get(message_ts)
        if message and message.number_of_replies():
            completion_list_add(
                completion, "$" + thread_id, 0, w.WEECHAT_LIST_POS_BEGINNING
            )
    return w.WEECHAT_RC_OK


@utf8_decode
def topic_completion_cb(data, completion_item, current_buffer, completion):
    """
    Adds topic for current channel to completion list
    """
    current_channel = EVENTROUTER.weechat_controller.buffers.get(current_buffer)
    if current_channel is None:
        return w.WEECHAT_RC_OK

    topic = current_channel.render_topic()
    channel_names = [channel.name for channel in current_channel.team.channels.values()]
    if topic.split(" ", 1)[0] in channel_names:
        topic = "{} {}".format(current_channel.name, topic)

    completion_list_add(completion, topic, 0, w.WEECHAT_LIST_POS_SORT)
    return w.WEECHAT_RC_OK


@utf8_decode
def usergroups_completion_cb(data, completion_item, current_buffer, completion):
    """
    Adds all @-prefixed usergroups to completion list
    """
    current_channel = EVENTROUTER.weechat_controller.buffers.get(current_buffer)
    if current_channel is None:
        return w.WEECHAT_RC_OK

    subteam_handles = [
        subteam.handle for subteam in current_channel.team.subteams.values()
    ]
    for group in subteam_handles + ["@channel", "@everyone", "@here"]:
        completion_list_add(completion, group, 1, w.WEECHAT_LIST_POS_SORT)
    return w.WEECHAT_RC_OK


@utf8_decode
def complete_next_cb(data, current_buffer, command):
    """Extract current word, if it is equal to a nick, prefix it with @ and
    rely on nick_completion_cb adding the @-prefixed versions to the
    completion lists, then let WeeChat's internal completion do its
    thing
    """
    current_channel = EVENTROUTER.weechat_controller.buffers.get(current_buffer)
    if (
        not hasattr(current_channel, "members")
        or current_channel is None
        or current_channel.members is None
    ):
        return w.WEECHAT_RC_OK

    line_input = w.buffer_get_string(current_buffer, "input")
    current_pos = w.buffer_get_integer(current_buffer, "input_pos") - 1
    input_length = w.buffer_get_integer(current_buffer, "input_length")

    word_start = 0
    word_end = input_length
    # If we're on a non-word, look left for something to complete
    while (
        current_pos >= 0
        and line_input[current_pos] != "@"
        and not line_input[current_pos].isalnum()
    ):
        current_pos = current_pos - 1
    if current_pos < 0:
        current_pos = 0
    for l in range(current_pos, 0, -1):
        if line_input[l] != "@" and not line_input[l].isalnum():
            word_start = l + 1
            break
    for l in range(current_pos, input_length):
        if not line_input[l].isalnum():
            word_end = l
            break
    word = line_input[word_start:word_end]

    for member in current_channel.members:
        user = current_channel.team.users.get(member)
        if user and user.name == word:
            # Here, we cheat.  Insert a @ in front and rely in the @
            # nicks being in the completion list
            w.buffer_set(
                current_buffer,
                "input",
                line_input[:word_start] + "@" + line_input[word_start:],
            )
            w.buffer_set(
                current_buffer,
                "input_pos",
                str(w.buffer_get_integer(current_buffer, "input_pos") + 1),
            )
            return w.WEECHAT_RC_OK_EAT
    return w.WEECHAT_RC_OK


def script_unloaded():
    stop_talking_to_slack()
    return w.WEECHAT_RC_OK


def stop_talking_to_slack():
    """
    complete
    Prevents a race condition where quitting closes buffers
    which triggers leaving the channel because of how close
    buffer is handled
    """
    if "EVENTROUTER" in globals():
        EVENTROUTER.shutdown()
        for team in EVENTROUTER.teams.values():
            team.ws.shutdown()
    return w.WEECHAT_RC_OK


##### New Classes


class SlackRequest(object):
    """
    Encapsulates a Slack api request. Valuable as an object that we can add to the queue and/or retry.
    makes a SHA of the requst url and current time so we can re-tag this on the way back through.
    """

    def __init__(
        self,
        team,
        request,
        post_data=None,
        channel=None,
        metadata=None,
        retries=3,
        token=None,
        cookies=None,
        callback=None,
    ):
        if team is None and token is None:
            raise ValueError("Both team and token can't be None")
        self.team = team
        self.request = request
        self.post_data = post_data if post_data else {}
        self.channel = channel
        self.metadata = metadata if metadata else {}
        self.retries = retries
        self.retry_time = 0
        self.token = token if token else team.token
        self.cookies = cookies or {}
        if ":" in self.token:
            token, cookie = self.token.split(":", 1)
            self.token = token
            if cookie.startswith("d="):
                for name, value in [c.split("=") for c in cookie.split(";")]:
                    self.cookies[name] = value
            else:
                self.cookies["d"] = cookie
        self.callback = callback
        self.domain = "api.slack.com"
        self.reset()

    def reset(self):
        self.tries = 0
        self.start_time = time.time()
        self.request_normalized = re.sub(r"\W+", "", self.request)
        self.url = "https://{}/api/{}?{}".format(
            self.domain, self.request, urlencode(encode_to_utf8(self.post_data))
        )
        self.response_id = sha1_hex("{}{}".format(self.url, self.start_time))

    def __repr__(self):
        return (
            "SlackRequest(team={}, request='{}', post_data={}, retries={}, token='{}', "
            "cookies={}, tries={}, start_time={})"
        ).format(
            self.team,
            self.request,
            self.post_data,
            self.retries,
            token_for_print(self.token),
            self.cookies,
            self.tries,
            self.start_time,
        )

    def request_string(self):
        return "{}".format(self.url)

    def options(self):
        cookies = "; ".join(
            [
                "{}={}".format(key, url_encode_if_not_encoded(value))
                for key, value in self.cookies.items()
            ]
        )
        return {
            "useragent": "wee_slack {}".format(SCRIPT_VERSION),
            "httpheader": "Authorization: Bearer {}".format(self.token),
            "cookie": cookies,
        }

    def options_as_cli_args(self):
        options = self.options()
        options["user-agent"] = options.pop("useragent")
        httpheader = options.pop("httpheader")
        headers = [": ".join(x) for x in options.items()] + httpheader.split("\n")
        return ["-H{}".format(header) for header in headers]

    def tried(self):
        self.tries += 1
        self.response_id = sha1_hex("{}{}".format(self.url, time.time()))

    def should_try(self):
        return self.tries < self.retries

    def retry_ready(self):
        if self.retry_time:
            return time.time() > self.retry_time
        else:
            return (self.start_time + (self.tries**2)) < time.time()


class SlackSubteam(object):
    """
    Represents a slack group or subteam
    """

    def __init__(self, originating_team_id, is_member, **kwargs):
        self.handle = "@{}".format(kwargs["handle"])
        self.identifier = kwargs["id"]
        self.name = kwargs["name"]
        self.description = kwargs.get("description")
        self.team_id = originating_team_id
        self.is_member = is_member

    def __repr__(self):
        return "Name:{} Identifier:{}".format(self.name, self.identifier)

    def __eq__(self, compare_str):
        return compare_str == self.identifier


class SlackTeam(object):
    """
    incomplete
    Team object under which users and channels live.. Does lots.
    """

    def __init__(
        self,
        eventrouter,
        token,
        team_hash,
        websocket_url,
        team_info,
        subteams,
        nick,
        myidentifier,
        my_manual_presence,
        users,
        bots,
        channels,
        **kwargs
    ):
        self.slack_api_translator = copy.deepcopy(SLACK_API_TRANSLATOR)
        self.identifier = team_info["id"]
        self.type = "team"
        self.active = True
        self.team_hash = team_hash
        self.ws_url = websocket_url
        self.connected = False
        self.connecting_rtm = False
        self.connecting_ws = False
        self.ws = None
        self.ws_counter = 0
        self.ws_replies = {}
        self.last_ping_time = 0
        self.last_pong_time = time.time()
        self.eventrouter = eventrouter
        self.token = token
        self.team = self
        self.subteams = subteams
        self.team_info = team_info
        self.subdomain = team_info["domain"]
        self.domain = self.subdomain + ".slack.com"
        self.set_name()
        self.nick = nick
        self.myidentifier = myidentifier
        self.my_manual_presence = my_manual_presence
        try:
            if self.channels:
                for c in channels.keys():
                    if not self.channels.get(c):
                        self.channels[c] = channels[c]
        except:
            self.channels = channels
        self.users = users
        self.bots = bots
        self.channel_buffer = None
        self.got_history = True
        self.history_needs_update = False
        self.create_buffer()
        self.set_muted_channels(kwargs.get("muted_channels", ""))
        self.set_highlight_words(kwargs.get("highlight_words", ""))
        for c in self.channels.keys():
            channels[c].set_related_server(self)
            channels[c].check_should_open()
        # Last step is to make sure my nickname is the set color
        self.users[self.myidentifier].force_color(
            w.config_string(w.config_get("weechat.color.chat_nick_self"))
        )
        # This highlight step must happen after we have set related server
        self.load_emoji_completions()

    def __repr__(self):
        return "domain={} nick={}".format(self.subdomain, self.nick)

    def __eq__(self, compare_str):
        return (
            compare_str == self.token
            or compare_str == self.domain
            or compare_str == self.subdomain
        )

    @property
    def members(self):
        return self.users.keys()

    def load_emoji_completions(self):
        self.emoji_completions = list(EMOJI.keys())
        if self.emoji_completions:
            s = SlackRequest(self, "emoji.list")
            self.eventrouter.receive(s)

    def add_channel(self, channel):
        self.channels[channel["id"]] = channel
        channel.set_related_server(self)

    def generate_usergroup_map(self):
        return {s.handle: s.identifier for s in self.subteams.values()}

    def set_name(self):
        alias = config.server_aliases.get(self.subdomain)
        if alias:
            self.name = alias
        elif config.short_buffer_names:
            self.name = self.subdomain
        else:
            self.name = "slack.{}".format(self.subdomain)

    def create_buffer(self):
        if not self.channel_buffer:
            self.channel_buffer = w.buffer_new(
                self.name, "buffer_input_callback", "EVENTROUTER", "", ""
            )
            self.eventrouter.weechat_controller.register_buffer(
                self.channel_buffer, self
            )
            w.buffer_set(self.channel_buffer, "input_multiline", "1")
            w.buffer_set(self.channel_buffer, "localvar_set_type", "server")
            w.buffer_set(self.channel_buffer, "localvar_set_slack_type", self.type)
            w.buffer_set(self.channel_buffer, "localvar_set_nick", self.nick)
            w.buffer_set(self.channel_buffer, "localvar_set_server", self.name)
            w.buffer_set(
                self.channel_buffer,
                "localvar_set_completion_default_template",
                "${weechat.completion.default_template}|%(usergroups)|%(emoji)",
            )
            self.buffer_merge()

    def buffer_merge(self, config_value=None):
        if not config_value:
            config_value = w.config_string(w.config_get("irc.look.server_buffer"))
        if config_value == "merge_with_core":
            w.buffer_merge(self.channel_buffer, w.buffer_search_main())
        else:
            w.buffer_unmerge(self.channel_buffer, 0)

    def destroy_buffer(self, update_remote):
        pass

    def set_muted_channels(self, muted_str):
        self.muted_channels = {x for x in muted_str.split(",") if x}
        for channel in self.channels.values():
            channel.set_highlights()
            channel.rename()

    def set_highlight_words(self, highlight_str):
        self.highlight_words = {x for x in highlight_str.split(",") if x}
        for channel in self.channels.values():
            channel.set_highlights()

    def formatted_name(self):
        return self.domain

    def buffer_prnt(self, data, message=False):
        tag_name = "team_message" if message else "team_info"
        ts = SlackTS()
        w.prnt_date_tags(self.channel_buffer, ts.major, tag(ts, tag_name), data)

    def send_message(self, message, subtype=None, request_dict_ext={}):
        w.prnt("", "ERROR: Sending a message in the team buffer is not supported")

    def find_channel_by_members(self, members, channel_type=None):
        for channel in self.channels.values():
            if channel.members == members and (
                channel_type is None or channel.type == channel_type
            ):
                return channel

    def get_channel_map(self):
        return {v.name: k for k, v in self.channels.items()}

    def get_username_map(self):
        return {v.name: k for k, v in self.users.items()}

    def get_team_hash(self):
        return self.team_hash

    @staticmethod
    def generate_team_hash(team_id, subdomain):
        return str(sha1_hex("{}{}".format(team_id, subdomain)))

    def refresh(self):
        pass

    def is_user_present(self, user_id):
        user = self.users.get(user_id)
        if user and user.presence == "active":
            return True
        else:
            return False

    def mark_read(self, ts=None, update_remote=True, force=False):
        pass

    def connect(self):
        if not self.connected and not self.connecting_ws:
            if self.ws_url:
                self.connecting_ws = True
                try:
                    # only http proxy is currently supported
                    proxy = ProxyWrapper()
                    timeout = config.slack_timeout / 1000
                    cookie = SlackRequest(self.team, "").options()["cookie"]
                    if proxy.has_proxy:
                        ws = create_connection(
                            self.ws_url,
                            cookie=cookie,
                            timeout=timeout,
                            sslopt=sslopt_ca_certs,
                            http_proxy_host=proxy.proxy_address,
                            http_proxy_port=proxy.proxy_port,
                            http_proxy_auth=(proxy.proxy_user, proxy.proxy_password),
                        )
                    else:
                        ws = create_connection(
                            self.ws_url,
                            cookie=cookie,
                            timeout=timeout,
                            sslopt=sslopt_ca_certs,
                        )

                    self.hook = w.hook_fd(
                        ws.sock.fileno(),
                        1,
                        0,
                        0,
                        "receive_ws_callback",
                        self.get_team_hash(),
                    )
                    ws.sock.setblocking(0)
                except:
                    w.prnt(
                        self.channel_buffer,
                        "Failed connecting to slack team {}, retrying.".format(
                            self.domain
                        ),
                    )
                    dbg(
                        "connect failed with exception:\n{}".format(format_exc_tb()),
                        level=5,
                    )
                    return False
                finally:
                    self.connecting_ws = False
                self.ws = ws
                self.set_reconnect_url(None)
                self.set_connected()
            elif not self.connecting_rtm:
                # The fast reconnect failed, so start over-ish
                for chan in self.channels:
                    self.channels[chan].history_needs_update = True
                s = get_rtm_connect_request(self.token, retries=999, team=self)
                self.eventrouter.receive(s)
                self.connecting_rtm = True

    def set_connected(self):
        self.connected = True
        self.last_pong_time = time.time()
        self.buffer_prnt(
            "Connected to Slack team {} ({}) with username {}".format(
                self.team_info["name"], self.domain, self.nick
            )
        )
        dbg("connected to {}".format(self.domain))

        if config.background_load_all_history:
            for channel in self.channels.values():
                if channel.channel_buffer:
                    channel.get_history(slow_queue=True)
        else:
            current_channel = self.eventrouter.weechat_controller.buffers.get(
                w.current_buffer()
            )
            if (
                isinstance(current_channel, SlackChannelCommon)
                and current_channel.team == self
            ):
                current_channel.get_history(slow_queue=True)

    def set_disconnected(self):
        w.unhook(self.hook)
        self.connected = False

    def set_reconnect_url(self, url):
        self.ws_url = url

    def next_ws_transaction_id(self):
        self.ws_counter += 1
        return self.ws_counter

    def send_to_websocket(self, data, expect_reply=True):
        data["id"] = self.next_ws_transaction_id()
        message = json.dumps(data)
        try:
            if expect_reply:
                self.ws_replies[data["id"]] = data
            self.ws.send(encode_to_utf8(message))
            dbg("Sent {}...".format(message[:100]))
        except (WebSocketConnectionClosedException, socket.error) as e:
            handle_socket_error(e, self, "send")

    def update_member_presence(self, user, presence):
        user.presence = presence

        for c in self.channels:
            c = self.channels[c]
            if user.id in c.members:
                c.buffer_name_needs_update = True
                c.update_nicklist(user.id)

    def subscribe_users_presence(self):
        # FIXME: There is a limitation in the API to the size of the
        # json we can send.
        # We should try to be smarter to fetch the users whom we want to
        # subscribe to.
        users = list(self.users.keys())[:750]
        if self.myidentifier not in users:
            users.append(self.myidentifier)
        self.send_to_websocket(
            {
                "type": "presence_sub",
                "ids": users,
            },
            expect_reply=False,
        )


class SlackChannelCommon(object):
    def __init__(self):
        self.label_full_drop_prefix = False
        self.label_full = None
        self.label_short_drop_prefix = False
        self.label_short = None
        self.buffer_rename_in_progress = False

    def prnt_message(
        self, message, history_message=False, no_log=False, force_render=False
    ):
        text = self.render(message, force_render)
        thread_channel = isinstance(self, SlackThreadChannel)

        if message.subtype == "join":
            tagset = "join"
            prefix = w.prefix("join").strip()
        elif message.subtype == "leave":
            tagset = "leave"
            prefix = w.prefix("quit").strip()
        elif message.subtype == "topic":
            tagset = "topic"
            prefix = w.prefix("network").strip()
        else:
            channel_type = self.parent_channel.type if thread_channel else self.type
            if channel_type in ["im", "mpim"]:
                tagset = "dm"
            else:
                tagset = "channel"

            if message.subtype == "me_message":
                prefix = w.prefix("action").rstrip()
            else:
                prefix = message.sender

        extra_tags = None
        if message.subtype == "thread_broadcast":
            extra_tags = [message.subtype]
        elif isinstance(message, SlackThreadMessage) and not thread_channel:
            if config.thread_messages_in_channel:
                extra_tags = [message.subtype]
            else:
                return

        self.buffer_prnt(
            prefix,
            text,
            message.ts,
            tagset=tagset,
            tag_nick=message.sender_plain,
            history_message=history_message,
            no_log=no_log,
            extra_tags=extra_tags,
        )

    def print_getting_history(self):
        if self.channel_buffer:
            ts = SlackTS()
            w.buffer_set(self.channel_buffer, "print_hooks_enabled", "0")
            w.prnt_date_tags(
                self.channel_buffer,
                ts.major,
                tag(ts, backlog=True, no_log=True),
                "\tgetting channel history...",
            )
            w.buffer_set(self.channel_buffer, "print_hooks_enabled", "1")

    def reprint_messages(self, history_message=False, no_log=True, force_render=False):
        if self.channel_buffer:
            w.buffer_clear(self.channel_buffer)
            self.last_line_from = None
            for message in self.visible_messages.values():
                self.prnt_message(message, history_message, no_log, force_render)
            if (
                self.identifier in self.pending_history_requests
                or config.thread_messages_in_channel
                and self.pending_history_requests
            ):
                self.print_getting_history()

    def send_message(self, message, subtype=None, request_dict_ext={}):
        if subtype == "me_message":
            message = linkify_text(message, self.team, escape_characters=False)
            s = SlackRequest(
                self.team,
                "chat.meMessage",
                {"channel": self.identifier, "text": message},
                channel=self,
            )
            self.eventrouter.receive(s)
        else:
            message = linkify_text(message, self.team)
            request = {
                "type": "message",
                "channel": self.identifier,
                "text": message,
                "user": self.team.myidentifier,
            }
            request.update(request_dict_ext)
            self.team.send_to_websocket(request)

    def send_add_reaction(self, msg_id, reaction):
        self.send_change_reaction("reactions.add", msg_id, reaction)

    def send_remove_reaction(self, msg_id, reaction):
        self.send_change_reaction("reactions.remove", msg_id, reaction)

    def send_change_reaction(self, method, msg_id, reaction):
        message = self.message_from_hash_or_index(msg_id)
        if message is None:
            print_message_not_found_error(msg_id)
            return

        reaction_name = replace_emoji_with_string(reaction)
        if method == "toggle":
            reaction = message.get_reaction(reaction_name)
            if reaction and self.team.myidentifier in reaction["users"]:
                method = "reactions.remove"
            else:
                method = "reactions.add"

        data = {
            "channel": self.identifier,
            "timestamp": message.ts,
            "name": reaction_name,
        }
        s = SlackRequest(
            self.team, method, data, channel=self, metadata={"reaction": reaction}
        )
        self.eventrouter.receive(s)

    def edit_nth_previous_message(self, msg_id, old, new, flags):
        message_filter = (
            lambda message: message.user_identifier == self.team.myidentifier
        )
        message = self.message_from_hash_or_index(msg_id, message_filter)
        if message is None:
            if msg_id:
                print_error(
                    "Invalid id given, must be an existing id to one of your "
                    + "messages or a number greater than 0 and less than the number "
                    + "of your messages in the channel"
                )
            else:
                print_error("You don't have any messages in this channel")
            return
        if new == "" and old == "":
            post_data = {"channel": self.identifier, "ts": message.ts}
            s = SlackRequest(self.team, "chat.delete", post_data, channel=self)
            self.eventrouter.receive(s)
        else:
            num_replace = 0 if "g" in flags else 1
            f = re.UNICODE
            f |= re.IGNORECASE if "i" in flags else 0
            f |= re.MULTILINE if "m" in flags else 0
            f |= re.DOTALL if "s" in flags else 0
            old_message_text = message.message_json["text"]
            new_message_text = re.sub(old, new, old_message_text, num_replace, f)
            if new_message_text != old_message_text:
                post_data = {
                    "channel": self.identifier,
                    "ts": message.ts,
                    "text": new_message_text,
                }
                s = SlackRequest(self.team, "chat.update", post_data, channel=self)
                self.eventrouter.receive(s)
            else:
                print_error("The regex didn't match any part of the message")

    def message_from_hash(self, ts_hash, message_filter=None):
        if not ts_hash:
            return
        ts_hash_without_prefix = ts_hash[1:] if ts_hash[0] == "$" else ts_hash
        ts = self.hashed_messages.get(ts_hash_without_prefix)
        message = self.messages.get(ts)
        if message is None:
            return
        if message_filter and not message_filter(message):
            return
        return message

    def message_from_index(self, index, message_filter=None, reverse=True):
        for ts in reversed(self.visible_messages) if reverse else self.visible_messages:
            message = self.messages[ts]
            if not message_filter or message_filter(message):
                index -= 1
                if index == 0:
                    return message

    def message_from_hash_or_index(
        self, hash_or_index=None, message_filter=None, reverse=True
    ):
        message = self.message_from_hash(hash_or_index, message_filter)
        if not message:
            if not hash_or_index:
                index = 1
            elif hash_or_index.isdigit():
                index = int(hash_or_index)
            else:
                return
            message = self.message_from_index(index, message_filter, reverse)
        return message

    def change_message(self, ts, message_json=None):
        ts = SlackTS(ts)
        m = self.messages.get(ts)
        if not m:
            return
        if message_json:
            m.message_json.update(message_json)

        if (
            not isinstance(m, SlackThreadMessage)
            or m.subtype == "thread_broadcast"
            or config.thread_messages_in_channel
        ):
            new_text = self.render(m, force=True)
            modify_buffer_line(self.channel_buffer, ts, new_text)
        if isinstance(m, SlackThreadMessage) or m.thread_channel is not None:
            thread_channel = (
                m.parent_message.thread_channel
                if isinstance(m, SlackThreadMessage)
                else m.thread_channel
            )
            if thread_channel and thread_channel.active:
                new_text = thread_channel.render(m, force=True)
                modify_buffer_line(thread_channel.channel_buffer, ts, new_text)

    def mark_read(self, ts=None, update_remote=True, force=False, post_data={}):
        if self.new_messages or force:
            if self.channel_buffer:
                w.buffer_set(self.channel_buffer, "unread", "")
                w.buffer_set(self.channel_buffer, "hotlist", "-1")
            if not ts:
                ts = next(reversed(self.messages), SlackTS())
            if ts > self.last_read:
                self.last_read = SlackTS(ts)
            if update_remote:
                args = {"channel": self.identifier, "ts": ts}
                args.update(post_data)
                mark_method = self.team.slack_api_translator[self.type].get("mark")
                if mark_method:
                    s = SlackRequest(self.team, mark_method, args, channel=self)
                    self.eventrouter.receive(s)
                    self.new_messages = False

    def destroy_buffer(self, update_remote):
        self.channel_buffer = None
        self.got_history = False
        self.active = False


class SlackChannel(SlackChannelCommon):
    """
    Represents an individual slack channel.
    """

    def __init__(self, eventrouter, channel_type="channel", **kwargs):
        super(SlackChannel, self).__init__()
        self.active = False
        for key, value in kwargs.items():
            setattr(self, key, value)
        self.eventrouter = eventrouter
        self.team = kwargs.get("team")
        self.identifier = kwargs["id"]
        self.type = channel_type
        self.set_name(kwargs["name"])
        self.slack_purpose = kwargs.get("purpose", {"value": ""})
        self.topic = kwargs.get("topic", {"value": ""})
        self.last_read = SlackTS(kwargs.get("last_read", 0))
        self.channel_buffer = None
        self.got_history = False
        self.got_members = False
        self.history_needs_update = False
        self.pending_history_requests = set()
        self.messages = OrderedDict()
        self.visible_messages = SlackChannelVisibleMessages(self)
        self.hashed_messages = SlackChannelHashedMessages(self)
        self.thread_channels = {}
        self.new_messages = False
        self.typing = {}
        # short name relates to the localvar we change for typing indication
        self.set_members(kwargs.get("members", []))
        self.unread_count_display = 0
        self.last_line_from = None
        self.buffer_name_needs_update = False
        self.last_refresh_typing = False

    def __eq__(self, compare_str):
        if (
            compare_str == self.slack_name
            or compare_str == self.formatted_name()
            or compare_str == self.formatted_name(style="long_default")
        ):
            return True
        else:
            return False

    def __repr__(self):
        return "Name:{} Identifier:{}".format(self.name, self.identifier)

    @property
    def muted(self):
        return self.identifier in self.team.muted_channels

    def set_name(self, slack_name):
        self.slack_name = slack_name
        self.name = self.formatted_name()
        self.buffer_name_needs_update = True

    def refresh(self):
        typing = self.is_someone_typing()
        if self.buffer_name_needs_update or typing != self.last_refresh_typing:
            self.last_refresh_typing = typing
            self.buffer_name_needs_update = False
            self.rename(typing)

    def rename(self, typing=None):
        if self.channel_buffer:
            self.buffer_rename_in_progress = True
            if typing is None:
                typing = self.is_someone_typing()
            present = (
                self.team.is_user_present(self.user) if self.type == "im" else None
            )

            name = self.formatted_name("long_default", typing, present)
            short_name = self.formatted_name("sidebar", typing, present)
            w.buffer_set(self.channel_buffer, "name", name)
            w.buffer_set(self.channel_buffer, "short_name", short_name)
            self.buffer_rename_in_progress = False

    def set_members(self, members):
        self.members = set(members)
        self.update_nicklist()

    def set_unread_count_display(self, count):
        self.unread_count_display = count
        self.new_messages = bool(self.unread_count_display)
        if self.muted and config.muted_channels_activity != "all":
            return
        for c in range(self.unread_count_display):
            if self.type in ["im", "mpim"]:
                w.buffer_set(self.channel_buffer, "hotlist", "2")
            else:
                w.buffer_set(self.channel_buffer, "hotlist", "1")

    def formatted_name(self, style="default", typing=False, present=None):
        show_typing = typing and not self.muted and config.channel_name_typing_indicator
        if style == "sidebar" and show_typing:
            prepend = ">"
        elif self.type == "group" or self.type == "private":
            prepend = config.group_name_prefix
        elif self.type == "shared":
            prepend = config.shared_name_prefix
        elif self.type == "im":
            if style != "sidebar":
                prepend = ""
            elif present and config.show_buflist_presence:
                prepend = "+"
            elif config.channel_name_typing_indicator or config.show_buflist_presence:
                prepend = " "
            else:
                prepend = ""
        elif self.type == "mpim":
            if style == "sidebar":
                prepend = "@"
            else:
                prepend = ""
        else:
            prepend = "#"

        name = self.label_full or self.slack_name

        if style == "sidebar":
            name = self.label_short or name
            if self.label_short_drop_prefix:
                if show_typing:
                    name = prepend + name[1:]
                elif (
                    self.type == "im"
                    and present
                    and config.show_buflist_presence
                    and name[0] == " "
                ):
                    name = prepend + name[1:]
            else:
                name = prepend + name

            if self.muted:
                sidebar_color = config.color_buflist_muted_channels
            elif self.type == "im" and config.colorize_private_chats:
                sidebar_color = self.color_name
            else:
                sidebar_color = ""

            return colorize_string(sidebar_color, name)
        elif style == "long_default":
            if self.label_full_drop_prefix:
                return name
            else:
                return "{}.{}{}".format(self.team.name, prepend, name)
        else:
            if self.label_full_drop_prefix:
                return name
            else:
                return prepend + name

    def render_topic(self, fallback_to_purpose=False):
        topic = self.topic["value"]
        if not topic and fallback_to_purpose:
            topic = self.slack_purpose["value"]
        return unhtmlescape(unfurl_refs(topic))

    def set_topic(self, value=None):
        if value is not None:
            self.topic = {"value": value}
        if self.channel_buffer:
            topic = self.render_topic(fallback_to_purpose=True)
            w.buffer_set(self.channel_buffer, "title", topic)

    def update_from_message_json(self, message_json):
        for key, value in message_json.items():
            setattr(self, key, value)

    def open(self, update_remote=True):
        if update_remote:
            join_method = self.team.slack_api_translator[self.type].get("join")
            if join_method:
                s = SlackRequest(
                    self.team, join_method, {"channel": self.identifier}, channel=self
                )
                self.eventrouter.receive(s)
        self.create_buffer()
        self.active = True
        self.get_history()

    def check_should_open(self, force=False):
        if hasattr(self, "is_archived") and self.is_archived:
            return

        if force:
            self.create_buffer()
            return

        if (
            getattr(self, "is_open", False)
            or self.unread_count_display
            or self.type not in ["im", "mpim"]
            and getattr(self, "is_member", False)
        ):
            self.create_buffer()
        elif self.type in ["im", "mpim"]:
            # If it is an IM or MPIM, we still might want to open it if there are unread messages.
            info_method = self.team.slack_api_translator[self.type].get("info")
            if info_method:
                s = SlackRequest(
                    self.team, info_method, {"channel": self.identifier}, channel=self
                )
                self.eventrouter.receive(s)

    def set_related_server(self, team):
        self.team = team

    def highlights(self):
        nick_highlights = {"@" + self.team.nick, self.team.myidentifier}
        subteam_highlights = {
            subteam.handle
            for subteam in self.team.subteams.values()
            if subteam.is_member
        }
        highlights = nick_highlights | subteam_highlights | self.team.highlight_words
        if self.muted and config.muted_channels_activity == "personal_highlights":
            return highlights
        else:
            return highlights | {"@channel", "@everyone", "@group", "@here"}

    def set_highlights(self):
        # highlight my own name and any set highlights
        if self.channel_buffer:
            h_str = ",".join(self.highlights())
            w.buffer_set(self.channel_buffer, "highlight_words", h_str)

            if self.muted and config.muted_channels_activity != "all":
                notify_level = "0" if config.muted_channels_activity == "none" else "1"
                w.buffer_set(self.channel_buffer, "notify", notify_level)
            else:
                buffer_full_name = w.buffer_get_string(self.channel_buffer, "full_name")
                w.command(
                    self.channel_buffer,
                    "/mute /unset weechat.notify.{}".format(buffer_full_name),
                )

            if self.muted and config.muted_channels_activity == "none":
                w.buffer_set(
                    self.channel_buffer, "highlight_tags_restrict", "highlight_force"
                )
            else:
                w.buffer_set(self.channel_buffer, "highlight_tags_restrict", "")

            for thread_channel in self.thread_channels.values():
                thread_channel.set_highlights(h_str)

    def create_buffer(self):
        """
        Creates the WeeChat buffer where the channel magic happens.
        """
        if not self.channel_buffer:
            self.active = True
            self.channel_buffer = w.buffer_new(
                self.formatted_name(style="long_default"),
                "buffer_input_callback",
                "EVENTROUTER",
                "",
                "",
            )
            self.eventrouter.weechat_controller.register_buffer(
                self.channel_buffer, self
            )
            w.buffer_set(self.channel_buffer, "input_multiline", "1")
            w.buffer_set(
                self.channel_buffer, "localvar_set_type", get_localvar_type(self.type)
            )
            w.buffer_set(self.channel_buffer, "localvar_set_slack_type", self.type)
            w.buffer_set(
                self.channel_buffer, "localvar_set_channel", self.formatted_name()
            )
            w.buffer_set(self.channel_buffer, "localvar_set_nick", self.team.nick)
            w.buffer_set(
                self.channel_buffer,
                "localvar_set_completion_default_template",
                "${weechat.completion.default_template}|%(usergroups)|%(emoji)",
            )
            self.buffer_rename_in_progress = True
            w.buffer_set(
                self.channel_buffer, "short_name", self.formatted_name(style="sidebar")
            )
            self.buffer_rename_in_progress = False
            self.set_highlights()
            self.set_topic()
            if self.channel_buffer:
                w.buffer_set(self.channel_buffer, "localvar_set_server", self.team.name)
        self.update_nicklist()

        info_method = self.team.slack_api_translator[self.type].get("info")
        if info_method:
            s = SlackRequest(
                self.team, info_method, {"channel": self.identifier}, channel=self
            )
            self.eventrouter.receive(s)

        if self.type == "im":
            join_method = self.team.slack_api_translator[self.type].get("join")
            if join_method:
                s = SlackRequest(
                    self.team,
                    join_method,
                    {"users": self.user, "return_im": True},
                    channel=self,
                )
                self.eventrouter.receive(s)

    def destroy_buffer(self, update_remote):
        super(SlackChannel, self).destroy_buffer(update_remote)
        self.messages = OrderedDict()
        if update_remote and not self.eventrouter.shutting_down:
            s = SlackRequest(
                self.team,
                self.team.slack_api_translator[self.type]["leave"],
                {"channel": self.identifier},
                channel=self,
            )
            self.eventrouter.receive(s)

    def buffer_prnt(
        self,
        nick,
        text,
        timestamp,
        tagset,
        tag_nick=None,
        history_message=False,
        no_log=False,
        extra_tags=None,
    ):
        data = "{}\t{}".format(format_nick(nick, self.last_line_from), text)
        self.last_line_from = nick
        ts = SlackTS(timestamp)
        # without this, DMs won't open automatically
        if not self.channel_buffer and ts > self.last_read:
            self.open(update_remote=False)
        if self.channel_buffer:
            # backlog messages - we will update the read marker as we print these
            backlog = ts <= self.last_read
            if not backlog:
                self.new_messages = True

            no_log = no_log or history_message and backlog
            self_msg = tag_nick == self.team.nick
            tags = tag(
                ts,
                tagset,
                user=tag_nick,
                self_msg=self_msg,
                backlog=backlog,
                no_log=no_log,
                extra_tags=extra_tags,
            )

            if (
                config.unhide_buffers_with_activity
                and not self.is_visible()
                and not self.muted
                and not no_log
            ):
                w.buffer_set(self.channel_buffer, "hidden", "0")

            if no_log:
                w.buffer_set(self.channel_buffer, "print_hooks_enabled", "0")
            w.prnt_date_tags(self.channel_buffer, ts.major, tags, data)
            if no_log:
                w.buffer_set(self.channel_buffer, "print_hooks_enabled", "1")
            if backlog or (self_msg and tagset != "join"):
                self.mark_read(ts, update_remote=False, force=True)

    def store_message(self, message_to_store):
        if not self.active:
            return

        old_message = self.messages.get(message_to_store.ts)
        if old_message and old_message.submessages and not message_to_store.submessages:
            message_to_store.submessages = old_message.submessages

        self.messages[message_to_store.ts] = message_to_store
        self.messages = OrderedDict(sorted(self.messages.items()))

        max_history = w.config_integer(
            w.config_get("weechat.history.max_buffer_lines_number")
        )
        messages_to_check = islice(
            self.messages.items(), max(0, len(self.messages) - max_history)
        )
        messages_to_delete = []
        for ts, message in messages_to_check:
            if ts == message_to_store.ts:
                pass
            elif isinstance(message, SlackThreadMessage):
                thread_channel = self.thread_channels.get(message.thread_ts)
                if thread_channel is None or not thread_channel.active:
                    messages_to_delete.append(ts)
            elif message.number_of_replies():
                if (
                    message.thread_channel is None or not message.thread_channel.active
                ) and not any(
                    submessage in self.messages for submessage in message.submessages
                ):
                    messages_to_delete.append(ts)
            else:
                messages_to_delete.append(ts)

        for ts in messages_to_delete:
            message_hash = self.hashed_messages.get(ts)
            if message_hash:
                del self.hashed_messages[ts]
                del self.hashed_messages[message_hash]
            del self.messages[ts]

    def is_visible(self):
        return w.buffer_get_integer(self.channel_buffer, "hidden") == 0

    def get_members(self):
        if not self.got_members:
            # Slack has started returning only a few members for some channels
            # in rtm.start. I don't know how we can check if the member list is
            # complete, so we have to fetch members for all channels.
            s = SlackRequest(
                self.team,
                "conversations.members",
                {"channel": self.identifier, "limit": 1000},
                channel=self,
            )
            self.eventrouter.receive(s)

    def get_history(self, slow_queue=False, full=False, no_log=False):
        if self.identifier in self.pending_history_requests:
            return

        self.print_getting_history()
        self.pending_history_requests.add(self.identifier)
        self.get_members()

        post_data = {"channel": self.identifier, "limit": config.history_fetch_count}
        if self.got_history and self.messages and not full:
            post_data["oldest"] = next(reversed(self.messages))

        s = SlackRequest(
            self.team,
            self.team.slack_api_translator[self.type]["history"],
            post_data,
            channel=self,
            metadata={"slow_queue": slow_queue, "no_log": no_log},
        )
        self.eventrouter.receive(s, slow_queue)
        self.got_history = True
        self.history_needs_update = False

    def get_thread_history(self, thread_ts, slow_queue=False, no_log=False):
        if thread_ts in self.pending_history_requests:
            return

        if config.thread_messages_in_channel:
            self.print_getting_history()
        thread_channel = self.thread_channels.get(thread_ts)
        if thread_channel and thread_channel.active:
            thread_channel.print_getting_history()
        self.pending_history_requests.add(thread_ts)

        post_data = {
            "channel": self.identifier,
            "ts": thread_ts,
            "limit": config.history_fetch_count,
        }
        s = SlackRequest(
            self.team,
            "conversations.replies",
            post_data,
            channel=self,
            metadata={"thread_ts": thread_ts, "no_log": no_log},
        )
        self.eventrouter.receive(s, slow_queue)

    # Typing related
    def set_typing(self, user):
        if self.channel_buffer and self.is_visible():
            self.typing[user.name] = time.time()
            self.buffer_name_needs_update = True

    def is_someone_typing(self):
        """
        Walks through dict of typing folks in a channel and fast
        returns if any of them is actively typing. If none are,
        nulls the dict and returns false.
        """
        typing_expire_time = time.time() - TYPING_DURATION
        for timestamp in self.typing.values():
            if timestamp > typing_expire_time:
                return True
        if self.typing:
            self.typing = {}
        return False

    def get_typing_list(self):
        """
        Returns the names of everyone in the channel who is currently typing.
        """
        typing_expire_time = time.time() - TYPING_DURATION
        typing = []
        for user, timestamp in self.typing.items():
            if timestamp > typing_expire_time:
                typing.append(user)
            else:
                del self.typing[user]
        return typing

    def user_joined(self, user_id):
        # ugly hack - for some reason this gets turned into a list
        self.members = set(self.members)
        self.members.add(user_id)
        self.update_nicklist(user_id)

    def user_left(self, user_id):
        self.members.discard(user_id)
        self.update_nicklist(user_id)

    def update_nicklist(self, user=None):
        if not self.channel_buffer:
            return
        if self.type not in ["channel", "group", "mpim", "private", "shared"]:
            return
        w.buffer_set(self.channel_buffer, "nicklist", "1")
        # create nicklists for the current channel if they don't exist
        # if they do, use the existing pointer
        here = w.nicklist_search_group(self.channel_buffer, "", NICK_GROUP_HERE)
        if not here:
            here = w.nicklist_add_group(
                self.channel_buffer,
                "",
                NICK_GROUP_HERE,
                "weechat.color.nicklist_group",
                1,
            )
        afk = w.nicklist_search_group(self.channel_buffer, "", NICK_GROUP_AWAY)
        if not afk:
            afk = w.nicklist_add_group(
                self.channel_buffer,
                "",
                NICK_GROUP_AWAY,
                "weechat.color.nicklist_group",
                1,
            )

        # Add External nicklist group only for shared channels
        if self.type == "shared":
            external = w.nicklist_search_group(
                self.channel_buffer, "", NICK_GROUP_EXTERNAL
            )
            if not external:
                external = w.nicklist_add_group(
                    self.channel_buffer,
                    "",
                    NICK_GROUP_EXTERNAL,
                    "weechat.color.nicklist_group",
                    2,
                )

        if user and len(self.members) < 1000:
            user = self.team.users.get(user)
            # External users that have left shared channels won't exist
            if not user or user.deleted:
                return
            nick = w.nicklist_search_nick(self.channel_buffer, "", user.name)
            # since this is a change just remove it regardless of where it is
            w.nicklist_remove_nick(self.channel_buffer, nick)
            # now add it back in to whichever..
            nick_group = afk
            if user.is_external:
                nick_group = external
            elif self.team.is_user_present(user.identifier):
                nick_group = here
            if user.identifier in self.members:
                w.nicklist_add_nick(
                    self.channel_buffer,
                    nick_group,
                    user.name,
                    user.color_name,
                    "",
                    "",
                    1,
                )

        # if we didn't get a user, build a complete list. this is expensive.
        else:
            if len(self.members) < 1000:
                try:
                    for user in self.members:
                        user = self.team.users.get(user)
                        if user.deleted:
                            continue
                        nick_group = afk
                        if user.is_external:
                            nick_group = external
                        elif self.team.is_user_present(user.identifier):
                            nick_group = here
                        w.nicklist_add_nick(
                            self.channel_buffer,
                            nick_group,
                            user.name,
                            user.color_name,
                            "",
                            "",
                            1,
                        )
                except:
                    dbg(
                        "DEBUG: {} {} {}".format(
                            self.identifier, self.name, format_exc_only()
                        )
                    )
            else:
                w.nicklist_remove_all(self.channel_buffer)
                for fn in ["1| too", "2| many", "3| users", "4| to", "5| show"]:
                    w.nicklist_add_group(
                        self.channel_buffer, "", fn, w.color("white"), 1
                    )

    def render(self, message, force=False):
        text = message.render(force)
        if isinstance(message, SlackThreadMessage):
            thread_hash = self.hashed_messages[message.thread_ts]
            if config.thread_broadcast_prefix and message.subtype == "thread_broadcast":
                prefix = config.thread_broadcast_prefix
            else:
                prefix = ""

            hash_str = colorize_string(
                get_thread_color(str(thread_hash)),
                "[{}{}]".format(prefix, thread_hash),
            )
            return "{} {}".format(hash_str, text)

        return text


class SlackChannelVisibleMessages(MappingReversible):
    """
    Class with a reversible mapping interface (like a read-only OrderedDict)
    which doesn't include the messages older than first_ts_to_display.
    """

    def __init__(self, channel):
        self.channel = channel
        self.first_ts_to_display = SlackTS(0)

    def __getitem__(self, key):
        if key < self.first_ts_to_display:
            raise KeyError(key)
        return self.channel.messages[key]

    def _is_visible(self, ts):
        if ts < self.first_ts_to_display:
            return False

        message = self.get(ts)
        if (
            isinstance(message, SlackThreadMessage)
            and message.subtype != "thread_broadcast"
            and not config.thread_messages_in_channel
        ):
            return False

        return True

    def __iter__(self):
        for ts in self.channel.messages:
            if self._is_visible(ts):
                yield ts

    def __len__(self):
        i = 0
        for _ in self:
            i += 1
        return i

    def __reversed__(self):
        for ts in reversed(self.channel.messages):
            if self._is_visible(ts):
                yield ts


class SlackChannelHashedMessages(dict):
    def __init__(self, channel):
        self.channel = channel

    def __missing__(self, key):
        if not isinstance(key, SlackTS):
            raise KeyError(key)

        hash_len = 3
        full_hash = sha1_hex(str(key))
        short_hash = full_hash[:hash_len]

        while any(x.startswith(short_hash) for x in self if isinstance(x, str)):
            hash_len += 1
            short_hash = full_hash[:hash_len]

        if short_hash[:-1] in self:
            ts_with_same_hash = self.pop(short_hash[:-1])
            other_full_hash = sha1_hex(str(ts_with_same_hash))
            other_short_hash = other_full_hash[:hash_len]
            while short_hash == other_short_hash:
                hash_len += 1
                short_hash = full_hash[:hash_len]
                other_short_hash = other_full_hash[:hash_len]
            self[other_short_hash] = ts_with_same_hash
            self[ts_with_same_hash] = other_short_hash

            other_message = self.channel.messages.get(ts_with_same_hash)
            if other_message:
                self.channel.change_message(other_message.ts)
                if other_message.thread_channel:
                    other_message.thread_channel.rename()
                for thread_message in other_message.submessages:
                    self.channel.change_message(thread_message)

        self[short_hash] = key
        self[key] = short_hash
        return self[key]


class SlackDMChannel(SlackChannel):
    """
    Subclass of a normal channel for person-to-person communication, which
    has some important differences.
    """

    def __init__(self, eventrouter, users, **kwargs):
        dmuser = kwargs["user"]
        kwargs["name"] = users[dmuser].name if dmuser in users else dmuser
        super(SlackDMChannel, self).__init__(eventrouter, "im", **kwargs)
        self.update_color()
        self.members = {self.user}
        if dmuser in users:
            self.set_topic(create_user_status_string(users[dmuser].profile))

    def set_related_server(self, team):
        super(SlackDMChannel, self).set_related_server(team)
        if self.user not in self.team.users:
            s = SlackRequest(self.team, "users.info", {"user": self.user}, channel=self)
            self.eventrouter.receive(s)

    def create_buffer(self):
        if not self.channel_buffer:
            super(SlackDMChannel, self).create_buffer()
            w.buffer_set(self.channel_buffer, "localvar_set_type", "private")

    def update_color(self):
        if config.colorize_private_chats:
            self.color_name = get_nick_color(self.name)
        else:
            self.color_name = ""

    def open(self, update_remote=True):
        self.create_buffer()
        self.get_history()
        info_method = self.team.slack_api_translator[self.type].get("info")
        if info_method:
            s = SlackRequest(
                self.team, info_method, {"channel": self.identifier}, channel=self
            )
            self.eventrouter.receive(s)
        if update_remote:
            join_method = self.team.slack_api_translator[self.type].get("join")
            if join_method:
                s = SlackRequest(
                    self.team,
                    join_method,
                    {"users": self.user, "return_im": True},
                    channel=self,
                )
                self.eventrouter.receive(s)


class SlackGroupChannel(SlackChannel):
    """
    A group channel is a private discussion group.
    """

    def __init__(self, eventrouter, channel_type="group", **kwargs):
        super(SlackGroupChannel, self).__init__(eventrouter, channel_type, **kwargs)


class SlackPrivateChannel(SlackGroupChannel):
    """
    A private channel is a private discussion group. At the time of writing, it
    differs from group channels in that group channels are channels initially
    created as private, while private channels are public channels which are
    later converted to private.
    """

    def __init__(self, eventrouter, **kwargs):
        super(SlackPrivateChannel, self).__init__(eventrouter, "private", **kwargs)


class SlackMPDMChannel(SlackChannel):
    """
    An MPDM channel is a special instance of a 'group' channel.
    We change the name to look less terrible in WeeChat.
    """

    def __init__(self, eventrouter, team_users, myidentifier, **kwargs):
        if kwargs.get("members"):
            kwargs["name"] = self.name_from_members(
                team_users, kwargs["members"], myidentifier
            )
        super(SlackMPDMChannel, self).__init__(eventrouter, "mpim", **kwargs)

    def name_from_members(self, team_users=None, members=None, myidentifier=None):
        return ",".join(
            sorted(
                getattr((team_users or self.team.users).get(user_id), "name", user_id)
                for user_id in (members or self.members)
                if user_id != (myidentifier or self.team.myidentifier)
            )
        )

    def create_buffer(self):
        if not self.channel_buffer:
            self.get_members()
            super(SlackMPDMChannel, self).create_buffer()

    def open(self, update_remote=True):
        self.create_buffer()
        self.active = True
        self.get_history()
        info_method = self.team.slack_api_translator[self.type].get("info")
        if info_method:
            s = SlackRequest(
                self.team, info_method, {"channel": self.identifier}, channel=self
            )
            self.eventrouter.receive(s)
        if update_remote:
            join_method = self.team.slack_api_translator[self.type].get("join")
            if join_method:
                s = SlackRequest(
                    self.team,
                    join_method,
                    {"users": ",".join(self.members)},
                    channel=self,
                )
                self.eventrouter.receive(s)


class SlackSharedChannel(SlackChannel):
    def __init__(self, eventrouter, **kwargs):
        super(SlackSharedChannel, self).__init__(eventrouter, "shared", **kwargs)


class SlackThreadChannel(SlackChannelCommon):
    """
    A thread channel is a virtual channel. We don't inherit from
    SlackChannel, because most of how it operates will be different.
    """

    def __init__(self, eventrouter, parent_channel, thread_ts):
        super(SlackThreadChannel, self).__init__()
        self.active = False
        self.eventrouter = eventrouter
        self.parent_channel = parent_channel
        self.thread_ts = thread_ts
        self.messages = SlackThreadChannelMessages(self)
        self.channel_buffer = None
        self.type = "thread"
        self.got_history = False
        self.history_needs_update = False
        self.team = self.parent_channel.team
        self.last_line_from = None
        self.new_messages = False
        self.buffer_name_needs_update = False

    @property
    def members(self):
        return self.parent_channel.members

    @property
    def parent_message(self):
        return self.parent_channel.messages[self.thread_ts]

    @property
    def hashed_messages(self):
        return self.parent_channel.hashed_messages

    @property
    def last_read(self):
        return self.parent_message.last_read

    @last_read.setter
    def last_read(self, ts):
        self.parent_message.last_read = ts

    @property
    def identifier(self):
        return self.parent_channel.identifier

    @property
    def visible_messages(self):
        return self.messages

    @property
    def muted(self):
        return self.parent_channel.muted

    @property
    def pending_history_requests(self):
        if self.thread_ts in self.parent_channel.pending_history_requests:
            return {self.identifier, self.thread_ts}
        else:
            return set()

    def formatted_name(self, style="default"):
        name = self.label_full or self.parent_message.hash
        if style == "sidebar":
            name = self.label_short or name
            if self.label_short_drop_prefix:
                return name
            else:
                indent_expr = w.config_string(w.config_get("buflist.format.indent"))
                # Only indent with space if slack_type isn't mentioned in the indent option
                indent = "" if "slack_type" in indent_expr else " "
                return "{}${}".format(indent, name)
        elif style == "long_default":
            if self.label_full_drop_prefix:
                return name
            else:
                channel_name = self.parent_channel.formatted_name(style="long_default")
                return "{}.{}".format(channel_name, name)
        else:
            if self.label_full_drop_prefix:
                return name
            else:
                channel_name = self.parent_channel.formatted_name()
                return "{}.{}".format(channel_name, name)

    def mark_read(self, ts=None, update_remote=True, force=False, post_data={}):
        if not self.parent_message.subscribed:
            return
        args = {"thread_ts": self.thread_ts}
        args.update(post_data)
        super(SlackThreadChannel, self).mark_read(
            ts=ts, update_remote=update_remote, force=force, post_data=args
        )

    def buffer_prnt(
        self,
        nick,
        text,
        timestamp,
        tagset,
        tag_nick=None,
        history_message=False,
        no_log=False,
        extra_tags=None,
    ):
        data = "{}\t{}".format(format_nick(nick, self.last_line_from), text)
        self.last_line_from = nick
        ts = SlackTS(timestamp)
        if self.channel_buffer:
            # backlog messages - we will update the read marker as we print these
            backlog = ts <= self.last_read
            if not backlog:
                self.new_messages = True

            no_log = no_log or history_message and backlog
            self_msg = tag_nick == self.team.nick
            tags = tag(
                ts,
                tagset,
                user=tag_nick,
                self_msg=self_msg,
                backlog=backlog,
                no_log=no_log,
                extra_tags=extra_tags,
            )

            if no_log:
                w.buffer_set(self.channel_buffer, "print_hooks_enabled", "0")
            w.prnt_date_tags(self.channel_buffer, ts.major, tags, data)
            if no_log:
                w.buffer_set(self.channel_buffer, "print_hooks_enabled", "1")
            if backlog or self_msg:
                self.mark_read(ts, update_remote=False, force=True)

    def get_history(self, slow_queue=False, full=False, no_log=False):
        self.got_history = True
        self.history_needs_update = False

        any_msg_is_none = any(message is None for message in self.messages.values())
        if not any_msg_is_none:
            self.reprint_messages(history_message=True, no_log=no_log)

        if (
            full
            or any_msg_is_none
            or len(self.parent_message.submessages)
            < self.parent_message.number_of_replies()
        ):
            self.parent_channel.get_thread_history(self.thread_ts, slow_queue, no_log)

    def send_message(self, message, subtype=None, request_dict_ext={}):
        if subtype == "me_message":
            w.prnt("", "ERROR: /me is not supported in threads")
            return w.WEECHAT_RC_ERROR

        request = {"thread_ts": str(self.thread_ts)}
        request.update(request_dict_ext)
        super(SlackThreadChannel, self).send_message(message, subtype, request)

    def open(self, update_remote=True):
        self.create_buffer()
        self.active = True
        self.get_history()

    def refresh(self):
        if self.buffer_name_needs_update:
            self.buffer_name_needs_update = False
            self.rename()

    def rename(self):
        if self.channel_buffer:
            self.buffer_rename_in_progress = True
            w.buffer_set(
                self.channel_buffer, "name", self.formatted_name(style="long_default")
            )
            w.buffer_set(
                self.channel_buffer, "short_name", self.formatted_name(style="sidebar")
            )
            self.buffer_rename_in_progress = False

    def set_highlights(self, highlight_string=None):
        if self.channel_buffer:
            if highlight_string is None:
                highlight_string = ",".join(self.parent_channel.highlights())
            w.buffer_set(self.channel_buffer, "highlight_words", highlight_string)

    def create_buffer(self):
        """
        Creates the WeeChat buffer where the thread magic happens.
        """
        if not self.channel_buffer:
            self.channel_buffer = w.buffer_new(
                self.formatted_name(style="long_default"),
                "buffer_input_callback",
                "EVENTROUTER",
                "",
                "",
            )
            self.eventrouter.weechat_controller.register_buffer(
                self.channel_buffer, self
            )
            w.buffer_set(self.channel_buffer, "input_multiline", "1")
            w.buffer_set(
                self.channel_buffer,
                "localvar_set_type",
                get_localvar_type(self.parent_channel.type),
            )
            w.buffer_set(self.channel_buffer, "localvar_set_slack_type", self.type)
            w.buffer_set(self.channel_buffer, "localvar_set_nick", self.team.nick)
            w.buffer_set(
                self.channel_buffer, "localvar_set_channel", self.formatted_name()
            )
            w.buffer_set(self.channel_buffer, "localvar_set_server", self.team.name)
            w.buffer_set(
                self.channel_buffer,
                "localvar_set_completion_default_template",
                "${weechat.completion.default_template}|%(usergroups)|%(emoji)",
            )
            self.buffer_rename_in_progress = True
            w.buffer_set(
                self.channel_buffer, "short_name", self.formatted_name(style="sidebar")
            )
            self.buffer_rename_in_progress = False
            self.set_highlights()
            time_format = w.string_eval_expression(
                w.config_string(w.config_get("weechat.look.buffer_time_format")),
                {},
                {},
                {},
            )
            parent_time = time.localtime(SlackTS(self.thread_ts).major)
            topic = "{} {} | {}".format(
                time.strftime(time_format, parent_time),
                self.parent_message.sender,
                self.render(self.parent_message),
            )
            w.buffer_set(self.channel_buffer, "title", topic)

    def destroy_buffer(self, update_remote):
        super(SlackThreadChannel, self).destroy_buffer(update_remote)
        if update_remote and not self.eventrouter.shutting_down:
            self.mark_read()

    def render(self, message, force=False):
        return message.render(force)


class SlackThreadChannelMessages(MappingReversible):
    """
    Class with a reversible mapping interface (like a read-only OrderedDict)
    which looks up messages using the parent channel and parent message.
    """

    def __init__(self, thread_channel):
        self.thread_channel = thread_channel

    @property
    def _parent_message(self):
        return self.thread_channel.parent_message

    def __getitem__(self, key):
        if (
            key != self._parent_message.ts
            and key not in self._parent_message.submessages
        ):
            raise KeyError(key)
        return self.thread_channel.parent_channel.messages[key]

    def __iter__(self):
        yield self._parent_message.ts
        for ts in self._parent_message.submessages:
            yield ts

    def __len__(self):
        return 1 + len(self._parent_message.submessages)

    def __reversed__(self):
        for ts in reversed(self._parent_message.submessages):
            yield ts
        yield self._parent_message.ts


class SlackUser(object):
    """
    Represends an individual slack user. Also where you set their name formatting.
    """

    def __init__(self, originating_team_id, **kwargs):
        self.identifier = kwargs["id"]
        # These attributes may be missing in the response, so we have to make
        # sure they're set
        self.profile = {}
        self.presence = kwargs.get("presence", "unknown")
        self.deleted = kwargs.get("deleted", False)
        self.is_external = (
            not kwargs.get("is_bot") and kwargs.get("team_id") != originating_team_id
        )
        for key, value in kwargs.items():
            setattr(self, key, value)

        self.name = nick_from_profile(self.profile, kwargs["name"])
        self.username = kwargs["name"]
        self.update_color()

    def __repr__(self):
        return "Name:{} Identifier:{}".format(self.name, self.identifier)

    def force_color(self, color_name):
        self.color_name = color_name

    def update_color(self):
        # This will automatically be none/"" if the user has disabled nick
        # colourization.
        self.color_name = get_nick_color(self.name)

    def update_status(self, status_emoji, status_text):
        self.profile["status_emoji"] = status_emoji
        self.profile["status_text"] = status_text

    def formatted_name(self, prepend="", enable_color=True):
        name = prepend + self.name
        if enable_color:
            return colorize_string(self.color_name, name)
        else:
            return name


class SlackBot(SlackUser):
    """
    Basically the same as a user, but split out to identify and for future
    needs
    """

    def __init__(self, originating_team_id, **kwargs):
        super(SlackBot, self).__init__(originating_team_id, **kwargs)


class SlackMessage(object):
    """
    Represents a single slack message and associated context/metadata.
    These are modifiable and can be rerendered to change a message,
    delete a message, add a reaction, add a thread.
    Note: these can't be tied to a SlackUser object because users
    can be deleted, so we have to store sender in each one.
    """

    def __init__(self, subtype, message_json, channel):
        self.team = channel.team
        self.channel = channel
        self.subtype = subtype
        self.user_identifier = message_json.get("user")
        self.message_json = message_json
        self.submessages = []
        self.ts = SlackTS(message_json["ts"])
        self.subscribed = message_json.get("subscribed", False)
        self.last_read = SlackTS(message_json.get("last_read", 0))
        self.last_notify = SlackTS(0)

    def __hash__(self):
        return hash(self.ts)

    @property
    def hash(self):
        return self.channel.hashed_messages[self.ts]

    @property
    def thread_channel(self):
        return self.channel.thread_channels.get(self.ts)

    def open_thread(self, switch=False):
        if not self.thread_channel or not self.thread_channel.active:
            self.channel.thread_channels[self.ts] = SlackThreadChannel(
                EVENTROUTER, self.channel, self.ts
            )
            self.thread_channel.open()
        if switch:
            w.buffer_set(self.thread_channel.channel_buffer, "display", "1")

    def render(self, force=False):
        # If we already have a rendered version in the object, just return that.
        if not force and self.message_json.get("_rendered_text"):
            return self.message_json["_rendered_text"]

        if self.message_json.get("deleted"):
            text = colorize_string(config.color_deleted, "(deleted)")
            self.message_json["_rendered_text"] = text
            return text

        blocks = self.message_json.get("blocks", [])
        blocks_rendered = "\n".join(unfurl_blocks(blocks))
        if blocks_rendered:
            text = blocks_rendered
        else:
            text = unhtmlescape(unfurl_refs(self.message_json.get("text", "")))

        if self.message_json.get("mrkdwn", True):
            text = render_formatting(text)

        if self.message_json.get("subtype") in (
            "channel_join",
            "group_join",
        ) and self.message_json.get("inviter"):
            inviter_id = self.message_json.get("inviter")
            text += unfurl_refs(" by invitation from <@{}>".format(inviter_id))

        if self.subtype == "me_message" and not self.message_json["text"].startswith(
            self.sender
        ):
            text = "{} {}".format(self.sender, text)

        if "edited" in self.message_json:
            text += " " + colorize_string(config.color_edited_suffix, "(edited)")

        text += unwrap_attachments(self, text)
        text += unhtmlescape(unfurl_refs(unwrap_files(self, self.message_json, text)))
        text += unwrap_huddle(self, self.message_json, text)
        text = text.lstrip().replace("\t", "    ")

        text += create_reactions_string(
            self.message_json.get("reactions", ""), self.team.myidentifier
        )

        if self.number_of_replies():
            text += " " + colorize_string(
                get_thread_color(self.hash),
                "[ Thread: {} Replies: {}{} ]".format(
                    self.hash,
                    self.number_of_replies(),
                    " Subscribed" if self.subscribed else "",
                ),
            )

        # replace_string_with_emoji() was called on blocks earlier via
        # unfurl_blocks(), so exclude them here
        text_to_replace = text[len(blocks_rendered) :]
        text = text[: len(blocks_rendered)] + replace_string_with_emoji(text_to_replace)

        self.message_json["_rendered_text"] = text
        return text

    def get_sender(self, plain):
        user = self.team.users.get(self.user_identifier)
        if user:
            name = "{}".format(user.formatted_name(enable_color=not plain))
            if user.is_external:
                name += config.external_user_suffix
            return name
        elif "user_profile" in self.message_json:
            nick = nick_from_profile(
                self.message_json["user_profile"], self.user_identifier
            )
            color_name = get_nick_color(nick)
            name = nick if plain else colorize_string(color_name, nick)
            if self.message_json.get("user_team") != self.message_json.get("team"):
                name += config.external_user_suffix
            return name
        elif "username" in self.message_json:
            username = self.message_json["username"]
            if plain:
                return username
            elif self.message_json.get("subtype") == "bot_message":
                return "{} :]".format(username)
            else:
                return "-{}-".format(username)
        elif "service_name" in self.message_json:
            service_name = self.message_json["service_name"]
            if plain:
                return service_name
            else:
                return "-{}-".format(service_name)
        elif self.message_json.get("bot_id") in self.team.bots:
            bot = self.team.bots[self.message_json["bot_id"]]
            name = bot.formatted_name(enable_color=not plain)
            if plain:
                return name
            else:
                return "{} :]".format(name)
        return self.user_identifier or self.message_json.get("bot_id") or ""

    @property
    def sender(self):
        return self.get_sender(False)

    @property
    def sender_plain(self):
        return self.get_sender(True)

    def get_reaction(self, reaction_name):
        for reaction in self.message_json.get("reactions", []):
            if reaction["name"] == reaction_name:
                return reaction
        return None

    def add_reaction(self, reaction_name, user):
        reaction = self.get_reaction(reaction_name)
        if reaction:
            reaction["count"] += 1
            if user not in reaction["users"]:
                reaction["users"].append(user)
        else:
            if "reactions" not in self.message_json:
                self.message_json["reactions"] = []
            self.message_json["reactions"].append(
                {"name": reaction_name, "count": 1, "users": [user]}
            )

    def remove_reaction(self, reaction_name, user):
        reaction = self.get_reaction(reaction_name)
        reaction["count"] -= 1
        if user in reaction["users"]:
            reaction["users"].remove(user)

    def has_mention(self):
        return w.string_has_highlight(
            unfurl_refs(self.message_json.get("text")),
            ",".join(self.channel.highlights()),
        )

    def number_of_replies(self):
        return max(len(self.submessages), self.message_json.get("reply_count", 0))

    def notify_thread(self, message=None):
        if message is None:
            if not self.submessages:
                return
            message = self.channel.messages.get(self.submessages[-1])

        if (
            self.thread_channel
            and self.thread_channel.active
            or message.ts <= self.last_read
            or message.ts <= self.last_notify
        ):
            return

        if message.has_mention():
            template = "You were mentioned in thread {hash}, channel {channel}"
        elif self.subscribed:
            template = "New message in thread {hash}, channel {channel} to which you are subscribed"
        else:
            return

        self.last_notify = max(message.ts, SlackTS())

        if config.auto_open_threads and self.subscribed:
            self.open_thread()

        if message.user_identifier != self.team.myidentifier and (
            config.notify_subscribed_threads is True
            or config.notify_subscribed_threads == "auto"
            and not config.auto_open_threads
            and not config.thread_messages_in_channel
        ):
            message = template.format(
                hash=self.hash, channel=self.channel.formatted_name()
            )
            self.team.buffer_prnt(message, message=True)


class SlackThreadMessage(SlackMessage):
    def __init__(self, parent_channel, thread_ts, message_json, *args):
        subtype = message_json.get(
            "subtype",
            "thread_broadcast"
            if message_json.get("reply_broadcast")
            else "thread_message",
        )
        super(SlackThreadMessage, self).__init__(subtype, message_json, *args)
        self.parent_channel = parent_channel
        self.thread_ts = thread_ts

    @property
    def parent_message(self):
        return self.parent_channel.messages.get(self.thread_ts)

    def open_thread(self, switch=False):
        self.parent_message.open_thread(switch)


class Hdata(object):
    def __init__(self, w):
        self.buffer = w.hdata_get("buffer")
        self.line = w.hdata_get("line")
        self.line_data = w.hdata_get("line_data")
        self.lines = w.hdata_get("lines")


class SlackTS(object):
    def __init__(self, ts=None):
        if isinstance(ts, int):
            self.major = ts
            self.minor = 0
        elif ts is not None:
            self.major, self.minor = [int(x) for x in ts.split(".", 1)]
        else:
            self.major = int(time.time())
            self.minor = 0

    def __cmp__(self, other):
        if isinstance(other, SlackTS):
            if self.major < other.major:
                return -1
            elif self.major > other.major:
                return 1
            elif self.major == other.major:
                if self.minor < other.minor:
                    return -1
                elif self.minor > other.minor:
                    return 1
                else:
                    return 0
        elif isinstance(other, str):
            s = self.__str__()
            if s < other:
                return -1
            elif s > other:
                return 1
            elif s == other:
                return 0

    def __lt__(self, other):
        return self.__cmp__(other) < 0

    def __le__(self, other):
        return self.__cmp__(other) <= 0

    def __eq__(self, other):
        return self.__cmp__(other) == 0

    def __ne__(self, other):
        return self.__cmp__(other) != 0

    def __ge__(self, other):
        return self.__cmp__(other) >= 0

    def __gt__(self, other):
        return self.__cmp__(other) > 0

    def __hash__(self):
        return hash("{}.{}".format(self.major, self.minor))

    def __repr__(self):
        return str("{0}.{1:06d}".format(self.major, self.minor))

    def split(self, *args, **kwargs):
        return [self.major, self.minor]

    def majorstr(self):
        return str(self.major)

    def minorstr(self):
        return str(self.minor)


###### New handlers


def handle_rtmstart(login_data, eventrouter, team, channel, metadata):
    """
    This handles the main entry call to slack, rtm.start
    """
    metadata = login_data["wee_slack_request_metadata"]

    if not login_data["ok"]:
        w.prnt(
            "",
            "ERROR: Failed connecting to Slack with token {}: {}".format(
                token_for_print(metadata.token), login_data["error"]
            ),
        )
        if not re.match(r"^xo\w\w(-\d+){3}-[0-9a-f]+$", metadata.token):
            w.prnt(
                "",
                "ERROR: Token does not look like a valid Slack token. "
                "Ensure it is a valid token and not just a OAuth code.",
            )

        return

    self_profile = next(
        user["profile"]
        for user in login_data["users"]
        if user["id"] == login_data["self"]["id"]
    )
    self_nick = nick_from_profile(self_profile, login_data["self"]["name"])

    # Let's reuse a team if we have it already.
    th = SlackTeam.generate_team_hash(
        login_data["team"]["id"], login_data["team"]["domain"]
    )
    if not eventrouter.teams.get(th):
        users = {}
        for item in login_data["users"]:
            users[item["id"]] = SlackUser(login_data["team"]["id"], **item)

        bots = {}
        for item in login_data["bots"]:
            bots[item["id"]] = SlackBot(login_data["team"]["id"], **item)

        subteams = {}
        for item in login_data["subteams"]["all"]:
            is_member = item["id"] in login_data["subteams"]["self"]
            subteams[item["id"]] = SlackSubteam(
                login_data["team"]["id"], is_member=is_member, **item
            )

        channels = {}
        for item in login_data["channels"]:
            if item["is_shared"]:
                channels[item["id"]] = SlackSharedChannel(eventrouter, **item)
            elif item["is_mpim"]:
                channels[item["id"]] = SlackMPDMChannel(
                    eventrouter, users, login_data["self"]["id"], **item
                )
            elif item["is_private"]:
                channels[item["id"]] = SlackPrivateChannel(eventrouter, **item)
            else:
                channels[item["id"]] = SlackChannel(eventrouter, **item)

        for item in login_data["ims"]:
            channels[item["id"]] = SlackDMChannel(eventrouter, users, **item)

        for item in login_data["mpims"]:
            channels[item["id"]] = SlackMPDMChannel(
                eventrouter, users, login_data["self"]["id"], **item
            )

        for item in login_data["groups"]:
            if not item["is_mpim"]:
                channels[item["id"]] = SlackGroupChannel(eventrouter, **item)

        t = SlackTeam(
            eventrouter,
            metadata.token,
            th,
            login_data["url"],
            login_data["team"],
            subteams,
            self_nick,
            login_data["self"]["id"],
            login_data["self"]["manual_presence"],
            users,
            bots,
            channels,
            muted_channels=login_data["self"]["prefs"]["muted_channels"],
            highlight_words=login_data["self"]["prefs"]["highlight_words"],
        )
        eventrouter.register_team(t)

    else:
        t = eventrouter.teams.get(th)
        if t.myidentifier != login_data["self"]["id"]:
            print_error(
                "The Slack team {} has tokens for two different users, this is not supported. The "
                "token {} is for user {}, and the token {} is for user {}. Please remove one of "
                "them.".format(
                    t.team_info["name"],
                    token_for_print(t.token),
                    t.nick,
                    token_for_print(metadata.token),
                    self_nick,
                )
            )
            return
        elif not metadata.metadata.get("reconnect"):
            print_error(
                "Ignoring duplicate Slack tokens for the same team ({}) and user ({}). The two "
                "tokens are {} and {}.".format(
                    t.team_info["name"],
                    t.nick,
                    token_for_print(t.token),
                    token_for_print(metadata.token),
                ),
                warning=True,
            )
            return
        else:
            t.set_reconnect_url(login_data["url"])
            t.connecting_rtm = False

    t.connect()


def handle_rtmconnect(login_data, eventrouter, team, channel, metadata):
    metadata = login_data["wee_slack_request_metadata"]
    team = metadata.team
    team.connecting_rtm = False

    if not login_data["ok"]:
        w.prnt(
            "",
            "ERROR: Failed reconnecting to Slack with token {}: {}".format(
                token_for_print(metadata.token), login_data["error"]
            ),
        )
        return

    team.set_reconnect_url(login_data["url"])
    team.connect()


def handle_emojilist(emoji_json, eventrouter, team, channel, metadata):
    if emoji_json["ok"]:
        team.emoji_completions.extend(emoji_json["emoji"].keys())


def handle_conversationsinfo(channel_json, eventrouter, team, channel, metadata):
    channel_info = channel_json["channel"]
    if "unread_count_display" in channel_info:
        unread_count = channel_info["unread_count_display"]
        if unread_count and channel.channel_buffer is None:
            channel.create_buffer()
        channel.set_unread_count_display(unread_count)
    if channel_info.get("is_open") and channel.channel_buffer is None:
        channel.create_buffer()
    if "last_read" in channel_info:
        channel.last_read = SlackTS(channel_info["last_read"])
    if "members" in channel_info:
        channel.set_members(channel_info["members"])

    # MPIMs don't have unread_count_display so we have to request the history to check if there are unread messages
    if channel.type == "mpim" and not channel.got_history:
        s = SlackRequest(
            team,
            "conversations.history",
            {"channel": channel.identifier, "limit": 1},
            channel=channel,
            metadata={"only_set_unread": True},
        )
        eventrouter.receive(s)


def handle_conversationsopen(
    conversation_json, eventrouter, team, channel, metadata, object_name="channel"
):
    channel_info = conversation_json[object_name]
    if not channel:
        channel = create_channel_from_info(
            eventrouter, channel_info, team, team.myidentifier, team.users
        )
        team.channels[channel_info["id"]] = channel

    if channel.channel_buffer is None:
        channel.create_buffer()

    unread_count_display = channel_info.get("unread_count_display")
    if unread_count_display is not None:
        channel.set_unread_count_display(unread_count_display)

    if metadata.get("switch") and config.switch_buffer_on_join:
        w.buffer_set(channel.channel_buffer, "display", "1")


def handle_mpimopen(
    mpim_json, eventrouter, team, channel, metadata, object_name="group"
):
    handle_conversationsopen(
        mpim_json, eventrouter, team, channel, metadata, object_name
    )


def handle_history(
    message_json, eventrouter, team, channel, metadata, includes_threads=True
):
    if metadata.get("only_set_unread"):
        if message_json["messages"]:
            latest = message_json["messages"][0]
            latest_ts = SlackTS(latest["ts"])
            if latest_ts > channel.last_read:
                if not channel.channel_buffer:
                    channel.create_buffer()
                channel.set_unread_count_display(1)
        return

    channel.got_history = True
    channel.history_needs_update = False
    for message in reversed(message_json["messages"]):
        message = process_message(
            message, eventrouter, team, channel, metadata, history_message=True
        )
        if (
            not includes_threads
            and message
            and message.number_of_replies()
            and (
                config.thread_messages_in_channel
                or message.subscribed
                and SlackTS(message.message_json.get("latest_reply", 0))
                > message.last_read
            )
        ):
            channel.get_thread_history(
                message.ts, metadata["slow_queue"], metadata["no_log"]
            )

    channel.pending_history_requests.discard(channel.identifier)
    if (
        channel.visible_messages.first_ts_to_display.major == 0
        and message_json["messages"]
    ):
        channel.visible_messages.first_ts_to_display = SlackTS(
            message_json["messages"][-1]["ts"]
        )
    channel.reprint_messages(history_message=True, no_log=metadata["no_log"])
    for thread_channel in channel.thread_channels.values():
        thread_channel.reprint_messages(history_message=True, no_log=metadata["no_log"])


handle_channelshistory = handle_history
handle_groupshistory = handle_history
handle_imhistory = handle_history
handle_mpimhistory = handle_history


def handle_conversationshistory(
    message_json, eventrouter, team, channel, metadata, includes_threads=True
):
    handle_history(message_json, eventrouter, team, channel, metadata, False)


def handle_conversationsreplies(message_json, eventrouter, team, channel, metadata):
    for message in message_json["messages"]:
        process_message(
            message, eventrouter, team, channel, metadata, history_message=True
        )
    channel.pending_history_requests.discard(metadata.get("thread_ts"))
    thread_channel = channel.thread_channels.get(metadata.get("thread_ts"))
    if thread_channel and thread_channel.active:
        thread_channel.got_history = True
        thread_channel.history_needs_update = False
        thread_channel.reprint_messages(history_message=True, no_log=metadata["no_log"])
    if config.thread_messages_in_channel:
        channel.reprint_messages(history_message=True, no_log=metadata["no_log"])


def handle_conversationsmembers(members_json, eventrouter, team, channel, metadata):
    if members_json["ok"]:
        channel.got_members = True
        channel.set_members(members_json["members"])
        unknown_users = set(members_json["members"]) - set(team.users.keys())
        for user in unknown_users:
            s = SlackRequest(team, "users.info", {"user": user}, channel=channel)
            eventrouter.receive(s)
        if channel.type == "mpim":
            name = channel.name_from_members()
            channel.set_name(name)
    else:
        w.prnt(
            team.channel_buffer,
            "{}Couldn't load members for channel {}. Error: {}".format(
                w.prefix("error"), channel.name, members_json["error"]
            ),
        )


def handle_usersinfo(user_json, eventrouter, team, channel, metadata):
    user_info = user_json["user"]
    if not metadata.get("user"):
        user = SlackUser(team.identifier, **user_info)
        team.users[user_info["id"]] = user

    if channel.type == "shared":
        channel.update_nicklist(user_info["id"])
    elif channel.type == "im":
        channel.set_name(user.name)
        channel.set_topic(create_user_status_string(user.profile))


def handle_usergroupsuserslist(users_json, eventrouter, team, channel, metadata):
    header = "Users in {}".format(metadata["usergroup_handle"])
    users = [team.users[key] for key in users_json["users"]]
    return print_users_info(team, header, users)


def handle_usersprofileset(json, eventrouter, team, channel, metadata):
    if not json["ok"]:
        w.prnt("", "ERROR: Failed to set profile: {}".format(json["error"]))


def handle_conversationscreate(json, eventrouter, team, channel, metadata):
    metadata = json["wee_slack_request_metadata"]
    if not json["ok"]:
        name = metadata.post_data["name"]
        print_error("Couldn't create channel {}: {}".format(name, json["error"]))


def handle_conversationsinvite(json, eventrouter, team, channel, metadata):
    nicks = ", ".join(metadata["nicks"])
    if json["ok"]:
        w.prnt(team.channel_buffer, "Invited {} to {}".format(nicks, channel.name))
    else:
        w.prnt(
            team.channel_buffer,
            "ERROR: Couldn't invite {} to {}. Error: {}".format(
                nicks, channel.name, json["error"]
            ),
        )


def handle_chatcommand(json, eventrouter, team, channel, metadata):
    command = "{} {}".format(metadata["command"], metadata["command_args"]).rstrip()
    response = unfurl_refs(json["response"]) if "response" in json else ""
    if json["ok"]:
        response_text = "Response: {}".format(response) if response else "No response"
        w.prnt(
            team.channel_buffer, 'Ran command "{}". {}'.format(command, response_text)
        )
    else:
        response_text = ". Response: {}".format(response) if response else ""
        w.prnt(
            team.channel_buffer,
            'ERROR: Couldn\'t run command "{}". Error: {}{}'.format(
                command, json["error"], response_text
            ),
        )


def handle_chatdelete(json, eventrouter, team, channel, metadata):
    if not json["ok"]:
        print_error("Couldn't delete message: {}".format(json["error"]))


def handle_chatupdate(json, eventrouter, team, channel, metadata):
    if not json["ok"]:
        print_error("Couldn't change message: {}".format(json["error"]))


def handle_reactionsadd(json, eventrouter, team, channel, metadata):
    if not json["ok"]:
        print_error(
            "Couldn't add reaction {}: {}".format(metadata["reaction"], json["error"])
        )


def handle_reactionsremove(json, eventrouter, team, channel, metadata):
    if not json["ok"]:
        print_error(
            "Couldn't remove reaction {}: {}".format(
                metadata["reaction"], json["error"]
            )
        )


def handle_subscriptionsthreadmark(json, eventrouter, team, channel, metadata):
    if not json["ok"]:
        if json["error"] == "not_allowed_token_type":
            team.slack_api_translator["thread"]["mark"] = None
        else:
            print_error("Couldn't set thread read status: {}".format(json["error"]))


def handle_subscriptionsthreadadd(json, eventrouter, team, channel, metadata):
    if not json["ok"]:
        if json["error"] == "not_allowed_token_type":
            print_error(
                "Can only subscribe to a thread when using a session token, see the readme: https://github.com/wee-slack/wee-slack#4-add-your-slack-api-tokens"
            )
        else:
            print_error("Couldn't add thread subscription: {}".format(json["error"]))


def handle_subscriptionsthreadremove(json, eventrouter, team, channel, metadata):
    if not json["ok"]:
        if json["error"] == "not_allowed_token_type":
            print_error(
                "Can only unsubscribe from a thread when using a session token, see the readme: https://github.com/wee-slack/wee-slack#4-add-your-slack-api-tokens"
            )
        else:
            print_error("Couldn't remove thread subscription: {}".format(json["error"]))


###### New/converted process_ and subprocess_ methods
def process_hello(message_json, eventrouter, team, channel, metadata):
    team.subscribe_users_presence()


def process_reconnect_url(message_json, eventrouter, team, channel, metadata):
    team.set_reconnect_url(message_json["url"])


def process_presence_change(message_json, eventrouter, team, channel, metadata):
    users = [team.users[user_id] for user_id in message_json.get("users", [])]
    if "user" in metadata:
        users.append(metadata["user"])
    for user in users:
        team.update_member_presence(user, message_json["presence"])
    if team.myidentifier in users:
        w.bar_item_update("away")
        w.bar_item_update("slack_away")


def process_manual_presence_change(message_json, eventrouter, team, channel, metadata):
    team.my_manual_presence = message_json["presence"]
    w.bar_item_update("away")
    w.bar_item_update("slack_away")


def process_pref_change(message_json, eventrouter, team, channel, metadata):
    if message_json["name"] == "muted_channels":
        team.set_muted_channels(message_json["value"])
    elif message_json["name"] == "highlight_words":
        team.set_highlight_words(message_json["value"])
    else:
        dbg("Preference change not implemented: {}\n".format(message_json["name"]))


def process_user_change(message_json, eventrouter, team, channel, metadata):
    """
    Currently only used to update status, but lots here we could do.
    """
    user = metadata["user"]
    profile = message_json["user"]["profile"]
    if user:
        user.update_status(profile.get("status_emoji"), profile.get("status_text"))
        dmchannel = team.find_channel_by_members({user.identifier}, channel_type="im")
        if dmchannel:
            dmchannel.set_topic(create_user_status_string(profile))


def process_user_typing(message_json, eventrouter, team, channel, metadata):
    if channel and metadata["user"]:
        channel.set_typing(metadata["user"])
        w.bar_item_update("slack_typing_notice")


def process_team_join(message_json, eventrouter, team, channel, metadata):
    user = message_json["user"]
    team.users[user["id"]] = SlackUser(team.identifier, **user)


def process_pong(message_json, eventrouter, team, channel, metadata):
    team.last_pong_time = time.time()


def process_message(
    message_json, eventrouter, team, channel, metadata, history_message=False
):
    if channel is None:
        return

    subtype = message_json.get("subtype")
    if (
        not history_message
        and not subtype
        and "ts" in message_json
        and SlackTS(message_json["ts"]) in channel.messages
    ):
        return

    subtype_functions = get_functions_with_prefix("subprocess_")

    if "thread_ts" in message_json and "reply_count" not in message_json:
        message = subprocess_thread_message(
            message_json, eventrouter, team, channel, history_message
        )
    elif subtype in subtype_functions:
        message = subtype_functions[subtype](
            message_json, eventrouter, team, channel, history_message
        )
    else:
        message = SlackMessage(subtype or "normal", message_json, channel)
        channel.store_message(message)
        channel.unread_count_display += 1

    if message and not history_message:
        channel.prnt_message(message, history_message)

    if not history_message:
        download_files(message_json, channel)

    return message


def download_files(message_json, channel):
    download_location = config.files_download_location
    if not download_location:
        return
    options = {
        "directory": "data",
    }
    download_location = w.string_eval_path_home(download_location, {}, {}, options)

    if not os.path.exists(download_location):
        try:
            os.makedirs(download_location)
        except:
            w.prnt(
                "",
                "ERROR: Failed to create directory at files_download_location: {}".format(
                    format_exc_only()
                ),
            )

    def fileout_iter(path):
        yield path
        main, ext = os.path.splitext(path)
        for i in count(start=1):
            yield main + "-{}".format(i) + ext

    for f in message_json.get("files", []):
        if f.get("mode") == "tombstone":
            continue

        filetype = "" if f["title"].endswith(f["filetype"]) else "." + f["filetype"]
        filename = "{}.{}_{}{}".format(
            channel.team.name, channel.name, f["title"], filetype
        )
        for fileout in fileout_iter(os.path.join(download_location, filename)):
            if os.path.isfile(fileout):
                continue
            curl_options = SlackRequest(channel.team, "").options()
            curl_options["file_out"] = fileout
            w.hook_process_hashtable(
                "url:" + f["url_private"],
                curl_options,
                config.slack_timeout,
                "",
                "",
            )
            break


def subprocess_thread_message(
    message_json, eventrouter, team, channel, history_message
):
    parent_ts = SlackTS(message_json["thread_ts"])
    message = SlackThreadMessage(channel, parent_ts, message_json, channel)

    parent_message = message.parent_message
    if parent_message and message.ts not in parent_message.submessages:
        parent_message.submessages.append(message.ts)
        parent_message.submessages.sort()

    channel.store_message(message)

    if parent_message:
        channel.change_message(parent_ts)
        if parent_message.thread_channel and parent_message.thread_channel.active:
            if not history_message:
                parent_message.thread_channel.prnt_message(message, history_message)
        else:
            parent_message.notify_thread(message)
    else:
        channel.get_thread_history(parent_ts)

    return message


subprocess_thread_broadcast = subprocess_thread_message


def subprocess_channel_join(message_json, eventrouter, team, channel, history_message):
    message = SlackMessage("join", message_json, channel)
    channel.store_message(message)
    channel.user_joined(message_json["user"])
    return message


def subprocess_channel_leave(message_json, eventrouter, team, channel, history_message):
    message = SlackMessage("leave", message_json, channel)
    channel.store_message(message)
    channel.user_left(message_json["user"])
    return message


def subprocess_channel_topic(message_json, eventrouter, team, channel, history_message):
    message = SlackMessage("topic", message_json, channel)
    channel.store_message(message)
    channel.set_topic(message_json["topic"])
    return message


subprocess_group_join = subprocess_channel_join
subprocess_group_leave = subprocess_channel_leave
subprocess_group_topic = subprocess_channel_topic


def subprocess_message_replied(
    message_json, eventrouter, team, channel, history_message
):
    pass


def subprocess_message_changed(
    message_json, eventrouter, team, channel, history_message
):
    new_message = message_json.get("message")
    channel.change_message(new_message["ts"], message_json=new_message)


def subprocess_message_deleted(
    message_json, eventrouter, team, channel, history_message
):
    channel.change_message(message_json["deleted_ts"], {"deleted": True})


def process_reply(message_json, eventrouter, team, channel, metadata):
    reply_to = int(message_json["reply_to"])
    original_message_json = team.ws_replies.pop(reply_to, None)
    if original_message_json:
        dbg("REPLY {}".format(message_json))
        channel = team.channels[original_message_json.get("channel")]
        if message_json["ok"]:
            original_message_json.update(message_json)
            process_message(
                original_message_json,
                eventrouter,
                team=team,
                channel=channel,
                metadata={},
            )
        else:
            print_error(
                "Couldn't send message to channel {}: {}".format(
                    channel.name, message_json["error"]
                )
            )
    else:
        dbg("Unexpected reply {}".format(message_json))


def process_channel_marked(message_json, eventrouter, team, channel, metadata):
    ts = message_json.get("ts")
    if ts and channel is not None:
        channel.mark_read(ts=ts, force=True, update_remote=False)
    else:
        dbg("tried to mark something weird {}".format(message_json))


process_group_marked = process_channel_marked
process_im_marked = process_channel_marked
process_mpim_marked = process_channel_marked


def process_thread_marked(message_json, eventrouter, team, channel, metadata):
    subscription = message_json.get("subscription", {})
    ts = subscription.get("last_read")
    thread_ts = subscription.get("thread_ts")
    channel = team.channels.get(subscription.get("channel"))
    if ts and thread_ts and channel:
        thread_channel = channel.thread_channels.get(SlackTS(thread_ts))
        if thread_channel:
            thread_channel.mark_read(ts=ts, force=True, update_remote=False)
    else:
        dbg("tried to mark something weird {}".format(message_json))


def process_channel_joined(message_json, eventrouter, team, channel, metadata):
    if channel is None:
        channel = create_channel_from_info(
            eventrouter, message_json["channel"], team, team.myidentifier, team.users
        )
        team.channels[message_json["channel"]["id"]] = channel
    else:
        channel.update_from_message_json(message_json["channel"])

    channel.open()


def process_channel_created(message_json, eventrouter, team, channel, metadata):
    item = message_json["channel"]
    item["is_member"] = False
    channel = SlackChannel(eventrouter, team=team, **item)
    team.channels[item["id"]] = channel
    team.buffer_prnt("Channel created: {}".format(channel.name))


def process_channel_rename(message_json, eventrouter, team, channel, metadata):
    if channel is None:
        return
    channel.set_name(message_json["channel"]["name"])


def process_im_created(message_json, eventrouter, team, channel, metadata):
    item = message_json["channel"]
    channel = SlackDMChannel(eventrouter, team=team, users=team.users, **item)
    team.channels[item["id"]] = channel
    team.buffer_prnt("IM channel created: {}".format(channel.name))


def process_im_open(message_json, eventrouter, team, channel, metadata):
    channel.check_should_open(True)
    w.buffer_set(channel.channel_buffer, "hotlist", "2")


def process_im_close(message_json, eventrouter, team, channel, metadata):
    if channel.channel_buffer:
        w.prnt(
            team.channel_buffer,
            "IM {} closed by another client or the server".format(channel.name),
        )
    eventrouter.weechat_controller.unregister_buffer(
        channel.channel_buffer, False, True
    )


def process_mpim_joined(message_json, eventrouter, team, channel, metadata):
    item = message_json["channel"]
    channel = SlackMPDMChannel(
        eventrouter, team.users, team.myidentifier, team=team, **item
    )
    team.channels[item["id"]] = channel
    channel.open()


def process_group_joined(message_json, eventrouter, team, channel, metadata):
    item = message_json["channel"]
    if item["is_mpim"]:
        return
    channel = SlackGroupChannel(eventrouter, team=team, **item)
    team.channels[item["id"]] = channel
    channel.open()


def process_reaction_added(message_json, eventrouter, team, channel, metadata):
    channel = team.channels.get(message_json["item"].get("channel"))
    if channel is None:
        return

    if message_json["item"].get("type") == "message":
        ts = SlackTS(message_json["item"]["ts"])

        message = channel.messages.get(ts)
        if message:
            message.add_reaction(message_json["reaction"], message_json["user"])
            channel.change_message(ts)
    else:
        dbg("reaction to item type not supported: " + str(message_json))


def process_reaction_removed(message_json, eventrouter, team, channel, metadata):
    channel = team.channels.get(message_json["item"].get("channel"))
    if channel is None:
        return

    if message_json["item"].get("type") == "message":
        ts = SlackTS(message_json["item"]["ts"])

        message = channel.messages.get(ts)
        if message:
            message.remove_reaction(message_json["reaction"], message_json["user"])
            channel.change_message(ts)
    else:
        dbg("Reaction to item type not supported: " + str(message_json))


def process_subteam_created(subteam_json, eventrouter, team, channel, metadata):
    subteam_json_info = subteam_json["subteam"]
    is_member = team.myidentifier in subteam_json_info.get("users", [])
    subteam = SlackSubteam(team.identifier, is_member=is_member, **subteam_json_info)
    team.subteams[subteam_json_info["id"]] = subteam


def process_subteam_updated(subteam_json, eventrouter, team, channel, metadata):
    current_subteam_info = team.subteams.get(subteam_json["subteam"]["id"])
    if current_subteam_info is None:
        return

    is_member = team.myidentifier in subteam_json["subteam"].get("users", [])
    new_subteam_info = SlackSubteam(
        team.identifier, is_member=is_member, **subteam_json["subteam"]
    )
    team.subteams[subteam_json["subteam"]["id"]] = new_subteam_info

    if current_subteam_info.is_member != new_subteam_info.is_member:
        for channel in team.channels.values():
            channel.set_highlights()

    if (
        config.notify_usergroup_handle_updated
        and current_subteam_info.handle != new_subteam_info.handle
    ):
        message = "User group {old_handle} has updated its handle to {new_handle} in team {team}.".format(
            old_handle=current_subteam_info.handle,
            new_handle=new_subteam_info.handle,
            team=team.name,
        )
        team.buffer_prnt(message, message=True)


def process_emoji_changed(message_json, eventrouter, team, channel, metadata):
    team.load_emoji_completions()


def process_thread_subscribed(message_json, eventrouter, team, channel, metadata):
    dbg("THREAD SUBSCRIBED {}".format(message_json))
    channel = team.channels[message_json["subscription"]["channel"]]
    parent_ts = SlackTS(message_json["subscription"]["thread_ts"])
    parent_message = channel.messages.get(parent_ts)
    if parent_message:
        parent_message.last_read = SlackTS(message_json["subscription"]["last_read"])
        parent_message.subscribed = True
        channel.change_message(parent_ts)
        parent_message.notify_thread()
    else:
        channel.get_thread_history(parent_ts)


def process_thread_unsubscribed(message_json, eventrouter, team, channel, metadata):
    dbg("THREAD UNSUBSCRIBED {}".format(message_json))
    channel = team.channels[message_json["subscription"]["channel"]]
    parent_ts = SlackTS(message_json["subscription"]["thread_ts"])
    parent_message = channel.messages.get(parent_ts)
    if parent_message:
        parent_message.subscribed = False
        channel.change_message(parent_ts)


###### New module/global methods
def render_formatting(text):
    text = re.sub(
        r"(^| )\*([^*\n`]+)\*(?=[^\w]|$)",
        r"\1{}*\2*{}".format(
            w.color(config.render_bold_as), w.color("-" + config.render_bold_as)
        ),
        text,
        flags=re.UNICODE,
    )
    text = re.sub(
        r"(^| )_([^_\n`]+)_(?=[^\w]|$)",
        r"\1{}_\2_{}".format(
            w.color(config.render_italic_as), w.color("-" + config.render_italic_as)
        ),
        text,
        flags=re.UNICODE,
    )
    return text


def linkify_text(message, team, only_users=False, escape_characters=True):
    # The get_username_map function is a bit heavy, but this whole
    # function is only called on message send..
    usernames = team.get_username_map()
    channels = team.get_channel_map()
    usergroups = team.generate_usergroup_map()
    if escape_characters:
        message = (
            message
            # Replace IRC formatting chars with Slack formatting chars.
            .replace("\x02", "*")
            .replace("\x1D", "_")
            .replace("\x1F", config.map_underline_to)
            # Escape chars that have special meaning to Slack. Note that we do not
            # (and should not) perform full HTML entity-encoding here.
            # See https://api.slack.com/docs/message-formatting for details.
            .replace("&", "&amp;")
            .replace("<", "&lt;")
            .replace(">", "&gt;")
        )

    def linkify_word(match):
        word = match.group(0)
        prefix, name = match.groups()
        if prefix == "@":
            if name in ["channel", "everyone", "group", "here"]:
                return "<!{}>".format(name)
            elif name in usernames:
                return "<@{}>".format(usernames[name])
            elif word in usergroups.keys():
                return "<!subteam^{}|{}>".format(usergroups[word], word)
        elif prefix == "#" and not only_users:
            if word in channels:
                return "<#{}|{}>".format(channels[word], name)
        return word

    linkify_regex = r"(?:^|(?<=\s))([@#])([\w\(\)\'.-]+)"
    return re.sub(linkify_regex, linkify_word, message, flags=re.UNICODE)


def unfurl_blocks(blocks):
    block_text = []
    for block in blocks:
        try:
            if block["type"] == "section":
                fields = block.get("fields", [])
                if "text" in block:
                    fields.insert(0, block["text"])
                block_text.extend(unfurl_block_element(field) for field in fields)
            elif block["type"] == "actions":
                elements = []
                for element in block["elements"]:
                    if element["type"] == "button":
                        elements.append(unfurl_block_element(element["text"]))
                        if "url" in element:
                            elements.append(element["url"])
                    else:
                        elements.append(
                            colorize_string(
                                config.color_deleted,
                                '<<Unsupported block action type "{}">>'.format(
                                    element["type"]
                                ),
                            )
                        )
                block_text.append(" | ".join(elements))
            elif block["type"] == "call":
                block_text.append("Join via " + block["call"]["v1"]["join_url"])
            elif block["type"] == "divider":
                block_text.append("---")
            elif block["type"] == "context":
                block_text.append(
                    " | ".join(unfurl_block_element(el) for el in block["elements"])
                )
            elif block["type"] == "image":
                if "title" in block:
                    block_text.append(unfurl_block_element(block["title"]))
                block_text.append(unfurl_block_element(block))
            elif block["type"] == "rich_text":
                for element in block.get("elements", []):
                    if element["type"] == "rich_text_section":
                        rendered = unfurl_rich_text_section(element)
                        if rendered:
                            block_text.append(rendered)
                    elif element["type"] == "rich_text_list":
                        rendered = [
                            "{}{} {}".format(
                                "    " * element.get("indent", 0),
                                block_list_prefix(
                                    element, element.get("offset", 0) + i
                                ),
                                unfurl_rich_text_section(e),
                            )
                            for i, e in enumerate(element["elements"])
                        ]
                        block_text.extend(rendered)
                    elif element["type"] == "rich_text_quote":
                        lines = [
                            "> {}".format(line)
                            for e in element["elements"]
                            for line in unfurl_block_rich_text_element(e).split("\n")
                        ]
                        block_text.extend(lines)
                    elif element["type"] == "rich_text_preformatted":
                        texts = [
                            e.get("text", e.get("url", "")) for e in element["elements"]
                        ]
                        if texts:
                            block_text.append("```\n{}\n```".format("".join(texts)))
                    else:
                        text = '<<Unsupported rich_text type "{}">>'.format(
                            element["type"]
                        )
                        block_text.append(colorize_string(config.color_deleted, text))
                        dbg(
                            "Unsupported rich_text element: '{}'".format(
                                json.dumps(element)
                            ),
                            level=4,
                        )
            else:
                block_text.append(
                    colorize_string(
                        config.color_deleted,
                        '<<Unsupported block type "{}">>'.format(block["type"]),
                    )
                )
                dbg("Unsupported block: '{}'".format(json.dumps(block)), level=4)
        except Exception as e:
            dbg(
                "Failed to unfurl block ({}): {}".format(repr(e), json.dumps(block)),
                level=4,
            )
    return block_text


def convert_int_to_letter(num):
    letter = ""
    while num > 0:
        num -= 1
        letter = chr((num % 26) + 97) + letter
        num //= 26
    return letter


def convert_int_to_roman(num):
    roman_numerals = {
        1000: "m",
        900: "cm",
        500: "d",
        400: "cd",
        100: "c",
        90: "xc",
        50: "l",
        40: "xl",
        10: "x",
        9: "ix",
        5: "v",
        4: "iv",
        1: "i",
    }
    roman_numeral = ""
    for value, symbol in roman_numerals.items():
        while num >= value:
            roman_numeral += symbol
            num -= value
    return roman_numeral


def block_list_prefix(element, index):
    if element["style"] == "ordered":
        if element["indent"] == 0 or element["indent"] == 3:
            return "{}.".format(index + 1)
        elif element["indent"] == 1 or element["indent"] == 4:
            return "{}.".format(convert_int_to_letter(index + 1))
        else:
            return "{}.".format(convert_int_to_roman(index + 1))
    else:
        if element["indent"] == 0 or element["indent"] == 3:
            return "•"
        elif element["indent"] == 1 or element["indent"] == 4:
            return "◦"
        else:
            return "▪︎"


def unfurl_rich_text_section(block):
    texts = []
    prev_element = {"type": "text", "text": ""}
    for element in block["elements"] + [prev_element.copy()]:
        colors_apply = []
        colors_remove = []
        characters_apply = []
        characters_remove = []
        prev_style = prev_element.get("style", {})
        cur_style = element.get("style", {})
        if cur_style.get("bold", False) != prev_style.get("bold", False):
            if cur_style.get("bold"):
                colors_apply.append(w.color(config.render_bold_as))
                characters_apply.append("*")
            else:
                colors_remove.append(w.color("-" + config.render_bold_as))
                characters_remove.append("*")
        if cur_style.get("italic", False) != prev_style.get("italic", False):
            if cur_style.get("italic"):
                colors_apply.append(w.color(config.render_italic_as))
                characters_apply.append("_")
            else:
                colors_remove.append(w.color("-" + config.render_italic_as))
                characters_remove.append("_")
        if cur_style.get("strike", False) != prev_style.get("strike", False):
            if cur_style.get("strike"):
                characters_apply.append("~")
            else:
                characters_remove.append("~")
        if cur_style.get("code", False) != prev_style.get("code", False):
            if cur_style.get("code"):
                characters_apply.append("`")
            else:
                characters_remove.append("`")

        texts.extend(reversed(characters_remove))
        texts.extend(reversed(colors_remove))
        texts.extend(colors_apply)
        texts.extend(characters_apply)
        texts.append(unfurl_block_rich_text_element(element))
        prev_element = element

    text = "".join(texts)

    if text.endswith("\n"):
        return text[:-1]
    else:
        return text


def unfurl_block_rich_text_element(element):
    if element["type"] == "text":
        return element["text"]
    elif element["type"] == "link":
        text = element.get("text")
        if text and text != element["url"]:
            if element.get("style", {}).get("code"):
                return text
            else:
                return unfurl_link(element["url"], text)
        else:
            return element["url"]
    elif element["type"] == "emoji":
        return replace_string_with_emoji(":{}:".format(element["name"]))
    elif element["type"] == "color":
        rgb_int = int(element["value"].lstrip("#"), 16)
        weechat_color = w.info_get("color_rgb2term", str(rgb_int))
        return "{} {}".format(element["value"], colorize_string(weechat_color, "■"))
    elif element["type"] == "user":
        return resolve_ref("@{}".format(element["user_id"]))
    elif element["type"] == "usergroup":
        return resolve_ref("!subteam^{}".format(element["usergroup_id"]))
    elif element["type"] == "broadcast":
        return resolve_ref("@{}".format(element["range"]))
    elif element["type"] == "channel":
        return resolve_ref("#{}".format(element["channel_id"]))
    else:
        dbg("Unsupported rich text element: '{}'".format(json.dumps(element)), level=4)
        return colorize_string(
            config.color_deleted,
            '<<Unsupported rich text element type "{}">>'.format(element["type"]),
        )


def unfurl_block_element(element):
    if element["type"] == "mrkdwn":
        return render_formatting(unhtmlescape(unfurl_refs(element["text"])))
    elif element["type"] == "plain_text":
        return unhtmlescape(unfurl_refs(element["text"]))
    elif element["type"] == "image":
        if element.get("alt_text"):
            return "{} ({})".format(element["image_url"], element["alt_text"])
        else:
            return element["image_url"]
    else:
        dbg("Unsupported block element: '{}'".format(json.dumps(element)), level=4)
        return colorize_string(
            config.color_deleted,
            '<<Unsupported block element type "{}">>'.format(element["type"]),
        )


def unfurl_link(url, text):
    match_url = r"^\w+:(//)?{}$".format(re.escape(text))
    url_matches_desc = re.match(match_url, url)
    if url_matches_desc and config.unfurl_auto_link_display == "text":
        return text
    elif url_matches_desc and config.unfurl_auto_link_display == "url":
        return url
    else:
        return "{} ({})".format(url, text)


def unfurl_refs(text):
    """
    input : <@U096Q7CQM|someuser> has joined the channel
    ouput : someuser has joined the channel
    """
    # Find all strings enclosed by <>
    #  - <https://example.com|example with spaces>
    #  - <#C2147483705|#otherchannel>
    #  - <@U2147483697|@othernick>
    #  - <!subteam^U2147483697|@group>
    # Test patterns lives in ./_pytest/test_unfurl.py

    def unfurl_ref(match):
        ref, fallback = match.groups()

        resolved_ref = resolve_ref(ref)
        if resolved_ref != ref:
            return resolved_ref

        if fallback and fallback != ref and not config.unfurl_ignore_alt_text:
            if ref.startswith("#"):
                return "#{}".format(fallback)
            elif ref.startswith("@"):
                return fallback
            elif ref.startswith("!subteam"):
                prefix = "@" if not fallback.startswith("@") else ""
                return prefix + fallback
            elif ref.startswith("!date"):
                return fallback
            else:
                return unfurl_link(ref, fallback)
        return ref

    return re.sub(r"<([^|>]*)(?:\|([^>]*))?>", unfurl_ref, text)


def htmlescape(text):
    return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")


def unhtmlescape(text):
    return text.replace("&lt;", "<").replace("&gt;", ">").replace("&amp;", "&")


def unwrap_attachments(message, text_before):
    attachment_texts = []
    a = message.message_json.get("attachments")
    if a:
        if text_before:
            attachment_texts.append("")
        for attachment in a:
            # Attachments should be rendered roughly like:
            #
            # $pretext
            # $author: (if rest of line is non-empty) $title ($title_link) OR $from_url
            # $author: (if no $author on previous line) $text
            # $fields
            if not config.link_previews and (
                "original_url" in attachment or attachment.get("is_app_unfurl")
            ):
                continue
            t = []
            prepend_title_text = ""
            if "author_name" in attachment:
                prepend_title_text = attachment["author_name"] + ": "
            if "pretext" in attachment:
                t.append(attachment["pretext"])
            link_shown = False
            title = attachment.get("title")
            title_link = attachment.get("title_link", "")
            if title_link and title_link in text_before:
                title_link = ""
                link_shown = True
            if title and title_link:
                t.append(
                    "%s%s (%s)"
                    % (
                        prepend_title_text,
                        title,
                        htmlescape(title_link),
                    )
                )
                prepend_title_text = ""
            elif title and not title_link:
                t.append(
                    "%s%s"
                    % (
                        prepend_title_text,
                        title,
                    )
                )
                prepend_title_text = ""
            from_url = attachment.get("from_url", "")
            if from_url not in text_before and from_url != title_link:
                t.append(htmlescape(from_url))
            elif from_url:
                link_shown = True

            atext = attachment.get("text")
            if atext:
                tx = re.sub(r" *\n[\n ]+", "\n", atext)
                t.append(prepend_title_text + tx)
                prepend_title_text = ""

            image_url = attachment.get("image_url", "")
            if (
                image_url not in text_before
                and image_url != from_url
                and image_url != title_link
            ):
                t.append(htmlescape(image_url))
            elif image_url:
                link_shown = True

            for field in attachment.get("fields", []):
                if field.get("title"):
                    t.append("{}: {}".format(field["title"], field["value"]))
                else:
                    t.append(field["value"])

            files = unwrap_files(message, attachment, None)
            if files:
                t.append(files)

            t = [unhtmlescape(unfurl_refs(x)) for x in t]

            blocks = attachment.get("blocks", [])
            t.extend(unfurl_blocks(blocks))

            if attachment.get("is_msg_unfurl"):
                channel_name = resolve_ref("#{}".format(attachment["channel_id"]))
                if attachment.get("is_reply_unfurl"):
                    footer = "From a thread in {}".format(channel_name)
                else:
                    footer = "Posted in {}".format(channel_name)
            else:
                footer = attachment.get("footer")

            if footer:
                ts = attachment.get("ts")
                if ts:
                    ts_int = ts if isinstance(ts, int) else SlackTS(ts).major
                    if ts_int > 100000000000:
                        # The Slack web interface interprets very large timestamps
                        # as milliseconds after the epoch instead of regular Unix
                        # timestamps. We use the same heuristic here.
                        ts_int = ts_int // 1000
                    time_string = ""
                    if date.today() - date.fromtimestamp(ts_int) <= timedelta(days=1):
                        time_string = " at {time}"
                    timestamp_formatted = resolve_ref(
                        "!date^{}^{{date_short_pretty}}{}".format(ts_int, time_string)
                    ).capitalize()
                    footer += " | {}".format(timestamp_formatted)
                t.append(unhtmlescape(unfurl_refs(footer)))

            fallback = attachment.get("fallback")
            if t == [] and fallback and not link_shown:
                t.append(fallback)
            if t:
                lines = [
                    line for part in t for line in part.strip().split("\n") if part
                ]
                prefix = "|"
                line_color = None
                color = attachment.get("color")
                if color and config.colorize_attachments != "none":
                    weechat_color = w.info_get(
                        "color_rgb2term", str(int(color.lstrip("#"), 16))
                    )
                    if config.colorize_attachments == "prefix":
                        prefix = colorize_string(weechat_color, prefix)
                    elif config.colorize_attachments == "all":
                        line_color = weechat_color
                attachment_texts.extend(
                    colorize_string(line_color, "{} {}".format(prefix, line))
                    for line in lines
                )
    return "\n".join(attachment_texts)


def unwrap_huddle(message, message_json, text_before):
    """
    If huddle is linked to message, append huddle information and link
    to connect.
    """
    huddle_texts = []

    if "room" in message_json:
        if "name" in message_json.get("room"):
            room_name = message_json.get("room").get("name")

            if room_name != "":
                huddle_texts.append("Huddle name: {}".format(room_name))

        for channel in message_json.get("room").get("channels"):
            huddle_texts.append(
                "https://app.slack.com/client/{team}/{channel}?open=start_huddle".format(
                    team=message_json.get("team"), channel=channel
                )
            )

    if text_before:
        huddle_texts.insert(0, "")
    return "\n".join(huddle_texts)


def unwrap_files(message, message_json, text_before):
    files_texts = []
    for f in message_json.get("files", []):
        if f.get("mode", "") == "tombstone":
            text = colorize_string(config.color_deleted, "(This file was deleted.)")
        elif f.get("mode", "") == "hidden_by_limit":
            text = colorize_string(
                config.color_deleted,
                "(This file is hidden because the workspace has passed its storage limit.)",
            )
        elif f.get("mimetype") == "application/vnd.slack-docs":
            url = "{}?origin_team={}&origin_channel={}".format(
                f["permalink"], message.team.identifier, message.channel.identifier
            )
            text = "{} ({})".format(url, f["title"])
        elif f.get("url_private"):
            if f.get("title"):
                text = "{} ({})".format(f["url_private"], f["title"])
            else:
                text = f["url_private"]
        else:
            dbg("File {} has unrecognized mode {}".format(f["id"], f.get("mode")), 5)
            text = colorize_string(
                config.color_deleted, "(This file cannot be handled.)"
            )
        files_texts.append(text)

    if text_before:
        files_texts.insert(0, "")
    return "\n".join(files_texts)


def resolve_ref(ref):
    if ref in ["!channel", "!everyone", "!group", "!here"]:
        return ref.replace("!", "@")
    for team in EVENTROUTER.teams.values():
        if ref.startswith("@"):
            user = team.users.get(ref[1:])
            if user:
                suffix = config.external_user_suffix if user.is_external else ""
                return "@{}{}".format(user.name, suffix)
        elif ref.startswith("#"):
            channel = team.channels.get(ref[1:])
            if channel:
                return channel.name
        elif ref.startswith("!subteam"):
            _, subteam_id = ref.split("^")
            subteam = team.subteams.get(subteam_id)
            if subteam:
                return subteam.handle
        elif ref.startswith("!date"):
            parts = ref.split("^")
            ref_datetime = datetime.fromtimestamp(int(parts[1]))
            link_suffix = " ({})".format(parts[3]) if len(parts) > 3 else ""
            token_to_format = {
                "date_num": "%Y-%m-%d",
                "date": "%B %d, %Y",
                "date_short": "%b %d, %Y",
                "date_long": "%A, %B %d, %Y",
                "time": "%H:%M",
                "time_secs": "%H:%M:%S",
            }

            def replace_token(match):
                token = match.group(1)
                if token.startswith("date_") and token.endswith("_pretty"):
                    if ref_datetime.date() == date.today():
                        return "today"
                    elif ref_datetime.date() == date.today() - timedelta(days=1):
                        return "yesterday"
                    elif ref_datetime.date() == date.today() + timedelta(days=1):
                        return "tomorrow"
                    else:
                        token = token.replace("_pretty", "")
                if token in token_to_format:
                    return decode_from_utf8(
                        ref_datetime.strftime(token_to_format[token])
                    )
                else:
                    return match.group(0)

            return re.sub(r"{([^}]+)}", replace_token, parts[2]) + link_suffix

    # Something else, just return as-is
    return ref


def create_user_status_string(profile):
    real_name = profile.get("real_name")
    status_emoji = replace_string_with_emoji(profile.get("status_emoji", ""))
    status_text = profile.get("status_text")
    if status_emoji or status_text:
        return "{} | {} {}".format(real_name, status_emoji, status_text)
    else:
        return real_name


def create_reaction_string(reaction, myidentifier):
    if config.show_reaction_nicks:
        nicks = [resolve_ref("@{}".format(user)) for user in reaction["users"]]
        nicks_extra = (
            ["and others"] if len(reaction["users"]) < reaction["count"] else []
        )
        users = "({})".format(", ".join(nicks + nicks_extra))
    else:
        users = reaction["count"]
    reaction_string = ":{}:{}".format(reaction["name"], users)
    if myidentifier in reaction["users"]:
        return colorize_string(
            config.color_reaction_suffix_added_by_you,
            reaction_string,
            reset_color=config.color_reaction_suffix,
        )
    else:
        return reaction_string


def create_reactions_string(reactions, myidentifier):
    reactions_with_users = [r for r in reactions if r["count"] > 0]
    reactions_string = " ".join(
        create_reaction_string(r, myidentifier) for r in reactions_with_users
    )
    if reactions_string:
        return " " + colorize_string(
            config.color_reaction_suffix, "[{}]".format(reactions_string)
        )
    else:
        return ""


def hdata_line_ts(line_pointer):
    data = w.hdata_pointer(hdata.line, line_pointer, "data")
    for i in range(w.hdata_integer(hdata.line_data, data, "tags_count")):
        tag = w.hdata_string(hdata.line_data, data, "{}|tags_array".format(i))
        if tag.startswith("slack_ts_"):
            return SlackTS(tag[9:])
    return None


def modify_buffer_line(buffer_pointer, ts, new_text):
    own_lines = w.hdata_pointer(hdata.buffer, buffer_pointer, "own_lines")
    line_pointer = w.hdata_pointer(hdata.lines, own_lines, "last_line")

    # Find the last line with this ts
    is_last_line = True
    while line_pointer and hdata_line_ts(line_pointer) != ts:
        is_last_line = False
        line_pointer = w.hdata_move(hdata.line, line_pointer, -1)

    if not line_pointer:
        return w.WEECHAT_RC_OK

    if weechat_version >= 0x04000000:
        data = w.hdata_pointer(hdata.line, line_pointer, "data")
        w.hdata_update(hdata.line_data, data, {"message": new_text})
        return w.WEECHAT_RC_OK

    # Find all lines for the message
    pointers = []
    while line_pointer and hdata_line_ts(line_pointer) == ts:
        pointers.append(line_pointer)
        line_pointer = w.hdata_move(hdata.line, line_pointer, -1)
    pointers.reverse()

    if not pointers:
        return w.WEECHAT_RC_OK

    if is_last_line:
        lines = new_text.split("\n")
        extra_lines_count = len(lines) - len(pointers)
        if extra_lines_count > 0:
            line_data = w.hdata_pointer(hdata.line, pointers[0], "data")
            tags_count = w.hdata_integer(hdata.line_data, line_data, "tags_count")
            tags = [
                w.hdata_string(hdata.line_data, line_data, "{}|tags_array".format(i))
                for i in range(tags_count)
            ]
            tags = tags_set_notify_none(tags)
            tags_str = ",".join(tags)
            last_read_line = w.hdata_pointer(hdata.lines, own_lines, "last_read_line")
            should_set_unread = last_read_line == pointers[-1]

            # Insert new lines to match the number of lines in the message
            w.buffer_set(buffer_pointer, "print_hooks_enabled", "0")
            for _ in range(extra_lines_count):
                w.prnt_date_tags(buffer_pointer, ts.major, tags_str, " \t ")
                pointers.append(w.hdata_pointer(hdata.lines, own_lines, "last_line"))
            if should_set_unread:
                w.buffer_set(buffer_pointer, "unread", "")
            w.buffer_set(buffer_pointer, "print_hooks_enabled", "1")
    else:
        # Split the message into at most the number of existing lines as we can't insert new lines
        lines = new_text.split("\n", len(pointers) - 1)
        # Replace newlines to prevent garbled lines in bare display mode
        lines = [line.replace("\n", " | ") for line in lines]

    # Extend lines in case the new message is shorter than the old as we can't delete lines
    lines += [""] * (len(pointers) - len(lines))

    for pointer, line in zip(pointers, lines):
        data = w.hdata_pointer(hdata.line, pointer, "data")
        w.hdata_update(hdata.line_data, data, {"message": line})

    return w.WEECHAT_RC_OK


def nick_from_profile(profile, username):
    full_name = profile.get("real_name") or username
    if config.use_full_names:
        nick = full_name
    else:
        nick = profile.get("display_name") or full_name
    return nick.replace(" ", "")


def format_nick(nick, previous_nick=None):
    if nick == previous_nick:
        nick = w.config_string(w.config_get("weechat.look.prefix_same_nick")) or nick
    nick_prefix = w.config_string(w.config_get("weechat.look.nick_prefix"))
    nick_prefix_color_name = w.config_string(
        w.config_get("weechat.color.chat_nick_prefix")
    )

    nick_suffix = w.config_string(w.config_get("weechat.look.nick_suffix"))
    nick_suffix_color_name = w.config_string(
        w.config_get("weechat.color.chat_nick_prefix")
    )
    return (
        colorize_string(nick_prefix_color_name, nick_prefix)
        + nick
        + colorize_string(nick_suffix_color_name, nick_suffix)
    )


def tags_set_notify_none(tags):
    notify_tags = {"notify_highlight", "notify_message", "notify_private"}
    tags = [tag for tag in tags if tag not in notify_tags]
    tags += ["no_highlight", "notify_none"]
    return tags


def tag(
    ts,
    tagset=None,
    user=None,
    self_msg=False,
    backlog=False,
    no_log=False,
    extra_tags=None,
):
    tagsets = {
        "team_info": ["no_highlight", "log3"],
        "team_message": ["irc_privmsg", "notify_message", "log1"],
        "dm": ["irc_privmsg", "notify_private", "log1"],
        "join": ["irc_join", "no_highlight", "log4"],
        "leave": ["irc_part", "no_highlight", "log4"],
        "topic": ["irc_topic", "no_highlight", "log3"],
        "channel": ["irc_privmsg", "notify_message", "log1"],
    }
    ts_tag = "slack_ts_{}".format(ts)
    slack_tag = "slack_{}".format(tagset or "default")
    nick_tag = ["nick_{}".format(user).replace(" ", "_")] if user else []
    tags = [ts_tag, slack_tag] + nick_tag + tagsets.get(tagset, [])
    if (self_msg and tagset != "join") or backlog:
        tags = tags_set_notify_none(tags)
        if self_msg:
            tags += ["self_msg"]
        if backlog:
            tags += ["logger_backlog"]
    if no_log:
        tags += ["no_log"]
        tags = [
            tag for tag in tags if not tag.startswith("log") or tag == "logger_backlog"
        ]
    if extra_tags:
        tags += extra_tags
    return ",".join(OrderedDict.fromkeys(tags))


def set_own_presence_active(team):
    slackbot = team.get_channel_map()["Slackbot"]
    channel = team.channels[slackbot]
    request = {"type": "typing", "channel": channel.identifier}
    channel.team.send_to_websocket(request, expect_reply=False)


###### New/converted command_ commands


@slack_buffer_or_ignore
@utf8_decode
def invite_command_cb(data, current_buffer, args):
    team = EVENTROUTER.weechat_controller.buffers[current_buffer].team
    split_args = args.split()[1:]
    if not split_args:
        w.prnt(
            "",
            'Too few arguments for command "/invite" (help on command: /help invite)',
        )
        return w.WEECHAT_RC_OK_EAT

    if split_args[-1].startswith("#") or split_args[-1].startswith(
        config.group_name_prefix
    ):
        nicks = split_args[:-1]
        channel = team.channels.get(team.get_channel_map().get(split_args[-1]))
        if not nicks or not channel:
            w.prnt("", "{}: No such nick/channel".format(split_args[-1]))
            return w.WEECHAT_RC_OK_EAT
    else:
        nicks = split_args
        channel = EVENTROUTER.weechat_controller.buffers[current_buffer]

    all_users = team.get_username_map()
    users = set()
    for nick in nicks:
        user = all_users.get(nick.lstrip("@"))
        if not user:
            w.prnt("", "ERROR: Unknown user: {}".format(nick))
            return w.WEECHAT_RC_OK_EAT
        users.add(user)

    s = SlackRequest(
        team,
        "conversations.invite",
        {"channel": channel.identifier, "users": ",".join(users)},
        channel=channel,
        metadata={"nicks": nicks},
    )
    EVENTROUTER.receive(s)
    return w.WEECHAT_RC_OK_EAT


@slack_buffer_or_ignore
@utf8_decode
def part_command_cb(data, current_buffer, args):
    e = EVENTROUTER
    args = args.split()
    if len(args) > 1:
        team = e.weechat_controller.buffers[current_buffer].team
        cmap = team.get_channel_map()
        channel = "".join(args[1:])
        if channel in cmap:
            buffer_ptr = team.channels[cmap[channel]].channel_buffer
            e.weechat_controller.unregister_buffer(
                buffer_ptr, update_remote=True, close_buffer=True
            )
        else:
            w.prnt(team.channel_buffer, "{}: No such channel".format(channel))
    else:
        e.weechat_controller.unregister_buffer(
            current_buffer, update_remote=True, close_buffer=True
        )
    return w.WEECHAT_RC_OK_EAT


def parse_topic_command(command):
    _, _, args = command.partition(" ")
    if args.startswith("#"):
        channel_name, _, topic_arg = args.partition(" ")
    else:
        channel_name = None
        topic_arg = args

    if topic_arg == "-delete":
        topic = ""
    elif topic_arg:
        topic = topic_arg
    else:
        topic = None

    return channel_name, topic


@slack_buffer_or_ignore
@utf8_decode
def topic_command_cb(data, current_buffer, command):
    """
    Change the topic of a channel
    /topic [<channel>] [<topic>|-delete]
    """
    channel_name, topic = parse_topic_command(command)
    team = EVENTROUTER.weechat_controller.buffers[current_buffer].team

    if channel_name:
        channel = team.channels.get(team.get_channel_map().get(channel_name))
    else:
        channel = EVENTROUTER.weechat_controller.buffers[current_buffer]

    if not channel:
        w.prnt(team.channel_buffer, "{}: No such channel".format(channel_name))
        return w.WEECHAT_RC_OK_EAT

    if topic is None:
        w.prnt(
            channel.channel_buffer,
            'Topic for {} is "{}"'.format(channel.name, channel.render_topic()),
        )
    else:
        s = SlackRequest(
            team,
            "conversations.setTopic",
            {"channel": channel.identifier, "topic": linkify_text(topic, team)},
            channel=channel,
        )
        EVENTROUTER.receive(s)
    return w.WEECHAT_RC_OK_EAT


@slack_buffer_or_ignore
@utf8_decode
def whois_command_cb(data, current_buffer, command):
    """
    Get real name of user
    /whois <nick>
    """
    args = command.split()
    if len(args) < 2:
        w.prnt(current_buffer, "Not enough arguments")
        return w.WEECHAT_RC_OK_EAT
    user = args[1]
    if user.startswith("@"):
        user = user[1:]
    team = EVENTROUTER.weechat_controller.buffers[current_buffer].team
    u = team.users.get(team.get_username_map().get(user))
    if u:

        def print_profile(field):
            value = u.profile.get(field)
            if value:
                team.buffer_prnt("[{}]: {}: {}".format(user, field, value))

        team.buffer_prnt("[{}]: {}".format(user, u.real_name))
        status_emoji = replace_string_with_emoji(u.profile.get("status_emoji", ""))
        status_text = u.profile.get("status_text", "")
        if status_emoji or status_text:
            team.buffer_prnt("[{}]: {} {}".format(user, status_emoji, status_text))

        team.buffer_prnt("[{}]: username: {}".format(user, u.username))
        team.buffer_prnt("[{}]: id: {}".format(user, u.identifier))

        print_profile("title")
        print_profile("email")
        print_profile("phone")
        print_profile("skype")
    else:
        team.buffer_prnt("[{}]: No such user".format(user))
    return w.WEECHAT_RC_OK_EAT


@slack_buffer_or_ignore
@utf8_decode
def me_command_cb(data, current_buffer, args):
    channel = EVENTROUTER.weechat_controller.buffers[current_buffer]
    message = args.split(" ", 1)[1]
    channel.send_message(message, subtype="me_message")
    return w.WEECHAT_RC_OK_EAT


@utf8_decode
def command_register(data, current_buffer, args):
    """
    /slack register [-nothirdparty] [code/token]
    Register a Slack team in wee-slack. Call this without any arguments and
    follow the instructions to register a new team. If you already have a token
    for a team, you can call this with that token to add it.

    By default GitHub Pages will see a temporary code used to create your token
    (but not the token itself). If you're worried about this, you can use the
    -nothirdparty option, though the process will be a bit less user friendly.
    """
    CLIENT_ID = "2468770254.51917335286"
    CLIENT_SECRET = "dcb7fe380a000cba0cca3169a5fe8d70"  # Not really a secret.
    REDIRECT_URI_GITHUB = "https://wee-slack.github.io/wee-slack/oauth"
    REDIRECT_URI_NOTHIRDPARTY = "http://not.a.realhost/"

    args = args.strip()
    if " " in args:
        nothirdparty_arg, _, code = args.partition(" ")
        nothirdparty = nothirdparty_arg == "-nothirdparty"
    else:
        nothirdparty = args == "-nothirdparty"
        code = "" if nothirdparty else args
    redirect_uri = quote(
        REDIRECT_URI_NOTHIRDPARTY if nothirdparty else REDIRECT_URI_GITHUB, safe=""
    )

    if not code:
        if nothirdparty:
            nothirdparty_note = ""
            last_step = "You will see a message that the site can't be reached, this is expected. The URL for the page will have a code in it of the form `?code=<code>`. Copy the code after the equals sign, return to WeeChat and run `/slack register -nothirdparty <code>`."
        else:
            nothirdparty_note = "\nNote that by default GitHub Pages will see a temporary code used to create your token (but not the token itself). If you're worried about this, you can use the -nothirdparty option, though the process will be a bit less user friendly."
            last_step = "The web page will show a command in the form `/slack register <code>`. Run this command in WeeChat."
        message = (
            textwrap.dedent(
                """
            ### Connecting to a Slack team with OAuth ###{}
            1) Paste this link into a browser: https://slack.com/oauth/authorize?client_id={}&scope=client&redirect_uri={}
            2) Select the team you wish to access from wee-slack in your browser. If you want to add multiple teams, you will have to repeat this whole process for each team.
            3) Click "Authorize" in the browser.
               If you get a message saying you are not authorized to install wee-slack, the team has restricted Slack app installation and you will have to request it from an admin. To do that, go to https://my.slack.com/apps/A1HSZ9V8E-wee-slack and click "Request to Install".
            4) {}
        """
            )
            .strip()
            .format(nothirdparty_note, CLIENT_ID, redirect_uri, last_step)
        )
        w.prnt("", "\n" + message)
        return w.WEECHAT_RC_OK_EAT
    elif code.startswith("xox"):
        add_token(code)
        return w.WEECHAT_RC_OK_EAT

    uri = (
        "https://slack.com/api/oauth.access?"
        "client_id={}&client_secret={}&redirect_uri={}&code={}"
    ).format(CLIENT_ID, CLIENT_SECRET, redirect_uri, code)
    params = {"useragent": "wee_slack {}".format(SCRIPT_VERSION)}
    w.hook_process_hashtable(
        "url:{}".format(uri), params, config.slack_timeout, "register_callback", ""
    )
    return w.WEECHAT_RC_OK_EAT


command_register.completion = "-nothirdparty %-"


@utf8_decode
def register_callback(data, command, return_code, out, err):
    if return_code != 0:
        w.prnt(
            "",
            "ERROR: problem when trying to get Slack OAuth token. Got return code {}. Err: {}".format(
                return_code, err
            ),
        )
        w.prnt("", "Check the network or proxy settings")
        return w.WEECHAT_RC_OK_EAT

    if len(out) <= 0:
        w.prnt(
            "",
            "ERROR: problem when trying to get Slack OAuth token. Got 0 length answer. Err: {}".format(
                err
            ),
        )
        w.prnt("", "Check the network or proxy settings")
        return w.WEECHAT_RC_OK_EAT

    d = json.loads(out)
    if not d["ok"]:
        w.prnt("", "ERROR: Couldn't get Slack OAuth token: {}".format(d["error"]))
        return w.WEECHAT_RC_OK_EAT

    add_token(d["access_token"], d["team_name"])
    return w.WEECHAT_RC_OK_EAT


def add_token(token, team_name=None):
    if config.is_default("slack_api_token"):
        w.config_set_plugin("slack_api_token", token)
    else:
        # Add new token to existing set, joined by comma.
        existing_tokens = config.get_string("slack_api_token")
        if token in existing_tokens:
            print_error("This token is already registered")
            return
        w.config_set_plugin("slack_api_token", ",".join([existing_tokens, token]))

    if team_name:
        w.prnt("", 'Success! Added team "{}"'.format(team_name))
    else:
        w.prnt("", "Success! Added token")
    w.prnt("", "Please reload wee-slack with: /python reload slack")
    w.prnt(
        "",
        "If you want to add another team you can repeat this process from step 1 before reloading wee-slack.",
    )


@slack_buffer_or_ignore
@utf8_decode
def msg_command_cb(data, current_buffer, args):
    aargs = args.split(None, 2)
    who = aargs[1].lstrip("@")
    if who != "*":
        join_query_command_cb(data, current_buffer, "/query " + who)

    if len(aargs) > 2:
        message = aargs[2]
        buffer_pointer = EVENTROUTER.weechat_controller.buffers[current_buffer]
        team = buffer_pointer.team
        if who == "*":
            channel = buffer_pointer
        else:
            cmap = team.get_channel_map()
            channel = team.channels.get(cmap.get(who))
        if channel:
            channel.send_message(message)
    return w.WEECHAT_RC_OK_EAT


def print_team_items_info(team, header, items, extra_info_function):
    team.buffer_prnt("{}:".format(header))
    if items:
        max_name_length = max(len(item.name) for item in items)
        for item in sorted(items, key=lambda item: item.name.lower()):
            extra_info = extra_info_function(item)
            team.buffer_prnt(
                "    {:<{}}({})".format(item.name, max_name_length + 2, extra_info)
            )
    return w.WEECHAT_RC_OK_EAT


def print_users_info(team, header, users):
    def extra_info_function(user):
        external_text = ", external" if user.is_external else ""
        return user.presence + external_text

    return print_team_items_info(team, header, users, extra_info_function)


@slack_buffer_required
@utf8_decode
def command_teams(data, current_buffer, args):
    """
    /slack teams
    List the connected Slack teams.
    """
    team = EVENTROUTER.weechat_controller.buffers[current_buffer].team
    teams = EVENTROUTER.teams.values()
    extra_info_function = lambda team: "token: {}".format(token_for_print(team.token))
    return print_team_items_info(team, "Slack teams", teams, extra_info_function)


@slack_buffer_required
@utf8_decode
def command_channels(data, current_buffer, args):
    """
    /slack channels [regex]
    List the channels in the current team.
    If regex is given show channels whose names match the regular expression.
    """
    team = EVENTROUTER.weechat_controller.buffers[current_buffer].team
    pat = re.compile(args)
    channels = [
        channel
        for channel in team.channels.values()
        if channel.type not in ["im", "mpim"] and pat.search(channel.name)
    ]

    def extra_info_function(channel):
        if channel.active:
            return "member"
        elif getattr(channel, "is_archived", None):
            return "archived"
        else:
            return "not a member"

    if args:
        return print_team_items_info(
            team, 'Channels that match "' + args + '"', channels, extra_info_function
        )
    else:
        return print_team_items_info(team, "Channels", channels, extra_info_function)


@slack_buffer_required
@utf8_decode
def command_users(data, current_buffer, args):
    """
    /slack users
    List the users in the current team.
    """
    team = EVENTROUTER.weechat_controller.buffers[current_buffer].team
    return print_users_info(team, "Users", team.users.values())


@slack_buffer_required
@utf8_decode
def command_usergroups(data, current_buffer, args):
    """
    /slack usergroups [handle]
    List the usergroups in the current team
    If handle is given show the members in the usergroup
    """
    team = EVENTROUTER.weechat_controller.buffers[current_buffer].team
    usergroups = team.generate_usergroup_map()
    usergroup_key = usergroups.get(args)

    if usergroup_key:
        s = SlackRequest(
            team,
            "usergroups.users.list",
            {"usergroup": usergroup_key},
            metadata={"usergroup_handle": args},
        )
        EVENTROUTER.receive(s)
    elif args:
        w.prnt("", "ERROR: Unknown usergroup handle: {}".format(args))
        return w.WEECHAT_RC_ERROR
    else:

        def extra_info_function(subteam):
            is_member = "member" if subteam.is_member else "not a member"
            return "{}, {}".format(subteam.handle, is_member)

        return print_team_items_info(
            team, "Usergroups", team.subteams.values(), extra_info_function
        )
    return w.WEECHAT_RC_OK_EAT


command_usergroups.completion = "%(usergroups) %-"


@slack_buffer_required
@utf8_decode
def command_talk(data, current_buffer, args):
    """
    /slack talk <user>[,<user2>[,<user3>...]]
    Open a chat with the specified user(s).
    """
    if not args:
        w.prnt("", "Usage: /slack talk <user>[,<user2>[,<user3>...]]")
        return w.WEECHAT_RC_ERROR
    return join_query_command_cb(data, current_buffer, "/query " + args)


command_talk.completion = "%(nicks)"


@slack_buffer_or_ignore
@utf8_decode
def join_query_command_cb(data, current_buffer, args):
    team = EVENTROUTER.weechat_controller.buffers[current_buffer].team
    split_args = args.split(" ", 1)
    if len(split_args) < 2 or not split_args[1]:
        w.prnt(
            "",
            'Too few arguments for command "{}" (help on command: /help {})'.format(
                split_args[0], split_args[0].lstrip("/")
            ),
        )
        return w.WEECHAT_RC_OK_EAT
    query = split_args[1]

    # Try finding the channel by name
    channel = team.channels.get(team.get_channel_map().get(query))

    # If the channel doesn't exist, try finding a DM or MPDM instead
    if not channel:
        if query.startswith("#"):
            w.prnt("", "ERROR: Unknown channel: {}".format(query))
            return w.WEECHAT_RC_OK_EAT

        # Get the IDs of the users
        all_users = team.get_username_map()
        users = set()
        for username in query.split(","):
            user = all_users.get(username.lstrip("@"))
            if not user:
                w.prnt("", "ERROR: Unknown user: {}".format(username))
                return w.WEECHAT_RC_OK_EAT
            users.add(user)

        if users:
            if len(users) > 1:
                channel_type = "mpim"
                # Add the current user since MPDMs include them as a member
                users.add(team.myidentifier)
            else:
                channel_type = "im"

            channel = team.find_channel_by_members(users, channel_type=channel_type)

            # If the DM or MPDM doesn't exist, create it
            if not channel:
                s = SlackRequest(
                    team,
                    team.slack_api_translator[channel_type]["join"],
                    {"users": ",".join(users)},
                    metadata={"switch": True},
                )
                EVENTROUTER.receive(s)

    if channel:
        channel.open()
        if config.switch_buffer_on_join:
            w.buffer_set(channel.channel_buffer, "display", "1")
    return w.WEECHAT_RC_OK_EAT


@slack_buffer_required
@utf8_decode
def command_create(data, current_buffer, args):
    """
    /slack create [-private] <channel_name>
    Create a public or private channel.
    """
    team = EVENTROUTER.weechat_controller.buffers[current_buffer].team

    parts = args.split(None, 1)
    if parts[0] == "-private":
        args = parts[1]
        private = True
    else:
        private = False

    post_data = {"name": args, "is_private": private}
    s = SlackRequest(team, "conversations.create", post_data)
    EVENTROUTER.receive(s)
    return w.WEECHAT_RC_OK_EAT


command_create.completion = "-private"


@slack_buffer_required
@utf8_decode
def command_showmuted(data, current_buffer, args):
    """
    /slack showmuted
    List the muted channels in the current team.
    """
    team = EVENTROUTER.weechat_controller.buffers[current_buffer].team
    muted_channels = [
        team.channels[key].name for key in team.muted_channels if key in team.channels
    ]
    team.buffer_prnt("Muted channels: {}".format(", ".join(muted_channels)))
    return w.WEECHAT_RC_OK_EAT


@slack_buffer_required
@utf8_decode
def command_thread(data, current_buffer, args):
    """
    /thread [count/message_id]
    Open the thread for the message.
    If no message id is specified the last thread in channel will be opened.
    """
    channel = EVENTROUTER.weechat_controller.buffers[current_buffer]

    if not isinstance(channel, SlackChannelCommon):
        print_error("/thread can not be used in the team buffer, only in a channel")
        return w.WEECHAT_RC_ERROR

    message = channel.message_from_hash(args)
    if not message:
        message_filter = lambda message: message.number_of_replies()
        message = channel.message_from_hash_or_index(args, message_filter)

    if message:
        message.open_thread(switch=config.switch_buffer_on_join)
    elif args:
        print_error(
            "Invalid id given, must be an existing id or a number greater "
            + "than 0 and less than the number of thread messages in the channel"
        )
    else:
        print_error("No threads found in channel")

    return w.WEECHAT_RC_OK_EAT


command_thread.completion = "%(threads) %-"


def subscribe_helper(current_buffer, args, usage, api):
    channel = EVENTROUTER.weechat_controller.buffers[current_buffer]
    team = channel.team

    if isinstance(channel, SlackThreadChannel) and not args:
        message = channel.parent_message
    else:
        message_filter = lambda message: message.number_of_replies()
        message = channel.message_from_hash_or_index(args, message_filter)

    if not message:
        print_message_not_found_error(args)
        return w.WEECHAT_RC_OK_EAT

    last_read = next(reversed(message.submessages), message.ts)
    post_data = {
        "channel": channel.identifier,
        "thread_ts": message.ts,
        "last_read": last_read,
    }
    s = SlackRequest(team, api, post_data, channel=channel)
    EVENTROUTER.receive(s)
    return w.WEECHAT_RC_OK_EAT


@slack_buffer_required
@utf8_decode
def command_subscribe(data, current_buffer, args):
    """
    /slack subscribe <thread>
    Subscribe to a thread, so that you are alerted to new messages. When in a
    thread buffer, you can omit the thread id.

    This command only works when using a session token, see the readme: https://github.com/wee-slack/wee-slack#4-add-your-slack-api-tokens
    """
    return subscribe_helper(
        current_buffer,
        args,
        "Usage: /slack subscribe <thread>",
        "subscriptions.thread.add",
    )


command_subscribe.completion = "%(threads) %-"


@slack_buffer_required
@utf8_decode
def command_unsubscribe(data, current_buffer, args):
    """
    /slack unsubscribe <thread>
    Unsubscribe from a thread that has been previously subscribed to, so that
    you are not alerted to new messages. When in a thread buffer, you can omit
    the thread id.

    This command only works when using a session token, see the readme: https://github.com/wee-slack/wee-slack#4-add-your-slack-api-tokens
    """
    return subscribe_helper(
        current_buffer,
        args,
        "Usage: /slack unsubscribe <thread>",
        "subscriptions.thread.remove",
    )


command_unsubscribe.completion = "%(threads) %-"


@slack_buffer_required
@utf8_decode
def command_reply(data, current_buffer, args):
    """
    /reply [-alsochannel] [<count/message_id>] <message>

    When in a channel buffer:
    /reply [-alsochannel] <count/message_id> <message>
    Reply in a thread on the message. Specify either the message id or a count
    upwards to the message from the last message.

    When in a thread buffer:
    /reply [-alsochannel] <message>
    Reply to the current thread.  This can be used to send the reply to the
    rest of the channel.

    In either case, -alsochannel also sends the reply to the parent channel.
    """
    channel = EVENTROUTER.weechat_controller.buffers[current_buffer]

    parts = args.split(None, 1)
    if len(parts) < 1:
        w.prnt(
            "", 'Too few arguments for command "/reply" (help on command: /help reply)'
        )
        return w.WEECHAT_RC_ERROR

    if parts[0] == "-alsochannel":
        args = parts[1]
        broadcast = True
    else:
        broadcast = False

    if isinstance(channel, SlackThreadChannel):
        text = args
        message = channel.parent_message
    else:
        try:
            msg_id, text = args.split(None, 1)
        except ValueError:
            w.prnt(
                "",
                "Usage (when in a channel buffer): /reply [-alsochannel] <count/message_id> <message>",
            )
            return w.WEECHAT_RC_OK_EAT
        message = channel.message_from_hash_or_index(msg_id)

        if not message:
            print_message_not_found_error(args)
            return w.WEECHAT_RC_OK_EAT

    if isinstance(message, SlackThreadMessage):
        parent_id = str(message.parent_message.ts)
    elif message:
        parent_id = str(message.ts)

    channel.send_message(
        text, request_dict_ext={"thread_ts": parent_id, "reply_broadcast": broadcast}
    )
    return w.WEECHAT_RC_OK_EAT


command_reply.completion = "%(threads)|-alsochannel %(threads)"


@slack_buffer_required
@utf8_decode
def command_rehistory(data, current_buffer, args):
    """
    /rehistory [-remote]
    Reload the history in the current channel.
    With -remote the history will be downloaded again from Slack.
    """
    channel = EVENTROUTER.weechat_controller.buffers[current_buffer]
    if args == "-remote":
        channel.get_history(full=True, no_log=True)
    else:
        channel.reprint_messages(force_render=True)
    return w.WEECHAT_RC_OK_EAT


command_rehistory.completion = "-remote"


@slack_buffer_required
@utf8_decode
def command_hide(data, current_buffer, args):
    """
    /hide
    Hide the current channel if it is marked as distracting.
    """
    channel = EVENTROUTER.weechat_controller.buffers[current_buffer]
    name = channel.formatted_name(style="long_default")
    if name in config.distracting_channels:
        w.buffer_set(channel.channel_buffer, "hidden", "1")
    return w.WEECHAT_RC_OK_EAT


@utf8_decode
def slack_command_cb(data, current_buffer, args):
    split_args = args.split(" ", 1)
    cmd_name = split_args[0]
    cmd_args = split_args[1] if len(split_args) > 1 else ""
    cmd = EVENTROUTER.cmds.get(cmd_name or "help")
    if not cmd:
        w.prnt("", "Command not found: " + cmd_name)
        return w.WEECHAT_RC_OK
    return cmd(data, current_buffer, cmd_args)


@utf8_decode
def command_help(data, current_buffer, args):
    """
    /slack help [command]
    Print help for /slack commands.
    """
    if args:
        cmd = EVENTROUTER.cmds.get(args)
        if cmd:
            cmds = {args: cmd}
        else:
            w.prnt("", "Command not found: " + args)
            return w.WEECHAT_RC_OK
    else:
        cmds = EVENTROUTER.cmds
        w.prnt("", "\n{}".format(colorize_string("bold", "Slack commands:")))

    script_prefix = "{0}[{1}python{0}/{1}slack{0}]{1}".format(
        w.color("green"), w.color("reset")
    )

    for _, cmd in sorted(cmds.items()):
        name, cmd_args, description = parse_help_docstring(cmd)
        w.prnt(
            "",
            "\n{}  {} {}\n\n{}".format(
                script_prefix, colorize_string("white", name), cmd_args, description
            ),
        )
    return w.WEECHAT_RC_OK


@slack_buffer_required
@utf8_decode
def command_distracting(data, current_buffer, args):
    """
    /slack distracting
    Add or remove the current channel from distracting channels. You can hide
    or unhide these channels with /slack nodistractions.
    """
    channel = EVENTROUTER.weechat_controller.buffers[current_buffer]
    fullname = channel.formatted_name(style="long_default")
    if fullname in config.distracting_channels:
        config.distracting_channels.remove(fullname)
    else:
        config.distracting_channels.append(fullname)
    w.config_set_plugin("distracting_channels", ",".join(config.distracting_channels))
    return w.WEECHAT_RC_OK_EAT


@slack_buffer_required
@utf8_decode
def command_slash(data, current_buffer, args):
    """
    /slack slash /customcommand arg1 arg2 arg3
    Run a custom slack command.
    """
    channel = EVENTROUTER.weechat_controller.buffers[current_buffer]
    team = channel.team

    split_args = args.split(" ", 1)
    command = split_args[0]
    text = split_args[1] if len(split_args) > 1 else ""
    text_linkified = linkify_text(text, team, only_users=True)

    s = SlackRequest(
        team,
        "chat.command",
        {"command": command, "text": text_linkified, "channel": channel.identifier},
        channel=channel,
        metadata={"command": command, "command_args": text},
    )
    EVENTROUTER.receive(s)
    return w.WEECHAT_RC_OK_EAT


@slack_buffer_required
@utf8_decode
def command_mute(data, current_buffer, args):
    """
    /slack mute
    Toggle mute on the current channel.
    """
    channel = EVENTROUTER.weechat_controller.buffers[current_buffer]
    team = channel.team
    team.muted_channels ^= {channel.identifier}
    muted_str = "Muted" if channel.identifier in team.muted_channels else "Unmuted"
    team.buffer_prnt("{} channel {}".format(muted_str, channel.name))
    s = SlackRequest(
        team,
        "users.prefs.set",
        {"name": "muted_channels", "value": ",".join(team.muted_channels)},
        channel=channel,
    )
    EVENTROUTER.receive(s)
    return w.WEECHAT_RC_OK_EAT


@slack_buffer_required
@utf8_decode
def command_linkarchive(data, current_buffer, args):
    """
    /slack linkarchive [message_id]
    Place a link to the channel or message in the input bar.
    Use cursor or mouse mode to get the id.
    """
    channel = EVENTROUTER.weechat_controller.buffers[current_buffer]
    url = "https://{}/".format(channel.team.domain)

    if isinstance(channel, SlackChannelCommon):
        url += "archives/{}/".format(channel.identifier)
        if args:
            message = channel.message_from_hash_or_index(args)
            if message:
                url += "p{}{:0>6}".format(message.ts.majorstr(), message.ts.minorstr())
                if isinstance(message, SlackThreadMessage):
                    url += "?thread_ts={}&cid={}".format(
                        message.parent_message.ts, channel.identifier
                    )
            else:
                print_message_not_found_error(args)
                return w.WEECHAT_RC_OK_EAT

    w.command(current_buffer, "/input insert {}".format(url))
    return w.WEECHAT_RC_OK_EAT


command_linkarchive.completion = "%(threads) %-"


@utf8_decode
def command_nodistractions(data, current_buffer, args):
    """
    /slack nodistractions
    Hide or unhide all channels marked as distracting.
    """
    global hide_distractions
    hide_distractions = not hide_distractions
    channels = [
        channel
        for channel in EVENTROUTER.weechat_controller.buffers.values()
        if channel in config.distracting_channels
    ]
    for channel in channels:
        w.buffer_set(channel.channel_buffer, "hidden", str(int(hide_distractions)))
    return w.WEECHAT_RC_OK_EAT


@slack_buffer_required
@utf8_decode
def command_upload(data, current_buffer, args):
    """
    /slack upload <filename>
    Uploads a file to the current buffer.
    """
    channel = EVENTROUTER.weechat_controller.buffers[current_buffer]
    weechat_dir = w.info_get("weechat_data_dir", "") or w.info_get("weechat_dir", "")
    file_path = os.path.join(weechat_dir, os.path.expanduser(args))

    if channel.type == "team":
        w.prnt("", "ERROR: Can't upload a file to the team buffer")
        return w.WEECHAT_RC_ERROR

    if not os.path.isfile(file_path):
        unescaped_file_path = file_path.replace(r"\ ", " ")
        if os.path.isfile(unescaped_file_path):
            file_path = unescaped_file_path
        else:
            w.prnt("", "ERROR: Could not find file: {}".format(file_path))
            return w.WEECHAT_RC_ERROR

    post_data = {
        "channels": channel.identifier,
    }
    if isinstance(channel, SlackThreadChannel):
        post_data["thread_ts"] = channel.thread_ts

    request = SlackRequest(channel.team, "files.upload", post_data, channel=channel)
    options = request.options_as_cli_args() + [
        "-s",
        "-Ffile=@{}".format(file_path),
        request.request_string(),
    ]

    proxy_string = ProxyWrapper().curl()
    if proxy_string:
        options.append(proxy_string)

    options_hashtable = {"arg{}".format(i + 1): arg for i, arg in enumerate(options)}
    w.hook_process_hashtable(
        "curl", options_hashtable, config.slack_timeout, "upload_callback", ""
    )
    return w.WEECHAT_RC_OK_EAT


command_upload.completion = "%(filename) %-"


@utf8_decode
def upload_callback(data, command, return_code, out, err):
    if return_code != 0:
        w.prnt(
            "",
            "ERROR: Couldn't upload file. Got return code {}. Error: {}".format(
                return_code, err
            ),
        )
        return w.WEECHAT_RC_OK_EAT

    try:
        response = json.loads(out)
    except JSONDecodeError:
        w.prnt(
            "", "ERROR: Couldn't process response from file upload. Got: {}".format(out)
        )
        return w.WEECHAT_RC_OK_EAT

    if not response["ok"]:
        w.prnt("", "ERROR: Couldn't upload file. Error: {}".format(response["error"]))
    return w.WEECHAT_RC_OK_EAT


@utf8_decode
def away_command_cb(data, current_buffer, args):
    all_servers, message = re.match("^/away( -all)? ?(.*)", args).groups()
    if all_servers:
        team_buffers = [team.channel_buffer for team in EVENTROUTER.teams.values()]
    elif current_buffer in EVENTROUTER.weechat_controller.buffers:
        team_buffers = [current_buffer]
    else:
        return w.WEECHAT_RC_OK

    for team_buffer in team_buffers:
        if message:
            command_away(data, team_buffer, args)
        else:
            command_back(data, team_buffer, args)
    return w.WEECHAT_RC_OK


@slack_buffer_required
@utf8_decode
def command_away(data, current_buffer, args):
    """
    /slack away
    Sets your status as 'away'.
    """
    team = EVENTROUTER.weechat_controller.buffers[current_buffer].team
    s = SlackRequest(team, "users.setPresence", {"presence": "away"})
    EVENTROUTER.receive(s)
    return w.WEECHAT_RC_OK


@slack_buffer_required
@utf8_decode
def command_status(data, current_buffer, args):
    """
    /slack status [<emoji> [<status_message>]|-delete]
    Lets you set your Slack Status (not to be confused with away/here).
    Prints current status if no arguments are given, unsets the status if -delete is given.
    """
    team = EVENTROUTER.weechat_controller.buffers[current_buffer].team

    split_args = args.split(" ", 1)
    if not split_args[0]:
        profile = team.users[team.myidentifier].profile
        team.buffer_prnt(
            "Status: {} {}".format(
                replace_string_with_emoji(profile.get("status_emoji", "")),
                profile.get("status_text", ""),
            )
        )
        return w.WEECHAT_RC_OK

    emoji = "" if split_args[0] == "-delete" else split_args[0]
    text = split_args[1] if len(split_args) > 1 else ""
    new_profile = {"status_text": text, "status_emoji": emoji}

    s = SlackRequest(team, "users.profile.set", {"profile": new_profile})
    EVENTROUTER.receive(s)
    return w.WEECHAT_RC_OK


command_status.completion = "-delete|%(emoji) %-"


@utf8_decode
def line_event_cb(data, signal, hashtable):
    tags = hashtable["_chat_line_tags"].split(",")
    for tag in tags:
        if tag.startswith("slack_ts_"):
            ts = SlackTS(tag[9:])
            break
    else:
        return w.WEECHAT_RC_OK

    buffer_pointer = hashtable["_buffer"]
    channel = EVENTROUTER.weechat_controller.buffers.get(buffer_pointer)

    if isinstance(channel, SlackChannelCommon):
        message_hash = channel.hashed_messages[ts]
        if message_hash is None:
            return w.WEECHAT_RC_OK
        message_hash = "$" + message_hash

        if data == "auto":
            reaction = EMOJI_CHAR_OR_NAME_REGEX.match(hashtable["_chat_eol"])
            if reaction:
                emoji = reaction.group("emoji_char") or reaction.group("emoji_name")
                channel.send_change_reaction("toggle", message_hash, emoji)
            else:
                data = "message"
        if data == "message":
            w.command(buffer_pointer, "/cursor stop")
            w.command(buffer_pointer, "/input insert {}".format(message_hash))
        elif data == "delete":
            w.command(buffer_pointer, "/input send {}s///".format(message_hash))
        elif data == "linkarchive":
            w.command(buffer_pointer, "/cursor stop")
            w.command(buffer_pointer, "/slack linkarchive {}".format(message_hash))
        elif data == "reply":
            w.command(buffer_pointer, "/cursor stop")
            w.command(
                buffer_pointer, "/input insert /reply {}\\x20".format(message_hash)
            )
        elif data == "thread":
            w.command(buffer_pointer, "/cursor stop")
            w.command(buffer_pointer, "/thread {}".format(message_hash))
    return w.WEECHAT_RC_OK


@utf8_decode
def info_slack_message_cb(data, info_name, args):
    current_channel = EVENTROUTER.weechat_controller.buffers.get(w.current_buffer())
    message = current_channel.message_from_hash_or_index(args)

    if not message:
        print_message_not_found_error(args)
        return ""
    return message.render()


@slack_buffer_required
@utf8_decode
def command_back(data, current_buffer, args):
    """
    /slack back
    Sets your status as 'back'.
    """
    team = EVENTROUTER.weechat_controller.buffers[current_buffer].team
    s = SlackRequest(team, "users.setPresence", {"presence": "auto"})
    EVENTROUTER.receive(s)
    set_own_presence_active(team)
    return w.WEECHAT_RC_OK


@slack_buffer_required
@utf8_decode
def command_label(data, current_buffer, args):
    """
    /label [-full] <name>|-unset
    Rename a channel or thread buffer. Note that this is not permanent, it will
    only last as long as you keep the buffer and wee-slack open. Changes the
    short_name by default, and the name and full_name if you use the -full
    option. If you haven't set the short_name explicitly, that will also be
    changed when using the -full option. Use the -unset option to set it back
    to the default.
    """
    channel = EVENTROUTER.weechat_controller.buffers[current_buffer]

    split_args = args.split(None, 1)
    if split_args[0] == "-full":
        channel.label_full_drop_prefix = False
        channel.label_full = split_args[1] if split_args[1] != "-unset" else None
    else:
        channel.label_short_drop_prefix = False
        channel.label_short = args if args != "-unset" else None

    channel.rename()
    return w.WEECHAT_RC_OK


command_label.completion = "-unset|-full -unset %-"


@utf8_decode
def set_unread_cb(data, current_buffer, command):
    for channel in EVENTROUTER.weechat_controller.buffers.values():
        channel.mark_read()
    return w.WEECHAT_RC_OK


@slack_buffer_or_ignore
@utf8_decode
def set_unread_current_buffer_cb(data, current_buffer, command):
    channel = EVENTROUTER.weechat_controller.buffers[current_buffer]
    channel.mark_read()
    return w.WEECHAT_RC_OK


###### NEW EXCEPTIONS


class InvalidType(Exception):
    """
    Raised when we do type checking to ensure objects of the wrong
    type are not used improperly.
    """

    def __init__(self, type_str):
        super(InvalidType, self).__init__(type_str)


###### New but probably old and need to migrate


def closed_slack_debug_buffer_cb(data, buffer):
    global slack_debug
    slack_debug = None
    return w.WEECHAT_RC_OK


def create_slack_debug_buffer():
    global slack_debug, debug_string
    if slack_debug is None:
        debug_string = None
        slack_debug = w.buffer_new(
            "slack-debug", "", "", "closed_slack_debug_buffer_cb", ""
        )
        w.buffer_set(slack_debug, "print_hooks_enabled", "0")
        w.buffer_set(slack_debug, "notify", "0")
        w.buffer_set(slack_debug, "highlight_tags_restrict", "highlight_force")


def load_emoji():
    try:
        weechat_dir = w.info_get("weechat_data_dir", "") or w.info_get(
            "weechat_dir", ""
        )
        weechat_sharedir = w.info_get("weechat_sharedir", "")
        local_weemoji, global_weemoji = (
            "{}/weemoji.json".format(path) for path in (weechat_dir, weechat_sharedir)
        )
        path = (
            global_weemoji
            if os.path.exists(global_weemoji) and not os.path.exists(local_weemoji)
            else local_weemoji
        )
        with open(path, "r") as ef:
            emojis = json.loads(ef.read())
            if "emoji" in emojis:
                print_error(
                    "The weemoji.json file is in an old format. Please update it."
                )
            else:
                emoji_unicode = {key: value["unicode"] for key, value in emojis.items()}

                emoji_skin_tones = {
                    skin_tone["name"]: skin_tone["unicode"]
                    for emoji in emojis.values()
                    for skin_tone in emoji.get("skinVariations", {}).values()
                }

                emoji_with_skin_tones = chain(
                    emoji_unicode.items(), emoji_skin_tones.items()
                )
                emoji_with_skin_tones_reverse = {v: k for k, v in emoji_with_skin_tones}
                return emoji_unicode, emoji_with_skin_tones_reverse
    except:
        dbg("Couldn't load emoji list: {}".format(format_exc_only()), 5)
    return {}, {}


def parse_help_docstring(cmd):
    doc = textwrap.dedent(cmd.__doc__).strip().split("\n", 1)
    cmd_line = doc[0].split(None, 1)
    args = "".join(cmd_line[1:])
    return cmd_line[0], args, doc[1].strip()


def setup_hooks():
    w.bar_item_new("slack_typing_notice", "(extra)typing_bar_item_cb", "")
    w.bar_item_new("away", "(extra)away_bar_item_cb", "")
    w.bar_item_new("slack_away", "(extra)away_bar_item_cb", "")

    w.hook_timer(5000, 0, 0, "ws_ping_cb", "")
    w.hook_timer(1000, 0, 0, "typing_update_cb", "")
    w.hook_timer(1000, 0, 0, "buffer_list_update_callback", "")
    w.hook_timer(3000, 0, 0, "reconnect_callback", "EVENTROUTER")
    w.hook_timer(1000 * 60 * 5, 0, 0, "slack_never_away_cb", "")

    w.hook_signal("buffer_closing", "buffer_closing_callback", "")
    w.hook_signal("buffer_renamed", "buffer_renamed_cb", "")
    w.hook_signal("buffer_switch", "buffer_switch_callback", "")
    w.hook_signal("window_switch", "buffer_switch_callback", "")
    w.hook_signal("quit", "quit_notification_callback", "")
    if config.send_typing_notice:
        w.hook_signal("input_text_changed", "typing_notification_cb", "")

    command_help.completion = "|".join(EVENTROUTER.cmds.keys())
    completions = "||".join(
        "{} {}".format(name, getattr(cmd, "completion", ""))
        for name, cmd in EVENTROUTER.cmds.items()
    )

    w.hook_command(
        # Command name and description
        "slack",
        "Plugin to allow typing notification and sync of read markers for slack.com",
        # Usage
        "<command> [<command options>]",
        # Description of arguments
        "Commands:\n"
        + "\n".join(sorted(EVENTROUTER.cmds.keys()))
        + "\nUse /slack help <command> to find out more\n",
        # Completions
        completions,
        # Function name
        "slack_command_cb",
        "",
    )

    w.hook_command_run("/me", "me_command_cb", "")
    w.hook_command_run("/query", "join_query_command_cb", "")
    w.hook_command_run("/join", "join_query_command_cb", "")
    w.hook_command_run("/part", "part_command_cb", "")
    w.hook_command_run("/topic", "topic_command_cb", "")
    w.hook_command_run("/msg", "msg_command_cb", "")
    w.hook_command_run("/invite", "invite_command_cb", "")
    w.hook_command_run("/input complete_next", "complete_next_cb", "")
    w.hook_command_run("/input set_unread", "set_unread_cb", "")
    w.hook_command_run(
        "/input set_unread_current_buffer", "set_unread_current_buffer_cb", ""
    )
    w.hook_command_run("/buffer set unread", "set_unread_current_buffer_cb", "")
    w.hook_command_run("/away", "away_command_cb", "")
    w.hook_command_run("/whois", "whois_command_cb", "")

    for cmd_name in ["hide", "label", "rehistory", "reply", "thread"]:
        cmd = EVENTROUTER.cmds[cmd_name]
        _, args, description = parse_help_docstring(cmd)
        completion = getattr(cmd, "completion", "")
        w.hook_command(
            cmd_name, description, args, "", completion, "command_" + cmd_name, ""
        )

    w.hook_completion(
        "irc_channel_topic", "complete topic for slack", "topic_completion_cb", ""
    )
    w.hook_completion(
        "irc_channels", "complete channels for slack", "channel_completion_cb", ""
    )
    w.hook_completion(
        "irc_privates", "complete dms/mpdms for slack", "dm_completion_cb", ""
    )
    w.hook_completion("nicks", "complete @-nicks for slack", "nick_completion_cb", "")
    w.hook_completion(
        "threads", "complete thread ids for slack", "thread_completion_cb", ""
    )
    w.hook_completion(
        "usergroups", "complete @-usergroups for slack", "usergroups_completion_cb", ""
    )
    w.hook_completion("emoji", "complete :emoji: for slack", "emoji_completion_cb", "")

    w.key_bind(
        "mouse",
        {
            "@chat(python.*):button2": "hsignal:slack_mouse",
        },
    )
    w.key_bind(
        "cursor",
        {
            "@chat(python.*):D": "hsignal:slack_cursor_delete",
            "@chat(python.*):L": "hsignal:slack_cursor_linkarchive",
            "@chat(python.*):M": "hsignal:slack_cursor_message",
            "@chat(python.*):R": "hsignal:slack_cursor_reply",
            "@chat(python.*):T": "hsignal:slack_cursor_thread",
        },
    )

    w.hook_hsignal("slack_mouse", "line_event_cb", "auto")
    w.hook_hsignal("slack_cursor_delete", "line_event_cb", "delete")
    w.hook_hsignal("slack_cursor_linkarchive", "line_event_cb", "linkarchive")
    w.hook_hsignal("slack_cursor_message", "line_event_cb", "message")
    w.hook_hsignal("slack_cursor_reply", "line_event_cb", "reply")
    w.hook_hsignal("slack_cursor_thread", "line_event_cb", "thread")

    w.hook_info(
        "slack_message",
        "get contents of a slack message",
        "id or count to the message",
        "info_slack_message_cb",
        "",
    )

    # Hooks to fix/implement
    # w.hook_signal('buffer_opened', "buffer_opened_cb", "")
    # w.hook_signal('window_scrolled', "scrolled_cb", "")
    # w.hook_timer(3000, 0, 0, "slack_connection_persistence_cb", "")


##### END NEW


def dbg(message, level=0, main_buffer=False, fout=False):
    """
    send debug output to the slack-debug buffer and optionally write to a file.
    """
    # TODO: do this smarter
    if level >= config.debug_level:
        global debug_string
        message = "DEBUG: {}".format(message)
        if fout:
            with open("/tmp/debug.log", "a+") as log_file:
                log_file.writelines(message + "\n")
        if main_buffer:
            w.prnt("", "slack: " + message)
        else:
            if slack_debug and (not debug_string or debug_string in message):
                w.prnt(slack_debug, message)


###### Config code
class PluginConfig(object):
    Setting = namedtuple("Setting", ["default", "desc"])
    # Default settings.
    # These are, initially, each a (default, desc) tuple; the former is the
    # default value of the setting, in the (string) format that weechat
    # expects, and the latter is the user-friendly description of the setting.
    # At __init__ time these values are extracted, the description is used to
    # set or update the setting description for use with /help, and the default
    # value is used to set the default for any settings not already defined.
    # Following this procedure, the keys remain the same, but the values are
    # the real (python) values of the settings.
    default_settings = {
        "auto_open_threads": Setting(
            default="false",
            desc="Automatically open threads when mentioned or in"
            " response to own messages.",
        ),
        "background_load_all_history": Setting(
            default="true",
            desc="Load the history for all channels in the background when the script is loaded,"
            " rather than waiting until the buffer is switched to. You can set this to false if"
            " you experience performance issues, however that causes some loss of functionality,"
            " see known issues in the readme.",
        ),
        "channel_name_typing_indicator": Setting(
            default="true",
            desc="Change the prefix of a channel from # to > when someone is"
            " typing in it. Note that this will (temporarily) affect the sort"
            " order if you sort buffers by name rather than by number.",
        ),
        "color_buflist_muted_channels": Setting(
            default="darkgray", desc="Color to use for muted channels in the buflist"
        ),
        "color_deleted": Setting(
            default="red", desc="Color to use for deleted messages and files."
        ),
        "color_edited_suffix": Setting(
            default="095",
            desc="Color to use for (edited) suffix on messages that have been edited.",
        ),
        "color_reaction_suffix": Setting(
            default="darkgray",
            desc="Color to use for the [:wave:(@user)] suffix on messages that"
            " have reactions attached to them.",
        ),
        "color_reaction_suffix_added_by_you": Setting(
            default="blue", desc="Color to use for reactions that you have added."
        ),
        "color_thread_suffix": Setting(
            default="lightcyan",
            desc="Color to use for the [thread: XXX] suffix on messages that"
            ' have threads attached to them. The special value "multiple" can'
            " be used to use a different color for each thread.",
        ),
        "color_typing_notice": Setting(
            default="yellow", desc="Color to use for the typing notice."
        ),
        "colorize_attachments": Setting(
            default="prefix",
            desc='Whether to colorize attachment lines. Values: "prefix": Only colorize'
            ' the prefix, "all": Colorize the whole line, "none": Don\'t colorize.',
        ),
        "colorize_private_chats": Setting(
            default="false", desc="Whether to use nick-colors in DM windows."
        ),
        "debug_mode": Setting(
            default="false",
            desc="Open a dedicated buffer for debug messages and start logging"
            " to it. How verbose the logging is depends on log_level.",
        ),
        "debug_level": Setting(
            default="3",
            desc="Show only this level of debug info (or higher) when"
            " debug_mode is on. Lower levels -> more messages.",
        ),
        "distracting_channels": Setting(default="", desc="List of channels to hide."),
        "external_user_suffix": Setting(
            default="*", desc="The suffix appended to nicks to indicate external users."
        ),
        "files_download_location": Setting(
            default="",
            desc="If set, file attachments will be automatically downloaded"
            ' to this location. "%h" will be replaced by WeeChat home,'
            ' "~/.weechat" by default. Requires WeeChat 2.2 or newer.',
        ),
        "group_name_prefix": Setting(
            default="&",
            desc="The prefix of buffer names for groups (private channels).",
        ),
        "history_fetch_count": Setting(
            default="200",
            desc="The number of messages to fetch for each channel when fetching"
            " history, between 1 and 1000.",
        ),
        "link_previews": Setting(
            default="true", desc="Show previews of website content linked by teammates."
        ),
        "map_underline_to": Setting(
            default="_",
            desc="When sending underlined text to slack, use this formatting"
            ' character for it. The default ("_") sends it as italics. Use'
            ' "*" to send bold instead.',
        ),
        "muted_channels_activity": Setting(
            default="personal_highlights",
            desc="Control which activity you see from muted channels, either"
            " none, personal_highlights, all_highlights or all. none: Don't"
            " show any activity. personal_highlights: Only show personal"
            " highlights, i.e. not @channel and @here. all_highlights: Show"
            " all highlights, but not other messages. all: Show all activity,"
            " like other channels.",
        ),
        "notify_subscribed_threads": Setting(
            default="auto",
            desc="Control if you want to see a notification in the team buffer when a"
            " thread you're subscribed to receives a new message, either auto, true or"
            " false. auto means that you only get a notification if auto_open_threads"
            " and thread_messages_in_channel both are false. Defaults to auto.",
        ),
        "notify_usergroup_handle_updated": Setting(
            default="false",
            desc="Control if you want to see a notification in the team buffer when a"
            "usergroup's handle has changed, either true or false.",
        ),
        "never_away": Setting(
            default="false",
            desc='Poke Slack every five minutes so that it never marks you "away".',
        ),
        "record_events": Setting(
            default="false", desc="Log all traffic from Slack to disk as JSON."
        ),
        "render_bold_as": Setting(
            default="bold",
            desc="When receiving bold text from Slack, render it as this in WeeChat.",
        ),
        "render_emoji_as_string": Setting(
            default="false",
            desc="Render emojis as :emoji_name: instead of emoji characters. Enable this"
            " if your terminal doesn't support emojis, or set to 'both' if you want to"
            " see both renderings. Note that even though this is"
            " disabled by default, you need to place {}/blob/master/weemoji.json in your"
            " WeeChat directory to enable rendering emojis as emoji characters.".format(
                REPO_URL
            ),
        ),
        "render_italic_as": Setting(
            default="italic",
            desc="When receiving bold text from Slack, render it as this in WeeChat."
            ' If your terminal lacks italic support, consider using "underline" instead.',
        ),
        "send_typing_notice": Setting(
            default="true",
            desc="Alert Slack users when you are typing a message in the input bar "
            "(Requires reload)",
        ),
        "server_aliases": Setting(
            default="",
            desc="A comma separated list of `subdomain:alias` pairs. The alias"
            " will be used instead of the actual name of the slack (in buffer"
            " names, logging, etc). E.g `work:no_fun_allowed` would make your"
            " work slack show up as `no_fun_allowed` rather than `work.slack.com`.",
        ),
        "shared_name_prefix": Setting(
            default="%", desc="The prefix of buffer names for shared channels."
        ),
        "short_buffer_names": Setting(
            default="false",
            desc="Use `foo.#channel` rather than `foo.slack.com.#channel` as the"
            " internal name for Slack buffers.",
        ),
        "show_buflist_presence": Setting(
            default="true",
            desc="Display a `+` character in the buffer list for present users.",
        ),
        "show_reaction_nicks": Setting(
            default="false",
            desc="Display the name of the reacting user(s) alongside each reactji.",
        ),
        "slack_api_token": Setting(
            default="INSERT VALID KEY HERE!",
            desc="List of Slack API tokens, one per Slack instance you want to"
            " connect to; see the README for details on how to get these"
            " (note: content is evaluated, see /help eval).",
        ),
        "slack_timeout": Setting(
            default="20000", desc="How long (ms) to wait when communicating with Slack."
        ),
        "switch_buffer_on_join": Setting(
            default="true",
            desc="When /joining a channel, automatically switch to it as well.",
        ),
        "thread_broadcast_prefix": Setting(
            default="+ ",
            desc="Prefix to distinguish thread messages that were also sent "
            "to the channel, when thread_messages_in_channel is enabled.",
        ),
        "thread_messages_in_channel": Setting(
            default="false",
            desc="When enabled shows thread messages in the parent channel.",
        ),
        "unfurl_ignore_alt_text": Setting(
            default="false",
            desc='When displaying ("unfurling") links to channels/users/etc,'
            ' ignore the "alt text" present in the message and instead use the'
            " canonical name of the thing being linked to.",
        ),
        "unfurl_auto_link_display": Setting(
            default="both",
            desc='When displaying ("unfurling") links to channels/users/etc,'
            " determine what is displayed when the text matches the url"
            " without the protocol. This happens when Slack automatically"
            " creates links, e.g. from words separated by dots or email"
            ' addresses. Set it to "text" to only display the text written by'
            ' the user, "url" to only display the url or "both" (the default)'
            " to display both.",
        ),
        "unhide_buffers_with_activity": Setting(
            default="false",
            desc="When activity occurs on a buffer, unhide it even if it was"
            " previously hidden (whether by the user or by the"
            " distracting_channels setting).",
        ),
        "use_full_names": Setting(
            default="false",
            desc="Use full names as the nicks for all users. When this is"
            " false (the default), display names will be used if set, with a"
            " fallback to the full name if display name is not set.",
        ),
    }

    # Set missing settings to their defaults. Load non-missing settings from
    # weechat configs.
    def __init__(self):
        self.settings = {}
        # Set all descriptions, replace the values in the dict with the
        # default setting value rather than the (setting,desc) tuple.
        for key, (default, desc) in self.default_settings.items():
            w.config_set_desc_plugin(key, desc)
            self.settings[key] = default

        # Migrate settings from old versions of Weeslack...
        self.migrate()
        # ...and then set anything left over from the defaults.
        for key, default in self.settings.items():
            if not w.config_get_plugin(key):
                w.config_set_plugin(key, default)
        self.config_changed(None, None, None)

    def __str__(self):
        return "".join(
            [x + "\t" + str(self.settings[x]) + "\n" for x in self.settings.keys()]
        )

    def config_changed(self, data, full_key, value):
        if full_key is None:
            for key in self.settings:
                self.settings[key] = self.fetch_setting(key)
        else:
            key = full_key.replace(CONFIG_PREFIX + ".", "")
            self.settings[key] = self.fetch_setting(key)

        if (
            full_key is None or full_key == CONFIG_PREFIX + ".debug_mode"
        ) and self.debug_mode:
            create_slack_debug_buffer()
        return w.WEECHAT_RC_OK

    def fetch_setting(self, key):
        try:
            return getattr(self, "get_" + key)(key)
        except AttributeError:
            # Most settings are on/off, so make get_boolean the default
            return self.get_boolean(key)
        except:
            # There was setting-specific getter, but it failed.
            print(format_exc_tb())
            return self.settings[key]

    def __getattr__(self, key):
        try:
            return self.settings[key]
        except KeyError:
            raise AttributeError(key)

    def get_boolean(self, key):
        return w.config_string_to_boolean(w.config_get_plugin(key))

    def get_string(self, key):
        return w.config_get_plugin(key)

    def get_int(self, key):
        return int(w.config_get_plugin(key))

    def is_default(self, key):
        default = self.default_settings.get(key).default
        return w.config_get_plugin(key) == default

    get_color_buflist_muted_channels = get_string
    get_color_deleted = get_string
    get_color_edited_suffix = get_string
    get_color_reaction_suffix = get_string
    get_color_reaction_suffix_added_by_you = get_string
    get_color_thread_suffix = get_string
    get_color_typing_notice = get_string
    get_colorize_attachments = get_string
    get_debug_level = get_int
    get_external_user_suffix = get_string
    get_files_download_location = get_string
    get_group_name_prefix = get_string
    get_history_fetch_count = get_int
    get_map_underline_to = get_string
    get_muted_channels_activity = get_string
    get_thread_broadcast_prefix = get_string
    get_render_bold_as = get_string
    get_render_italic_as = get_string
    get_shared_name_prefix = get_string
    get_slack_timeout = get_int
    get_unfurl_auto_link_display = get_string

    def get_distracting_channels(self, key):
        return [x.strip() for x in w.config_get_plugin(key).split(",") if x]

    def get_server_aliases(self, key):
        alias_list = w.config_get_plugin(key)
        return dict(item.split(":") for item in alias_list.split(",") if ":" in item)

    def get_slack_api_token(self, key):
        token = w.config_get_plugin("slack_api_token")
        if token.startswith("${sec.data"):
            return w.string_eval_expression(token, {}, {}, {})
        else:
            return token

    def get_string_or_boolean(self, key, *valid_strings):
        value = w.config_get_plugin(key)
        if value in valid_strings:
            return value
        return w.config_string_to_boolean(value)

    def get_notify_subscribed_threads(self, key):
        return self.get_string_or_boolean(key, "auto")

    def get_render_emoji_as_string(self, key):
        return self.get_string_or_boolean(key, "both")

    def migrate(self):
        """
        This is to migrate the extension name from slack_extension to slack
        """
        if not w.config_get_plugin("migrated"):
            for k in self.settings.keys():
                if not w.config_is_set_plugin(k):
                    p = w.config_get("{}_extension.{}".format(CONFIG_PREFIX, k))
                    data = w.config_string(p)
                    if data != "":
                        w.config_set_plugin(k, data)
            w.config_set_plugin("migrated", "true")

        old_thread_color_config = w.config_get_plugin("thread_suffix_color")
        new_thread_color_config = w.config_get_plugin("color_thread_suffix")
        if old_thread_color_config and not new_thread_color_config:
            w.config_set_plugin("color_thread_suffix", old_thread_color_config)


def config_server_buffer_cb(data, key, value):
    for team in EVENTROUTER.teams.values():
        team.buffer_merge(value)
    return w.WEECHAT_RC_OK


# to Trace execution, add `setup_trace()` to startup
# and  to a function and sys.settrace(trace_calls)  to a function
def setup_trace():
    global f
    now = time.time()
    f = open("{}/{}-trace.json".format(RECORD_DIR, now), "w")


def trace_calls(frame, event, arg):
    global f
    if event != "call":
        return
    co = frame.f_code
    func_name = co.co_name
    if func_name == "write":
        # Ignore write() calls from print statements
        return
    func_line_no = frame.f_lineno
    func_filename = co.co_filename
    caller = frame.f_back
    caller_line_no = caller.f_lineno
    caller_filename = caller.f_code.co_filename
    print(
        "Call to %s on line %s of %s from line %s of %s"
        % (func_name, func_line_no, func_filename, caller_line_no, caller_filename),
        file=f,
    )
    f.flush()
    return


def get_rtm_connect_request(token, retries=3, team=None, callback=None):
    return SlackRequest(
        team,
        "rtm.connect",
        {"batch_presence_aware": 1},
        retries=retries,
        token=token,
        callback=callback,
    )


def get_next_page(response_json):
    next_cursor = response_json.get("response_metadata", {}).get("next_cursor")
    if next_cursor:
        request = response_json["wee_slack_request_metadata"]
        request.post_data["cursor"] = next_cursor
        request.reset()
        EVENTROUTER.receive(request)
        return True
    else:
        return False


def initiate_connection(token):
    initial_data = {
        "channels": [],
        "members": [],
        "usergroups": [],
        "remaining": {
            "channels": 2,
            "members": 1,
            "usergroups": 1,
            "prefs": 1,
            "presence": 1,
        },
        "errors": [],
    }

    def handle_initial(data_type):
        def handle(response_json, eventrouter, team, channel, metadata):
            if not response_json["ok"]:
                if response_json["error"] == "user_is_restricted":
                    w.prnt(
                        "",
                        "You are a restricted user in this team, "
                        "{} not loaded".format(data_type),
                    )
                else:
                    initial_data["errors"].append(
                        "{}: {}".format(data_type, response_json["error"])
                    )
                initial_data["remaining"][data_type] -= 1
                create_team(token, initial_data)
                return

            initial_data[data_type].extend(response_json[data_type])

            if not get_next_page(response_json):
                initial_data["remaining"][data_type] -= 1
                create_team(token, initial_data)

        return handle

    def handle_prefs(response_json, eventrouter, team, channel, metadata):
        if not response_json["ok"]:
            initial_data["errors"].append("prefs: {}".format(response_json["error"]))
            initial_data["remaining"]["prefs"] -= 1
            create_team(token, initial_data)
            return

        initial_data["prefs"] = response_json["prefs"]
        initial_data["remaining"]["prefs"] -= 1
        create_team(token, initial_data)

    def handle_getPresence(response_json, eventrouter, team, channel, metadata):
        if not response_json["ok"]:
            initial_data["errors"].append("presence: {}".format(response_json["error"]))
            initial_data["remaining"]["presence"] -= 1
            create_team(token, initial_data)
            return

        initial_data["presence"] = response_json
        initial_data["remaining"]["presence"] -= 1
        create_team(token, initial_data)

    s = SlackRequest(
        None,
        "conversations.list",
        {
            "exclude_archived": True,
            "types": "public_channel,private_channel,im",
            "limit": 1000,
        },
        token=token,
        callback=handle_initial("channels"),
    )
    EVENTROUTER.receive(s)
    s = SlackRequest(
        None,
        "conversations.list",
        {
            "exclude_archived": True,
            "types": "mpim",
            "limit": 1000,
        },
        token=token,
        callback=handle_initial("channels"),
    )
    EVENTROUTER.receive(s)
    s = SlackRequest(
        None,
        "users.list",
        {"limit": 1000},
        token=token,
        callback=handle_initial("members"),
    )
    EVENTROUTER.receive(s)
    s = SlackRequest(
        None,
        "usergroups.list",
        {"include_users": True},
        token=token,
        callback=handle_initial("usergroups"),
    )
    EVENTROUTER.receive(s)
    s = SlackRequest(
        None,
        "users.prefs.get",
        token=token,
        callback=handle_prefs,
    )
    EVENTROUTER.receive(s)
    s = SlackRequest(
        None,
        "users.getPresence",
        token=token,
        callback=handle_getPresence,
    )
    EVENTROUTER.receive(s)


def create_channel_from_info(eventrouter, channel_info, team, myidentifier, users):
    if channel_info.get("is_im"):
        return SlackDMChannel(eventrouter, users, team=team, **channel_info)
    elif channel_info.get("is_mpim"):
        return SlackMPDMChannel(
            eventrouter, users, myidentifier, team=team, **channel_info
        )
    elif channel_info.get("is_shared"):
        return SlackSharedChannel(eventrouter, team=team, **channel_info)
    elif channel_info.get("is_private"):
        return SlackPrivateChannel(eventrouter, team=team, **channel_info)
    else:
        return SlackChannel(eventrouter, team=team, **channel_info)


def create_team(token, initial_data):
    if not any(initial_data["remaining"].values()):
        if initial_data["errors"]:
            w.prnt(
                "",
                "ERROR: Failed connecting to Slack with token {}: {}".format(
                    token_for_print(token), ", ".join(initial_data["errors"])
                ),
            )
            if not re.match(r"^xo\w\w(-\d+){3}-[0-9a-f]+(:.*)?$", token):
                w.prnt(
                    "",
                    "ERROR: Token does not look like a valid Slack token. "
                    "Ensure it is a valid token and not just a OAuth code.",
                )

            return

        def handle_rtmconnect(response_json, eventrouter, team, channel, metadata):
            if not response_json["ok"]:
                print(response_json["error"])
                return

            team_id = response_json["team"]["id"]
            myidentifier = response_json["self"]["id"]

            users = {}
            bots = {}
            for member in initial_data["members"]:
                if member.get("is_bot"):
                    bots[member["id"]] = SlackBot(team_id, **member)
                else:
                    users[member["id"]] = SlackUser(team_id, **member)

            self_nick = nick_from_profile(
                users[myidentifier].profile, response_json["self"]["name"]
            )

            channels = {}
            for channel_info in initial_data["channels"]:
                channels[channel_info["id"]] = create_channel_from_info(
                    eventrouter, channel_info, None, myidentifier, users
                )

            subteams = {}
            for usergroup in initial_data["usergroups"]:
                is_member = myidentifier in usergroup["users"]
                subteams[usergroup["id"]] = SlackSubteam(
                    team_id, is_member=is_member, **usergroup
                )

            manual_presence = (
                "away" if initial_data["presence"]["manual_away"] else "active"
            )

            team_info = {
                "id": team_id,
                "name": response_json["team"]["id"],
                "domain": response_json["team"]["domain"],
            }

            team_hash = SlackTeam.generate_team_hash(
                team_id, response_json["team"]["domain"]
            )
            if not eventrouter.teams.get(team_hash):
                team = SlackTeam(
                    eventrouter,
                    token,
                    team_hash,
                    response_json["url"],
                    team_info,
                    subteams,
                    self_nick,
                    myidentifier,
                    manual_presence,
                    users,
                    bots,
                    channels,
                    muted_channels=initial_data["prefs"]["muted_channels"],
                    highlight_words=initial_data["prefs"]["highlight_words"],
                )
                eventrouter.register_team(team)
                team.connect()
            else:
                team = eventrouter.teams.get(team_hash)
                if team.myidentifier != myidentifier:
                    print_error(
                        "The Slack team {} has tokens for two different users, this is not supported. The "
                        "token {} is for user {}, and the token {} is for user {}. Please remove one of "
                        "them.".format(
                            team.team_info["name"],
                            token_for_print(team.token),
                            team.nick,
                            token_for_print(token),
                            self_nick,
                        )
                    )
                else:
                    print_error(
                        "Ignoring duplicate Slack tokens for the same team ({}) and user ({}). The two "
                        "tokens are {} and {}.".format(
                            team.team_info["name"],
                            team.nick,
                            token_for_print(team.token),
                            token_for_print(token),
                        ),
                        warning=True,
                    )

        s = get_rtm_connect_request(token, callback=handle_rtmconnect)
        EVENTROUTER.receive(s)


if __name__ == "__main__":
    w = WeechatWrapper(weechat)

    if w.register(
        SCRIPT_NAME,
        SCRIPT_AUTHOR,
        SCRIPT_VERSION,
        SCRIPT_LICENSE,
        SCRIPT_DESC,
        "script_unloaded",
        "",
    ):
        weechat_version = int(w.info_get("version_number", "") or 0)
        weechat_upgrading = w.info_get("weechat_upgrading", "")

        completion_get_string = (
            w.hook_completion_get_string
            if weechat_version < 0x2090000
            else w.completion_get_string
        )

        completion_list_add = (
            w.hook_completion_list_add
            if weechat_version < 0x2090000
            else w.completion_list_add
        )

        if weechat_version < 0x2020000:
            w.prnt(
                "",
                "\nERROR: WeeChat version 2.2+ is required to use {}.\n\n".format(
                    SCRIPT_NAME
                ),
            )
        elif weechat_upgrading == "1":
            w.prnt(
                "",
                "NOTE: wee-slack will not work after running /upgrade until it's"
                " reloaded. Please run `/python reload slack` to continue using it. You"
                " will not receive any new messages in wee-slack buffers until doing this.",
            )
        else:
            EVENTROUTER = EventRouter()

            receive_httprequest_callback = EVENTROUTER.receive_httprequest_callback
            receive_ws_callback = EVENTROUTER.receive_ws_callback

            # Global var section
            slack_debug = None
            config = PluginConfig()
            config_changed_cb = config.config_changed

            typing_timer = time.time()

            hide_distractions = False

            w.hook_config(CONFIG_PREFIX + ".*", "config_changed_cb", "")
            w.hook_config("irc.look.server_buffer", "config_server_buffer_cb", "")
            if weechat_version < 0x2090000:
                w.hook_modifier("input_text_for_buffer", "input_text_for_buffer_cb", "")

            EMOJI, EMOJI_WITH_SKIN_TONES_REVERSE = load_emoji()
            setup_hooks()

            if config.record_events:
                EVENTROUTER.record()

            hdata = Hdata(w)

            auto_connect = weechat.info_get("auto_connect", "") != "0"

            if auto_connect:
                tokens = [
                    token.strip()
                    for token in config.slack_api_token.split(",")
                    if token
                ]
                w.prnt(
                    "",
                    "Connecting to {} slack team{}.".format(
                        len(tokens), "" if len(tokens) == 1 else "s"
                    ),
                )
                for t in tokens:
                    if t.startswith("xoxc-") and ":" not in t:
                        w.prnt(
                            "",
                            "{}When using an xoxc token, you need to also provide the d cookie in the format token:cookie".format(
                                w.prefix("error")
                            ),
                        )
                    else:
                        initiate_connection(t)
                EVENTROUTER.handle_next()