Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
water_order
from slackclient import SlackClient
import json
import logging
from dateutil.relativedelta import relativedelta
import urllib.parse
import ast
import boto3
import datetime
ch_id='XXXXXXXXXX' #本番用
slack_token='xoxp-XXXXXXXXXXX-XXXXXXXXXXX-XXXXXXXXXXXXXXXXX' #本番用
ts='1544601329.007800' #残すメッセージts本番用
#---ボタン設定-load-from-json--------------------------
with open("./water_cupps.json") as f:
water_cupps = json.load(f)
#---MailAddress---------------------------------------
FROM_MAIL = "XXXXXXXXXXXX@XXXXXXX"
TO_MAIL = "XXXXXXXXXXXXXX@XXXXXXXX"
CC_MAIL = "XXXXXXX@XXXXXX"
CC_MAIL2="XXXXXXXXXXXXX@XXXXXXXXX"
TEXT_MAIL_SUBJECT="発注のご依頼"
TEXT_MAIL_FAST = "XXXXXXXXXXXXXXXXXXご担当者様\n\nいつもお世話になっております。TOWN株式会社 XXXXと申します。\n弊社にて利用させて頂いております、ウォーターサーバーの替えの水"
TEXT_MAIL_LAST = "をお願いできますでしょうか。\nこちら、ご確認の上、ご返信頂ければ幸いです。\nご不明点等ございましたら、XX-XXXX-XXXX TOWN株式会社までご連絡をお願いします。\n\nXXXX XXXX"
class Slack:
def __init__(self,slack_token=slack_token,channel_id=ch_id):
self.slack_token=slack_token
self.slack_client=SlackClient(slack_token)
self.channel_id=channel_id
def send_message(self, message):
response = self.slack_client.api_call(
"chat.postMessage",
channel=self.channel_id,
text=message
)
return response
def send_message_button(self, message,button_set):
response = self.slack_client.api_call(
"chat.postMessage",
channel=self.channel_id,
text=message,
attachments = [button_set]
)
return response
def update_message(self, message,ts):
response = self.slack_client.api_call(
"chat.update",
channel=self.channel_id,
text=message,
ts=ts
)
return response
def update_message_button(self, message,ts,button_set):
response = self.slack_client.api_call(
"chat.update",
channel=self.channel_id,
text=message,
ts=ts,
attachments = [button_set]
)
return response
def delete_message(self,ts):
response = self.slack_client.api_call(
"chat.delete",
channel=self.channel_id,
ts=ts
)
return response
def get_history(self):
response = self.slack_client.api_call(
"channels.history",
channel=self.channel_id,
)
return response
class S3:
def __init__(self,S3_MONTH_LOG_NAME,NOWTIME,S3_BUCKET_NAME = 'XXXXXXXXXXX',S3_DB_NAME = 'XXXXXXXXXXX.db',S3_LOG_NAME = 'XXXXXXXXXX.csv'):
self.client=boto3.client('s3')
self.bucket_name=S3_BUCKET_NAME
self.db_name=S3_DB_NAME
self.csv_name=S3_LOG_NAME
self.month_csv_name='log/' + S3_MONTH_LOG_NAME + '.csv'
self.nowtime=NOWTIME
def load_db(self):
response=self.client.get_object(Bucket=self.bucket_name, Key=self.db_name)
data = json.loads(response["Body"].read())
# w_count = data['water']
# c_count = data['paper_cups']
# last_buy_day = data['last_date']
# last_w_buy = data['w_buy']
# last_c_buy = data['c_buy']
return data
def save_db(self,data):
self.client.put_object(Body=json.dumps(data, indent=4), Bucket=self.bucket_name, Key=self.db_name)
def save_csv(self,w_buy, c_buy, last_buy_day):
last_month = datetime.datetime.strptime(last_buy_day, '%Y/%m/%d-%H:%M').month
month = datetime.datetime.strptime(self.nowtime, '%Y/%m/%d-%H:%M').month
datalist = self.nowtime + "," + str(w_buy) + "," + str(c_buy) + "\n"
response_log = self.client.get_object(Bucket=self.bucket_name, Key=self.csv_name)
log = response_log["Body"].read()
logstr = log.decode('utf-8')
#最後の購入月と比較
if month == last_month:
#そのまま更新
lines = logstr + datalist
self.client.put_object(Body=lines, Bucket=self.bucket_name, Key=self.csv_name)
else:
#先月のログファイルを写す
colums = "date,water,paper_cups\n"
newlines = colums + datalist
self.client.put_object(Body=newlines, Bucket=self.bucket_name, Key=self.csv_name)
self.client.put_object(Body=logstr, Bucket=self.bucket_name, Key=self.month_csv_name)
class SES:
def __init__(self,mail_subject,mail_text,region_name="us-east-1", aws_access_key_id='XXXXXXXXXXXXXXXXXXXXXXXX',aws_secret_access_key='XXXXXXXXXXXXXXXXXXXXXXXXX'):
self.client=boto3.client('ses',region_name=region_name,aws_access_key_id=aws_access_key_id,aws_secret_access_key=aws_secret_access_key)
self.mail_subject=mail_subject
self.mail_text=mail_text
def send_mail(self,from_add,to_add,cc1_add,cc2_add):
response = self.client.send_email(
Source=from_add,
Destination={
'ToAddresses': [
to_add,
],
'CcAddresses': [
cc1_add,
cc2_add,
]
},
Message={
'Subject': {
'Data': self.mail_subject,
},
'Body': {
'Text': {
'Data': self.mail_text,
},
}
}
)
return response
class Button:
def __init__(self,S3_MONTH_LOG_NAME,NOWTIME,TODAY):
self.nowtime=NOWTIME
self.today=TODAY
self.s3=S3(S3_MONTH_LOG_NAME,NOWTIME)
def count(self,w_count,c_count):
data=self.s3.load_db()
data['water'] += w_count
data['paper_cups'] += c_count
data['water'] = min([data['water'],5])
data['paper_cups'] = min([data['paper_cups'],1])
self.s3.save_db(data)
def make_text(self):
data=self.s3.load_db()
w_count = data['water']
c_count = data['paper_cups']
last_buy_day = data['last_date']
last_w_buy = data['w_buy']
last_c_buy = data['c_buy']
#---水と紙コップの数メール本文条件分岐---
if c_count==0:
TEXT_MAIL_MID = str(w_count)+""
elif c_count != 0:
TEXT_MAIL_MID = str(w_count)+"つと紙コップ1本"
TEXT = {'title': 'メール確認', 'text': ("送り先\n\nCc: "+CC_MAIL+"\n,\n"+CC_MAIL2+"\n\nTo: "+TO_MAIL+"本文:\n\n"+TEXT_MAIL_FAST+TEXT_MAIL_MID+TEXT_MAIL_LAST), 'ok_text': 'Yes', 'dismiss_text': 'No'}
water_cupps["actions"][3]={'name': 'select', 'text': ':メール送信: ', 'type': 'button', 'value': 'ok', 'style': 'primary','confirm': TEXT}
if w_count==0:
TEXT= {'title': 'メール確認', 'text': "水0なのでメールを送れません", 'ok_text': 'Yes'}
water_cupps["actions"][3]={'name': 'select', 'text': ':メール送信: ', 'type': 'button', 'value': 'no', 'confirm': TEXT}
mail_text=TEXT_MAIL_FAST+TEXT_MAIL_MID+TEXT_MAIL_LAST
water_cupps_text="`"+self.today+"更新`\n"+last_buy_day+"に :droplet: : "+str(last_w_buy)+","+":glass_of_milk: : "+str(last_c_buy)+"を注文しました。\n\n"+"発注予定 - :droplet: : " + str(w_count) + "," + ":glass_of_milk: : "+ str(c_count)
return water_cupps_text, water_cupps, mail_text #メッセージ,ボタン設定,メール本文
def reset(self):
data=self.s3.load_db()
data['water'] = 0
data['paper_cups'] = 0
self.s3.save_db(data)
def send_mail_button(self,mail_subject,mail_text,from_add,to_add,cc1_add,cc2_add):
ses=SES(mail_subject,mail_text)
ses.send_mail(from_add,to_add,cc1_add,cc2_add)
data = self.s3.load_db()
w_buy = data['water']
c_buy = data['paper_cups']
last_buy_day = data['last_date']
if w_buy > 0:
data['last_date'] = self.nowtime
data['w_buy'] = w_buy
data['c_buy'] = c_buy
data['water'] = 0
data['paper_cups'] = 0
self.s3.save_db(data)
self.s3.save_csv(w_buy, c_buy, last_buy_day)
else:
pass
def lambda_handler(event, context):
#---logging_set--------------------------------------
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logging.info(json.dumps(event)) #cloud_watchへのロギング必要無ければ本番環境で削除
#---time---use-S3------------------------------------------------
JST = datetime.timezone(datetime.timedelta(hours=+9), 'JST')
now = datetime.datetime.now(JST)
NOWTIME = now.strftime("%Y/%m/%d-%H:%M")
TODAY = now.strftime("%Y/%m/%d")
LAST_MONTH_TIME=(now - relativedelta(months=1)).strftime("%Y-%m")
slack=Slack()
payload=str(event)
if 'deviceInfo' in payload:
payload=payload.split(':')
payload2=payload[12]
else:
payload=str(event["body"]) #httpでpostされたpayloadの格納
payload=urllib.parse.unquote(payload) #URLデコード
#---余分なところの削ぎ落とし---
payload=payload.split(':')
payload=payload[:16]
payload=''.join(payload)
button=Button(LAST_MONTH_TIME,NOWTIME,TODAY)
if 'water' in payload:#水+1
button.count(1,0)
water_cupps_text, water_cupps, mail_text = button.make_text() #slackメッセージ,slackボタン設定,メール本文
slack.update_message_button(water_cupps_text,ts,water_cupps)
elif 'cup' in payload:#紙コップ+1
button.count(0,1)
water_cupps_text, water_cupps, mail_text = button.make_text() #slackメッセージ,slackボタン設定,メール本文
slack.update_message_button(water_cupps_text,ts,water_cupps)
elif 'reset' in payload:#リセットボタン
button.reset()
water_cupps_text, water_cupps, mail_text = button.make_text() #slackメッセージ,slackボタン設定,メール本文
slack.update_message_button(water_cupps_text,ts,water_cupps)
elif 'ok' in payload:#メール送信
water_cupps_text, water_cupps, mail_text = button.make_text()
button.send_mail_button(TEXT_MAIL_SUBJECT,mail_text,FROM_MAIL,TO_MAIL,CC_MAIL,CC_MAIL2)
water_cupps_text, water_cupps, mail_text = button.make_text()
slack.update_message_button(water_cupps_text,ts,water_cupps)
elif 'SINGLE' in payload2:#水+1
button.count(1,0)
water_cupps_text, water_cupps, mail_text = button.make_text() #slackメッセージ,slackボタン設定,メール本文
slack.update_message_button(water_cupps_text,ts,water_cupps)
elif 'DOUBLE' in payload2:#紙コップ+1
button.count(0,1)
water_cupps_text, water_cupps, mail_text = button.make_text() #slackメッセージ,slackボタン設定,メール本文
slack.update_message_button(water_cupps_text,ts,water_cupps)
#---余分なメッセージをtsで識別して削除-----------------------------
for message in slack.get_history()["messages"]:
ts_del=message["ts"]
if ts_del != ts:
response=slack.delete_message(str(ts_del))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.