English 中文(简体)
A. 探索斯特鲁斯特定特性的问题
原标题:Issues when searching for specific special characters in string Python

I m working on a discord bot in Python that will look for specific trigger words on a blacklist and censor them. I ve got it mostly working, but words already being censored gives it issues.
My solution was to search for "||" (for those unfamiliar, putting text between sets of || puts it behind spoiler tags on discord) and then only run the function if the word is NOT between them. The issue I m running into is actually finding the position of || .
This is my first real attempt at using Python, and its mostly been via googling, so sorry if this is something obvious ^^

Edit for Clarity: an example ideal input-output would be
In: "Omg I m so dead"
Out: "Omg I m so d||ead||"
which currently functions
In: "||Omg I m so dead||"
Ideal Out: "||Omg I m so dead||
does not currently function and returns the error

My first attempt was using
censor_pos = [m.span() for m in re.finditer( || , mge, flags=0)] where mge is the message. This returned every postion in the string (aka dead would return (0,0)(1,1)(2,2)(3,3),(4,4)) I realized this was because | was a special character.
Next I tried changing it to
censor_pos = [m.span() for m in re.finditer(re.escape( || ), mge, flags=0)] (adding re.escape) which returned TypeError: expected string or bytes-like object, got NoneType Interestingly, I did try printing censor_pos to the console to see what was going on, and it does seem to be getting the correct position, the error occurs after.

Because I know it could be an issue elsewhere in the code, here s the full function I m running it in:

def Censor_Trigger(mge, word): #function to censor trigger words given a message and a trigger word
    
    censor_pos = [m.span() for m in re.finditer(re.escape( || ), mge, flags=0)] #finds all instances of "||" to know which parts of message are censored
    trigger_pos = [m.span() for m in re.finditer(word, mge, flags=re.IGNORECASE)] #finds all instances of a trigger word, giving positions as tuples in an array
    censored_msg = mge
    print (censor_pos)
    print (trigger_pos)
    y = 0 #variable to account for position change when censoring multiple instances of the same word
    for x in trigger_pos:
        a = 0
        is_censored = False
        for z in censor_pos:
            if  0<=a and (a+1)<(len(censor_pos)):
                if censor_pos[a][1]<=x[0]<=censor_pos[a+1][0]:
                    is_censored = True
                    return
                else:
                    is_censored = False          

            a=a+1
                
        if is_censored == False:
            censored_msg = censored_msg[:x[1]+(y*4)] + "||" + censored_msg[x[1]+(y*4):]
            censored_msg = censored_msg[:(x[0]+1+(y*4))] + "||" + censored_msg[(x[0]+1+(y*4)):]    
            y=y+1
            print(censored_msg)
        else:
            return
        
        
    return censored_msg

并且要求他们选择住所

trigger_words = ["dead", "trigger", "example", "another"] #list of triggers
for x in trigger_words: #runs the function to censor trigger words for all words in the trigger list
                 Mess = Censor_Trigger(Mess, x)

完全错误是

[2023-09-03 19:26:01] [ERROR   ] discord.client: Ignoring exception in on_message
Traceback (most recent call last):
  File "C:UsersuserAppDataLocalProgramsPythonPython311Libsite-packagesdiscordclient.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "C:UsersuserDesktopDiscord Bot FunTest Code.py", line 17, in on_message
    Mess = Censor_Trigger(Mess, x)
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:UsersuserDesktopDiscord Bot FunTest Code.py", line 37, in Censor_Trigger
    censor_pos = [m.span() for m in re.finditer(re.escape( || ), mge, flags=0)] #finds all instances of "||" to know which parts of message are censored
                                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:UsersuserAppDataLocalProgramsPythonPython311Lib
e\__init__.py", line 223, in finditer
    return _compile(pattern, flags).finditer(string)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: expected string or bytes-like object, got  NoneType 
问题回答

What you are trying to accomplish is possible only with messages from your own bot. As stated in Message.edit Documentation the Bot can Not edit another user s message, and it will raise a Forbidden exception.

用你想要的模式取代:

@bot.listen()
async def on_message(message: discord.Message):
    censor_words = ["dead", "trigger", "example", "another"]

    matching_item = next((item for item in censor_words if item in message.content), None)
    if matching_item:
        ret_message = message.content.replace(matching_item, f"{matching_item[0]}||{matching_item[1:]}||")
        await message.edit(content=ret_message)

如果你想删除先前发出的信息,并通过警告和打扰他而将其发回用户,那么你将使用下述内容:

@bot.listen()
async def on_message(message: discord.Message):
    censor_words = ["dead", "trigger", "example", "another"]

    if message.author == bot.user:
        return
    
    matching_item = next((item for item in censor_words if item in message.content), None)
    if matching_item:
        user = message.author
        ret_message = message.content.replace(matching_item, f"{matching_item[0]}||{matching_item[1:]}||")
        await message.delete()
        await message.channel.send(content=f"{user.mention}
{ret_message}")

通知说,如果电文的作者是Bot公司本身,我也增加了检查,但我并不认为需要,因为答复将在该词的第一封信之后有t > /code”,因此它会引发这种情况。

With a lot of printing to console mid program, I realized my issue! during my check to see if the censored word was between censor bars, I had added a return in the if statements, thus applying nothing to Mess, thus when it tried to run the function again using Mess, it gave the error. The actual code to find and avoid the censor bars was completely functional facepalm
For those here looking for the actual answer, the exact line of code I used to identify the censor bars was

censor_pos = [m.span() for m in re.finditer(re.escape( || ), mge, flags=0)]  

问题中所贴出的代码仅需要从该职能中的陈述中删除<代码>return。 然后,我补充说,如果说要将问题的最后价值(即警告性信息)进行比较的话。 内容(原电文),只有删除,如果信息不同,则不予理会。





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签