A memorandum part 3 that created a slackbot using python
It's been a long time since [Last time] 1 ...
Do you not often see such a sample?
@respond_to("^test\s+\S.*")
At first, I used it without thinking "It's like this!"
However, when I think about it carefully, I noticed that the inside of () is a regular expression (slow).
So I had a problem "I want to make such a respond_to", so I tried to solve it with a regular expression!
This time I tried to summarize the regular expression
The item description is as follows
Can be used with PHP, Perl, Python, Ruby, etc.
Python has a library ([re] 2) that performs operations such as search and replace using regular expressions. However, since it will not be used this time, the explanation is omitted.
If you like, please also see [Regular expression] 3 that I summarized | д ゚)
@respond_to("^Good morning") #Beginning of sentence
@respond_to("Good evening.$") #End of sentence
def respond_func(message):
message.react("+1")
Use ** ^ ** at the beginning of the sentence and ** $ ** at the end of the sentence You can see that it corresponds firmly!
@respond_to("^Hello$"):
def respond_func(message):
mes = message.body["text"]
message.send(mes)
Combining the two gives a "exact match" regular expression It does not respond only to the word "Hello"!
@listen_to("^repeat\s+\S.*")
def repeat_func(message):
rep_str = message.body["text"][7:]
message.send(rep_str)
Regular expressions that everyone loves
\s+
One or more spaces (tabs)
\s
One character except spaces (tabs)
.*Any character is 0 or more
Has become
Note that without \ S, even a single space (tab) will react.
![sb_sample3.png][c]
You can also move the bot like a command line like this!
# "I want you to execute the process only once even with multiple words."
I first came up with this
* Bad example
```python
@listen_to("How nice")
@listen_to("good")
@listen_to("good")
def reaction_func(message):
message.react("+1")
The bad thing about this is that if you enter something like "Like! Good! Good!", It will rotate three times.
Of course, you can't attach multiple same reactions by yourself, so you get the error already_reacted
If you use a regular expression, you can clear it without difficulty!
@listen_to("How nice|good|good")
def reaction_func(message):
message.react("+1")
** | ** was a regular expression meaning "or" (˘ω˘)
The process was completed without throwing an error like this!
Currently, a mysterious error is under investigation due to a large sale ... <(_ _>)
Regular expressions have blown away a lot of the worries I had! Recently, I've come to use regular expressions a lot not only on slackbot but also in business.
It was around this time that I wanted to become a regular expression master soon ...!
Recommended Posts