Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def generate_message(name="message", author=_missing, subject="", body=""):
msg = MagicMock(name=name, spec=praw.models.Message)
msg.kind = "t4"
if author is _missing:
author = generate_redditor().name
if author is None:
msg.author = None
else:
msg.author = generate_redditor(username=author)
msg.subject = subject
msg.body = body
msg.id = generate_reddit_id()
msg.mark_as_read = MagicMock(side_effect=None, return_value=None)
msg.reply = MagicMock(side_effect=None, return_value=None)
return msg
def message_guy(self):
self.log("MESSAGE GUY STARTING\n")
for message in self.reddit().inbox.unread(limit=None):
if isinstance(message, praw.models.Message):
self.log("Found a DM!\n", silent=True)
cb = ""
for line in message.body.splitlines():
if line.strip():
insensitive_hippo = re.compile(re.escape('**INPUT(.*):**'), re.IGNORECASE)
insensitive_d = re.compile(re.escape("Beep boop, I'm a bot."), re.IGNORECASE)
cb += str(insensitive_hippo.sub('', str(insensitive_d.sub('', line))))
cb = clean_input(cb)
if len(cb.strip()) < 2:
self.log("Parent comment was empty", silent=True)
continue
self.lock.acquire()
response = self.clean_response(self.get_response(cb), cb)
self.log("Bot replying to direct message: "+cb)
def get_item_url(item):
if isinstance(item, praw.models.Submission):
return "https://www.reddit.com/r/{}/comments/{}".format(item.subreddit, item)
elif isinstance(item, praw.models.Comment):
return "https://www.reddit.com/r/{}/comments/{}/_/{}".format(item.subreddit, item.submission, item)
elif isinstance(item, praw.models.ModmailConversation):
return "https://mod.reddit.com/mail/all/" + item.id
elif isinstance(item, praw.models.ModmailMessage):
return "https://mod.reddit.com/mail/all/" + item.conversation.id
elif isinstance(item, praw.models.Message):
if item.was_comment:
return "https://www.reddit.com/r/{}/comments/{}/_/{}".format(item.subreddit, item.submission, item)
else:
return "https://www.reddit.com/message/messages/{}".format(item)
elif isinstance(item, praw.models.Subreddit):
return "https://www.reddit.com/r/" + item.display_name
return ""
def __repr__(self):
return super(FollowLink, self).__repr__()
def _my_work_resolver(self):
_, link_href = self.args
reddit_item = Reddit.try_to_follow_link(link_href)
if reddit_item is None:
return "Refusing to follow non-Reddit link."
self.additional_work = [MixedType(reddit_item)]
@dataclass
class Request(Worknode, ABC):
args: Union[praw.models.Message, praw.models.Comment]
kwargs: Dict[str, Any] = field(default_factory=dict)
workload_type: WorkloadType = WorkloadType.request_type_private_message
name: str = "Request via PM"
def get_response_text(self, with_work_trace=False):
if not with_work_trace:
return f"{self}{WIDE_NEWLINE}{self.beep_boop()}"
return f"{self}{WIDE_NEWLINE}{self.beep_boop()}{TIGHT_NEWLINE}{self.humble_brag()}"
def __str__(self):
"""Core response text, not including the bot tag."""
return f"{WIDE_NEWLINE}-----{WIDE_NEWLINE}".join((str(work) for work in self.children if str(work)))
def __repr__(self):
if url:
# Return it
return url
# Else if the post is a link post, check it's URL
else:
url = self.ghm.extract_gif(reddit_object.url, nsfw=self.nsfw)
if url:
return url
else:
return None
except RecursionError:
submission = reddit.submission(id=reddit_object.id)
return self.determine_target_url(reddit, submission, layer + 1, checking_manual)
# Else if the object is a comment, check it's text
elif isinstance(reddit_object, praw.models.Comment):
# Any mention of NSFW must trip the NSFW flag
if is_nsfw_text(reddit_object.body) and not checking_manual:
self.nsfw = True
# If the comment was made by the bot, it must be a rereverse request
# If the rereverse flag is already set, we must be at least a loop deep
if reddit_object.author == consts.username and not self.rereverse and not checking_manual \
and not self.reupload:
self.rereverse = True
return self.determine_target_url(reddit, reddit_object.parent(), layer+1, checking_manual)
# If it's an AutoModerator summon, move our summon comment to the AutoMod's parent
if reddit_object.author == "AutoModerator":
# IF this is layer 0, this is an Automoderator summon. Check if we are doing a comment replacement
if layer == 0:
# Delete comment if a moderator
modded_subs = [i.name for i in reddit.user.moderator_subreddits()]
if reddit_object.subreddit.name in modded_subs:
from abc import ABC
from dataclasses import dataclass, field
from typing import Dict, Any, Union
# noinspection PyMethodParameters
import praw.models
from anytree import RenderTree
from rofm.classes.core.worknodes import parsers, core
@dataclass
class Request(ABC, core.Worknode):
args: Union[praw.models.Message, praw.models.Comment]
kwargs: Dict[str, Any] = field(default_factory=dict)
workload_type: core.WorkloadType = core.WorkloadType.request_type_private_message
name: str = "Request via PM"
def __str__(self):
return "\n\n\n".join((str(work) for work in self.additional_work if str(work))) + self.beep_boop()
def beep_boop(self):
return ("*Beep boop, I'm a bot.*\n\n"
"*I am maintained by /u/PurelyApplied,"
" for whom these username mentions are a huge morale boost.*\n\n"
"*You can find my source code and more details about me"
" on [GitHub](https://github.com/PurelyApplied/roll_one_for_me).*\n\n"
"*The following is the work I did for you!"
" I'm posting it for now for easier debugging and a little robot humble-bragging.*\n\n"
"ModmailMessage": models.ModmailMessage,
"Submenu": models.Submenu,
"TrophyList": models.TrophyList,
"UserList": models.RedditorList,
"button": models.ButtonWidget,
"calendar": models.Calendar,
"community-list": models.CommunityList,
"custom": models.CustomWidget,
"id-card": models.IDCard,
"image": models.ImageWidget,
"menu": models.Menu,
"modaction": models.ModAction,
"moderators": models.ModeratorsWidget,
"more": models.MoreComments,
"post-flair": models.PostFlairWidget,
"stylesheet": models.Stylesheet,
"subreddit-rules": models.RulesWidget,
"textarea": models.TextArea,
"widget": models.Widget,
}
self._objector = Objector(self, mappings)
def detect_type(self, obj):
""" Simple function to call the proper Comment or Submission handler. """
# noinspection PyUnresolvedReferences
tp = type(obj)
stp = str(tp).lower()
if type(obj) == praw.models.Submission:
self._submission(obj)
elif type(obj) == praw.models.reddit.comment.Comment:
self._comment(obj)
elif 'submission' in stp:
self._ps_submission(obj)
elif 'comment' in stp:
self._ps_comment(obj)
else:
raise Exception('Unknown Element Type: '+str(type(obj)))
def get_item_url(item):
if isinstance(item, praw.models.Submission):
return "https://www.reddit.com/r/{}/comments/{}".format(item.subreddit, item)
elif isinstance(item, praw.models.Comment):
return "https://www.reddit.com/r/{}/comments/{}/_/{}".format(item.subreddit, item.submission, item)
elif isinstance(item, praw.models.ModmailConversation):
return "https://mod.reddit.com/mail/all/" + item.id
elif isinstance(item, praw.models.ModmailMessage):
return "https://mod.reddit.com/mail/all/" + item.conversation.id
elif isinstance(item, praw.models.Message):
if item.was_comment:
return "https://www.reddit.com/r/{}/comments/{}/_/{}".format(item.subreddit, item.submission, item)
else:
return "https://www.reddit.com/message/messages/{}".format(item)
elif isinstance(item, praw.models.Subreddit):
return "https://www.reddit.com/r/" + item.display_name
return ""