In this article, I will explain the process of reading and writing files with Slackbot created in Python.
" Control reading and writing files with Python " We will make it possible to call the logic implemented in in from Slackbot.
The basic logic for reading and writing files uses the following modules created in "Controlling reading and writing of files with Python".
import codecs
class FileReadWrite:
#Method to read file
def file_read(self, path):
try:
#Open file
target_file = codecs.open(path, "r", "utf_8")
#Read the file
text = target_file.read()
target_file.close()
except:
#Exception handling when an error occurs
text = "ng"
return text
#Method to write file
def file_write(self, path, text):
try:
target_file = codecs.open(path, "a", "utf_8")
target_file.write(text)
result = "ok"
target_file.close()
except:
#Exception handling when an error occurs
result = "ng"
return result
Read " Create Slackbot in Python " for the basics of implementing Slackbot in Python. ..
from slackbot.bot import respond_to
from slackbot.bot import listen_to
from filereadwrite import FileReadWrite
@respond_to('^File write test$')
def write_test(message):
#Instantiate a class
f = FileReadWrite()
#Write to file
action = f.file_write("./test1.txt", "AIUEO\n")
#React the result
message.react(action)
◆ Execution result </ span> <img src = "https:: //miyabi-knock.com/tools/wp-content/uploads/2018/12/slackbot_write.png "width =" 500 "alt =" write file "class="alignnone size-large" />
◆ Contents to be described in botmodule.py </ span> Add the reading logic.
@respond_to('^File read test$')
def read_test(message):
#Instantiate a class
f = FileReadWrite()
#Read text from file
text = f.file_read("./test1.txt")
#When it fails, NG is returned as a reaction
if text == "ng":
message.react(text)
else:
#Returns text on success
message.reply(text)
◆ Execution result </ span> <img src = "https:: //miyabi-knock.com/tools/wp-content/uploads/2018/12/slackbot_read.png "width =" 500 "alt =" execution result "class="alignnone size-large" />
This is the implementation of file read / write logic in Slackbot.
Slackbot + Python Summary TOP >> How to make Slackbot Manual ~ Python ~
◆ Sample code </ span> Python Slackbot read / write sample code
Recommended Posts