-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbot.py
2959 lines (2657 loc) · 126 KB
/
bot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
""""
Copyright © twilsonco 2020
Description:
This is a discord bot to manage torrent transfers through the Transmission transmissionrpc python library.
Version: 1.2
"""
import discord
import asyncio
import aiohttp
import json
from json import dumps, load
import subprocess
from discord.ext.commands import Bot
from discord.ext import commands
from platform import python_version
import os
import sys
from os.path import expanduser, join, exists, isdir, isfile
import shutil
import re
import datetime
import pytz
import platform
import secrets
import transmissionrpc
import logging
from logging import handlers
import base64
import random
from enum import Enum
# BEGIN USER CONFIGURATION
CONFIG_DIR = os.path.dirname(os.path.realpath(__file__))
"""
Bot configuration is done with a config.json file.
"""
CONFIG = None
TSCLIENT_CONFIG = None
# logging.basicConfig(format='%(asctime)s %(message)s',filename=join(expanduser("~"),'ts_scripts.log'))
logName = join(CONFIG_DIR,'transmissionbot.log')
logging.basicConfig(format='%(asctime)s %(message)s',filename=join(CONFIG_DIR,'transmissionbot.log'))
logger = logging.getLogger('transmission_bot')
logger.setLevel(logging.DEBUG) # set according to table below. Events with values LESS than the set value will not be logged
"""
Level Numeric value
__________________________
CRITICAL 50
ERROR 40
WARNING 30
INFO 20
DEBUG 10
NOTSET 0
"""
fh = logging.handlers.RotatingFileHandler(logName, backupCount=5)
if os.path.isfile(logName): # log already exists, roll over!
fh.doRollover()
fmt = logging.Formatter('%(asctime)s [%(threadName)14s:%(filename)8s:%(lineno)5s - %(funcName)20s()] %(levelname)8s: %(message)s')
fh.setFormatter(fmt)
logger.addHandler(fh)
# END USER CONFIGURATION
# for storing config and transfer list
CONFIG_JSON = join(CONFIG_DIR, "config.json")
LOCK_FILE = join(CONFIG_DIR, "lock")
DEFAULT_REASON="TransmissionBot"
def lock(lockfile=LOCK_FILE):
""" Wait for LOCK_FILE to not exist, then create it to lock """
from time import sleep
from random import random
from pathlib import Path
lock_file = Path(lockfile)
logger.debug("Creating lock file '{}'".format(lockfile))
while lock_file.is_file():
logger.debug("Config file locked, waiting...")
sleep(0.5)
logger.debug("Lock file created '{}'".format(lockfile))
lock_file.touch()
def unlock(lockfile=LOCK_FILE):
""" Delete LOCK_FILE """
from pathlib import Path
lock_file = Path(lockfile)
logger.debug("Removing lock file '{}'".format(lockfile))
if lock_file.is_file():
lock_file.unlink()
logger.debug("Lock file removed '{}'".format(lockfile))
else:
logger.debug("Lock file didn't exist '{}'".format(lockfile))
def mkdir_p(path):
"""mimics the standard mkdir -p functionality when creating directories
:param path:
:return:
"""
try:
makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and isdir(path):
pass
else:
raise
def generate_json(json_data=None, path=None, overwrite=False):
"""Generate a new config file based on the value of the CONFIG global variable.
This function will cause a fatal error if trying to overwrite an exiting file
without setting overwrite to True.
:param overwrite: Overwrite existing config file
:type overwrite: bool
:return: Create status
:rtype: bool
"""
if not path or not json_data:
return False
if exists(path) and not overwrite:
logger.fatal("JSON file exists already! (Set overwite option to overwrite)")
return False
if not exists(os.path.dirname(path)):
mkdir_p(os.path.dirname(path))
try:
lock()
if exists(path):
# first backup the existing file
shutil.copy2(path,"{}.bak".format(path))
try:
with open(path, 'w') as cf:
cf.write(dumps(json_data, sort_keys=True, indent=4, separators=(',', ': ')))
except Exception as e:
logger.error("Exception when writing JSON file {}, reverting to backup: {}".format(path,e))
shutil.move("{}.bak".format(path), path)
else:
with open(path, 'w') as cf:
cf.write(dumps(json_data, sort_keys=True, indent=4, separators=(',', ': ')))
except Exception as e:
logger.fatal("Exception when writing JSON file: {}".format(e))
finally:
unlock()
return True
def load_json(path=None):
"""Load a config file from disk using the default location if it exists. If path is defined
it will be used instead of the default path.
:param path: Optional path to config file
:type path: str
:return: Load status
:rtype: bool
"""
if not path:
return False
if exists(path):
jsonContents = load(open(path))
logger.debug("Loaded JSON file: {}".format(path))
return jsonContents
return False
CONFIG = load_json(CONFIG_JSON) if exists(CONFIG_JSON) else None # will be read from CONFIG_JSON
class OutputMode(Enum):
AUTO = 1
DESKTOP = 2
MOBILE = 3
OUTPUT_MODE = OutputMode.AUTO
REPEAT_MSG_IS_PINNED = False
REPEAT_MSGS = {}
# REPEAT_MSGS[msg_key] = {
# 'msgs':msg_list,
# 'command':command,
# 'context':context,
# 'content':content,
# 'pin_to_bottom':False,
# 'reprint': False,
# 'freq':CONFIG['repeat_freq'],
# 'timeout':CONFIG['repeat_timeout'],
# 'timeout_verbose':REPEAT_TIMEOUT,
# 'cancel_verbose':CONFIG['repeat_cancel_verbose'],
# 'start_time':datetime.datetime.now(),
# 'do_repeat':True
# }
TORRENT_JSON = join(CONFIG_DIR, "transfers.json")
# list of transfer information to be stored in a separate file, used for
# checking for transfer state stanges for the notification system
# here's the structure, a dict with a dict for each transfer with select information.
# this will be a local var, since it's only needed in the function that checks for changes.
# TORRENT_LIST = {
# 'hashString':{
# 'name':t.name,
# 'error':t.error,
# 'errorString':t.errorString,
# 'status':t.status,
# 'isStalled':t.isStalled,
# 'progress':t.progress
# }
# }
TORRENT_ADDED_USERS = {}
TORRENT_NOTIFIED_USERS = {}
TORRENT_OPTOUT_USERS = {}
async def determine_prefix(bot, message):
return CONFIG['bot_prefix']
client = Bot(command_prefix=determine_prefix)
TSCLIENT = None
MAKE_CLIENT_FAILED = False
# Begin transmissionrpc functions, lovingly taken from https://github.com/leighmacdonald/transmission_scripts
filter_names = ( # these are the filters accepted by transmissionrpc
"all",
"active",
"downloading",
"seeding",
"stopped",
"finished"
)
filter_names_extra = ( # these are extra filters I've added
"stalled",
"private",
"public",
"error",
'err_none',
'err_tracker_warn',
'err_tracker_error',
'err_local',
'verifying',
'queued',
"running" # running means a non-zero transfer rate, not to be confused with "active"
)
filter_names_full = filter_names + filter_names_extra
sort_names = (
"id",
"progress",
"name",
"size",
"ratio",
"speed",
"speed_up",
"speed_down",
"status",
"queue",
"age",
"activity"
)
class TSClient(transmissionrpc.Client):
""" Basic subclass of the standard transmissionrpc client which provides some simple
helper functionality.
"""
def get_torrents_by(self, sort_by=None, filter_by=None, reverse=False, filter_regex=None, tracker_regex=None, id_list=None, num_results=None):
"""This method will call get_torrents and then perform any sorting or filtering
actions requested on the returned torrent set.
:param sort_by: Sort key which must exist in `Sort.names` to be valid;
:type sort_by: str
:param filter_by:
:type filter_by: str
:param reverse:
:return: Sorted and filter torrent list
:rtype: transmissionrpc.Torrent[]
"""
if id_list:
torrents = self.get_torrents(ids=id_list)
else:
torrents = self.get_torrents()
if filter_regex:
regex = re.compile(filter_regex, re.IGNORECASE)
torrents = [tor for tor in torrents if regex.search(tor.name)]
if tracker_regex:
regex = re.compile(tracker_regex, re.IGNORECASE)
torrents = [tor for tor in torrents if regex.search(str([t['announce'] for t in tor.trackers]))]
if filter_by:
for f in filter_by.split():
if f == "active":
torrents = [t for t in torrents if not t.isStalled and t.rateDownload + t.rateUpload == 0]
elif f in filter_names:
torrents = filter_torrents_by(torrents, key=getattr(Filter, filter_by))
elif f == "verifying":
torrents = [t for t in torrents if "check" in t.status]
elif f == "queued":
torrents = [t for t in torrents if "load pending" in t.status]
elif f == "stalled":
torrents = [t for t in torrents if t.isStalled]
elif f == "private":
torrents = [t for t in torrents if t.isPrivate]
elif f == "public":
torrents = [t for t in torrents if not t.isPrivate]
elif f == "error":
torrents = [t for t in torrents if t.error != 0]
elif f == "err_none":
torrents = [t for t in torrents if t.error == 0]
elif f == "err_tracker_warn":
torrents = [t for t in torrents if t.error == 1]
elif f == "err_tracker_error":
torrents = [t for t in torrents if t.error == 2]
elif f == "err_local":
torrents = [t for t in torrents if t.error == 3]
elif f == "running":
torrents = [t for t in torrents if t.rateDownload + t.rateUpload > 0]
else:
continue
if sort_by is None:
if "downloading" in filter_by or "seeding" in filter_by or "running" in filter_by:
sort_by = "speed"
elif "stopped" in filter_by or "finished" in filter_by:
sort_by = "ratio"
if sort_by:
torrents = sort_torrents_by(torrents, key=getattr(Sort, sort_by), reverse=reverse)
if num_results and num_results < len(torrents):
torrents = torrents[-num_results:]
return torrents
def make_client():
""" Create a new transmission RPC client
If you want to parse more than the standard CLI arguments, like when creating a new customized
script, you can append your options to the argument parser.
:param args: Optional CLI args passed in.
:return:
"""
logger.debug("Making new TSClient")
global MAKE_CLIENT_FAILED
tsclient = None
try:
lock()
tsclient = TSClient(
TSCLIENT_CONFIG['host'],
port=TSCLIENT_CONFIG['port'],
user=TSCLIENT_CONFIG['user'],
password=TSCLIENT_CONFIG['password']
)
MAKE_CLIENT_FAILED = False
logger.debug("Made new TSClient")
except Exception as e:
logger.error("Failed to make TS client: {}".format(e))
MAKE_CLIENT_FAILED = True
finally:
unlock()
return tsclient
def reload_client():
global TSCLIENT
TSCLIENT = make_client()
class Filter(object):
"""A set of filtering operations that can be used against a list of torrent objects"""
# names = (
# "all",
# "active",
# "downloading",
# "seeding",
# "stopped",
# "finished"
# )
names = filter_names
@staticmethod
def all(t):
return t
@staticmethod
def active(t):
return t.rateUpload > 0 or t.rateDownload > 0
@staticmethod
def downloading(t):
return t.status == 'downloading'
@staticmethod
def seeding(t):
return t.status == 'seeding'
@staticmethod
def stopped(t):
return t.status == 'stopped'
@staticmethod
def finished(t):
return t.status == 'finished'
@staticmethod
def lifetime(t):
return t.date_added
def filter_torrents_by(torrents, key=Filter.all):
"""
:param key:
:param torrents:
:return: []transmissionrpc.Torrent
"""
filtered_torrents = []
for torrent in torrents:
if key(torrent):
filtered_torrents.append(torrent)
return filtered_torrents
class Sort(object):
""" Defines methods for sorting torrent sequences """
# names = (
# "id",
# "progress",
# "name",
# "size",
# "ratio",
# "speed",
# "speed_up",
# "speed_down",
# "status",
# "queue",
# "age",
# "activity"
# )
names = sort_names
@staticmethod
def activity(t):
return t.date_active
@staticmethod
def age(t):
return t.date_added
@staticmethod
def queue(t):
return t.queue_position
@staticmethod
def status(t):
return t.status
@staticmethod
def progress(t):
return t.progress
@staticmethod
def name(t):
return t.name.lower()
@staticmethod
def size(t):
return -t.totalSize
@staticmethod
def id(t):
return t.id
@staticmethod
def ratio(t):
return t.ratio
@staticmethod
def speed(t):
return t.rateUpload + t.rateDownload
@staticmethod
def speed_up(t):
return t.rateUpload
@staticmethod
def speed_down(t):
return t.rateDownload
def sort_torrents_by(torrents, key=Sort.name, reverse=False):
return sorted(torrents, key=key, reverse=reverse)
# def print_torrent_line(torrent, colourize=True):
# name = torrent.name
# progress = torrent.progress / 100.0
# print("[{}] [{}] {} {}[{}/{}]{} ra: {} up: {} dn: {} [{}]".format(
# white_on_blk(torrent.id),
# find_tracker(torrent),
# print_pct(torrent) if colourize else name.decode("latin-1"),
# white_on_blk(""),
# red_on_blk("{:.0%}".format(progress)) if progress < 1 else green_on_blk("{:.0%}".format(progress)),
# magenta_on_blk(natural_size(torrent.totalSize)),
# white_on_blk(""),
# red_on_blk(torrent.ratio) if torrent.ratio < 1.0 else green_on_blk(torrent.ratio),
# green_on_blk(natural_size(float(torrent.rateUpload)) + "/s") if torrent.rateUpload else "0.0 kB/s",
# green_on_blk(natural_size(float(torrent.rateDownload)) + "/s") if torrent.rateDownload else "0.0 kB/s",
# yellow_on_blk(torrent.status)
# ))
def remove_torrent(torrent, reason=DEFAULT_REASON, delete_files=False):
""" Remove a torrent from the client stopping it first if its in a started state.
:param client: Transmission RPC Client
:type client: transmissionrpc.Client
:param torrent: Torrent instance to remove
:type torrent: transmissionrpc.Torrent
:param reason: Reason for removal
:type reason: str
:param dry_run: Do a dry run without actually running any commands
:type dry_run: bool
:return:
"""
if torrent.status != "stopped":
if not CONFIG['dryrun']:
TSCLIENT.stop_torrent(torrent.hashString)
if not CONFIG['dryrun']:
TSCLIENT.remove_torrent(torrent.hashString, delete_data=delete_files)
logger.info("Removed: {} {}\n\tReason: {}\n\tDry run: {}, Delete files: {}".format(torrent.name, torrent.hashString, reason, CONFIG['dryrun'],delete_files))
def remove_torrents(torrents, reason=DEFAULT_REASON, delete_files=False):
""" Remove a torrent from the client stopping it first if its in a started state.
:param client: Transmission RPC Client
:type client: transmissionrpc.Client
:param torrent: Torrent instance to remove
:type torrent: transmissionrpc.Torrent
:param reason: Reason for removal
:type reason: str
:param dry_run: Do a dry run without actually running any commands
:type dry_run: bool
:return:
"""
for torrent in torrents:
remove_torrent(torrent, reason=reason, delete_files=delete_files)
def stop_torrents(torrents=[], reason=DEFAULT_REASON):
""" Stop (pause) a list of torrents from the client.
:param client: Transmission RPC Client
:type client: transmissionrpc.Client
:param torrent: Torrent instance to remove
:type torrent: transmissionrpc.Torrent
:param reason: Reason for removal
:type reason: str
:param dry_run: Do a dry run without actually running any commands
:type dry_run: bool
:return:
"""
for torrent in (torrents if len(torrents) > 0 else TSCLIENT.get_torrents()):
if torrent.status not in ["stopped","finished"]:
if not CONFIG['dryrun']:
TSCLIENT.stop_torrent(torrent.hashString)
logger.info("Paused: {} {}\n\tReason: {}\n\tDry run: {}".format(torrent.name, torrent.hashString, reason, CONFIG['dryrun']))
def resume_torrents(torrents=[], reason=DEFAULT_REASON, start_all=False):
""" Stop (pause) a list of torrents from the client.
:param client: Transmission RPC Client
:type client: transmissionrpc.Client
:param torrent: Torrent instance to remove
:type torrent: transmissionrpc.Torrent
:param reason: Reason for removal
:type reason: str
:param dry_run: Do a dry run without actually running any commands
:type dry_run: bool
:return:
"""
if start_all:
if not CONFIG['dryrun']:
TSCLIENT.start_all()
logger.info("Resumed: all transfers\n\tReason: {}\n\tDry run: {}".format(reason, CONFIG['dryrun']))
else:
for torrent in (torrents if len(torrents) > 0 else TSCLIENT.get_torrents()):
if torrent.status == "stopped":
if not CONFIG['dryrun']:
TSCLIENT.start_torrent(torrent.hashString)
logger.info("Resumed: {} {}\n\tReason: {}\n\tDry run: {}".format(torrent.name, torrent.hashString, reason, CONFIG['dryrun']))
def verify_torrents(torrents=[]):
""" Verify a list of torrents from the client.
:param client: Transmission RPC Client
:type client: transmissionrpc.Client
:param torrent: Torrent instance to remove
:type torrent: transmissionrpc.Torrent
:type reason: str
:param dry_run: Do a dry run without actually running any commands
:type dry_run: bool
:return:
"""
for torrent in (torrents if len(torrents) > 0 else TSCLIENT.get_torrents()):
if not CONFIG['dryrun']:
TSCLIENT.verify_torrent(torrent.hashString)
logger.info("Verified: {} {}\n\tDry run: {}".format(torrent.name, torrent.hashString, CONFIG['dryrun']))
def add_torrent(torStr):
torrent = None
if not CONFIG['dryrun']:
if torStr != "":
torrent = TSCLIENT.add_torrent(torStr)
logger.info("Added: {} {}\n\tDry run: {}".format(torrent.name, torrent.hashString, CONFIG['dryrun']))
else:
logger.info("Added: {} \n\tDry run: {}".format(torStr if len(torStr) < 300 else torStr[:200], CONFIG['dryrun']))
return torrent
# Begin discord bot functions, adapted from https://github.com/kkrypt0nn/Python-Discord-Bot-Template
# async def status_task():
# while True:
# await client.change_presence(activity=discord.Game("{}help".format(CONFIG['bot_prefix'])))
# await asyncio.sleep(86400)
# check current transfers against those in TORRENT_JSON and print notifications to channel for certain changes
def check_for_transfer_changes():
global TORRENT_NOTIFIED_USERS, TORRENT_ADDED_USERS, TORRENT_OPTOUT_USERS
# get current transfer information
reload_client()
torrents = TSCLIENT.get_torrents()
# TORRENT_LIST = {
# 'hashString':{
# 'name':t.name,
# 'error':t.error,
# 'errorString':t.errorString,
# 'status':t.status,
# 'isStalled':t.isStalled,
# 'progress':t.progress
# }
# }
try:
lock()
curTorrents = {t.hashString:{
'name':t.name,
'error':t.error,
'errorString':t.errorString,
'status':t.status,
'isStalled':t.isStalled,
'progress':t.progress,
'added_user':None if t.hashString not in TORRENT_ADDED_USERS else TORRENT_ADDED_USERS[t.hashString],
'notified_users':[] if t.hashString not in TORRENT_NOTIFIED_USERS else TORRENT_NOTIFIED_USERS[t.hashString],
'optout_users':[] if t.hashString not in TORRENT_OPTOUT_USERS else TORRENT_OPTOUT_USERS[t.hashString]
} for t in torrents}
finally:
unlock()
if exists(TORRENT_JSON):
oldTorrents = load_json(path=TORRENT_JSON)
if len(curTorrents) > 0 and len(oldTorrents) > 0 and len(next(iter(curTorrents.values()))) != len(next(iter(oldTorrents.values()))):
logger.info("old transfer json {} is using an old format, replacing with current transfers and not checking for changes.".format(TORRENT_JSON))
generate_json(json_data=curTorrents, path=TORRENT_JSON, overwrite=True)
return None
# get added_user and notified_users from oldTorrents and copy to newTorrents
for h,t in oldTorrents.items():
if h in curTorrents:
if t['added_user']:
# this would overwrite a torrent that somehow had two added_users, but that should never happen
curTorrents[h]['added_user'] = t['added_user']
if len(t['notified_users']) > 0:
curTorrents[h]['notified_users'] += [u for u in t['notified_users'] if u not in curTorrents[h]['notified_users']]
if len(t['optout_users']) > 0:
curTorrents[h]['optout_users'] += [u for u in t['optout_users'] if u not in curTorrents[h]['optout_users'] and (h not in TORRENT_NOTIFIED_USERS or u not in TORRENT_NOTIFIED_USERS[h])]
# logger.debug("'optout_users' for {} ({}): {}".format(t['name'], h, str(t['optout_users'])))
# for u in t['optout_users']:
# if h in TORRENT_NOTIFIED_USERS and u in TORRENT_NOTIFIED_USERS[h]:
# user = client.get_user(u)
# logger.debug("Removing {} ({}) from 'optout_users' for {} ({})".format(user.name, u, t['name'], h))
# curTorrents[h]['optout_users'].remove(u)
# logger.debug("new 'optout_users' for {} ({}): {}".format(t['name'], h, str(curTorrents[h]['optout_users'])))
try:
lock()
TORRENT_NOTIFIED_USERS = {}
TORRENT_ADDED_USERS = {}
TORRENT_OPTOUT_USERS = {}
finally:
unlock()
generate_json(json_data=curTorrents, path=TORRENT_JSON, overwrite=True)
else:
try:
lock()
TORRENT_NOTIFIED_USERS = {}
TORRENT_ADDED_USERS = {}
TORRENT_OPTOUT_USERS = {}
finally:
unlock()
generate_json(json_data=curTorrents, path=TORRENT_JSON, overwrite=True)
return None
# print("before checking")
# get lists of different transfer changes
removedTransfers = {h:t for h,t in oldTorrents.items() if h not in curTorrents}
errorTransfers = {h:t for h,t in curTorrents.items() if t['error'] != 0 and ((h in oldTorrents and oldTorrents[h]['error'] == 0) or h not in oldTorrents)}
downloadedTransfers = {h:t for h,t in curTorrents.items() if t['progress'] == 100.0 and ((h in oldTorrents and oldTorrents[h]['progress'] < 100.0) or h not in oldTorrents)}
stalledTransfers = {h:t for h,t in curTorrents.items() if t['isStalled'] and ((h in oldTorrents and not oldTorrents[h]['isStalled']) or h not in oldTorrents)}
unstalledTransfers = {h:t for h,t in curTorrents.items() if not t['isStalled'] and h in oldTorrents and oldTorrents[h]['isStalled']}
finishedTransfers = {h:t for h,t in curTorrents.items() if t['status'] == 'finished' and ((h in oldTorrents and oldTorrents[h]['status'] != 'finished') or h not in oldTorrents)}
stoppedTransfers = {h:t for h,t in curTorrents.items() if t['status'] == 'stopped' and ((h in oldTorrents and oldTorrents[h]['status'] != 'stopped') or h not in oldTorrents)}
startedTransfers = {h:t for h,t in curTorrents.items() if t['status'] in ['downloading','seeding'] and h in oldTorrents and oldTorrents[h]['status'] not in ['downloading','seeding']}
# only report transfers as "new" if they haven't already been put in one of the dicts above
checkTransfers = {**errorTransfers, **downloadedTransfers, **stalledTransfers, **unstalledTransfers, **finishedTransfers, **stoppedTransfers, **startedTransfers, **oldTorrents}
newTransfers = {h:t for h,t in curTorrents.items() if h not in checkTransfers}
# print("done checking for changes")
# DEBUG grab a few random transfers for each type, vary the number to see if multiple embeds works
# print(str(oldTorrents))
# numTransfers = 3
# removedTransfers = {h:t for h,t in random.sample(oldTorrents.items(),numTransfers)}
# errorTransfers = {h:t for h,t in random.sample(curTorrents.items(),numTransfers)}
# downloadedTransfers = {h:t for h,t in random.sample(curTorrents.items(),numTransfers)}
# stalledTransfers = {h:t for h,t in random.sample(curTorrents.items(),numTransfers)}
# unstalledTransfers = {h:t for h,t in random.sample(curTorrents.items(),numTransfers)}
# finishedTransfers = {h:t for h,t in random.sample(curTorrents.items(),numTransfers)}
# newTransfers = {h:t for h,t in random.sample(curTorrents.items(),numTransfers)}
# print(str(errorTransfers))
# print("done applying debug changes")
return {
'new':{'name':"🟢 {0} new transfer{1}", 'data':newTransfers},
'removed':{'name':"❌ {0} removed transfer{1}", 'data':removedTransfers},
'error':{'name':"‼️ {0} transfer{1} with error{1}", 'data':errorTransfers},
'downloaded':{'name':"⬇️ {0} transfer{1} downloaded", 'data':downloadedTransfers},
'stalled':{'name':"🐢 {0} transfer{1} stalled", 'data':stalledTransfers},
'unstalled':{'name':"🐇 {0} stalled transfer{1} active", 'data':unstalledTransfers},
'finished':{'name':"🏁 {0} transfer{1} finished", 'data':finishedTransfers},
'stopped':{'name':"⏹ {0} transfer{1} paused", 'data':stoppedTransfers},
'started':{'name':"▶️ {0} transfer{1} resumed", 'data':startedTransfers}
}
def prepare_notifications(changedTransfers, states=["removed", "error", "downloaded", "stalled", "unstalled", "finished", "stopped", "started"]):
nTotal = sum([len(d['data']) for s,d in changedTransfers.items() if s in states]) if changedTransfers is not None else 0
torrents = {}
if nTotal > 0:
embeds = [discord.Embed(title="")]
ts = datetime.datetime.now(tz=pytz.timezone('America/Denver'))
embeds[-1].timestamp = ts
for s,d in changedTransfers.items():
if s in states:
n = len(d['data'])
if n > 0:
for h,t in d['data'].items():
torrents[h] = t
nameStr = d['name'].format(n, '' if n == 1 else 's')
vals = ["{}{}".format("{}.".format(i+1) if n > 1 else '', t['name'], "\n (error: *{}*)".format(t['errorString']) if t['errorString'] != "" else "") for i,t in enumerate(d['data'].values())]
valStr = ',\n'.join(vals)
if len(embeds[-1]) + len(nameStr) + len(valStr) >= 6000:
embeds.append(discord.Embed(title=""))
embeds[-1].timestamp = ts
if len(nameStr) + len(valStr) > 1000:
valStr = ""
for i,v in enumerate(vals):
if len(embeds[-1]) + len(nameStr) + len(valStr) + len(v) >= 6000:
embeds.append(discord.Embed(title=""))
embeds[-1].timestamp = ts
if len(nameStr) + len(valStr) + len(v) > 1000:
embeds[-1].add_field(name=nameStr, value=valStr, inline=False)
nameStr = ""
valStr = ""
else:
valStr += v
if i < len(vals) - 1:
valStr += ",\n"
pass
embeds[-1].add_field(name=nameStr, value=valStr, inline=False)
return embeds, nTotal, torrents
return None, nTotal, torrents
async def check_notification_reactions(message, is_text_channel, torrents, starttime=datetime.datetime.now()):
if (datetime.datetime.now() - starttime).total_seconds() >= CONFIG['reaction_wait_timeout']:
if is_text_channel:
await message.clear_reactions()
return
def check(reaction, user):
return user.id in CONFIG['whitelist_user_ids'] and reaction.message.id == message.id and (str(reaction.emoji) == '🔕' or (str(reaction.emoji) == '🔔' and is_text_channel))
try:
reaction, user = await client.wait_for('reaction_add', timeout=CONFIG['reaction_wait_timeout'], check=check)
except asyncio.TimeoutError:
return await check_notification_reactions(message, is_text_channel, torrents, starttime=starttime)
else:
if str(reaction.emoji) == '🔔':
if len(torrents) > 0:
for h,t in torrents.items():
if h in TORRENT_NOTIFIED_USERS:
TORRENT_NOTIFIED_USERS[h].append(user.id)
else:
TORRENT_NOTIFIED_USERS[h] = [user.id]
embed = discord.Embed(title="🔔 Notifications enabled for:", description=",\n".join(["{}{}".format("" if len(torrents) == 1 else "**{}.**".format(i+1),j) for i,j in enumerate([t['name'] for t in torrents.values()])]))
await user.send(embed=embed)
if str(reaction.emoji) == '🔕':
if len(torrents) > 0:
for h,t in torrents.items():
if h in TORRENT_OPTOUT_USERS:
TORRENT_OPTOUT_USERS[h].append(user.id)
else:
TORRENT_OPTOUT_USERS[h] = [user.id]
embed = discord.Embed(title="🔕 Notifications disabled for:", description=",\n".join(["{}{}".format("" if len(torrents) == 1 else "**{}.**".format(i+1),j) for i,j in enumerate([t['name'] for t in torrents.values()])]))
await user.send(embed=embed)
return await check_notification_reactions(message, is_text_channel, torrents, starttime=starttime)
async def run_notifications():
if CONFIG['notification_enabled']:
# get all changes
logger.debug("Running notification check")
changedTransfers = check_for_transfer_changes()
nTotal = sum([len(d['data']) for d in changedTransfers.values()]) if changedTransfers is not None else 0
if nTotal > 0:
addReactions = (sum([len(d['data']) for k,d in changedTransfers.items() if k != "removed"]) > 0)
# first in_channel notifications
if CONFIG['notification_enabled_in_channel'] and CONFIG['notification_channel_id'] > 0 and len(str(CONFIG['notification_channel_id'])) == 18:
embeds, n, torrents = prepare_notifications(changedTransfers, CONFIG['notification_states']['in_channel'])
logger.debug("in_channel notifications: {}".format(n))
# now post notifications
if n > 0:
ch = client.get_channel(CONFIG['notification_channel_id'])
msgs = [await ch.send(embed=e) for e in embeds]
if addReactions:
[await msgs[-1].add_reaction(s) for s in ['🔔','🔕']]
asyncio.create_task(check_notification_reactions(msgs[-1], True, torrents, datetime.datetime.now()))
# Now notify the users
# First get only the changedTransfers that require user notification.
# These will be stored separate because users *should* be reminded whether a notification
# is for a torrent they added versus one they elected to receive notifications for.
logger.debug("preparing list of transfers for user DM notifications")
addedUserChangedTransfers = {}
notifiedUserChangedTransfers = {}
for s,d in changedTransfers.items():
logger.debug("state: {} ({} transfers)".format(s, len(d['data'])))
if s in CONFIG['notification_states']['added_user']:
for h,t in d['data'].items():
logger.debug("Checking transfer: {} ({})".format(str(t), h))
if t['added_user'] is not None and t['added_user'] not in t['optout_users'] and t['added_user'] not in CONFIG['notification_DM_opt_out_user_ids']:
u = t['added_user']
if u in addedUserChangedTransfers:
if s in addedUserChangedTransfers[u]:
addedUserChangedTransfers[u][s]['data'][h] = t
else:
addedUserChangedTransfers[u][s] = {'name':d['name'],'data':{h:t}}
else:
addedUserChangedTransfers[u] = {s:{'name':d['name'],'data':{h:t}}}
if s in CONFIG['notification_states']['notified_users']:
for h,t in d['data'].items():
logger.debug("Checking transfer: {} ({})".format(str(t), h))
for u in t['notified_users']:
if u not in t['optout_users'] and (u not in addedUserChangedTransfers or s not in addedUserChangedTransfers[u] or h not in addedUserChangedTransfers[u][s]['data']):
if u in notifiedUserChangedTransfers:
if s in notifiedUserChangedTransfers[u]:
notifiedUserChangedTransfers[u][s]['data'][h] = t
else:
notifiedUserChangedTransfers[u][s] = {'name':d['name'],'data':{h:t}}
else:
notifiedUserChangedTransfers[u] = {s:{'name':d['name'],'data':{h:t}}}
logger.debug("DM notifications for notified_users: {}".format(str(notifiedUserChangedTransfers)))
logger.debug("DM notifications for added_user: {}".format(str(addedUserChangedTransfers)))
logger.debug("done preparing list of user DM notifications, now send notifications")
# now send notifications as DMs
for u,transfers in addedUserChangedTransfers.items():
logger.debug("Sending added_user notificaions for user {}".format(u))
embeds, n, torrents = prepare_notifications(transfers, CONFIG['notification_states']['added_user'])
if n > 0:
embeds[-1].set_author(name="Activity for transfer{} you added".format('' if n == 1 else 's'))
user = client.get_user(u)
msgs = [await user.send(embed=e) for e in embeds]
if addReactions:
await msgs[-1].add_reaction('🔕')
asyncio.create_task(check_notification_reactions(msgs[-1], False, torrents, datetime.datetime.now()))
for u,transfers in notifiedUserChangedTransfers.items():
logger.debug("Sending notified_user notificaions for user {}".format(u))
embeds, n, torrents = prepare_notifications(transfers, CONFIG['notification_states']['notified_users'])
if n > 0:
user = client.get_user(u)
msgs = [await user.send(embed=e) for e in embeds]
if addReactions:
await msgs[-1].add_reaction('🔕')
asyncio.create_task(check_notification_reactions(msgs[-1], False, torrents, datetime.datetime.now()))
else:
logger.debug("No changed transfers...")
return
async def loop_notifications():
while CONFIG['notification_enabled']:
# print("looping notifications")
try:
await run_notifications()
except Exception as e:
logger.error("Exception thrown in run_notifications: {}".format(e))
await asyncio.sleep(CONFIG['notification_freq'])
return
@client.event
async def on_ready():
global TSCLIENT_CONFIG, CONFIG
unlock()
TSCLIENT_CONFIG = CONFIG['tsclient']
if not CONFIG: # load from config file
CONFIG = load_json(path=CONFIG_JSON)
if not CONFIG:
logger.critical("Failed to load config from {}".format(CONFIG_JSON))
await client.change_presence(activity=discord.Game("config load error!"))
return
else: # config specified in this file, so try to write config file
if exists(CONFIG_JSON):
if load_json(CONFIG_JSON) != CONFIG:
# check current config against config file, throw error if different
logger.critical("Conflict: Config file exists and config specified in bot.py!")
await client.change_presence(activity=discord.Game("config load error!"))
return
elif not generate_json(json_data=CONFIG, path=CONFIG_JSON, overwrite=True):
logger.critical("Failed to write config file on startup!")
await client.change_presence(activity=discord.Game("config load error!"))
return
TSCLIENT_CONFIG = CONFIG['tsclient']
reload_client()
if TSCLIENT is None:
logger.critical("Failed to create transmissionrpc client")
await client.change_presence(activity=discord.Game("client load error!"))
else:
# client.loop.create_task(status_task())
await client.change_presence(activity=discord.Game("Listening {}help".format(CONFIG['bot_prefix'])))
print('Logged in as ' + client.user.name)
print("Discord.py API version:", discord.__version__)
print("Python version:", platform.python_version())
print("Running on:", platform.system(), platform.release(), "(" + os.name + ")")
print('-------------------')
# ch = client.get_channel(CONFIG['notification_channel_id'])
# await ch.send("test message")
# user = client.get_user(CONFIG['owner_user_ids'][0])
# await user.send("test message")
if CONFIG['notification_enabled']:
task = asyncio.create_task(loop_notifications())
def humantime(S, compact_output=(OUTPUT_MODE == OutputMode.MOBILE)): # return humantime for a number of seconds. If time is more than 36 hours, return only the largest rounded time unit (e.g. 2 days or 3 months)
S = int(S)
if S == -2:
return '?' if compact_output else 'Unknown'
elif S == -1:
return 'N/A'
elif S < 0:
return 'N/A'
if compact_output:
sStr = "sec"
mStr = "min"
hStr = "hr"
dStr = "dy"
wStr = "wk"
moStr = "mth"
yStr = "yr"
else:
sStr = "second"
mStr = "minute"
hStr = "hour"
dStr = "day"
wStr = "week"
moStr = "month"
yStr = "year"
M = 60
H = M * 60
D = H * 24