示例#1
0
 def valid_ex(cls, user_data):
     is_valid = True
     if len(user_data['exercise_name']) < 2 or user_data['exercise_name'] == '':
         is_valid = False
         flash("Please Enter an Exercise Name", "ex_error")
     if profanity.contains_profanity(user_data['exercise_name']) == True:
         is_valid = False
         flash("Please Enter an Appropriate Exercise Name", "ex_error");
     if user_data['hour'] == '':
         is_valid = False
         flash("Please Enter Amount of Hours", "ex_error")
     if user_data['minutes'] == '':
         is_valid = False
         flash("Please Enter Amount of Minutes", "ex_error")
     if user_data['calories_burned'] == '':
         is_valid = False
         flash("Please Enter Est. Calories Burned", "ex_error")
     if user_data['category'] == 'running' or user_data['category'] == 'walking' or user_data['category'] == 'cycling':
         if user_data['miles'] == '' or user_data['miles'] == 0:
             is_valid = False
             flash("Please Enter Amount of Miles", "ex_error")
     if user_data['category'] == 'weight_lifting':
         if user_data['reps'] == '':
             is_valid = False
             flash("Please Enter Amount of Repetitions", "ex_error")
         if user_data['sets'] == '':
             is_valid = False
             flash("Please Enter Amount of Sets", "ex_error")
     if user_data['category'] == 'other':
         if user_data['desc'] == '' or profanity.contains_profanity(user_data['desc']) == True:
             is_valid = False
             flash("Please Enter Valid Description", "ex_error")
     return is_valid
示例#2
0
 def processDone(self):
     global transcripts
     global s2t
     global fs
     global data
     wavlength = len(data) / float(fs)
     ydata = [i[0] for i in data]
     xdata = range(len(ydata))
     graphLineColor = (200, 200, 234)
     graphCriticalLineColor = (255, 128, 128)
     timeCount = 0
     for i in s2t:
         dataPointLeft = int((timeCount / wavlength) * len(ydata))
         dataPointRight = int((i[1] / wavlength) * len(ydata))
         color = graphCriticalLineColor if profanity.contains_profanity(
             i[0]) else graphLineColor
         self.graphWidget.plot(xdata[dataPointLeft:dataPointRight],
                               ydata[dataPointLeft:dataPointRight],
                               pen=pg.mkPen(color=color))
         timeCount = i[1]
     self.transcriptBox.clear()
     criticalBrush = QBrush(QColor(41, 41, 61))
     for tr in transcripts:
         item = QListWidgetItem(str(profanity.censor(tr)).capitalize())
         if profanity.contains_profanity(tr):
             item.setForeground(criticalBrush)
             item.setBackground(QColor(255, 128, 128))
         self.transcriptBox.addItem(item)
     self.recordButtonOn = True
示例#3
0
    def analyze_titles(self):
        start = time.time()
        all_video_titles = self.main_channel_html.findAll(
            "h3", {"class": "yt-lockup-title"})
        video_titles = []
        for i in range(10):
            video_title = all_video_titles[i].text
            if profanity.contains_profanity(video_title):
                self.bad_words += 1
            video_titles.append(video_title)
            video_id = all_video_titles[i].findAll("a", href=True)
            try:
                transcript = YouTubeTranscriptApi.get_transcript(
                    self.get_video_id(video_id[0]['href']))
                for j in range(len(transcript)):
                    if time.time() - start > 10:
                        break
                    if profanity.contains_profanity(transcript[j]["text"]):
                        self.bad_words += 1
            except Exception as e:
                print(e)
                continue

        end = time.time()
        print("TIME FOR TITLES : " + str(end - start))
        return video_titles
示例#4
0
def validate_registration(post_data):

    errors = {}

    if len(post_data['first_name']) < 1 or post_data['first_name'] == '':
        errors['first_name'] = "First Name must contain 2 letters or more"

    if profanity.contains_profanity(post_data['first_name']) == True:
        errors['bad_first_name'] = "Please Enter an appropriate First Name"

    if len(post_data['last_name']) < 1 or post_data['last_name'] == '':
        errors['last_name'] = "Last Name must contain 2 letters or more"

    if profanity.contains_profanity(post_data['last_name']) == True:
        errors['last_name'] = "Please Enter an appropriate Last Name"

    if len(post_data['username']) < 4 or post_data['username'] == '':
        errors['username'] = "******"

    if profanity.contains_profanity(post_data['username']) == True:
        errors['bad_username'] = "******"

    if len(post_data['password']) < 7 or post_data['password'] == '':
        errors['password'] = "******"

    if post_data['password'] != post_data['conf_password']:
        errors['conf_password'] = "******"

    return errors
示例#5
0
 def test_custom_wordlist(self):
     custom_badwords = ["happy", "jolly", "merry"]
     profanity.load_censor_words(custom_badwords)
     # make sure it doesn't find real profanity anymore
     self.assertFalse(profanity.contains_profanity("F**k you!"))
     # make sure it finds profanity in a sentence containing custom_badwords
     self.assertTrue(profanity.contains_profanity("Have a merry day! :)"))
示例#6
0
def create_post(request):
    user = get_user(request)
    if request.method == "POST":
        received_json_data = json.loads(request.body, strict=False)
        category = received_json_data["category"]
        title = received_json_data["title"]
        content = received_json_data["content"]
        thumbnail = received_json_data["thumbnail"]
        author = user
        author_username = user.username
        hidden = False

        if profanity.contains_profanity(title) or profanity.contains_profanity(
                content):
            hidden = True

        post = Post(category=Category.objects.get(name=category),
                    title=title,
                    content=content,
                    thumbnail=thumbnail,
                    author=author,
                    author_username=author_username,
                    hidden=hidden)
        post.save()
        if post:
            data = {"id": post.id, "title": post.title}
            return HttpResponse(json.dumps(data),
                                content_type="application/json")
    return render(request, "create_post.html")
示例#7
0
async def video(ctx, *, query):
    search = SearchVideos(query, offset=1, mode="json", max_results=20)
    results = json.loads(search.result())
    l = []
    t = []
    tn = []
    v = []
    c = []
    r = random.randint(0, 4)
    for result in results["search_result"]:
        l.append(result['link'])
        t.append(result['title'])
        tn.append(result['thumbnails'][0])
        v.append(result['views'])
        c.append(result['channel'])
    embed = discord.Embed(title=t[r],
                          type='rich',
                          url=l[r],
                          colour=random.randint(0, 0xFFFFFF))
    embed.set_footer(text=f"Views: {v[r]} | Made by {c[r]}.")
    embed.set_thumbnail(url=tn[r])
    if not ctx.channel.is_nsfw() and profanity.contains_profanity(
            t[r]
    ) or not ctx.channel.is_nsfw() and profanity.contains_profanity(query):
        await ctx.send('you need to be in a nsfw channel to seartch this')
    else:
        await ctx.send(embed=embed)
    def post(self, request, pk, *args, **kwargs):
        user = request.user
        profile = Profile.objects.get(user=user)
        group = Group.objects.get(pk=pk)

        # Custom profanity words
        custom_badwords = CustomProfanity.objects.values_list('bad_word',
                                                              flat=True)
        profanity.load_censor_words(custom_badwords)

        if 'submit_post_form' in request.POST:
            post_form = PostForm(request.POST, request.FILES)
            comment_form = None
            valid = post_form.is_valid()

            if profanity.contains_profanity(
                    post_form.cleaned_data.get('content')):
                custom_profanity_error = 'Please remove any profanity/swear words. (Added by an admin. Contact an admin if you believe this is wrong.)'
                valid = False
                post_form.errors['content'] = custom_profanity_error

            if valid:
                post_instance = post_form.save(commit=False)
                post_instance.author = profile
                post_instance.group = group
                post_instance.save()
                return redirect('groups:view-group', pk=pk)

        elif 'submit_comment_form' in request.POST:
            comment_form = CommentForm(request.POST)
            post_form = None
            valid = comment_form.is_valid()

            if profanity.contains_profanity(
                    comment_form.cleaned_data.get('body')):
                custom_profanity_error = 'Please remove any profanity/swear words. (Added by an admin. Contact an admin if you believe this is wrong.)'
                valid = False
                comment_form.errors['body'] = custom_profanity_error

            if valid:
                post_id = request.POST.get("post_id")
                comment_instance = comment_form.save(commit=False)
                comment_instance.user = profile
                comment_instance.post = Post.objects.get(id=post_id)
                comment_instance.save()
                return redirect(request.headers.get('Referer'))

        group_posts = Post.objects.filter(group=group)

        context = {
            'profile': profile,
            'group': group,
            'posts': group_posts,
            'post_form': post_form,
            'comment_form': comment_form
        }

        return render(request, 'groups/view.html', context)
示例#9
0
def profanity_word(text, lang):
    if lang == 'vi':
        profanity.load_censor_words_from_file('banned_word.text')
        if profanity.contains_profanity(text):
            return profanity.censor(text, '-')
        return text
    profanity.load_censor_words()
    if profanity.contains_profanity(text):
        return profanity.censor(text, '*')
    return text
示例#10
0
def search(query, type, limit, safe):
    def googleSearch():
        g_clean = []
        if safe:
            url = 'https://www.google.com/search?client=ubuntu&channel=fs&q={}&ie=utf-8&oe=utf-8'.format(
                query)
        else:
            url = 'https://www.google.com/search?client=firefox-b-1-d&q={}&safe=images'.format(
                query)
        try:
            html = requests.get(url)
            if html.status_code == 200:
                soup = BeautifulSoup(html.text, 'lxml')
                a = soup.find_all('a')
                for i in a:
                    k = i.get('href')
                    try:
                        m = re.search("(?P<url>https?://[^\s]+)", k)
                        n = m.group(0)
                        rul = n.split('&')[0]
                        domain = urlparse(rul)
                        if (re.search('google.com', domain.netloc)):
                            continue
                        else:
                            g_clean.append(rul)
                    except:
                        continue
        except:
            print(str(Exception))
        finally:
            return g_clean

    y = 0
    final = ''
    for result in googleSearch():
        if safe and profanity.contains_profanity(
                result) or safe and profanity.contains_profanity(query):
            final += ''
        else:
            if type == 'link':
                if not result[-3] + result[-2] + result[-1] in [
                        'jpeg', 'jpg', 'png', 'gif'
                ]:
                    if y <= limit:
                        final += result + '\n'
                    y += 1
            else:
                if y <= limit:
                    final += result + '\n'
                y += 1
    return final
示例#11
0
    async def on_message(self, message):
        def _check(m):
            return (m.author == message.author and len(m.mentions)
                    and (datetime.utcnow() - m.created_at).seconds < 60)

        if not message.author.bot:
            if len(list(filter(lambda m: _check(m),
                               self.bot.cached_messages))) >= 2:
                await message.channel.send("Don't spam mentions",
                                           delete_after=15)
                unmutes = await self.kick_members(message, [message.author],
                                                  reason="Mention spam")

            elif profanity.contains_profanity(message.content):
                await message.delete()
                await message.channel.send("You can't use that word here",
                                           delete_after=10)

            elif message.channel.id not in self.links_allowed and search(
                    self.url_regex, message.content):
                await message.delete()
                await message.channel.send(
                    "You can't send links in this channel.", delete_after=10)

            elif (message.channel.id not in self.images_allowed
                  and any([hasattr(a, "width") for a in message.attachments])):
                await message.delete()
                await message.channel.send(
                    "You can't send images in this channel.", delete_after=10)
示例#12
0
async def on_message(message):
    message_content = message.content.lower()
    message_content = message_content.replace("*", "")
    # Ignore empty messages like photos
    if message_content == "":
        return
    if modules["lol"]:
        if message_content == "lol" and str(message.author.id) == "756569562677510175" or devmode:
            await message.channel.send('All hail TurtleDude!')
            logger.debug(f"Lol triggered")
    # Don't trigger on the bots messages
    if message.author == bot.user:
        return

    if modules["swear"]:
        logger.debug("Swear triggered")
        Admin = discord.utils.get(message.guild.roles, name="Admin")
        bot_builder = discord.utils.get(message.guild.roles, name="Bot Builder")
        # Exempt og_squad and bot builder
        if not Admin in message.author.roles or devmode:
            if not bot_builder in message.author.roles or devmode:
                # Uses Better Profanity to check if the string contains 1 or more bad words.
                if profanity.contains_profanity(message_content):
                    await message.delete()
                    await user_strike_manager(message, userstrikes)
    await counting(message)
    await bot.process_commands(message)
示例#13
0
    async def on_message(self, message: discord.Message):
        if self.bot.config["profanity-check"]:
            if profanity.contains_profanity(message.content) and isinstance(message.channel, discord.TextChannel):
                await message.delete()

                # todo check if the content is longer than the max chars for the description
                censored_content = profanity.censor(message.content, '\\*')

                embed = discord.Embed(
                    title=f"I have deleted a message from {message.author.display_name} because it contains bad words! ",
                    description=f"Content of the message:\n||{censored_content}||\n\uFEFF",
                    colour=int(self.bot.config["embed-colours"]["default"], 16)
                )

                embed.set_footer(text="This message will delete itself after 15 seconds!")
                await message.channel.send(embed=embed, delete_after=15)

        if not await self.bot.check_message_reply(message, False):
            return

        prefix = self.bot.get_my_prefix(self.bot, message)

        # if the bot gets mentioned it replies
        if f"<@!{self.bot.user.id}>" in message.content:
            await message.channel.send(embed=discord.Embed(
                title=f"I If you need my help use `{prefix}help` to get a list of the available commands.",
                colour=int(self.bot.config["embed-colours"]["default"], 16)
            ))
 def process_crime(self, tweet_json):
     """
     Process city-level CRIME scenario analysis on the tweet.
     """
     text = tweet_json['text']
     if profanity.contains_profanity(text):
         self.analysis_result['crime']['vulgar_tweet_count'] += 1
示例#15
0
async def filter_message(message):
    mydb = databaseConnection()
    mycursor = mydb.cursor()
    profanity.add_censor_words(censored_words)

    containsProfanity = False
    if profanity.contains_profanity(message.content.lower()):
        containsProfanity = True

    if containsProfanity:
        mycursor.execute("SELECT * FROM strikes WHERE user='******'".format(
            message.author.name))
        result = mycursor.fetchall()
        count = 1

        if result:
            print('User: {} is in strikes table'.format(message.author.name))
            for row in result:
                count = row[1] + 1
                sql = "UPDATE strikes SET count = {} WHERE user = '******'".format(
                    count, row[0])
                mycursor.execute(sql)
        else:
            print("User:  {} not in strikes table".format(message.author.name))
            sql = "INSERT INTO strikes (user, count) VALUES (%s, %s)"
            val = (message.author.name, count)
            mycursor.execute(sql, val)

        mydb.commit()
        mydb.close()

        await message.delete()
        await message.channel.send(
            "{}, your message has been deleted as it contains inappropriate text. And you have received a strike. Total Strikes: {}"
            .format(message.author.mention, count))
示例#16
0
def check_name(name):
    # covers no user input
    if len(name) < 1:
        return False

    # checks name for only letters
    if any(chr.isalpha() == False for chr in name):
        print("I think a name is supposed to have all letters!")
        return False

    # checks for profanity
    if profanity.contains_profanity(name):
        print("You shouldn't say that...")
        return False

    # asks user if name is correct; must enter yes or no

    name_correct = input(f'Is {name}, correct? (yes/no)\n\n')
    while True:
        if name_correct == "yes" or name_correct == "no":
            break
        print("Please enter yes or no.")
        name_correct = input(f'Is {name}, correct? (yes/no)\n\n')

    if name_correct == "no":
        return False

    return True
示例#17
0
    async def on_message(self, message):
        def _check(m):
            return (m.author == message.author and len(m.mentions)
                    and (datetime.utcnow() - m.created_at).seconds < 60)

        if not message.author.bot:
            if len(list(filter(lambda m: _check(m),
                               self.bot.cached_messages))) >= 5:
                await message.channel.send("No hagas SPAM de menciones!",
                                           delete_after=10)
                unmutes = await self.mute_members(message, [message.author],
                                                  5,
                                                  reason="SPAM de menciones")

                if len(unmutes):
                    await sleep(5)
                    await self.unmute_members(message.guild, [message.author])

            if profanity.contains_profanity(message.content):
                await message.delete()
                await message.channel.send("Mejora tú vocabulario por favor.",
                                           delete_after=10)

            elif message.channel.id not in self.links_allowed and search(
                    self.url_regex, message.content):
                await message.delete()
                await message.channel.send("No puedes enviar links aquí.",
                                           delete_after=10)
示例#18
0
def action_commands(commands):
    for target in commands:
        for command in commands[target]:
            command_l = command.lower()
            logger.info(f"processing command: {command_l}")
            if profanity.contains_profanity(command_l):
                send_message("Don't be rude or I'll eat all your crypto.", SIGNAL_USER, target)
            elif command_l == "help":
                send_message(textwrap.dedent(HELP_TEXT), SIGNAL_USER, target)
            elif command_l.startswith("getprice") or command_l.startswith("gp"):
                sep = command_l.startswith("gp") and "gp" or "getprice"
                symbol = command_l.split(sep)[1].strip()
                if not 3 <= len(symbol) <= 4  or not symbol.isalpha():
                    send_message("Symbol must contain alpha characters only and be 3 or 4 characters in length.", SIGNAL_USER, target)
                    continue
                cmd = """coinmon -f %s | tail -n2 | head -n1 | sed 's/\x1B\[[0-9;]\{1,\}[A-Za-z]//g'  | awk '{print $2, $4, $6, $8, $10, $12, $14}'""" % symbol
                logger.debug(f"Fetching price for symbol: {symbol}")
                p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True)
                p.wait()
                result = p.stdout.read().decode('utf-8').strip()
                if result:
                    rank, coin, price, change24h, marketcap, supply, volume24h = result.split()
                    response = f"Coin: {coin}\nRank: {rank}\nPrice USD: ${price}\nChange 24h: {change24h}\nMarket Cap: {marketcap}\nSupply: {supply}\nVolume 24h: {volume24h}"
                else:
                    response = f"I've got no info about crypto symbol '{symbol}'. See coincap.io for a list of supported symbols."
                send_message(response, SIGNAL_USER, target)
            else:
                cmd = f"{working_dir}/tuxi '{command}'"
                p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True)
                p.wait()
                response = p.stdout.read().decode('utf-8').strip().replace('\n', ' ')
                if response == "No Result":
                    # just pass the question to the AI if Google doesn't have a featured snippet response
                    response = cb.single_exchange(command)
                send_message(response, SIGNAL_USER, target)
示例#19
0
    async def on_message(self, message):
        def _check(m):
            return (m.author == message.author
                    and len(m.mentions)
                    and (datetime.utcnow() - m.created_at).seconds < 60)
        if not message.author.bot:
            if len(list(filter(lambda m: _check(m), self.bot.cached_messages))) >= 3:
                await message.channel.send('Don`t spam mentions!', delete_after=10)
                unmutes = await self.mute_members(message, [message.author], 5, 'Mention spam')

                if len(unmutes):
                    await sleep(5)
                    await self.unmute_members(self.guild, [message.author])

            if profanity.contains_profanity(message.content):
                await message.delete()
                await message.channel.send('You can`t use that word here', delete_after=10)

            elif message.channel.id not in self.links_allowed and search(self.url_regex, message.content):
                await message.delete()
                await message.channel.send('You can`t send links to this channel', delete_after=10)

            elif message.channel.id not in self.images_allowed and any([hasattr(a, 'width') for a in message.attachments]):
                await message.delete()
                await message.channel.send('You can`t send images here.', delete_after=10)
示例#20
0
def listing_handler(video_id):
    '''Handles profanity-check for a video with the given video id'''
    response.headers['Content-Type'] = 'application/json'
    response.headers['Cache-Control'] = 'no-cache'

    text = ''
    profanity_detected = False
    censored_text = []

    print(video_id)

    transcript_list = YouTubeTranscriptApi.get_transcript(video_id)

    # iterate over all available transcripts
    for transcript in transcript_list:
        text = transcript['text']
        if profanity.contains_profanity(text):
            profanity_detected = True
            censored_text.append(profanity.censor(text))

    result = {
        'video-id': video_id,
        'profanity-detected': profanity_detected,
        'censored': censored_text
    }
    #    return json.dumps({'names': list(_names)})
    result = json.dumps(result)
    ##    return template("<html>{{result}}", result)
    return result
示例#21
0
async def check_for_profanity(bot, msg):
    if (
        # message just has plain profanity
        profanity.contains_profanity(msg) or
        profanity.contains_profanity(
            msg.replace(' ', '')) or  # message has spaces and remove the spaces
        profanity.contains_profanity(
            re.sub(r'[^\w\s]', '', msg)) or  # message has punctuation, remove punctuation
        # message has invisible unicode character
        profanity.contains_profanity(msg.replace('­', '')) or
        profanity.contains_profanity(
            "".join(collections.OrderedDict.fromkeys(msg)))  # duplicate chars
    ):
        return True

    return False
示例#22
0
async def on_message(message):
    mention = f'<@!{client.user.id}>'
    if mention in message.content:
        embed = discord.Embed(
            description=
            f"_{message.author.mention} :bell: You ping me, I ping you._",
            color=6400)
        await message.channel.send(embed=embed)

    if str(message.channel) == "pictures" and message.content != '':
        if message.author != client.user:
            await message.channel.purge(limit=1)
            embed = discord.Embed(
                description=f"Sorry{message.author.mention}! Only Pictures!",
                color=6400)
            await message.channel.send(embed=embed)
        else:
            pass

    if '' in message.content:
        embed = discord.Embed(
            title="Self Roles",
            description="React to this message to get these roles! ")

    if not message.author.bot:
        if profanity.contains_profanity(message.content):
            await message.delete()
            embed = discord.Embed(
                description=
                f"{message.author.mention} :octagonal_sign: Mind your language!",
                color=6400)
            await message.channel.send(embed=embed)

    await client.process_commands(message)
示例#23
0
 def on_status(self, status):
     print(status)
     direct_messages = api.list_direct_messages()
     # For each direct message in the list, tweet out the message and then delete it.
     for item in direct_messages:
         print(item)
         # check for profanity in the direct message before tweeting
         if (not profanity.contains_profanity(
                 str(item.message_create['message_data']['text']))):
             api.update_status(
                 str(item.message_create['message_data']['text']))
         # delete the message so it is not tweeted multiple times
         api.destroy_direct_message(item.id)
     if ((not (api.get_status(status.id).retweeted))) and (
             not profanity.contains_profanity(status.text)):
         api.retweet(status.id)
示例#24
0
def words(letters):
    wList = []
    gList = []
    numWords = 0
    for n in range(3, len(letters) + 1):
        twList = []
        tgList = []
        for i in set(permutations(letters, n)):
            temp = ''.join(i)
            if d.check(
                    temp
            ) and temp not in wList and not profanity.contains_profanity(temp):
                twList += [temp]
                tgList += ["_" * n]
                numWords += 1
        if twList != []:
            wList += [twList]
            gList += [tgList]
    if len(wList[-1]) > 0:
        if letters in wList[-1]:
            wList[-1].remove(letters)
            gList[-1].pop()
            numWords -= 1
            if [] in wList:
                wList.remove([])
                gList.remove([])
    return wList, gList, numWords
示例#25
0
    def get_tweets(self, query, count=100):
        # An empty list to store the parsed tweets
        tweets = []
        try:
            # Call Twitter API to fetch tweets
            fetched_tweets = self.api.search(q=query, count=count)
            # Parsing tweets
            for tweet in fetched_tweets:
                # Empty dictionary to store required parameters of a tweet
                parsed_tweet = {
                    'text': tweet.text,
                    'sentiment': self.get_tweet_sentiment(tweet.text),
                    'profanity': profanity.contains_profanity(tweet.text),
                    'screen_name': tweet.user.screen_name,
                    'created_at': tweet.created_at
                }

                # Checking for retweets
                # If a tweet has retweets append it only once
                if tweet.retweet_count > 0:
                    if parsed_tweet not in tweets:
                        tweets.append(parsed_tweet)
                else:
                    tweets.append(parsed_tweet)

            return tweets
        except tweepy.TweepError as e:
            print("Error : " + str(e))
示例#26
0
def result():

    req = request.get_json()

    # print(req)

    as_string = req['input']

    checked = "Yes" if profanity.contains_profanity(as_string) == True else "No"
    
    # print(checked)

    censored = profanity.censor(as_string, '🙉')

    count = censored.count('🙉🙉🙉🙉')

    # print(censored)

    res = make_response(jsonify(f'Contains profanity? {checked}. Profanity count: {count}. Censored version: "{censored}"'), 200)

    # custom = []
    # profanity.add_censor_words(custom)

    return res 
    return render_template("home.html")
示例#27
0
 async def speak(self, ctx, *, prompt=None):
     if str(ctx.message.channel.type).lower() == "private":
         return
     if profanity.contains_profanity(prompt):
         return
     j = discord.utils.get(self.client.voice_clients,
                           guild=ctx.message.guild)
     yeet = ctx.message.author.voice
     if yeet == None or prompt == None:
         await ctx.send("*no*")
         return
     channel = yeet.channel
     if j == None:
         await ctx.message.add_reaction('🤝')
         await channel.connect()
     #start playing
     output = gTTS(text=prompt)
     output.save("playing.mp3")
     voice = discord.utils.get(self.client.voice_clients,
                               guild=ctx.message.guild)
     await voice.play(
         discord.FFmpegPCMAudio(
             executable="ENTER PATH FOR FFMPEG EXECUTABLE",
             source="./playing.mp3"))
     await voice.disconnect()
     return
示例#28
0
    async def on_message(self, message: Message):
        def _check(m: Message):
            return (m.author == message.author
                    and len(m.mentions)
                    and (datetime.utcnow() - m.created_at).seconds < 60)

        if not message.author.bot:
            # SPAM DETECTION - this method recommended for single server only, otherwise cpu+mem intensive
            if len(list(filter(lambda m: _check(m), self.bot.cached_messages))) >= 3:
                await message.channel.send(f"Mention span Detected ! \n" +
                                           f"{message.author.mention} is muted for {self.mute_duration} minute(s).")
                await self.mute_members(message, [message.author], self.mute_duration, "For spamming @mentions")
                # await self.kick_or_ban_members(message, [message.author], "For spamming @mentions", mode="kick")

            elif profanity.contains_profanity(message.content) and not message.content.find("delprofanity") == 1:
                await message.delete()
                await message.channel.send("You can't use this word here", delete_after=10)
            elif message.channel.id in self.no_links_channels \
                    and search(self.url_regex, message.content) \
                    and not message.author.guild_permissions.manage_guild:
                await message.delete()
                await message.channel.send("You can't send links to this channel", delete_after=10)
            elif message.channel.id in self.no_images_channels \
                    and any([hasattr(a, "width") for a in message.attachments]) \
                    and not message.author.guild_permissions.manage_guild:
                await message.delete()
                await message.channel.send("You cant post images in this channel", delete_after=10)
示例#29
0
文件: chatbot.py 项目: bmai53/chatbot
    def chat(self, sentence):

        if(profanity.contains_profanity(sentence)):
            return self.bad_sentence()

        sentence = tokenize(sentence)
        X = bag_of_words(sentence, self.all_words)
        X = X.reshape(1, X.shape[0])
        X = torch.from_numpy(X).to(ChatBot.device)

        # get result from model
        output = self.model(X)
        all, predicted = torch.max(output, dim=1)
        tag = self.tags[predicted.item()]

        probs = torch.softmax(output, dim=1)
        prob = probs[0][predicted.item()]

        print(
            f'\nChatBot Prediction: \n\tsentence: {sentence} \n\tpredicted: {tag} \n\tprobability: {prob}\n')

        if prob.item() > 0.75:
            return self.make_response(tag)
        else:
            return self.no_intent_detected()
示例#30
0
 async def nickname_scanner(self, before, after):
     if exceptionsManager.contains('exempt', after.nick):
         return
     if profanity.contains_profanity(
             after.nick) or exceptionsManager.contains(
                 'restricted', after.nick):
         log_channel = self.config.getint('Settings', 'channel')
         if log_channel != -1:
             await after.guild.get_channel(
                 log_channel).send('User ||' + before.name +
                                   '|| tried to change nickname to ||' +
                                   after.nick + '|| - action blocked.')
         # Send Message
         await after.send(
             'The server ' + after.guild.name +
             ' detected that you tried to set a vulgar nickname. This action has been blocked. Please contact an administator if you feel this is an error.'
         )
         # Handle name edit back to previous value
         try:
             await after.edit(reason='Automated Protection',
                              nick=before.nick)
         except (discord.Forbidden):
             print("Could not change nickname")
             if log_channel != -1:
                 await after.guild.get_channel(log_channel).send(
                     'Error, can not change nickname')