def is_spam(request, comment): # If request user has uploaded sounds, we don't check for spam if request.user.sounds.count() > 0: return False domain = "http://%s" % Site.objects.get_current().domain api = Akismet(key=settings.AKISMET_KEY, blog_url=domain) data = { 'user_ip': request.META.get('REMOTE_ADDR', '127.0.0.1'), 'user_agent': request.META.get('HTTP_USER_AGENT', ''), 'referrer': request.META.get('HTTP_REFERER', ''), 'comment_type': 'comment', 'comment_author': request.user.username.encode("utf-8") if request.user.is_authenticated() else '', } if False: # set this to true to force a spam detection data['comment_author'] = "viagra-test-123" try: if api.comment_check(comment.encode('utf-8'), data=data, build_data=True): if request.user.is_authenticated(): AkismetSpam.objects.create(user=request.user, spam=comment) return True else: return False except AkismetError: # failed to contact akismet... return False except HTTPError: # failed to contact akismet... return False except URLError: # failed to contact akismet... return False
def akismet_moderate_comment(sender, comment, request, *args, **kwargs): from django.contrib.sites.models import Site from django.conf import settings if request.user.is_authenticated(): return try: from akismet import Akismet except: return ak = Akismet( key = settings.AKISMET_API_KEY, blog_url = 'http://%s/' % Site.objects.get(pk=settings.SITE_ID).domain ) if not ak.verify_key(): return data = { 'user_ip': request.META.get('REMOTE_ADDR', '127.0.0.1'), 'user_agent': request.META.get('HTTP_USER_AGENT', ''), 'referrer': request.META.get('HTTP_REFERER', ''), 'comment_type': 'comment', 'comment_author': comment.user_name.encode('utf-8'), } if ak.comment_check(comment.comment.encode('utf-8'), data=data, build_data=True): comment.flags.create( user=comment.content_object.author, flag='spam' ) comment.is_public = False comment.save()
def comment_check(self): ''' Check a comment. Return True for ham, False for spam. Use this function before save a comment. ''' try: if hasattr(settings, 'BAN_NON_CJK') and settings.BAN_NON_CJK: import re if not re.search("[\u4E00-\u9FC3\u3041-\u30FF]", self.comment): raise Exception() if hasattr(settings, 'AKISMET_API_KEY') and settings.AKISMET_API_KEY: from akismet import Akismet akismet_api = Akismet(key=settings.AKISMET_API_KEY, blog_url='http://%s/' % Site.objects.get_current().domain) if akismet_api.verify_key(): akismet_data = { 'comment_type': 'comment', 'user_ip': self.ip_address, 'user_agent': self.user_agent, 'referrer': '', } return not akismet_api.comment_check( self.comment.encode("utf8"), data=akismet_data, build_data=True) else: return True except: return False
def on_comment_was_posted(sender, comment, request, *args, **kwargs): try: from akismet import Akismet from akismet import AkismetError except: return if hasattr(settings, 'AKISMET_API_KEY'): ak = Akismet(key=settings.AKISMET_API_KEY, blog_url='http://%s/' % Site.objects.get(pk=settings.SITE_ID).domain) else: return try: if ak.verify_key(): data = { 'user_ip': request.META.get('REMOTE_ADDR', '127.0.0.1'), 'user_agent': request.META.get('HTTP_USER_AGENT', ''), 'referrer': request.META.get('HTTP_REFERER', ''), 'comment_type': 'comment', 'comment_author': comment.user_name.encode('utf-8'), } if ak.comment_check(comment.content.encode('utf-8'), data=data, build_data=True): comment.is_public = False comment.save() except AkismetError: comment.save()
def on_comment_was_posted(sender, comment, request, *args, **kwargs): """Spam checking can be enabled/disabled per the comment's target Model Usage: if comment.content_type.model_class() != CMSArticle: return """ try: from akismet import Akismet except: return ak = Akismet( key=settings.AKISMET_API_KEY, blog_url='http://%s/' % Site.objects.get(pk=settings.SITE_ID).domain ) if ak.verify_key(): data = { 'user_ip': request.META.get('REMOTE_ADDR', '127.0.0.1'), 'user_agent': request.META.get('HTTP_USER_AGENT', ''), 'referrer': request.META.get('HTTP_REFERER', ''), 'comment_type': 'comment', 'comment_author': comment.user_name.encode('utf-8'), } if ak.comment_check(comment.comment.encode('utf-8'), data=data, build_data=True): comment.flags.create( user=comment.content_object.author, flag='spam' ) comment.is_public = False comment.save()
def clean_body(self): """ Perform Akismet validation of the message. """ if 'body' in self.cleaned_data and getattr(settings, 'AKISMET_API_KEY', ''): from akismet import Akismet, AkismetError from django.utils.encoding import smart_str akismet_api = Akismet(key=settings.AKISMET_API_KEY, blog_url='http://%s/' % Site.objects.get_current().domain) try: if akismet_api.verify_key(): akismet_data = { 'comment_type': 'comment', 'referer': self.request.META.get('HTTP_REFERER', ''), 'user_ip': self.request.META.get('REMOTE_ADDR', ''), 'user_agent': self.request.META.get('HTTP_USER_AGENT', '') } akismet_check = akismet_api.comment_check(smart_str(self.cleaned_data['body']), data=akismet_data, build_data=True) except AkismetError: raise forms.ValidationError(u"Akismet connection error, please try again later") if akismet_check: raise forms.ValidationError(u"Akismet thinks this message is spam") return self.cleaned_data['body']
def cb_comment_reject(args): from akismet import Akismet, AkismetError request = args['request'] comment = args['comment'] config = request.get_configuration() reqdata = request.get_data() http = request.get_http() fields = {'comment': 'description', 'comment_author_email': 'email', 'comment_author': 'author', 'comment_author_url': 'link', 'comment_type': 'type', } data = {} for field in fields: if comment.has_key(fields[field]): data[field] = "" for char in list(comment[fields[field]]): try: char.encode('ascii') # FIXME - bare except--bad! except: data[field] = data[field] + "&#" + str(ord(char)) + ";" else: data[field] = data[field] + char if not data.get('comment'): print >>sys.stderr, "Comment info not enough.", return False body = data['comment'] if 'ipaddress' in comment: data['user_ip'] = comment['ipaddress'] data['user_agent'] = http.get('HTTP_USER_AGENT','') data['referrer'] = http.get('HTTP_REFERER','') api_key = config.get('akismet_api_key') base_url = config.get('base_url') # initialize the api api = Akismet(api_key, base_url, agent='PyBlosxom/1.3') if not api.verify_key(): print >>sys.stderr, "Could not verify akismet API key. Comments accepted.", return False # false is ham, true is spam try: if api.comment_check(body, data): print >>sys.stderr, "Rejecting comment", return (True, 'I\'m sorry, but your comment was rejected by the <a href="http://akismet.com/">Akismet</a> spam filtering system.') else: return False except AkismetError: print >>sys.stderr, "Rejecting comment (AkismetError)", return (True, "Missing essential data (e.g., a UserAgent string).")
def verify_installation(request): try: from akismet import Akismet except ImportError: print >>sys.stderr, "Missing module 'akismet'.", return False config = request.get_configuration() # try to check to se make sure that the config file has a key if not config.has_key("akismet_api_key"): print >>sys.stderr, "Missing required configuration value 'akismet_key'", return False try: from akismet import Akismet a = Akismet(config['akismet_api_key'], config['base_url'], agent='PyBlosxom/1.3') if not a.verify_key(): print >>sys.stderr, "Could not verify akismet API key.", return False except ImportError: print "Unknown error loading Akismet module!", return False return True
def moderate(self, comment, content_object): """ Determine whether a given comment on a given object should be allowed to show up immediately, or should be marked non-public and await approval. Return ``True`` if the comment should be moderated (marked non-public), ``False`` otherwise. """ if self.auto_moderate_field and self.moderate_after: if self._get_delta(datetime.datetime.now(), getattr(content_object, self.auto_moderate_field)).days >= self.moderate_after: return True if self.akismet: from akismet import Akismet from django.utils.encoding import smart_str akismet_api = Akismet(key=settings.AKISMET_API_KEY, blog_url='http://%s/' % Site.objects.get_current().domain) if akismet_api.verify_key(): akismet_data = { 'comment_type': 'comment', 'referrer': '', 'user_ip': comment.ip_address, 'user_agent': '' } if akismet_api.comment_check(smart_str(comment.comment), data=akismet_data, build_data=True): return True return False
def akismet_check_spam(text, request): """Returns True if spam found, false if not, May raise exceptions if something is not right with the Akismet account/service/setup""" if not askbot_settings.USE_AKISMET: return False try: if askbot_settings.USE_AKISMET and askbot_settings.AKISMET_API_KEY == "": raise ImproperlyConfigured('You have not set AKISMET_API_KEY') data = {'user_ip': request.META.get('REMOTE_ADDR'), 'user_agent': request.environ['HTTP_USER_AGENT'], 'comment_author': smart_str(request.user.username) } if request.user.is_authenticated(): data.update({'comment_author_email': request.user.email}) api = Akismet( askbot_settings.AKISMET_API_KEY, smart_str(site_url(reverse('questions'))), "Askbot/%s" % get_version() ) return api.comment_check(text, data, build_data=False) except APIKeyError: logging.critical('Akismet Key is missing') except AkismetError: logging.critical('Akismet error: Invalid Akismet key or Akismet account issue!') except Exception as e: logging.critical((u'Akismet error: %s' % unicode(e)).encode('utf-8')) return False
def clean_body(self): """ Check spam against Akismet. Backported from django-contact-form pre-1.0; 1.0 dropped built-in Akismet support. """ if 'body' in self.cleaned_data and hasattr( settings, 'AKISMET_API_KEY') and settings.AKISMET_API_KEY: akismet_api = Akismet(key=settings.AKISMET_API_KEY, blog_url='http://%s/' % Site.objects.get_current().domain) if akismet_api.verify_key(): akismet_data = { 'comment_type': 'comment', 'referer': self.request.META.get('HTTP_REFERER', ''), 'user_ip': self.request.META.get('REMOTE_ADDR', ''), 'user_agent': self.request.META.get('HTTP_USER_AGENT', '') } comment = force_bytes( self.cleaned_data['body']) # workaround for #21444 if akismet_api.comment_check(comment, data=akismet_data, build_data=True): raise forms.ValidationError( "Akismet thinks this message is spam") return self.cleaned_data['body']
def backend(comment, content_object, request): """ Akismet spam checker backend for Zinnia. """ blog_url = '%s://%s/' % (PROTOCOL, Site.objects.get_current().domain) akismet = Akismet(key=AKISMET_API_KEY, blog_url=blog_url) if not akismet.verify_key(): raise APIKeyError('Your Akismet API key is invalid.') akismet_data = { 'user_ip': request.META.get('REMOTE_ADDR', ''), 'user_agent': request.META.get('HTTP_USER_AGENT', ''), 'referrer': request.META.get('HTTP_REFERER', 'unknown'), 'permalink': content_object.get_absolute_url(), 'comment_type': 'comment', 'comment_author': smart_str(comment.name), 'comment_author_email': smart_str(comment.email), 'comment_author_url': smart_str(comment.url), } is_spam = akismet.comment_check(smart_str(comment.comment), data=akismet_data, build_data=True) return is_spam
def wrapper(request, *args, **kwargs): if askbot_settings.USE_AKISMET and askbot_settings.AKISMET_API_KEY == "": raise ImproperlyConfigured('You have not set AKISMET_API_KEY') if askbot_settings.USE_AKISMET and request.method == "POST": comment = smart_str(request.POST[field]) data = {'user_ip': request.META.get('REMOTE_ADDR'), 'user_agent': request.environ['HTTP_USER_AGENT'], 'comment_author': smart_str(request.user.username), } if request.user.is_authenticated(): data.update({'comment_author_email': request.user.email}) from akismet import Akismet api = Akismet( askbot_settings.AKISMET_API_KEY, smart_str(site_url(reverse('questions'))), "Askbot/%s" % get_version() ) if api.comment_check(comment, data, build_data=False): logging.debug('Spam detected in %s post at: %s', request.user.username, timezone.now()) spam_message = _( 'Spam was detected on your post, sorry ' 'for if this is a mistake' ) if request.is_ajax(): return HttpResponseForbidden(spam_message, mimetype="application/json") else: # request.user.message_set.create(message=spam_message) django_messages.info(request, spam_message) return redirect('index') return view_func(request, *args, **kwargs)
def check_spam(self, request, comment, key, blog_url=None, base_url=None): try: from akismet import Akismet except: return False if blog_url is None: blog_url = 'http://%s/' % Site.objects.get_current().domain ak = Akismet(key=key, blog_url=blog_url) if base_url is not None: ak.baseurl = base_url if ak.verify_key(): data = { 'user_ip': request.META.get('HTTP_X_FORWARDED_FOR', '127.0.0.1'), 'user_agent': request.META.get('HTTP_USER_AGENT', ''), 'referrer': request.META.get('HTTP_REFERER', ''), 'comment_type': 'comment', 'comment_author': comment.user_name.encode('utf-8') } if ak.comment_check(comment.comment.encode('utf-8'), data=data, build_data=True): return True return False
def check_with_akismet(comment=None, request=None, **kwargs): if config_value("PRODUCT", "AKISMET_ENABLE"): key = config_value("PRODUCT", "AKISMET_KEY") if key: site = Site.objects.get_current() shop = urlresolvers.reverse('satchmo_shop_home') from akismet import Akismet akismet = Akismet( key=settings.AKISMET_API_KEY, blog_url='http://%s' % url_join(site.domain, shop)) if akismet.verify_key(): akismet_data = { 'comment_type': 'comment', 'referrer': request.META.get('HTTP_REFERER', ""), 'user_ip': comment.ip_address, 'user_agent': '' } if akismet_api.comment_check(smart_str(comment.comment), data=akismet_data, build_data=True): comment.is_public=False comment.save() log.info("Akismet marked comment #%i as spam", comment.id) else: log.debug("Akismet accepted comment #%i", comment.id) else: log.warn("Akismet key '%s' not accepted by akismet service.", key) else: log.info("Akismet enabled, but no key found. Please put in your admin settings.")
def filter_spam(ctx): site_url = settings.DEFAULT_BACKEND_PROTOCOL + \ "://"+settings.DEFAULT_BACKEND_DOMAIN if site_url.find("localhost") != -1: return Comment = apps.get_model('projects.Comment') PublishingRule = apps.get_model('projects.PublishingRule') comment = Comment.objects.get(id=ctx.get("comment_id")) if ctx.get("method" ) == 'POST' and comment.publish.type != PublishingRule.DRAFT: akismet_api = Akismet(key=settings.AKISMET_API_KEY, blog_url=site_url) is_spam = akismet_api.comment_check( user_ip=ctx.get("REMOTE_ADDR"), user_agent=ctx.get("HTTP_USER_AGENT"), comment_type='comment', comment_content=ctx.get("text"), blog_lang=ctx.get("lang"), ) if is_spam: comment.publish.type = PublishingRule.DRAFT comment.publish.publisher_id = None ## Set publisher_id to none when zubhub system unpublished a comment. comment.save() staffs_and_mods = Creator.objects.filter(is_staff=True) staffs_and_mods = staffs.union( Creator.objects.filter(tags__name="moderator")) send_spam_notification(ctx.get("comment_id"), staffs_and_mods)
class AkismetSpam(BaseSpam): def __init__(self): self.data = { 'blog': 'sentiment-analysis6', 'user_ip': '127.0.0.1', 'comment_type': 'comment', 'comment_author': 0, 'user_agent': 'sentiment-analysis6/0.6.0' } self.db_column_en = 'spam_api1_en' self.db_column = 'spam_api1_with_comment_author_and_blog' # self.api_key = 'ade34decf355' self.api_key = 'c7f3ea2b654d' self.api = Akismet(self.api_key, 'sentiment-analysis6.ml') print ('Using AkismetSpamAPI') def is_spam(self, content, comment_author, post_id): self.data['comment_author'] = comment_author self.data['blog'] = post_id try: is_spam = self.api.comment_check(content, data=self.data) except UnicodeEncodeError: is_spam = self.api.comment_check(content.encode('utf-8'), data=self.data) return is_spam def get_db_column(self, use_en): return self.db_column_en if use_en else self.db_column
def moderate(self, comment, content_object): """ Determine whether a given comment on a given object should be allowed to show up immediately, or should be marked non-public and await approval. Return ``True`` if the comment should be moderated (marked non-public), ``False`` otherwise. """ if self.auto_moderate_field and self.moderate_after: if self._get_delta( datetime.datetime.now(), getattr( content_object, self.auto_moderate_field)).days >= self.moderate_after: return True if self.akismet: from akismet import Akismet from django.utils.encoding import smart_str akismet_api = Akismet(key=settings.AKISMET_API_KEY, blog_url='http://%s/' % Site.objects.get_current().domain) if akismet_api.verify_key(): akismet_data = { 'comment_type': 'comment', 'referrer': '', 'user_ip': comment.ip_address, 'user_agent': '' } if akismet_api.comment_check(smart_str(comment.comment), data=akismet_data, build_data=True): return True return False
def _check_akismet(self): def add_error(error): self._add_error('akismet_api_key', error) try: from akismet import Akismet except ImportError: self._add_error('spam_protection_method', _('Akismet library is not installed. Use ' '"easy_install akismet" or "pip install ' 'akismet".')) api_key = getattr(settings, "AKISMET_API_KEY", self.cleaned_data['akismet_api_key']) if not hasattr(settings, "AKISMET_API_KEY"): if not api_key: add_error(Field.default_error_messages['required']) else: ak = Akismet( key = api_key, blog_url = 'http://%s/' % ( Site.objects.get(pk=settings.SITE_ID).domain) ) if not ak.verify_key(): add_error(_('The API Key is not valid.'))
def moderate_akismet(self, comment, content_object, request): """Need to pass Akismet test""" if not AKISMET_COMMENT: return False from akismet import Akismet from akismet import APIKeyError akismet = Akismet(key=AKISMET_API_KEY, blog_url='http://%s/' % Site.objects.get_current().domain) if akismet.verify_key(): akismet_data = { 'user_ip': request.META.get('REMOTE_ADDR', ''), 'user_agent': request.META.get('HTTP_USER_AGENT', ''), 'referrer': request.META.get('HTTP_REFERER', 'unknown'), 'permalink': content_object.get_absolute_url(), 'comment_type': 'comment', 'comment_author': comment.userinfo.get('name', ''), 'comment_author_email': comment.userinfo.get('email', ''), 'comment_author_url': comment.userinfo.get('url', ''), } return akismet.comment_check(smart_str(comment.comment), data=akismet_data, build_data=True) raise APIKeyError("Your Akismet API key is invalid.")
def setUp(self): try: akismet_api_key = os.environ['AKISMET_API_KEY'] except KeyError: raise EnvironmentError( 'Provide AKISMET_API_KEY environment setting.') self.akismet = Akismet(akismet_api_key, is_test=True)
def comment_spam_check(sender, comment, request, **kwargs): """ Check a comment to see if Akismet flags it as spam and deletes it if it was detected as such. """ AKISMET_API_KEY = getattr(settings, 'AKISMET_API_KEY', False) if AKISMET_API_KEY: from akismet import Akismet ak = Akismet( key=AKISMET_API_KEY, blog_url='http://%s/' % Site.objects.get_current().domain ) if ak.verify_key(): data = { 'user_ip': request.META.get('REMOTE_ADDR', '127.0.0.1'), 'user_agent': request.META.get('HTTP_USER_AGENT', ''), 'referrer': request.META.get('HTTP_REFERER', ''), 'comment_type': 'comment', 'comment_author': comment.user_name.encode('utf-8'), } if ak.comment_check(comment.comment.encode('utf-8'), data=data, build_data=True): return False else: return True
def on_comment_was_posted(sender, comment, request, *args, **kwargs): try: from akismet import Akismet from akismet import AkismetError except: return if hasattr(settings, 'AKISMET_API_KEY'): ak = Akismet( key = settings.AKISMET_API_KEY, blog_url='http://%s/' % Site.objects.get(pk=settings.SITE_ID).domain ) else: return try: if ak.verify_key(): data = { 'user_ip': request.META.get('REMOTE_ADDR', '127.0.0.1'), 'user_agent': request.META.get('HTTP_USER_AGENT', ''), 'referrer': request.META.get('HTTP_REFERER', ''), 'comment_type': 'comment', 'comment_author': comment.user_name.encode('utf-8'), } if ak.comment_check(comment.content.encode('utf-8'), data=data, build_data=True): comment.is_public = False comment.save() except AkismetError: comment.save()
def save(self, *args, **kwargs): from akismet import Akismet from django.conf import settings if not self.pk: api = Akismet(agent = 'transphorm/akismet 0.1') api.setAPIKey( getattr(settings, 'AKISMET_KEY') ) print 'Set API key' data = { 'comment_author': self.name, 'comment_author_url': self.website, 'user_ip': self.ip, 'user_agent': self.user_agent } if api.comment_check(self.body, data): print 'Comment is SPAM' self.is_spam = True else: print 'Comment is NOT spam' super(Comment, self).save(*args, **kwargs)
def moderate(self, comment, content_object, request): """Need to pass Akismet test""" if not AKISMET_COMMENT: return False try: from akismet import Akismet from akismet import APIKeyError except ImportError: return False akismet = Akismet(key=AKISMET_API_KEY, blog_url='%s://%s/' % ( PROTOCOL, Site.objects.get_current().domain)) if akismet.verify_key(): akismet_data = { 'user_ip': request.META.get('REMOTE_ADDR', ''), 'user_agent': request.META.get('HTTP_USER_AGENT', ''), 'referrer': request.META.get('HTTP_REFERER', 'unknown'), 'permalink': content_object.get_absolute_url(), 'comment_type': 'comment', 'comment_author': smart_str(comment.userinfo.get('name', '')), 'comment_author_email': smart_str(comment.userinfo.get('email', '')), 'comment_author_url': smart_str(comment.userinfo.get('url', '')), } is_spam = akismet.comment_check(smart_str(comment.comment), data=akismet_data, build_data=True) if is_spam: comment.save() user = comment.content_object.authors.all()[0] comment.flags.create(user=user, flag='spam') return is_spam raise APIKeyError("Your Akismet API key is invalid.")
def _check_akismet(self): def add_error(error): self._add_error('akismet_api_key', error) try: from akismet import Akismet except ImportError: self._add_error( 'spam_protection_method', _('Akismet library is not installed. Use ' '"easy_install akismet" or "pip install ' 'akismet".')) api_key = getattr(settings, "AKISMET_API_KEY", self.cleaned_data['akismet_api_key']) if not hasattr(settings, "AKISMET_API_KEY"): if not api_key: add_error(Field.default_error_messages['required']) else: ak = Akismet(key=api_key, blog_url='http://%s/' % (Site.objects.get(pk=settings.SITE_ID).domain)) if not ak.verify_key(): add_error(_('The API Key is not valid.'))
def check_typepad_antispam(comment, request): logger = logging.getLogger('fccv.check_typepad_antispam') try: from akismet import Akismet except: return None if hasattr(settings, 'TYPEPAD_ANTISPAM_API_KEY'): ak = Akismet( key=settings.TYPEPAD_ANTISPAM_API_KEY, blog_url='http://%s/' % Site.objects.get(pk=settings.SITE_ID).domain ) ak.baseurl = 'api.antispam.typepad.com/1.1/' else: ak = Akismet( key=settings.AKISMET_API_KEY, blog_url='http://%s/' % Site.objects.get(pk=settings.SITE_ID).domain ) if ak.verify_key(): data = { 'user_ip': comment.ip_address, 'user_agent': request.META.get('HTTP_USER_AGENT', ''), 'referrer': request.META.get('HTTP_REFERER', ''), 'comment_type': 'comment', 'comment_author': comment.user_name.encode('utf-8'), } if ak.comment_check(comment.comment.encode('utf-8'), data=data, build_data=True): if settings.DEBUG: logger.debug("""TypePad AntiSpam thought this comment was spam.""") return .5 return None
def validate_comment(self, comment): akismet_enable = web.ctx.orm.query(Option).\ filter(Option.name=='comment_akismet_enable').first() if (not akismet_enable) or (not akismet_enable.value): return akismet_key = web.ctx.orm.query(Option).\ filter(Option.name=='comment_akismet_key').first() domain = web.ctx.get('homedomain', '') # create an Akismet instance ak = Akismet( key=akismet_key.value, # akismet key blog_url=domain # your blog url ) try: if ak.verify_key(): data = { 'user_ip': web.ctx.get('ip', ''), 'user_agent': web.ctx.env.get('HTTP_USER_AGENT', ''), 'referer': web.ctx.env.get('HTTP_REFERER', 'unknown'), 'comment_type': 'comment', 'comment_author': comment.author.encode('utf-8') } if ak.comment_check(comment.content.encode('utf-8'), data=data, build_data=True): comment.status = 'spam' ak.submit_spam(comment.content.encode('utf-8'), data=data, build_data=True) except AkismetError, APIKeyError: pass
def akismet_check_spam(text, request): """Returns True if spam found, false if not, May raise exceptions if something is not right with the Akismet account/service/setup""" if not askbot_settings.USE_AKISMET: return False try: if askbot_settings.USE_AKISMET and askbot_settings.AKISMET_API_KEY == "": raise ImproperlyConfigured("You have not set AKISMET_API_KEY") data = { "user_ip": request.META.get("REMOTE_ADDR"), "user_agent": request.environ["HTTP_USER_AGENT"], "comment_author": smart_str(request.user.username), } if request.user.is_authenticated(): data.update({"comment_author_email": request.user.email}) api = Akismet( askbot_settings.AKISMET_API_KEY, smart_str(site_url(reverse("questions"))), "Askbot/%s" % get_version() ) return api.comment_check(text, data, build_data=False) except APIKeyError: logging.critical("Akismet Key is missing") except AkismetError: logging.critical("Akismet error: Invalid Akismet key or Akismet account issue!") except Exception, e: logging.critical((u"Akismet error: %s" % unicode(e)).encode("utf-8"))
def _akismet_check(self, comment, content_object, request): """ Connects to Akismet and returns True if Akismet marks this comment as spam. Otherwise returns False. """ # Get Akismet data AKISMET_API_KEY = appsettings.AKISMET_API_KEY if not AKISMET_API_KEY: raise ImproperlyConfigured( 'You must set AKISMET_API_KEY to use comment moderation with Akismet.' ) current_domain = get_current_site(request).domain auto_blog_url = '{0}://{1}/'.format( request.is_secure() and 'https' or 'http', current_domain) blog_url = appsettings.AKISMET_BLOG_URL or auto_blog_url akismet_api = Akismet(key=AKISMET_API_KEY, blog_url=blog_url) if akismet_api.verify_key(): akismet_data = self._get_akismet_data(blog_url, comment, content_object, request) if akismet_api.comment_check(smart_str(comment.comment), data=akismet_data, build_data=True): return True return False
def check_spam(self, request, comment, key, blog_url=None, base_url=None): try: from akismet import Akismet except: return False if blog_url is None: blog_url = "http://%s/" % Site.objects.get_current().domain ak = Akismet(key=key, blog_url=blog_url) if base_url is not None: ak.baseurl = base_url if ak.verify_key(): data = { "user_ip": request.META.get("HTTP_X_FORWARDED_FOR", "127.0.0.1"), "user_agent": request.META.get("HTTP_USER_AGENT", ""), "referrer": request.META.get("HTTP_REFERER", ""), "comment_type": "comment", "comment_author": comment.user_name.encode("utf-8"), } if ak.comment_check(comment.comment.encode("utf-8"), data=data, build_data=True): return True return False
def _akismet_check(self, comment, content_object, request): """ Connects to Akismet and returns True if Akismet marks this comment as spam. Otherwise returns False. """ # Check if the akismet library is installed, fail silently if # settings.DEBUG is False and return False (not moderated) try: from akismet import Akismet except ImportError: raise ImportError('Akismet library is not installed. "easy_install akismet" does the job.') # Check if the akismet api key is set, fail silently if # settings.DEBUG is False and return False (not moderated) AKISMET_API_KEY = getattr(settings, 'AKISMET_SECRET_API_KEY', False) if not AKISMET_API_KEY: raise ImproperlyConfigured('You must set AKISMET_SECRET_API_KEY with your api key in your settings file.') from django.utils.encoding import smart_str akismet_api = Akismet(key=AKISMET_API_KEY, blog_url='%s://%s/' % (request.is_secure() and 'https' or 'http', Site.objects.get_current().domain)) if akismet_api.verify_key(): akismet_data = {'comment_type': 'comment', 'referrer': '', 'user_agent': '', 'user_ip': comment.ip_address} if akismet_api.comment_check(smart_str(comment.comment), data=akismet_data, build_data=True): return True return False
def is_spam(request, comment): # If request user has uploaded sounds, we don't check for spam if request.user.sounds.count() > 0: return False domain = "http://%s" % Site.objects.get_current().domain api = Akismet(key=settings.AKISMET_KEY, blog_url=domain) data = { 'user_ip': request.META.get('REMOTE_ADDR', '127.0.0.1'), 'user_agent': request.META.get('HTTP_USER_AGENT', ''), 'referrer': request.META.get('HTTP_REFERER', ''), 'comment_type': 'comment', 'comment_author': request.user.username.encode("utf-8") if request.user.is_authenticated else '', } if False: # set this to true to force a spam detection data['comment_author'] = "viagra-test-123" try: if api.comment_check(comment.encode('utf-8'), data=data, build_data=True): if request.user.is_authenticated: AkismetSpam.objects.create(user=request.user, spam=comment) return True else: return False except AkismetError: # failed to contact akismet... return False except HTTPError: # failed to contact akismet... return False except URLError: # failed to contact akismet... return False
def verify_installation(request): try: from akismet import Akismet except ImportError: print >> sys.stderr, "Missing module 'akismet'.", return False config = request.get_configuration() # try to check to se make sure that the config file has a key if not config.has_key("akismet_api_key"): print >> sys.stderr, "Missing required configuration value 'akismet_key'", return False try: from akismet import Akismet a = Akismet(config['akismet_api_key'], config['base_url'], agent='PyBlosxom/1.3') if not a.verify_key(): print >> sys.stderr, "Could not verify akismet API key.", return False except ImportError: print "Unknown error loading Akismet module!", return False return True
def check_with_akismet(comment=None, request=None, **kwargs): if config_value("PRODUCT", "AKISMET_ENABLE"): key = config_value("PRODUCT", "AKISMET_KEY") if key: site = Site.objects.get_current() shop = urlresolvers.reverse('satchmo_shop_home') from akismet import Akismet akismet = Akismet(key=settings.AKISMET_API_KEY, blog_url='http://%s' % url_join(site.domain, shop)) if akismet.verify_key(): akismet_data = { 'comment_type': 'comment', 'referrer': request.META.get('HTTP_REFERER', ""), 'user_ip': comment.ip_address, 'user_agent': '' } if akismet.comment_check(smart_str(comment.comment), data=akismet_data, build_data=True): comment.is_public = False comment.save() log.info("Akismet marked comment #%i as spam", comment.id) else: log.debug("Akismet accepted comment #%i", comment.id) else: log.warn("Akismet key '%s' not accepted by akismet service.", key) else: log.info( "Akismet enabled, but no key found. Please put in your admin settings." )
def _akismet_check(self, comment, content_object, request): """ Connects to Akismet and returns True if Akismet marks this comment as spam. Otherwise returns False. """ # Get Akismet data AKISMET_API_KEY = appsettings.AKISMET_API_KEY if not AKISMET_API_KEY: raise ImproperlyConfigured('You must set AKISMET_API_KEY to use comment moderation with Akismet.') current_domain = get_current_site(request).domain auto_blog_url = '{0}://{1}/'.format(request.is_secure() and 'https' or 'http', current_domain) blog_url = appsettings.AKISMET_BLOG_URL or auto_blog_url akismet_api = Akismet( key=AKISMET_API_KEY, blog_url=blog_url ) if akismet_api.verify_key(): akismet_data = self._get_akismet_data(blog_url, comment, content_object, request) if akismet_api.comment_check(smart_str(comment.comment), data=akismet_data, build_data=True): return True return False
def video(solicitud, video_slug): # video por slug (nombre) video = get_object_or_404(Video, slug=video_slug) # si son datos del formulario de comentarios if solicitud.method == 'POST': form = VideoComentarioForm(solicitud.POST) # validar los datos if(form.is_valid()): # asignar el video comentario = form.save(commit=False) comentario.video = video # detectar spam api = Akismet(key=settings.AKISMET_API_KEY, blog_url=settings.AKISMET_URL, agent=settings.AKISMET_AGENT) if api.verify_key(): if not api.comment_check(comment=comentario.content, data={ 'user_ip': solicitud.META['REMOTE_ADDR'], 'user_agent': solicitud.META['HTTP_USER_AGENT'] }): # guardar el video comentario.save() else: form = VideoComentarioForm() comentarios = VideoComentario.objects.filter(video_id=video.id).\ order_by('-fecha', '-id') return render_to_response('website/video.html', { 'video': video, # datos del video particular 'form': form, # formulario de comentarios 'comentarios': comentarios # comentarios al video })
def moderate(self, comment, content_object, request): """Need to pass Akismet test""" if not AKISMET_COMMENT: return False try: from akismet import Akismet from akismet import APIKeyError except ImportError: return False akismet = Akismet(key=AKISMET_API_KEY, blog_url="%s://%s/" % (PROTOCOL, Site.objects.get_current().domain)) if akismet.verify_key(): akismet_data = { "user_ip": request.META.get("REMOTE_ADDR", ""), "user_agent": request.META.get("HTTP_USER_AGENT", ""), "referrer": request.META.get("HTTP_REFERER", "unknown"), "permalink": content_object.get_absolute_url(), "comment_type": "comment", "comment_author": smart_str(comment.userinfo.get("name", "")), "comment_author_email": smart_str(comment.userinfo.get("email", "")), "comment_author_url": smart_str(comment.userinfo.get("url", "")), } is_spam = akismet.comment_check(smart_str(comment.comment), data=akismet_data, build_data=True) if is_spam: comment.save() user = comment.content_object.authors.all()[0] comment.flags.create(user=user, flag="spam") return is_spam raise APIKeyError("Your Akismet API key is invalid.")
def on_comment_was_posted(sender, comment, request, *args, **kwargs): # spam checking can be enabled/disabled per the comment's target Model # if comment.content_type.model_class() != Entry: # return from django.contrib.sites.models import Site from django.conf import settings try: from akismet import Akismet except: return ak = Akismet(key=settings.AKISMET_API_KEY, blog_url='http://%s/' % Site.objects.get(pk=settings.SITE_ID).domain) if ak.verify_key(): data = { 'user_ip': request.META.get('REMOTE_ADDR', '127.0.0.1'), 'user_agent': request.META.get('HTTP_USER_AGENT', ''), 'referrer': request.META.get('HTTP_REFERER', ''), 'comment_type': 'comment', 'comment_author': comment.user_name.encode('utf-8'), } if ak.comment_check(comment.comment.encode('utf-8'), data=data, build_data=True): comment.flags.create(user=comment.content_object.author, flag='spam') comment.is_public = False comment.save()
def _akismet_spam_check(self): """ Checks the comment against the Akismet spam prevention web service. Returns "spam" if the comment is found to be spam, "ham" if the comment isn't found to be spam, and "error" if the check doesn't complete successfully. """ from akismet import Akismet, AkismetError import unicodedata akismet = Akismet(key=settings.AKISMET_API_KEY, blog_url=settings.AKISMET_SITE_URL, agent=settings.AKISMET_USER_AGENT) comment_data = { 'user_ip': self.author_ip_address, 'user_agent': self.author_user_agent_string, 'comment_author': unicodedata.normalize('NFKD', self.author_name).encode('ascii','ignore'), 'comment_author_email': self.author_email_address, 'comment_author_url': self.author_url, } try: # Pass the comment through Akisment and find out if it thinks it's spam. is_spam = akismet.comment_check(comment=unicodedata.normalize('NFKD', unicode(self.body)).encode('ascii','ignore'), data=comment_data) if is_spam == True: return "spam" elif is_spam == False: return "ham" except AkismetError: pass return "error"
def wrapper(request, *args, **kwargs): if askbot_settings.USE_AKISMET and askbot_settings.AKISMET_API_KEY == "": raise ImproperlyConfigured('You have not set AKISMET_API_KEY') if askbot_settings.USE_AKISMET and request.method == "POST": comment = smart_str(request.POST[field]) data = { 'user_ip': request.META.get('REMOTE_ADDR'), 'user_agent': request.environ['HTTP_USER_AGENT'], 'comment_author': smart_str(request.user.username), } if request.user.is_authenticated(): data.update({'comment_author_email': request.user.email}) from akismet import Akismet api = Akismet(askbot_settings.AKISMET_API_KEY, smart_str(site_url(reverse('questions'))), "Askbot/%s" % get_version()) if api.comment_check(comment, data, build_data=False): logging.debug('Spam detected in %s post at: %s', request.user.username, datetime.datetime.now()) spam_message = _('Spam was detected on your post, sorry ' 'for if this is a mistake') if request.is_ajax(): return HttpResponseForbidden( spam_message, mimetype="application/json") else: request.user.message_set.create(message=spam_message) return HttpResponseRedirect(reverse('index')) return view_func(request, *args, **kwargs)
def handle_noargs(self, **options): comments = Comment.objects.filter(is_public=True, is_removed=False, submit_date__gte=datetime.date( 2010, 07, 01)) for comment in comments: a = Akismet(AKISMET_KEY, blog_url='http://%s/' % Site.objects.get_current().domain) akismet_data = { 'user_ip': comment.ip_address, 'user_agent': 'Mozilla/5.0 (X11; U; Linux x86_64; de; rv:1.9.2.8) Gecko/20100723 Ubuntu/10.04 (lucid) Firefox/3.6.8', 'comment_author': comment.user_name.encode('ascii', 'ignore'), 'comment_author_email': comment.user_email.encode('ascii', 'ignore'), 'comment_author_url': comment.user_url.encode('ascii', 'ignore'), 'comment_type': 'comment', } is_spam = a.comment_check( comment.comment.encode('ascii', 'ignore'), akismet_data) if is_spam: post = Post.objects.get(pk=comment.object_pk) #print comment.user_name.encode('ascii', 'ignore'), post.get_absolute_url() + '#' + str(comment.pk) comment.is_removed = True comment.is_public = False comment.save()
def clean_body(self): """ Perform Akismet validation of the message. """ if 'body' in self.cleaned_data and getattr(settings, 'AKISMET_API_KEY', ''): from akismet import Akismet from django.utils.encoding import smart_str akismet_api = Akismet(key=settings.AKISMET_API_KEY, blog_url='http://%s/' % Site.objects.get_current().domain) if akismet_api.verify_key(): akismet_data = { 'comment_type': 'comment', 'referer': self.request.META.get('HTTP_REFERER', ''), 'user_ip': self.request.META.get('REMOTE_ADDR', ''), 'user_agent': self.request.META.get('HTTP_USER_AGENT', '') } if akismet_api.comment_check(smart_str( self.cleaned_data['body']), data=akismet_data, build_data=True): raise forms.ValidationError( u"Akismet thinks this message is spam") return self.cleaned_data['body']
def on_comment_will_be_posted(sender, comment, request, *args, **kwargs): if hasattr(settings, 'ADV_COMMENTS_SPAMPROTECTION'): if not settings.ADV_COMMENTS_SPAMPROTECTION: return #if spamprotection is the choice, go on try: from akismet import Akismet except: return ak = Akismet( key=settings.ADV_COMMENTS_AKISMET_API_KEY, blog_url='http://%s/' % Site.objects.get(pk=settings.SITE_ID).domain ) if ak.verify_key(): data = { 'user_ip': request.META.get('REMOTE_ADDR', '127.0.0.1'), 'user_agent': request.META.get('HTTP_USER_AGENT', ''), 'referrer': request.META.get('HTTP_REFERER', ''), 'comment_type': 'comment', 'comment_author': comment.user_name.encode('utf-8'), } if ak.comment_check(comment.comment.encode('utf-8'), data=data, build_data=True): return False
def clean_body(self): """ Perform Akismet validation of the message. """ if 'body' in self.cleaned_data and getattr(settings, 'AKISMET_API_KEY', ''): from akismet import Akismet from django.utils.encoding import smart_str akismet_api = Akismet(key=settings.AKISMET_API_KEY, blog_url='http://%s/' % Site.objects.get_current().domain) if self.cleaned_data.get('email',''): if akismet_api.verify_key(): akismet_data = { 'comment_type': 'comment', 'comment_author':self.cleaned_data['name'].encode('utf-8'), 'comment_author_email':self.cleaned_data['email'].encode('utf-8'), 'referer': self.request.META.get('HTTP_REFERER', ''), 'user_ip': self.request.META.get('REMOTE_ADDR', ''), 'user_agent': self.request.META.get('HTTP_USER_AGENT', '') } if akismet_api.comment_check(smart_str(self.cleaned_data['body']), data=akismet_data, build_data=True): raise forms.ValidationError(_(u"Akismet thinks this message is spam")) else: return False return self.cleaned_data['body']
def _akismet_check(self, comment, content_object, request): """ Connects to Akismet and returns True if Akismet marks this comment as spam. Otherwise returns False. """ # Get Akismet data AKISMET_API_KEY = appsettings.AKISMET_API_KEY if not AKISMET_API_KEY: raise ImproperlyConfigured( 'You must set AKISMET_API_KEY to use comment moderation with Akismet.' ) current_domain = get_current_site(request).domain auto_blog_url = '{0}://{1}/'.format( request.is_secure() and 'https' or 'http', current_domain) blog_url = appsettings.AKISMET_BLOG_URL or auto_blog_url akismet = Akismet( AKISMET_API_KEY, blog=blog_url, is_test=int(bool(appsettings.AKISMET_IS_TEST)), application_user_agent='django-fluent-comments/{0}'.format( fluent_comments.__version__), ) akismet_data = self._get_akismet_data(blog_url, comment, content_object, request) return akismet.check( **akismet_data) # raises AkismetServerError when key is invalid
def check_spam(self, request, comment, key, blog_url=None, base_url=None): try: from akismet import Akismet except: return False if blog_url is None: blog_url = 'http://%s/' % Site.objects.get_current().domain ak = Akismet( key=settings.AKISMET_API_KEY, blog_url=blog_url ) if base_url is not None: ak.baseurl = base_url if ak.verify_key(): data = { 'user_ip': request.META.get('REMOTE_ADDR', '127.0.0.1'), 'user_agent': request.META.get('HTTP_USER_AGENT', ''), 'referrer': request.META.get('HTTP_REFERER', ''), 'comment_type': 'comment', 'comment_author': comment.user_name.encode('utf-8'), } if ak.comment_check(comment.comment.encode('utf-8'), data=data, build_data=True): return True return False
def akismet_check_spam(text, request): """Returns True if spam found, false if not, May raise exceptions if something is not right with the Akismet account/service/setup""" try: if askbot_settings.USE_AKISMET and askbot_settings.AKISMET_API_KEY == "": raise ImproperlyConfigured('You have not set AKISMET_API_KEY') data = {'user_ip': request.META.get('REMOTE_ADDR'), 'user_agent': request.environ['HTTP_USER_AGENT'], 'comment_author': smart_str(request.user.username) } if request.user.is_authenticated(): data.update({'comment_author_email': request.user.email}) api = Akismet( askbot_settings.AKISMET_API_KEY, smart_str(site_url(reverse('questions'))), "Askbot/%s" % get_version() ) return api.comment_check(text, data, build_data=False) except APIKeyError: logging.critical('Akismet Key is missing') except AkismetError: logging.critical('Akismet error: Invalid Akismet key or Akismet account issue!') except Exception, e: logging.critical((u'Akismet error: %s' % unicode(e)).encode('utf-8'))
def on_comment_was_posted(sender, comment, request, *args, **kwargs): """ Spam guard for comments. Lifted from this guy: http://sciyoshi.com/blog/2008/aug/27/using-akismet-djangos-new-comments-framework/ """ from django.contrib.sites.models import Site from django.conf import settings from django.template import Context, loader from django.core.mail import send_mail try: from akismet import Akismet except: return # use TypePad's AntiSpam if the key is specified in settings.py if hasattr(settings, 'TYPEPAD_ANTISPAM_API_KEY'): ak = Akismet( key=settings.TYPEPAD_ANTISPAM_API_KEY, blog_url='http://%s/' % Site.objects.get(pk=settings.SITE_ID).domain ) ak.baseurl = 'api.antispam.typepad.com/1.1/' else: ak = Akismet( key=settings.AKISMET_API_KEY, blog_url='http://%s/' % Site.objects.get(pk=settings.SITE_ID).domain ) if ak.verify_key(): data = { 'user_ip': request.META.get('REMOTE_ADDR', '127.0.0.1'), 'user_agent': request.META.get('HTTP_USER_AGENT', ''), 'referrer': request.META.get('HTTP_REFERER', ''), 'comment_type': 'comment', 'comment_author': comment.user_name.encode('utf-8'), } # If it's spam... if ak.comment_check(comment.comment.encode('utf-8'), data=data, build_data=True): comment.flags.create( user=comment.content_object.author, flag='spam' ) comment.is_public = False comment.is_removed = True comment.save() # If it's not... else: # Send an email recipient_list = [manager_tuple[1] for manager_tuple in settings.MANAGERS] t = loader.get_template('comments/comment_notification_email.txt') c = Context({ 'comment': comment, 'content_object': comment.content_object }) subject = '[%s] New comment posted on "%s"' % (Site.objects.get_current().name, comment.content_object) message = t.render(c) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipient_list, fail_silently=True)
def _akismet_api(): api = Akismet(agent='*****@*****.**') if not api.key: api.setAPIKey(settings.AKISMET_KEY, 'http://vorushin2.wordpress.com') if not api.verify_key(): return None else: return api
def moderate(self, comment, content_object, request): already_moderated = super(EntryModerator, self).moderate(comment, content_object) if already_moderated: return True akismet_api = Akismet(key=settings.AKISMET_API_KEY, blog_url="http:/%s/" % Site.objects.get_current().domain) if akismet_api.verify_key(): akismet_data = { 'comment_type': 'comment', 'referrer': request.META['HTTP_REFERER'], 'user_ip': comment.ip_address, 'user-agent': request.META['HTTP_USER_AGENT']} return akismet_api.comment_check(smart_str(comment.comment), akismet_data, build_data=True) return False
def test_timeout(self): self.akismet = Akismet(os.environ['AKISMET_API_KEY'], timeout=0.000001, is_test=True) with self.assertRaises(requests.ConnectionError): self.akismet.submit_ham('127.0.0.1', USER_AGENT, blog='http://127.0.0.1')
def akismet_check(request=None, comment_author='', comment_author_email='', comment_author_url='', comment_content='', akismet_api_key=None): """ Connects to Akismet and returns True if Akismet marks this content as spam. Otherwise returns False. """ # Check if the akismet library is installed try: from akismet import Akismet except ImportError: raise ImportError( 'Akismet library is not installed. "easy_install akismet" does the job.' ) # Check if the akismet api key is set, fail silently if # settings.DEBUG is False and return False (not moderated) AKISMET_API_KEY = akismet_api_key or getattr(settings, 'AKISMET_API_KEY', False) if not AKISMET_API_KEY: raise ImproperlyConfigured( 'You must set AKISMET_API_KEY with your api key in your settings file.' ) ak = Akismet(key=AKISMET_API_KEY, blog_url='http://%s/' % Site.objects.get(pk=settings.SITE_ID).domain) if ak.verify_key(): if request is not None: data = { 'user_ip': request.META.get('REMOTE_ADDR', '127.0.0.1'), 'user_agent': request.META.get('HTTP_USER_AGENT', ''), 'referrer': request.META.get('HTTP_REFERER', ''), } else: data = { 'user_ip': '', 'user_agent': '', 'referrer': '', } data.update({'comment_author': comment_author.encode('utf-8')}) data.update( {'comment_author_email': comment_author_email.encode('utf-8')}) data.update({'comment_author_url': comment_author_url.encode('utf-8')}) # Send the request to Akismet if ak.comment_check(comment_content.encode('utf-8'), data=data, build_data=True): return True return False
def is_spam(text, request): """Generic spam checker interface.""" if settings.AKISMET_API_KEY: from akismet import Akismet akismet = Akismet(settings.AKISMET_API_KEY, get_site_url()) return akismet.comment_check(get_ip_address(request), request.META.get('HTTP_USER_AGENT', ''), comment_content=text, comment_type='comment') return False
class SpamInspectionMiddleware(object): def __init__(self): # Create Akismet instance and check whether the API key is valid or not kwargs = { 'key': settings.SPAMINSPECTOR_AKISMET_KEY, 'blog_url': "http://%s/" % Site.objects.get(pk=settings.SITE_ID).domain, } self.akismet = Akismet(**kwargs) if not self.akismet.verify_key(): warnings.warn("Invalid Akismet API key. Spam inspection feture is turned off.") raise MiddlewareNotUsed # Create inspection_views dict self.inspection_profiles = {} for view_func, profile in settings.SPAMINSPECTOR_VIEWS: if isinstance(view_func, basestring): # Get callable view_func from path view_func = get_callable(view_func) self.inspection_profiles[view_func] = profile def _is_spam(self, request, profile): def _get(request, profile, key): value = profile.get(key, "") if callable(value): value = value(request) if isinstance(value, unicode): value = value.encode('utf-8') return value data = { 'user_ip': request.META.get('REMOTE_ADDR', '127.0.0.1'), 'user_agent': request.META.get('HTTP_USER_AGENT', ''), 'referrer': request.META.get('HTTP_REFERER', ''), 'comment_type': _get(request, profile, 'comment_type'), 'comment_author': _get(request, profile, 'comment_author'), 'comment_email': _get(request, profile, 'comment_email'), 'comment_url': _get(request, profile, 'comment_url'), } contents = _get(request, profile, 'comment_contents') return self.akismet.comment_check(contents, data, build_data=True) def process_view(self, request, view_func, view_args, view_kwargs): if view_func in self.inspection_profiles.keys(): # Check spamness of request inspection_profile = self.inspection_profiles[view_func] if self._is_spam(request, inspection_profile): # Detected as spam if settings.SPAMINSPECTOR_SPAM_TEMPLATE: rendered = loader.render_to_string( settings.SPAMINSPECTOR_SPAM_TEMPLATE, context_instance=RequestContext(request)) return HttpResponse(rendered, status=403) else: return HttpResponseForbidden("Your comment was detected as a SPAM") return None
def check_spam(ip, ua, author, content) -> int: # 0 means okay token = os.getenv("askismet") if token: with contextlib.suppress(Exception): akismet = Akismet(token, blog="https://yyets.dmesg.app/") return akismet.check(ip, ua, comment_author=author, blog_lang="zh_cn", comment_type="comment", comment_content=content) return 0
def report_spam(text, user_ip, user_agent): if not settings.AKISMET_API_KEY: return from akismet import Akismet, ProtocolError akismet = Akismet(settings.AKISMET_API_KEY, get_site_url()) try: akismet.submit_spam( user_ip, user_agent, comment_content=text, comment_type="comment" ) except (ProtocolError, OSError): report_error()
def report_spam(text, user_ip, user_agent): if not settings.AKISMET_API_KEY: return from akismet import Akismet, ProtocolError akismet = Akismet(settings.AKISMET_API_KEY, get_site_url()) try: akismet.submit_spam(user_ip, user_agent, comment_content=text, comment_type='comment') except ProtocolError as error: report_error(error, sys.exc_info())
def text_is_spam(text, request): # Based on a blog post by 'sciyoshi': # http://sciyoshi.com/blog/2008/aug/27/using-akismet-djangos-new-comments-framework/ # This will return 'True' is the given text is deemed to be spam, or # False if it is not spam. If it cannot be checked for some reason, we # assume it isn't spam. from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured try: from akismet import Akismet except ImportError: return False try: site = Site.objects.get_current() except ImproperlyConfigured: site = Site(domain='configure-django-sites.com') # see https://akismet.readthedocs.io/en/latest/overview.html#using-akismet apikey = None if hasattr(settings, 'TYPEPAD_ANTISPAM_API_KEY'): apikey = settings.TYPEPAD_ANTISPAM_API_KEY elif hasattr(settings, 'PYTHON_AKISMET_API_KEY'): # new env var expected by python-akismet package apikey = settings.PYTHON_AKISMET_API_KEY elif hasattr(settings, 'AKISMET_API_KEY'): # deprecated, but kept for backward compatibility apikey = settings.AKISMET_API_KEY else: return False ak = Akismet( blog_url='http://%s/' % site.domain, key=apikey, ) if hasattr(settings, 'TYPEPAD_ANTISPAM_API_KEY'): ak.baseurl = 'api.antispam.typepad.com/1.1/' if ak.verify_key(): ak_data = { 'user_ip': request.META.get('REMOTE_ADDR', '127.0.0.1'), 'user_agent': request.META.get('HTTP_USER_AGENT', ''), 'referrer': request.META.get('HTTP_REFERER', ''), 'comment_type': 'comment', 'comment_author': '', } return ak.comment_check(smart_text(text), data=ak_data) return False
def check(comment): from fypress.admin import Option if False: #check akismetapikey, ip= request.remote_addr akismet = Akismet('1ba29d6f120c', blog=Options.get('url'), user_agent=request.headers.get('User-Agent')) rv = akismet.check(comment.ip, request.headers.get('User-Agent'), comment_author=comment.author, comment_author_email=comment.email, comment_author_url=comment.uri, comment_content=comment.content) print rv