def del_profanity(update, context): bot = context.bot user_id = update.effective_user['id'] args = context.args chat_id = update.message.chat_id name = update.effective_user['first_name'] if userisAdmin(chat_id, user_id, bot) == True: if len(args) == 0: logger.info(f"{user_id}") bot.sendMessage( chat_id=chat_id, text=f"{name} pon la palabra a retirar por favor...") else: with open("data/badwords.txt", "r", encoding="utf-8") as f: stored = [w.strip() for w in f.readlines()] with open("data/badwords.txt", "w", encoding="utf-8") as f: f.write("".join([f"{w}\n" for w in stored if w not in args])) profanity.load_censor_words_from_file("badwords.txt") logger.info(f"{user_id} palabra removida") bot.sendMessage(chat_id=chat_id, text=f"{name}, palabra removida.") else: bot.sendMessage( chat_id=chat_id, text= f"Lo siento {name} solo los admins pueden ejecutar este mensaje.")
async def spill_profanity(self, ctx): profanity.load_censor_words_from_file("./data/rules.txt") a_file = open("./data/rules.txt") lines = a_file.readlines() for line in lines: await ctx.send(line)
async def echo_message(self, ctx, *, message): profanity.load_censor_words_from_file("./data/profanity.txt") if profanity.contains_profanity(message): await ctx.send("I cant say that") else: await ctx.message.delete() await ctx.send(message)
async def remove_profanity(self, ctx: Context, *words): with open(PROFANITY_TXT, 'r', encoding='utf-8') as f: stored = [w.strip() for w in f.readlines()] with open(PROFANITY_TXT, 'w', encoding='utf-8') as f: f.write(''.join([f'{w}\n' for w in stored if w not in words])) profanity.load_censor_words_from_file(PROFANITY_TXT) await ctx.send('Action complete', delete_after=10)
async def remove_profanity(self, ctx, *words): with open("./data/profanity.txt", "r", encoding="utf-8") as f: stored = [w.strip() for w in f.readlines()] with open("./data/profanity.txt", "w", encoding="utf-8") as f: f.write("".join([f"{w}\n" for w in stored if w not in words])) profanity.load_censor_words_from_file("./data/profanity.txt") await ctx.send("Action complete.")
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
async def add_profanity(self, ctx, *words): with open("./data/profanity.txt", "a", encoding="utf-8") as f: f.write("".join([f"{w}\n" for w in words])) profanity.load_censor_words_from_file("./data/profanity.txt") #this word is added immediately when you hit !addprofanity X #and it will show as notification about "You can't use that word..." #this needs to be fixed later on #maybe to use aiofiles? await ctx.send("Action complete.", delete_after=10)
async def add_rule(self, ctx, *, words): file = open("./data/rules.txt", "r") nonempty_lines = [line.strip("\n") for line in file if line != "\n"] line_count = len(nonempty_lines) with open("./data/rules.txt", "a", encoding="utf-8") as f: x = words.strip("[(' ',)]") f.write(" ".join([f"{line_count + 1}. {x}\n"])) await ctx.send("Rule added.") profanity.load_censor_words_from_file("./data/rules.txt")
async def on_message(self, message : discord.Message): sample_message = str(message.content).lower() if not message.author.bot: if message.content.startswith("<@!752666067536576512>"): await message.channel.send(content=f"what do you want {message.author.mention}, you know you can just do `s.help` to get all the commands right?", delete_after=5.0) return if int(message.channel.id) == 738155429342871623: async def add_reactions(): for emote in message.guild.emojis: if emote.name == "yes": global yes yes = emote elif emote.name == "no": global no no = emote elif emote.name == "thronking": global thronking thronking = emote else: pass #================================================================= await message.add_reaction(yes) await message.add_reaction(no) await message.add_reaction(thronking) return try: with open("./data/guest.txt", 'r') as e: if message.author.id == int(e.read()): await message.author.remove_roles(message.guild.get_role(832068361932111872)) await add_reactions() os.system("shred -z -v ./data/guest.txt; rm ./data/guest.txt") return except FileNotFoundError: pass if message.author.id == 547971853990494208: await add_reactions() return profanity.load_censor_words_from_file("./data/profanity.txt") #profanity.load_censor_words() if profanity.contains_profanity(sample_message): await message.delete() await message.channel.send(content=f"{message.author.mention} you cannot use that word here", delete_after=5.0) return
def message(update, context): text = update.message.text.lower() word = text.split() profanity.load_censor_words_from_file("badwords.txt") if profanity.contains_profanity(text) == True: user_id = update.effective_user['id'] chat_id = update.message.chat_id name = update.effective_user['first_name'] logger.info(f"El usuario {user_id} ha dicho una mala palabra") update.message.delete() context.bot.sendMessage( chat_id=chat_id, text= f"El mensaje de {name} fue eliminado por contener malas palabras..." ) context.bot.sendMessage( chat_id=user_id, text=f"Por favor mejora tu vocabulario o seras expulsado") elif word == ['hola']: name = update.effective_user['first_name'] update.message.reply_text(f"Hola {name}, ¿Como estas?")
async def profanity_check(bot, message): _data = await bot.config.find_one({"_id": message.guild.id}) msg = str(message.content).lower() try: if _data['profanity_toggle']: # check if profanity is enabled try: if _data['words']: # profanity.load_censor_words(_data['words']) except (TypeError, KeyError): profanity.load_censor_words_from_file( bot.path + '/assets/profanity.txt') # anti-profanity if await check_for_profanity(bot, msg): if await profanity_command_check(bot, message): return False # make sure that they're not adding a word # in that case then don't do stuff try: await message.delete() except (discord.NotFound, discord.Forbidden): pass em = SaturnEmbed( description=f"{WARNING} That word is not allowed in **{message.guild}**!", colour=GOLD) await message.channel.send(embed=em) await automod_log( bot, message, "warning", f"Said || {message.content} || which contains profanity") return True return False except (TypeError, KeyError): return False
def run(usernum, creds): spotify = get_spotify(creds["spotify"], usernum) current_song = spotify.current_user_playing_track() current_user = creds["spotify"]["usernames"][usernum] if (isinstance(current_song, type(None)) or not current_song["is_playing"] or not current_song["item"] # Happens with podcasts ): log(f"{current_user} not playing a song currently") return song_name = current_song["item"]["name"] artist_name = current_song["item"]["artists"][0]["name"] album_name = current_song["item"]["album"]["name"] progress = current_song["progress_ms"] song_label = (song_name, artist_name, progress) log(f"{current_user} playing {song_name} by {artist_name}") # Track previously played songs try: with open(PREV_SONGS) as f: prev_songs_all = json.load(f) except FileNotFoundError: prev_songs_all = {current_user: []} if current_user not in prev_songs_all: prev_songs_all[current_user] = [] # Add current song prev_songs = list(map(tuple, prev_songs_all[current_user])) replayed = bool(prev_songs and prev_songs[-1][:-1] == song_label[:-1] and prev_songs[-1][-1] >= song_label[-1]) continued = bool(prev_songs) and prev_songs[-1][:-1] == song_label[:-1] same_play = continued and not replayed if same_play: prev_songs = prev_songs[:-1] with open(PREV_SONGS, "w") as f: current_songs = prev_songs + [song_label] if len(current_songs) > MAX_PREV_SONGS: current_songs = current_songs[-MAX_PREV_SONGS:] prev_songs_all[current_user] = current_songs json.dump(prev_songs_all, f) if same_play and NO_RETRY and not FORCE: log("Already tried roll") # Only try once for each song return genius = lyricsgenius.Genius(creds["genius"]["client access token"], excluded_terms=EXCLUDED_GENIUS_TERMS) song = get_genius_song(song_name, artist_name, genius) if isinstance(song, type(None)): log("Song not found on Genius") return paragraphs = song.lyrics.split("\n\n") if not paragraphs: log("No paragraphs") return replays = list(map(lambda l: l[:-1], prev_songs)).count(song_label[:-1]) reduce_factor = max(replays * REPLAY_REDUCE_FACTOR, 1) odds = max(CHANCE_TO_TWEET // reduce_factor, 1) if replays: log(f"Song played {replays} times in last {MAX_PREV_SONGS} songs. " f"Dividing {CHANCE_TO_TWEET} by {reduce_factor} to {odds}.") if random.randrange(0, odds) and not FORCE: # One in CHANCE_TO_TWEET chance to tweet lyrics log("Failed roll") return chosen_lines = [set()] * len(paragraphs) chosen_paragraphs = set() selected_lines = [] while len(paragraphs) != len(chosen_paragraphs): remaining_choices = list( set(range(0, len(paragraphs))) - chosen_paragraphs) if not remaining_choices: break paragraph_num = random.choice(remaining_choices) paragraph = paragraphs[paragraph_num] lines = [ line for line in paragraph.split("\n") if line and line[0] != "[" ] start = random.choice( list(set(range(0, len(lines))) - chosen_lines[paragraph_num])) chosen_lines[paragraph_num].add(start) if len(lines) == len(chosen_lines[paragraph_num]): chosen_paragraphs.add(paragraph_num) selected = lines[start] shortened = False long_sentence = False while len(selected) > TWEET_LIMIT: if "." in selected: shortened = True selected = ".".join(selected.split(".")[:-1]) else: long_sentence = True break if long_sentence: continue selected_lines = [selected] while random.randrange(0, CHANCE_TO_ADD_LINE) and not shortened: next_line_num = start + len(selected_lines) if next_line_num >= len(lines): break next_line = lines[next_line_num] current_len = len("\n".join(selected_lines)) if current_len + len(next_line) > TWEET_LIMIT: break selected_lines.append(next_line) break if not selected_lines: log("No lines fit within tweet.") return if not (DONT_CONFIRM or input("Send Tweet? [Yy]").lower() == "y"): return status = "\n".join(selected_lines) if FILTER_SLURS: profanity.load_censor_words_from_file(BLACKLIST_PATH) if profanity.contains_profanity(status): log("Skipping tweet due to profanity:\n" + status) return log("****TWEETING****:\n" + status) twit = get_twitter(creds["twitter"][usernum]) tweet = twit.PostUpdate(status) apple_link = get_apple_link((artist_name, song_name, album_name)) genius_link = song.url spotify_link = current_song["item"]["external_urls"].get("spotify", "") lastfm_link = get_lastfm_link(artist_name, song_name, creds["lastfm"]) reply = f"\n\ngenius: {genius_link}" if lastfm_link: reply += f"\nlastfm: {lastfm_link}" if apple_link: reply += f"\napple: {apple_link}" if spotify_link: reply += f"\nspotify: {spotify_link}" twit.PostUpdate(reply, in_reply_to_status_id=tweet.id) # Remove past replays of this song to reset odds in future with open(PREV_SONGS, "w") as f: current_songs = list( filter(lambda l: l[:-1] != song_label[:-1], current_songs)) prev_songs_all[current_user] = current_songs + [song_label] json.dump(prev_songs_all, f)
async def add_profanity(self, ctx, *words): with open("./data/profanity.txt", "a", encoding="utf-8") as f: f.write("".join([f"{w}\n" for w in words])) profanity.load_censor_words_from_file("./data/profanity.txt") await ctx.send("Action complete.")
from asyncio import sleep from datetime import datetime, timedelta from re import search from typing import Optional from better_profanity import profanity from discord import Embed, Member from discord.ext.commands import Cog, Greedy from discord.ext.commands import CheckFailure from discord.ext.commands import command, has_permissions, bot_has_permissions from ..db import db profanity.load_censor_words_from_file("./data/profanity.txt") class Mod(Cog): def __init__(self, bot): self.bot = bot self.url_regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))" self.links_allowed = (711223407911370812, 711246048756236348) self.images_allowed = (711223407911370812, 711246048756236348) async def kick_members(self, message, targets, reason): for target in targets: if (message.guild.me.top_role.position > target.top_role.position and not target.guild_permissions.administrator): await target.kick(reason=reason) embed = Embed(title="Member kicked",
def __init__(self, bot): self.bot = bot profanity.load_censor_words_from_file("./data/default_word_list.txt") print("'Chat Filter' module loaded.")
from MashaRoBot import BOT_ID from MashaRoBot.function.telethonbasics import is_admin from MashaRoBot.services.events import register from MashaRoBot.services.mongo import mongodb as db from MashaRoBot.services.telethon import tbot translator = google_translator() MUTE_RIGHTS = ChatBannedRights(until_date=None, send_messages=False) approved_users = db.approve spammers = db.spammer globalchat = db.globchat CMD_STARTERS = "/" profanity.load_censor_words_from_file("./profanity_wordlist.txt") @register(pattern="^/profanity(?: |$)(.*)") async def profanity(event): if event.fwd_from: return if not event.is_group: await event.reply("You Can Only profanity in Groups.") return event.pattern_match.group(1) if not await is_admin(event, BOT_ID): await event.reply("`I Should Be Admin To Do This!`") return if await is_admin(event, event.message.sender_id): input = event.pattern_match.group(1)
def test_read_wordlist_not_found(self): with self.assertRaises(FileNotFoundError): profanity.load_censor_words_from_file("not_found_file.txt")
async def addbadword(self, ctx, arg): arg = str(arg).lower() with open("swearwords.txt", "a") as file: file.write("\n" + arg) profanity.load_censor_words_from_file("swearwords.txt") await ctx.message.delete()
import logging from better_profanity import profanity import datetime global modules modules = {} modules["swear"] = True modules["lol"] = True devmode = False bad_words = [] userstrikes = {} # Compsup 2021 logging.basicConfig(filename="logfile.log", format='%(asctime)s %(message)s', filemode='a') logger=logging.getLogger() logger.setLevel(logging.WARN) # Retrive all the badwords profanity.load_censor_words_from_file("swearwords.txt") intents = discord.Intents().all() bot = commands.Bot(command_prefix='?', intents=intents) @bot.event async def on_ready(): await settings_manager("load") print('Logged in as') print(bot.user.name) print(bot.user.id) print('------') print("Connected to: " + str(len(bot.guilds)) + " servers!") print('------') # await bot.change_presence(status=discord.Status.online, activity=discord.Activity(type=discord.ActivityType.watching, name='Messages')) logger.info("Ready!")
from asyncio import sleep from datetime import datetime, timedelta from typing import Optional from better_profanity import profanity from discord import Embed, Member from discord.ext.commands import Cog, Greedy from discord.ext.commands import CheckFailure from discord.ext.commands import command, has_permissions, bot_has_permissions profanity.load_censor_words_from_file("./assets/bad_words.txt") class Profanity(Cog, name="Profanity"): def __init__(self, bot): self.bot = bot @command(name="addprofanity", aliases=["addswears", "addcurses"]) @has_permissions(manage_guild=True) async def add_profanity(self, ctx, *words): with open("./assets/bad_words.txt", "a", encoding="utf-8") as f: f.write("".join([f"{w}\n" for w in words])) profanity.load_censor_words_from_file("./assets/bad_words.txt") await ctx.send("Action complete.") @command(name="delprofanity", aliases=["delswears", "delcurses"]) @has_permissions(manage_guild=True) async def remove_profanity(self, ctx, *words): with open("./assets/bad_words.txt", "r", encoding="utf-8") as f: stored = [w.strip() for w in f.readlines()]
import discord import os from keep_alive import keep_alive from discord.ext import commands from better_profanity import profanity os.system('python3 -m commands') profanity.load_censor_words_from_file('./profanity.txt') client = commands.Bot(command_prefix='$') money_registry = [] list1 = ['myself', 'me', 'i'] @client.event async def on_ready(): print('Bot is ready!') await client.change_presence(activity=discord.Game('$help')) @client.command() async def displayembed(ctx, *, Title): embed = discord.Embed(title=Title, description=Title, color=6400) #,color=Hex code await ctx.send(embed=embed) @client.command() async def ping(ctx): await ctx.send(f'Pong! {round (client.latency * 1000)}ms')
async def load_profanity(self, words=None): if words is None: profanity.load_censor_words_from_file(self.profanity_file) else: profanity.load_censor_words(words)
import os import discord from nltk.corpus import stopwords from dotenv import load_dotenv from better_profanity import profanity import csv import pandas as pd ppt = ''' ...!@#$%^&*(){}[]|._-`/?:;"'\,~12345678876543''' load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') GUILD = os.getenv('DISCORD_GUILD') intents = discord.Intents.all() client = discord.Client(intents=intents) profanity.load_censor_words_from_file("badwords.txt") stop_words = set(stopwords.words('english')) new_list = [] mydictionary = {} @client.event async def on_ready(): print(f"We have logged in as {client.user}") general_channel = client.get_channel(821240198884229122) await general_channel.send('Hi, Im here!') @client.event async def on_member_join(member):
async def add_profanity(self, ctx, *words): with open(PROFANITY_TXT, 'a', encoding='utf-8') as f: f.write(''.join([f'{w}\n' for w in words])) profanity.load_censor_words_from_file(PROFANITY_TXT) await ctx.send('Action complete', delete_after=10)
from asyncio import sleep from datetime import datetime, timedelta from typing import Optional from re import search from better_profanity import profanity from discord import Member, utils, Embed from discord.ext.commands import CheckFailure from discord.ext.commands import Cog, Greedy, Context from discord.ext.commands import command, has_permissions, bot_has_permissions from lib.db import db from settings.settings import PROFANITY_TXT profanity.load_censor_words_from_file(PROFANITY_TXT) class Mod(Cog): def __init__(self, bot): self.bot = bot self.links_allowed = (788706464562282516,) self.images_allowed = (788706464562282516,) self.url_regex = self.url_regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))" async def kick_members(self, message, targets, reason): for target in targets: if (message.guild.me.top_role.position > target.top_role.position and not target.guild_permissions.administrator): await target.kick(reason=reason) embed = Embed( title='Member kicked',