-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
293 lines (241 loc) · 9.57 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import os
import logging
import re
import random
import psycopg2
import datetime
import json
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
from time import sleep
from googleapiclient.discovery import build
from mugiRand import mugiRandClass as mugi
# app init
app = App(token=os.environ.get("SLACK_BOT_TOKEN"))
# log level
if os.environ.get("LOG_LEVEL") == "INFO":
logging.basicConfig(level=logging.INFO)
elif os.environ.get("LOG_LEVEL") == "DEBUG":
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.INFO)
# ---common function---
def file_read(filename):
f = open(filename,'r')
data = f.read()
f.close()
return data
def create_intro_message(joinUserName,inviteUserName):
filetext = file_read("intro_message.txt")
introductions_channel_id = os.environ.get("INTRODUCTIONS_CHANNEL_ID")
timeline_channel_id = os.environ.get("TIMELINE_CHANNEL_ID")
message = filetext.format(joinUserName,introductions_channel_id,timeline_channel_id,inviteUserName)
return message
def select_random_jikkainu():
dsn = os.environ.get("PSQL_DSN_DOG")
sql = "select id, text from tweet order by random() limit 1"
with psycopg2.connect(dsn) as conn:
with conn.cursor() as cur:
cur.execute(sql)
results = cur.fetchall()
return results
def get_search_img(keyword):
today = datetime.datetime.today().strftime("%Y%m%d")
timestamp = datetime.datetime.today().strftime("%Y-%m-%d_%H-%M-%S")
json_dir = os.environ.get("JSON_DIR")
g_api_key = os.environ.get("GOOGLE_API_KEY")
cse_id = os.environ.get("CUSTOM_SEARCH_ENGINE_ID")
if not os.path.isdir(json_dir):
os.mkdir(json_dir)
service = build("customsearch", "v1", developerKey=g_api_key, cache_discovery=False)
page_limit = 2
start_index = 1
response = []
for n_page in range(0, page_limit):
try:
sleep(1)
response.append(service.cse().list(
q=keyword,
cx=cse_id,
lr='lang_ja',
num=10,
start=start_index,
searchType='image'
).execute())
start_index = response[n_page].get("queries").get("nextPage")[0].get("startIndex")
except Exception as e:
logging.error(e)
break
out = {'snapshot_ymd': today, 'snapshot_timestamp': timestamp, 'response': []}
out['response'] = response
filename = os.path.join(json_dir, today + "_" + timestamp + '.json')
with open(filename,'w') as f:
json.dump(out, f, indent=4)
img_list = []
for one_res in range(len(response)):
if len(response[one_res]['items']) > 0:
for i in range(len(response[one_res]['items'])):
tmp_dic = {
"title":response[one_res]['items'][i]['title'],
"link":response[one_res]['items'][i]['link'],
"thmb":response[one_res]['items'][i]['image']['thumbnailLink']
}
img_list.append(tmp_dic)
# insert log
dsn = os.environ.get("PSQL_DSN_DEVO")
sql_head = "INSERT INTO gimglog_head(terms) VALUES (%s) RETURNING id"
sql_item = "INSERT INTO gimglog_item(id,count,title,link,thumb) VALUES(%s,%s,%s,%s,%s)"
with psycopg2.connect(dsn) as conn:
with conn.cursor() as cur:
cur.execute(sql_head,(keyword,))
db_id = cur.fetchone()[0]
db_count = 0
for lis in img_list:
db_count += 1
cur.execute(sql_item,(db_id,
db_count,
lis.get("title"),
lis.get("link"),
lis.get("thmb"),))
return img_list
# ---event function---
@app.event("member_joined_channel")
def check_inviter(body, logger, say):
logger.debug(body)
general_channel_id = os.environ.get("SLACK_GENERAL_CHANNEL_ID")
# join to general channel -> new person join
if body['event']['channel'] == general_channel_id:
guestUser = body['event']['user']
# in some cases, 'inviter' is null
if 'inviter' in body['event']:
inviteUser = body['event']['inviter']
else:
inviteUser = None
dsn = os.environ.get("PSQL_DSN_DEVO")
sql = "INSERT INTO inviter (guest_user_id,inviter_user_id) VALUES (%s,%s)"
with psycopg2.connect(dsn) as conn:
with conn.cursor() as cur:
cur.execute(sql,(guestUser,inviteUser))
@app.event({
"type": "message",
"subtype": "channel_join"
})
def ask_for_introduction(body, logger, say):
logger.debug(body)
general_channel_id = os.environ.get("SLACK_GENERAL_CHANNEL_ID")
# join to general channel -> new person join
if body['event']['channel'] == general_channel_id:
joinUser = body['event']['user']
# search inviter user in DB
dsn = os.environ.get("PSQL_DSN_DEVO")
sql = "SELECT seq,guest_user_id,inviter_user_id,created_at FROM inviter WHERE guest_user_id = %s AND delete_flag IS FALSE ORDER BY created_at DESC"
with psycopg2.connect(dsn) as conn:
with conn.cursor() as cur:
cur.execute(sql,(joinUser,))
res = cur.fetchall()
if len(res) == 0:
inviteUser = "unknown"
elif res[0][2] == None:
inviteUser = "unknown"
else:
inviteUser = res[0][2]
welcome_channel_id = os.environ.get("SLACK_WELCOME_CHANNEL_ID")
message = create_intro_message(joinUser,inviteUser)
say(text=message, channel=welcome_channel_id)
# delete flag
upd_sql = "UPDATE inviter SET delete_flag = TRUE WHERE guest_user_id = %s"
with psycopg2.connect(dsn) as conn:
with conn.cursor() as cur:
cur.execute(upd_sql,(joinUser,))
# TODO:add mention command
@app.message(re.compile('^devo '))
def handle_message_events(say, logger, context, message):
logger.debug(context)
input_text = message['text']
command = input_text.removeprefix("devo ")
if command == "help":
say(file_read("help.txt"))
if command == "ping":
say('PONG')
if command == "sugaicat":
mg = mugi.mugiRandClass()
filepath = mg.get_file()
channel = message['channel']
filename = mg.filename
title = "撮影日:" + mg.createDate.strftime('%Y-%m-%d')
app.client.files_upload_v2(
channel=channel,
file=filepath,
filename=filename,
title=title
)
if command == "intro_test":
test_user_id = os.environ.get("TEST_USER_ID")
say(create_intro_message(test_user_id,test_user_id))
if command == "jikkainu":
data = select_random_jikkainu()
tid = data[0][0]
url = "https://fxtwitter.com/jikkainu/status/" + tid
text = data[0][1]
message = text
message += "\n"
message += url
say(message)
if command[:4] == "img ":
keyword = command.removeprefix("img ")
img_list = get_search_img(keyword)
img_data = random.choice(img_list)
message = img_data.get("link")
message += "\n<"
message += img_data.get("thmb")
message += "|(thumbnail)>"
say(message)
if command[:6] == "image ":
keyword = command.removeprefix("image ")
img_list = get_search_img(keyword)
img_data = random.choice(img_list)
message = img_data.get("link")
message += "\n<"
message += img_data.get("thmb")
message += "|(thumbnail)>"
say(message)
# shinraisha
@app.action("shinraisha")
def handle_some_action(ack, body, logger):
ack()
logger.debug(body)
dsn = os.environ.get("PSQL_DSN_DEVO")
ch_id = body.get("channel").get("id")
user_id = body.get("user").get("id")
# check duplicate
sel_sql = "select count(*) from shinrai where user_id = %s and click_at between %s and %s"
today_str = datetime.datetime.today().strftime("%Y-%m-%d")
begin_str = today_str + " 6:30"
end_str = today_str + " 7:31"
with psycopg2.connect(dsn) as conn:
with conn.cursor() as cur:
cur.execute(sel_sql,(user_id,begin_str,end_str))
count_res = cur.fetchall()
if count_res[0][0] == 0:
ins_sql = "INSERT INTO shinrai (user_id) VALUES(%s)"
with psycopg2.connect(dsn) as conn:
with conn.cursor() as cur:
cur.execute(ins_sql,(user_id,))
app.client.chat_postEphemeral(
channel=ch_id,
user=user_id,
text="おはようございます! 今日も :shinraisha: ですね!\nあなたが今日の:shinraisha: であることを記録しました。そのうちランキングにしますね。\n\n :kawagoe: 「休日に早起きするやつは信頼できる」\n\n※このメッセージは自然消滅しますが、邪魔であれば削除ボタンから消してください。"
)
else:
app.client.chat_postEphemeral(
channel=ch_id,
user=user_id,
text="あなたは既に今日の :shinraisha: です!\n※このメッセージは自然消滅しますが、邪魔であれば削除ボタンから消してください。"
)
# other message
@app.event("message")
def handle_message_events(body, logger):
logger.debug(body)
# app start
if __name__ == "__main__":
SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"]).start()