Censoring words in lua - string

Im currently making a discord censor bot for my friend, and I was wondering if any advanced scripters could help me, or if theres an easier way to complete my code.
local BadWords = {
['poop']=true,
}
client:on('messageCreate', function(msg)
Msg = msg.content
local msgs = string.split(Msg,' ')
for i,v in pairs(msgs) do
if BadWords[v:lower()] then
msg:reply({
embed = {
fields = {
{name = "Bad Word",value=v,inline = true},
},
color = discordia.Color.fromRGB(114, 137, 218).value,
--footer = os.time(),
}
})
--msg:reply(('Blacklisted word: %s'):format(v))
end
end
--[[table.foreach(msgs,function(i,v)
if BadWords[i] or BadWords[v] then
msg:reply(('Blacklisted word: %s'):format(v))
end
end)--]]
end)
client:run(Settings.Token)
Theres nothing wrong with it, nor is it complete but my idea was to split, or concatenate all the words they send respectively, mutate into all versions of the word (i.e. farm, f4rm, type shit) and then checking the BadWord list.
Mostly what I was wondering was if theres a more efficient way to do this, or if I j gotta do what I gotta do

Related

Smiles bot in Lua: matching text

This is my bot, who copies smilies in game chat.
The smiles it copies are saved in the table called "emoticons". If someone writes ":)", the bot writes ":)" and so on
The code inside the loop is for this: if someone writes, for example, ">:)", you have to make the script copy ">:)" and not just ":)"
CreateFrame, RegisterEvent, SetScript and SendChatMessage are in-game built Lua API
local emoticons = {
":)", "(:", ":))", ">:)", "0:)", ":D", ":]", ":)))", "=]", "?_?", "+.+", ":P", ":3", "^^", "roar", ":V", "D:", ":C", ".D", ".)", "o_o",
"^-^", ":PPP", ":DDD", ":D:D:D", ":DDDD", ":D:D:D:D", ":DDDDD", ":d", ":L", "<O>_<O>", "o/", "+_+", "?_?", "*0*", ":}", ";)", ":))))", "o.o", "<.<''", ":|",
":-)", "^^^^", ":D:D:D:D:D:D", ":D :D :D", "^^^", ":c", ";]", ":9", ">:|", ">.<", ";3", ";P", "T_T", ":3c", ":)))))",
"^^^^^" }
local f = CreateFrame("Frame")
f:RegisterEvent("CHAT_MSG_GUILD")
f:SetScript("OnEvent", function(self, event, text, playerName, _, channelName, playerName2, _, _, channelIndex)
local msg
local n = 0
for x, key in ipairs(emoticons) do
local l = string.len(emoticons[x])
if (string.sub(text, -l) == emoticons[x]) then
if (l > n) then
msg = emoticons[x]
n = l
end
end
end
if (msg) and (playerName ~= UnitName("player")) then
if (event == "CHAT_MSG_GUILD") then SendChatMessage(msg, "GUILD", nil, channelIndex) end
end
end)
Is there any way to improve it? For example, if someone writes
"^^^^^^"
the bot copies
"^^^^^"
which would be the same with one less "^" as it was stored in the table
My goal is that if someone writes, for example, "^^^^^^" and it is not registered in the table, the script will not respond
You're probably better off learning how to use string.gmatch
As an example, let's say you only store one instance of ':D' in your emoticons table. You can iterate through the matches and respond in kind. Here's a small example:
local text = ':D:D:D'
local count = 0
for w in string.gmatch(text, ':D') do
count = count + 1
end
if count > 0 then
local response = ''
for i = 1, count do
response = response .. ':D'
end
print(response) -- prints ':D:D:D'
end
This doesn't handle every case, but hopefully it can help you get started
:D

How is the context treated?

I have a weird behaviour on Core Data with my App. I have an App where user can create their own words entries with translation. When deleting all my Core Data I checked the nb of item and it was 0. When adding later 4 items the nb of items was 5?? I found the issue after a lot of tests and it seems not consistent for me: the issue was with this code:
fileprivate func duplicateCheckAndImport() {
// Check for duplicates
do {
self.words = try context.fetch(Word.fetchRequest()) // grab all Words
let nbOfWords = words!.count
print ("The nb of words in duplicateCheck...: \(nbOfWords ?? 0)")
}
catch {
// error message to add
}
let newWord = Word(context: self.context)
do {
self.words = try context.fetch(Word.fetchRequest()) // grab all Words
let nbOfWords = words!.count
print ("The nb of words in duplicateCheck...: \(nbOfWords ?? 0)")
}
catch {
// error message to add
}
the result of the 2 prints is 0 for the first grab and 1 for the 2nd grab which means that just this line of code -> let newWord = Word(context: self.context) adds an entry in Core Data but my purpose was just to take the context add words later on like this:
let newWord = Word(context: self.context)
newWord.name = item.name.trimmingCharacters(in: .whitespaces)
newWord.definition = item.definition.trimmingCharacters(in: .whitespaces)
Can someone explain me?
The line of code you mention
let newWord = Word(context: self.context)
...creates a new instance. That's what Word(context: self.context) does-- it says, create a new instance of Word using the context that you pass in.
From the code you provide, it's hard to tell exactly what you're trying to do that would not create a new instance. Your variable is called newWord, which suggests that you do mean to create a new Word, and that's what's happening.
Update: If you don't want the new instance, you can delete it just like any other managed object. So if you don't want newWord, you can
context.delete(newWord)
And then save changes. There are other ways to do this, but this is the simplest.

Str::limit laravel

I have a file name examples:
4030-2210201884140.jpg
527884197_w640_h640_1ff2cccdbed562cef696d0c7adf41292.jpg
need to do to so was:
4030-22...1884140.jpg
5278841...df41292.jpg
Been looking for a solution but could not find it.
I have visited the post
Cutting down a length of a PHP string and inserting an ellipses
But sometimes it may not fit for you try below function
I have converted your requirement to a function with default arguments:
function getFirstLast($string='527884197_w640_h640_1ff2cccdbed562cef696d0c7adf41292.jpg',$orgOnF=7,$orgOnB=-11,$maskedString='.',$maskRepeat=3)
{
if (strlen($string) <= 21)
{
return $string;
}
$firstPartString = mb_substr($string, 0 ,$orgOnF);
$secondPartString = mb_substr($string,$orgOnB);
$maskedString = str_repeat($maskedString, $maskRepeat);
$finalResult = $firstPartString.$maskedString.$secondPartString;
return $finalResult;
}
echo getFirstLast();

How to parse a list in python3

So I get this list back from interactive brokers. (API 9.73 using this repo)
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=2)
data = ib.positions()
print((data))
print(type(data))
The data comes back as , but here is the response.
`[Position(account='DUC00074', contract=Contract(conId=43645865, symbol='IBKR', secType='STK', exchange='NASDAQ', currency='USD', localSymbol='IBKR', tradingClass='NMS'), position=2800.0, avgCost=39.4058383), Position(account='DUC00074', contract=Contract(conId=72063691, symbol='BRK B', secType='STK',exchange='NYSE', currency='USD', localSymbol='BRK B', tradingClass='BRK B'), position=250.0, avgCost=163.4365424)]`
I have got this far:
for d in data:
for i in d:
print(i)
But I have no idea as to how I would parse and then dump into a DB, anything after Position(... So to be really clear, I don't know how I would parse, like I would say in php / json.
Okay, Im new to python, not new to programing. So the response from Interactive Brokers threw me off. I'm so used to JSON response. Regardless, what it comes down to is this is a list of objects, (the example above). That might be simple, but missed it. Once I figured it out it became a little easier.
Here is the final code, hopefully this will help someone else down the line.
for obj in data:
#the line below just bascially dumps the object
print("obj={} ".format(obj))
#looking for account number
#"contract" is an object inside an object, so I had to extract that.
if(getattr(obj, 'account') == '123456'):
print("x={} ".format(getattr(obj, 'account')))
account = (getattr(obj, 'account'))
contract = getattr(obj, 'contract')
contractId = getattr(contract, 'conId')
symbol = getattr(contract, 'symbol')
secType = getattr(contract, 'secType')
exdate = getattr(contract, 'lastTradeDateOrContractMonth')
strike = getattr(contract, 'strike')
opt_type = getattr(contract, 'right')
localSymbol = getattr(contract, 'localSymbol')
position = getattr(obj, 'position')
avgCost = getattr(obj, 'avgCost')
sql = "insert into IB_opt (account, contractId, symbol, secType, exdate, opt_type, localSymbol, position, avgCost,strike) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)";
args = (account, contractId, symbol, secType, exdate, opt_type, localSymbol, position, avgCost,strike)
cursor.execute(sql, args)
Of all the sites I looked at this one was pretty helpful.

How to make Discord bot send image with the name of number chosen by user? (Python 3.5.x)

I'm still learning python and programming and i've got myself into a problem that i can't solve. I want to make a command that would make a bot send an image that its name corresponds to number what user wrote (e.g. user wrote "!image_nr 22" and bot sends 22.jpg). I've only made code that sends random image from folder but I cant get into chosen. Here's my latest code for this problem:
elif message.content.startswith("!obrazeknr"): #missing an argument or something, idk what to make here
obrazDirectoryChc = "C:/Users/Lewando54/Downloads/Localisation/English/" + liczba + ".jpg"
await client.send_file(message.channel, obrazDirectoryChc, content=obrazName[1])
You could try inside this elif statement:
msg = message.content[12:] #skips the command word and the '!' and the " "
msg = msg.split() #split the message into an array at the spaces.
#msg = ["!image_nr","22"]
if msg[0] == "!image_nr" and msg[1].isnumeric():
obrazDirectoryChc = "C:/Users/Lewando54/Downloads/Localisation/English/" +
liczba + ".jpg"
await client.send_file(message.channel, obrazDirectoryChc,
content=obrazName[int(msg[1]])
now it should send the user requested photo.
e.g. !obrazeknr image_nr 22
Hope this helps. Sorry for the long wait; I just saw this today.
Might be a better idea, for next time, posting on https://programming.stackoverflow.com could give you more help.
It works. I've slightly modified it and it works. Thx for idea :D
elif message.content.startswith('!obrazeknr'):
msg1 = message.content #skips the command word and the '!' and the " "
msg1 = msg1.split() #split the message into an array at the spaces.
#msg = ["!obrazeknr","22"]
if msg1[0] == "!obrazeknr" and msg1[1].isnumeric() == True:
await client.send_file(message.channel, "C:/Users/Lewando54/Downloads/Localisation/English/" + str(int(msg1[1])) + ".jpg")

Resources