forked from gerenook/titletoimagebot
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathbot.py
More file actions
1809 lines (1515 loc) · 68.3 KB
/
bot.py
File metadata and controls
1809 lines (1515 loc) · 68.3 KB
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Title2ImageBot
Complete redesign of titletoimagebot with non-deprecated apis
Always striving to improve this bot, fix bugs that crash it, and keep pushing forward with its design.
Contributions welcome
Written and maintained by CalicoCatalyst
"""
import argparse
import configparser
import curses
import logging
import os
import re
import sqlite3
import threading
import time
from io import BytesIO
from math import ceil
from os import remove
import praw
import praw.exceptions
import praw.models
import prawcore
# Use my custom fork until https://github.com/Damgaard/PyImgur/pull/43 is merged.
# pip3 install git+https://github.com/CalicoCatalyst/PyImgur
import pyimgur
import requests
from PIL import Image, ImageSequence, ImageFont, ImageDraw
from bs4 import BeautifulSoup
from gfypy import gfycat
# noinspection PyProtectedMember
from pyimgur.request import ImgurException
from requests import HTTPError
import messages
__author__ = 'calicocatalyst'
# [Major, e.g. a complete source code refactor].[Minor e.g. a large amount of changes].[Feature].[Patch]
__version__ = '1.1.3.0'
class TitleToImageBot(object):
"""Class for the bot itself.
Attributes:
config (Configuration): Bot Configuration Object
reddit (praw.Reddit): Reddit client object
imgur (PyImgur.Imgur): Imgur client object
gfycat (Gfycat.gfycat): Gfycat client object
screen (CLI): CLI interface object
killthreads (bool): Setting this to true will kill any active threads
"""
def __init__(self, config, database, screen):
"""Create the bot object
Args:
config (Configuration): Bot configuration API object
database (BotDatabase): Bot database API object
screen (CLI): Bot CLI API object
"""
# The conifugration has all of the usernames/passwords/keys.
self.config = config
# Ask for our API objects from the config
self.reddit = self.config.auth_reddit_from_config()
self.imgur = self.config.get_imgur_client_config()
self.gfycat = self.config.get_gfycat_client_config()
self.screen = screen
# get our custom BotDatabase object
self.database = database
self.killthreads = False
self.thread = None
def call_checks(self, limit):
"""Call the functions that check mentions and subs for requests
Args:
limit (int): How many posts back should be checked.
"""
# Set the curses (console) text
self.screen.set_current_action_status('Checking Mentions', "")
# Log it to the file
logging.info("Checking Mentions")
#######################
# CHECK MENTIONS #
#######################
self.check_mentions_for_requests(limit)
# Same stuff but for our listed auto-reply subs
self.screen.set_current_action_status('Checking Autoreply Subs', "")
logging.info("Checking Autoreply Subs")
#######################
# CHECK SUBS #
#######################
self.check_subs_for_posts(limit)
def read_comment_stream_for_manual_mentions(self):
"""Read a comment stream to check for all mentions of the old titletoimagebot
Returns:
"""
#######################
# START STREAM LOOP #
#######################
for comment in self.reddit.subreddit('all').stream.comments():
if 'u/titletoimagebot' in comment.body.lower() and comment.author.name is not 'Title2ImageBot':
#######################
# PROCESS SUBMISS #
#######################
processed = self.process_submission(comment.submission, comment, None,
dm=False, request_body=comment.body, customargs=[])
if processed is not None:
processed_url = processed[0]
processed_submission = processed[1]
processed_source_comment = processed[2]
# processed_custom_title_exists = processed[3]
#######################
# REPLY #
#######################
self.reply_imgur_url(processed_url, processed_submission, processed_source_comment,
None, customargs=[])
else:
pass
if self.killthreads:
break
def start_comment_streaming_thread(self):
"""Start up the comment streaming thread
"""
#######################
# CALL STREAM MTHD #
#######################
self.screen.set_stream_status("Active")
thread = threading.Thread(target=self.read_comment_stream_for_manual_mentions, args=())
thread.daemon = True
thread.start()
self.thread = thread
# self.screen.set_stream_status("Active")
def stop_comment_streaming_thread(self):
"""Stop the comment streaming thread
"""
self.killthreads = True
self.screen.set_stream_status("Disconnected")
# curses.echo()
# curses.nocbreak()
# curses.endwin()
def check_mentions_for_requests(self, post_limit=10):
"""Check the bot inbox for username mentions / PMs
Args:
post_limit (int): How far back in the inbox should we look.
"""
# A majority of this is for the progress bar
iteration = 1
# Start the progress bar before we make the request.
line = CLI.get_progress_line(iteration, post_limit)
self.screen.set_current_action_status("Checking Inbox for requests", line)
#######################
# START CHECK LOOP #
#######################
for message in self.reddit.inbox.all(limit=post_limit):
# If we're on the first one, show the progress bar not moving so we dont go over 100%
if iteration is 1:
# Add an iteration to the progress bar
iteration = iteration + 1
# Get our "Line" aka progress bar
line = CLI.get_progress_line(1, post_limit + 1)
# Send the line to curses (live console) with the included action.
self.screen.set_current_action_status("Checking Inbox for requests", line)
else:
iteration = iteration + 1
line = CLI.get_progress_line(iteration, post_limit + 1)
self.screen.set_current_action_status("Checking Inbox for requests", line)
# This is the actual function
# noinspection PyBroadException
try:
# Actually send the item in the inbox to the method to process it.
#######################
# PROCESS MSG #
#######################
self.process_message(message)
except Exception as ex:
# Broad catch to prevent freak cases from crashing program.
logging.info("Could not process %s with exception %s" % (message.id, ex))
def check_subs_for_posts(self, post_limit=25):
"""Check autoprocess subs for posts that meet set requirements for sub
Args:
post_limit: How far back in the sub should we check
"""
# Get list of subs from the config
subs = self.config.get_automatic_processing_subs()
# Caluclate the total amount of posts to be parsed
totalits = len(subs) * post_limit
iters = 0
for sub in subs:
# Subreddit Object for API interaction
subr = self.reddit.subreddit(sub)
# Grab posts from /new in sub to check
for post in subr.new(limit=post_limit):
iters += 1
line = CLI.get_progress_line(iters, totalits)
# Update curses
self.screen.set_current_action_status("Checking Subs for posts", line)
# If we've already parsed, skip this post iteration.
if self.database.submission_exists(post.id):
continue
title = post.title
# does this sub have list of keywords in the title that trigger the bot on this sub
has_triggers = self.config.configfile.has_option(sub, 'triggers')
# does this sub have an upvote-before-parsing threshold
has_threshold = self.config.configfile.has_option(sub, 'threshold')
if has_triggers:
# Get our list of triggers.
triggers = str(self.config.configfile[sub]['triggers']).split('|')
# Skip if the title doesnt have one, but mark it as parsed.
if not any(t in title.lower() for t in triggers):
logging.debug('Title %s doesnt appear to contain any of %s, adding to parsed and skipping'
% (title, self.config.configfile[sub]["triggers"]))
self.database.submission_insert(post.id, post.author.name, title, post.url)
continue
else:
# No triggers so keep moving
logging.debug('No triggers were defined for %s, not checking' % sub)
if has_threshold:
# Get the karma threshold
threshold = int(self.config.configfile[sub]['threshold'])
if post.score < threshold:
logging.debug('Threshold not met, not adding to parsed, just ignoring')
continue
else:
logging.debug('Threshold met, posting and adding to parsed')
else:
logging.debug('No threshold for %s, replying to everything :)' % sub)
#######################
# PROCESS SUBMISS #
#######################
processed = self.process_submission(post, None, None)
if processed is not None:
processed_url = processed[0]
processed_submission = processed[1]
processed_source_comment = processed[2]
# processed_custom_title_exists = processed[3]
#######################
# REPLY #
#######################
self.reply_imgur_url(processed_url, processed_submission, processed_source_comment,
None, customargs=None)
else:
if self.database.submission_exists(post.id):
continue
else:
self.database.submission_insert(post.id, post.author.name, title, post.url)
continue
if sub == "TitleToImageBotSpam":
for comment in processed[1].comments.list():
if isinstance(comment, praw.models.MoreComments):
# See praw docs on MoreComments
continue
if not comment or comment.author is None:
# If the comment or comment author was deleted, skip it
continue
if comment.author.name == self.reddit.user.me().name and \
"Image with added title" in comment.body:
comment.mod.distinguish(sticky=True)
if self.database.submission_exists(post.id):
continue
else:
self.database.submission_insert(post.id, post.author.name, title, post.url)
def process_message(self, message):
"""Process a detected username mention / DM
Args:
message (praw.models.Comment): Message to process
"""
if not message.author:
return
message_author = message.author.name
subject = message.subject.lower()
body_original = message.body
body = message.body.lower()
# Check if this message was already parsed. If so, dont parse it.
if self.database.message_exists(message.id):
logging.debug("bot.process_message() Message %s Already Parsed, Returning", message.id)
return
# Respond to the SCP Bot that erroneously detects "SCP-2" in every post.
# There are two.
if (message_author.lower() == "the-paranoid-android") or (message_author.lower() == "the-noided-android"):
message.reply("Thanks Marv")
logging.debug("Thanking marv")
self.database.message_insert(message.id, message_author, message.subject.lower(), body)
return
# Skip Messages Sent by Bot
if message_author == self.reddit.user.me().name:
logging.debug('Message was sent, returning')
return
# Live Management by Bot Maintainer
if message_author.lower() == self.config.maintainer.lower():
if "!eval" in body:
eval(body[5:])
if "!del" in body or "!delete" in body:
message.parent().delete()
if "!edit" in body:
message.parent().edit(body[5:])
if "!append" in body:
message.parent().edit(message.parent().body + body[7:])
# Process the typical username mention
if (isinstance(message, praw.models.Comment) and
(subject == 'username mention' or
(subject == 'comment reply' and 'u/%s' % (self.config.bot_username.lower()) in body))):
if message.author.name.lower() == 'automoderator':
message.mark_read()
return
match = re.match(r'.*u/%s\s*["“”](.+)["“”].*' % (self.config.bot_username.lower()),
body_original, re.RegexFlag.IGNORECASE)
title = None
if match:
title = match.group(1)
if len(title) > 512:
title = None
else:
logging.debug('Found custom title: %s', title)
if message.submission.subreddit.display_name not in self.config.get_automatic_processing_subs() and \
body is not None:
customargs = []
dark_mode_triggers = ["!dark", "!darkmode", "!black", "!d"]
center_mode_triggers = ["!center", "!middle", "!c"]
auth_tag_triggers = ["!author", "tagauthor", "tagauth", "!a"]
# If we find any apparent commands include them
if any(x in body for x in dark_mode_triggers):
customargs.append("dark")
if any(x in body for x in center_mode_triggers):
customargs.append("center")
if any(x in body for x in auth_tag_triggers):
customargs.append("tagauth")
else:
customargs = []
#######################
# PROCESS SUBMIS. #
#######################
processed = self.process_submission(message.submission, message, title,
dm=False, request_body=body, customargs=customargs)
if processed is not None:
processed_url = processed[0]
processed_submission = processed[1]
processed_source_comment = processed[2]
# processed_custom_title_exists = processed[3]
#######################
# REPLY #
#######################
self.reply_imgur_url(processed_url, processed_submission, processed_source_comment,
title, customargs=customargs)
else:
pass
message.mark_read()
# Process feedback and send it to bot maintainer
elif subject.startswith('feedback'):
self.reddit.redditor(self.config.maintainer).message("Feedback from %s" % message_author, body)
# mark short good/bad bot comments as read to keep inbox clean
elif 'good bot' in body and len(body) < 12:
logging.debug('Good bot message or comment reply found, marking as read')
message.mark_read()
elif 'bad bot' in body and len(body) < 12:
logging.debug('Bad bot message or comment reply found, marking as read')
message.mark_read()
# BETA Private Messaging Parsing feature
pm_process_triggers = ["add", "parse", "title", "image"]
if any(x in subject for x in pm_process_triggers):
re1 = '.*?' # Non-greedy match on filler
re2 = '((?:http|https)(?::\\/{2}[\\w]+)(?:[\\/|\\.]?)(?:[^\\s"]*))' # HTTP URL 1
rg = re.compile(re1 + re2, re.IGNORECASE | re.DOTALL)
m = rg.search(body)
if m:
http_url = m.group(1)
else:
return
submission = self.reddit.submission(url=http_url)
match = re.match(r'.*%s\s*["“”](.+)["“”].*' % http_url,
body_original, re.RegexFlag.IGNORECASE)
title = None
if match:
title = match.group(1)
if len(title) > 512:
title = None
else:
logging.debug('Found custom title: %s', title)
#######################
# PROCESS PM SUBM #
#######################
parsed = self.process_submission(submission, None, title, True, request_body=body_original)
processed = parsed
if processed is not None:
processed_url = processed[0]
# noinspection PyUnusedLocal
processed_submission = processed[1]
# noinspection PyUnusedLocal
processed_source_comment = processed[2]
processed_custom_title_exists = processed[3]
custom_title = processed_custom_title_exists
upscaled = False
else:
#######################
# FALLBACK REPLIES #
#######################
self.reddit.redditor(message_author).message("Sorry, I wasn't able to process that. This feature is in"
"beta and the conversation has been forwarded to the bot"
"author to see if a fix is possible.")
self.reddit.redditor(self.config.maintainer).message("Failed to process DM request. Plz investigate")
return
comment = messages.PM_reply_template.format(
image_url=processed_url,
warntag="PM Processing is in beta!",
custom="custom " if custom_title else "",
nsfw="(NSFW)" if submission.over_18 else '',
upscaled=' (image was upscaled)\n\n' if upscaled else '',
submission_id=submission.id
)
#######################
# REPLY TO USER #
#######################
self.reddit.redditor(message_author).message('Re: ' + subject, comment)
message.mark_read()
# Check if the bot has processed already, if so we dont need to do anything. If it hasn't,
# add it to the database and move on
if self.database.message_exists(message.id):
logging.debug("bot.process_message() Message %s Already Parsed, no need to add", message.id)
return
else:
self.database.message_insert(message.id, message_author, subject, body)
# noinspection PyUnusedLocal
def process_submission(self, submission, source_comment, title, dm=None, request_body=None, customargs=None):
"""Send info to process_image_submission and handle errors that arise from that method.
Args:
submission (praw.models.Submission): Post to process
source_comment (praw.models.Comment): Comment that summoned bot
title (str): Title to add to the image
dm (Optional[Any]): Unused variable
request_body (str): Unusued; Body of the request
customargs (list[str]): Custom arguments
"""
#######################
# MAIN FUNCTION #
#######################
url = self.process_image_submission(submission=submission, custom_title=title, customargs=customargs)
#######################
# DATABASE CHECKS #
#######################
if url is None:
self.screen.set_current_action_status('URL returned as none.', "")
logging.debug('Checking if Bot Has Already Processed Submission')
# This should return if the bot has already replied.
for comment in submission.comments.list():
if isinstance(comment, praw.models.MoreComments):
# See praw docs on MoreComments
continue
if not comment or comment.author is None:
# If the comment or comment author was deleted, skip it
continue
if comment.author.name == self.reddit.user.me().name and 'Image with added title' in comment.body:
if source_comment:
self.redirect_to_comment(source_comment, comment, submission)
# If there is no comment (automatic sub parsing) and the post wasn't deleted, and its not in the table, put
# it in. This was a very specific issue and I'm not sure what the exact problem was, but this fixes it :)
if (source_comment is None and
submission is not None and
not self.database.submission_exists(submission.id)):
self.database.submission_insert(submission.id, submission.author.name, submission.title,
submission.url)
return
# Dont parse if it's already been parsed
if self.database.message_exists(source_comment.id):
return
else:
self.database.message_insert(source_comment.id, source_comment.author.name, "comment reply",
source_comment.body)
return
######################
# RETURN #
######################
custom_title_exists = True if title is not None else False
return [url, submission, source_comment, custom_title_exists]
def redirect_to_comment(self, source_comment, comment, submission):
"""If a user isn't the first to ask for the bot to process, redirect them to the first asker
Args:
source_comment (praw.models.Comment): Comment that is currently asking
comment (praw.models.Comment): Comment to redirect said user to
submission (praw.models.Submission): Submission the post is on (for link generation purposes)
"""
com_url = messages.comment_url.format(postid=submission.id, commentid=comment.id)
reply = messages.already_responded_message.format(commentlink=com_url)
try:
#######################
# REPLY TO USER #
#######################
source_comment.reply(reply)
except prawcore.exceptions.Forbidden:
try:
source_comment.reply(reply)
except prawcore.exceptions.Forbidden:
logging.error("Failed to redirect user to comment")
except praw.exceptions.APIException:
logging.error("Failed to redirect user because user's comment was deleted")
except Exception as ex:
logging.critical("Failed to redirect user to comment with %s" % ex)
self.database.message_insert(source_comment.id, comment.author.name, "comment reply", source_comment.body)
# noinspection PyUnusedLocal
def process_image_submission(self, submission, custom_title=None, commenter=None, customargs=None):
"""Process an image submission
Args:
submission (praw.models.Submission): Submission to process
custom_title (str): Custom title to be potentially added
commenter (str): Name of the person who commented. I dont think this is ever used
customargs (list[str]): Custom arguments to process
Returns:
Imgur URL
"""
if customargs:
pls = ''.join(customargs)
else:
pls = ""
if custom_title:
parsed = self.database.submission_exists(submission.id + custom_title + pls)
else:
parsed = self.database.submission_exists(submission.id + pls)
subreddit = submission.subreddit.display_name
if parsed:
#######################
# BAIL #
#######################
return None
# Make sure author account exists
if submission.author is None:
self.database.submission_insert(submission.id, "deletedPost", submission.title, submission.url)
#######################
# BAIL #
#######################
return None
sub = submission.subreddit.display_name
url = submission.url
if custom_title is not None:
title = custom_title
else:
title = submission.title
submission_author = submission.author.name
# We need to verify everything is good to go
# Check every item in this list and verify it is 'True'
# If the submission has been parsed, throw false which will not allow the Bot
# To post.
if parsed:
#######################
# BAIL #
#######################
return None
if url.endswith('.gif') or url.endswith('.gifv'):
# Lets try this again.
# noinspection PyBroadException
try:
#######################
# PROCESS GIFS #
#######################
return self.process_gif(submission)
except Exception as ex:
logging.warning("gif upload failed with %s" % ex)
#######################
# BAIL #
#######################
return None
# Attempt to grab the images
try:
response = requests.get(url)
img = Image.open(BytesIO(response.content))
except (OSError, IOError) as error:
logging.warning('Converting to image failed, trying with <url>.jpg | %s', error)
try:
response = requests.get(url + '.jpg')
img = Image.open(BytesIO(response.content))
except (OSError, IOError) as error:
logging.error('Converting to image failed, skipping submission | %s', error)
#######################
# BAIL #
#######################
return None
except Exception as error:
logging.error(error)
logging.error('Exception on image conversion lines.')
#######################
# BAIL #
#######################
return None
# noinspection PyBroadException
try:
image = RedditImage(img)
except Exception as error:
logging.error('Could not create RedditImage with %s' % error)
#######################
# BAIL #
#######################
return None
if subreddit == "boottoobig":
boot = True
else:
boot = False
# I absolutely hate this method, would much rather just test length but people on StackOverflow bitch so
if not customargs:
image.add_title(title, boot)
else:
image.add_title(title=title, boot=boot, customargs=customargs, author=submission_author)
imgur_url = self.upload(image)
return imgur_url
def process_gif(self, submission):
"""Process a gif.
Notes:
This is ineffecient and awful. I need to either research and get familiar with animated picture processing
in python or call up on the expertise of someone experienced in the area; Also considering building a
library to do so in a better/more suitable language and calling it as a subprocess, which would work great
as well
See my GfyPy project for information on how that library works.
Args:
submission (praw.models.Submission): Submission to process
Returns:
Gfycat URL
"""
# TODO: hotfix framerate issues
# sub = submission.subreddit.display_name
url = submission.url
title = submission.title
# author = submission.author.name
# If its a gifv and hosted on imgur, we're ok, anywhere else I cant verify it works
if 'imgur' in url and url.endswith("gifv"):
# imgur will give us a (however large) gif if we ask for it
# thanks imgur <3
url = url.rstrip('v')
# Reddit Hosted gifs are going to be absolute hell, served via DASH which
# Can be checked through a fallback url :)
try:
response = requests.get(url)
# The nature of this throws tons of exceptions based on what users throw at the bot
except Exception as error:
logging.error(error)
logging.error('Exception on image conversion lines.')
return None
img = Image.open(BytesIO(response.content))
frames = []
# Process Gif
# We do this by creating a reddit image for every frame of the gif
# This is godawful, but the impact on performance isn't too bad
# Loop over each frame in the animated image
for frame in ImageSequence.Iterator(img):
# Draw the text on the frame
# We'll create a custom RedditImage for each frame to avoid
# redundant code
r_frame = RedditImage(frame)
r_frame.add_title(title, False)
frame = r_frame.image
# However, 'frame' is still the animated image with many frames
# It has simply been seeked to a later frame
# For our list of frames, we only want the current frame
# Saving the image without 'save_all' will turn it into a single frame image, and we can then re-open it
# To be efficient, we will save it to a stream, rather than to file
b = BytesIO()
frame.save(b, format="GIF")
frame = Image.open(b)
# The first successful image generation was 150MB, so lets see what all
# Can be done to not have that happen
# Then append the single frame image to a list of frames
frames.append(frame)
# Save the frames as a new image
path_gif = 'temp.gif'
# path_mp4 = 'temp.mp4'
frames[0].save(path_gif, save_all=True, append_images=frames[1:])
# ff = ffmpy.FFmpeg(inputs={path_gif: None},outputs={path_mp4: None})
# ff.run()
# noinspection PyBroadException
try:
########################
# UPLOAD TO GFYCAT #
########################
url = self.upload_to_gfycat(path_gif).url
remove(path_gif)
except Exception as ex:
logging.error('Gif Upload Failed with %s, Returning' % ex)
remove(path_gif)
return None
# remove(path_mp4)
return url
@staticmethod
def get_params_from_twitter(link):
""" Get the paramaters that we shove into process_image_submission from a twitter link.
Unfinished
TODO: REWORK HOW PROCESS_IMAGE_SUBMISSION WORKS TO ALLOW IT TO NOT NEED TO USE PRAW MODELS
Args:
link:
Returns:
"""
page = requests.get(link)
soup = BeautifulSoup(page.text, 'html.parser')
tweet_text = soup.select(".tweet-text")
tweet_text_raw = tweet_text[0] if len(tweet_text) > 0 else ""
cleaned = BeautifulSoup(str(tweet_text_raw))
invalid_tags = ['a', 'p']
for tag in invalid_tags:
for match in cleaned.findAll(tag):
match.unwrap()
twitpiclink = 'pic.twitter.com'
nonfluff = str(cleaned).split(twitpiclink, 1)[0]
return [nonfluff]
def upload(self, reddit_image):
"""
Upload self._image to imgur
:type reddit_image: RedditImage
:param reddit_image:
:returns: imgur url if upload successful, else None
:rtype: str, NoneType
"""
path_png = 'temp.png'
path_jpg = 'temp.jpg'
reddit_image.image.save(path_png)
reddit_image.image.save(path_jpg)
# noinspection PyBroadException
response = None
try:
# Upload to imgur using pyimgur
response = self.upload_to_imgur(path_png)
except ImgurException as ex:
logging.error('ImgurException: ' % ex)
# Likely too large
logging.warning('png upload failed with %s, trying jpg' % ex)
try:
# Upload to imgur using pyimgur
response = self.upload_to_imgur(path_jpg)
except ImgurException as ex:
logging.error('ImgurException: %s' % ex)
logging.error('jpg upload failed with %s, returning' % ex)
response = None
except HTTPError as ex:
logging.error('HTTPError: %s' % ex)
logging.error('jpg upload failed with %s, returning' % ex)
response = None
except HTTPError as ex:
logging.error('HTTPError: %s' % ex)
logging.error('png upload failed with %s, returning' % ex)
finally:
remove(path_png)
remove(path_jpg)
if response is None:
return None
return response.link
def upload_to_imgur(self, local_image_url):
"""Upload an image to imgur from a local image url
Make sure to use my fork of PyImgur or errors will not be raised when image upload fails. The public PyImgur
instead prints to console when it fails.
Args:
local_image_url (str): Path to local file
Returns:
Response from imgur.
Raises:
ImgurException: when image upload fails for whatever reason.
"""
# Actually call pyimgur and upload image with it
self.screen.set_current_action_status("Uploading to Imgur...", "")
self.screen.set_imgur_status("Uploading...")
response = self.imgur.upload_image(local_image_url, title="Uploaded by /u/%s" % self.config.bot_username)
self.screen.set_current_action_status("Complete", "")
self.screen.set_imgur_status("Connected")
return response
def upload_to_gfycat(self, local_gif_url):
"""Upload a local gif by path to gfycat
Args:
local_gif_url: path to gif
Returns:
GfyCat object
"""
generated_gfycat = self.gfycat.upload_file(local_gif_url)
return generated_gfycat
def reply_imgur_url(self, url, submission, source_comment, custom_title=None, upscaled=False, customargs=None):
"""Reply to a comment with the imgur url generated
Args:
url (str): URL that was generated
submission (praw.models.Submission): Submission that was processed
source_comment (praw.models.Comment): Comment that requested processing
custom_title (str): Custom title if it was added
upscaled (bool): Whether image was upscaled for processing
customargs (list[str]): List of custom arguments if any were passed
Returns:
True if reply succeeded, false otherwise
"""
self.screen.set_current_action_status('Creating reply', "")
if submission.subreddit.display_name.lower() in self.config.get_minimal_sub_list():
reply = messages.minimal_reply_template(
image_url=url,
nsfw="(NSFW)"
)
elif submission.subreddit.display_name.lower() == "dankmemesfromsite19":
# noinspection PyTypeChecker
reply = messages.site19_template.format(
image_url=url,
warntag="Custom titles/arguments are in beta" if customargs else "",
custom="custom " if custom_title and len(custom_title) > 0 else "",
nsfw="(NSFW)" if submission.over_18 else '',
upscaled=' (image was upscaled)\n\n' if upscaled else '',
submission_id=submission.id
)
elif submission.subreddit.display_name.lower() == "de":
# noinspection PyTypeChecker
reply = messages.de_reply_template.format(
image_url=url,
warntag="" if customargs else "",
custom="anpassen " if custom_title and len(custom_title) > 0 else "",
nsfw="(NSFW)" if submission.over_18 else '',
upscaled=' (Das Bild wurde in der Größe geändert)\n\n' if upscaled else ''
)
else:
# noinspection PyTypeChecker
reply = messages.standard_reply_template.format(
image_url=url,
warntag="Custom titles/arguments are in beta" if customargs else "",
custom="custom " if custom_title and len(custom_title) > 0 else "",
nsfw="(NSFW)" if submission.over_18 else '',
upscaled=' (image was upscaled)\n\n' if upscaled else '',
submission_id=submission.id
)
if submission.subreddit.display_name in self.config.get_ban_sub_list():
reply = messages.banned_PM_template.format(
image_url=url,
warntag="Custom titles/arguments are in beta" if customargs else "",
custom="custom " if custom_title and len(custom_title) > 0 else "",
nsfw="(NSFW)" if submission.over_18 else '',
upscaled=' (image was upscaled)\n\n' if upscaled else '',
submission_id=submission.id
)
# If we're banned shoot this to the sub. rest of the stuff can run, it has no effect
source_comment.author.message("Your Title2ImageBot'd Image", reply)
try:
if source_comment:
#######################
# REPLY #
#######################
source_comment.reply(reply)
else:
#######################
# REPLY TO SUB #
#######################
submission.reply(reply)
except praw.exceptions.APIException as error:
logging.error('Reddit api error, we\'ll try to repost later | %s', error)
return False
except Exception as error:
logging.error('Cannot reply, skipping submission | %s', error)
return False
if customargs:
pls = ''.join(customargs)
else:
pls = ""
if custom_title:
sid = submission.id + custom_title + pls
else:
sid = submission.id + pls
self.database.submission_insert(sid, submission.author.name, submission.title, url)
return True
class RedditImage:
"""Reddit Image class
A majority of this class is the work of gerenook, the author of the original bot. Its ingenious work, and
the bot absolutely could not function without it. Anything dumb here is my (CalicoCatalyst) work.
custom arguments are my work.
I'm going to do my best to document it.
Attributes: