Python3でSlackBotを作ってます。
色々と便利なのですが、Nodejs(Coffee)には存在している【help】が無かったので、雑ながら自作しました。
(良い物があったら教えてください…)
単純に考えたら、grep '@listen_to' *.py
の結果を出してくれればいいんですが、
python+正規表現だとreモジュールを使うのが多いらしいので、つかってみました。
help.py
# -*- coding: utf-8 -*-
import os,re
def main():
keyword = r"^@listen_to" #検索したい文字列を記載
keyword2 = r"^@respond_to" #検索したい文字列を記載
current_dir = os.path.dirname(os.path.abspath(__file__)) #実行ファイルのディレクトリパスを取得
filelist = os.listdir(current_dir)
helplist = "メンションつけなくても反応するモノ \n"
helplist2 = "メンションつけて呼んで上げると反応するもの \n"
for i in filelist:
if i.endswith('py'): #ファイルの拡張子がpyであるもの
with open(i,'r') as f:
lntmp = f.readlines()
for j in lntmp:
if len(re.findall(keyword,j)) : #正規表現にマッチするものをhelplistに追加
helplist += j
if len(re.findall(keyword2,j)) : #正規表現にマッチするものをhelplist2に追加
helplist2 += j
print(helplist)
print(helplist2)
if __name__ == '__main__':
main()
↑python help.py で動きますが、BOTに組み込むなら下記で良いかと思います。
@respond_to('help') #機能一覧の表示
@respond_to('hint') #機能一覧の表示(helpと同じ)
def mention_func(message):
if message.body["channel"] != channel_id:
return
keyword = r"^@listen_to" #検索したい文字列を記載
keyword2 = r"^@respond_to" #検索したい文字列を記載
current_dir = os.path.dirname(os.path.abspath(__file__)) #実行ファイルのディレクトリパスを取得
filelist = os.listdir(current_dir)
helplist = "メンションつけなくても反応するモノ \n"
helplist2 = "メンションつけて呼んで上げると反応するもの \n"
for i in filelist:
if i.endswith('py'):
with open(current_dir + "/"+ i,'r') as f:
lntmp = f.readlines()
for j in lntmp:
if len(re.findall(keyword,j)) :
helplist += j
if len(re.findall(keyword2,j)) :
helplist2 += j
message.send('```' + helplist + '```')
message.send('```' + helplist2 + '```')