forked from l-yohai/daily_papers_ko
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslackbot.py
90 lines (69 loc) · 2.6 KB
/
slackbot.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
import argparse
import re
from slack_sdk import WebClient
from utils import get_today
from request import get_url
yy, mm, dd = get_today().split("-")
def get_daily_papers():
with open(f"paper_logs/{yy}/{mm}/{dd}.md", "r") as f:
daily_papers = f.read()
return daily_papers
def make_template_for_slackbot(daily_papers: str):
templates = []
contents = daily_papers.split("###")[1:]
for content in contents:
# 0: 제목, 1: 썸네일, 2: 저자, 3: 요약
title_and_url, thumbnail, vote, authors, summary = content.split("\n\n")[:5]
title_and_url = title_and_url.strip().replace("[", "*").replace("]", "* ")
if "video" in thumbnail:
pattern = r'<video[^>]*src="([^"]+)"[^>]*>'
match = re.search(pattern, thumbnail)
if match:
thumbnail = match.group(1)
else:
thumbnail = ""
elif "png" in thumbnail:
pattern = r"!\[\]\(([^)]+)\)"
match = re.search(pattern, thumbnail)
if match:
thumbnail = match.group(1)
else:
thumbnail = ""
template = f"""{title_and_url}\n\n{vote}\n\n{authors}\n\n{summary}\n\nThumbnail: {thumbnail}\n\n"""
templates.append(template)
return templates
def send(args, templates=[]):
sc = WebClient(token=args.slack_api_token)
if not templates:
daily_papers = get_daily_papers()
templates = make_template_for_slackbot(daily_papers=daily_papers)
sc.chat_postMessage(
channel=args.target_channel_name,
text=f"{yy}-{mm}-{dd} Daily Papers ({get_url()})",
)
for template in templates:
# get the timestamp of the parent message
result = sc.conversations_history(channel=args.target_channel_id)
conversation_history = result["messages"] # [0] is the most recent message
message_ts = conversation_history[0]["ts"]
sc.chat_postMessage(
channel=args.target_channel_name,
text=template,
thread_ts=message_ts,
)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--workspace_name", type=str, default="", help="Slack workspace name"
)
parser.add_argument(
"--target_channel_name", type=str, default="", help="Target channel name"
)
parser.add_argument(
"--target_channel_id", type=str, default="", help="Target channel ID"
)
parser.add_argument(
"--slack_api_token", type=str, default="", help="Slack API token"
)
args = parser.parse_args()
send(args)