-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
190 lines (145 loc) · 5 KB
/
bot.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 31 12:49:25 2022
@author: eyob
"""
import slack
import os
from pathlib import Path
from dotenv import load_dotenv
from flask import Flask, request, Response
from slackeventsapi import SlackEventAdapter
import string
from datetime import datetime, timedelta
import time
load_dotenv()
app = Flask(__name__)
slack_event_adapter = SlackEventAdapter(
os.environ['SIGNING_SECRET_'], '/slack/events', app)
client = slack.WebClient(token=os.environ['SLACK_TOKEN_'])
BOT_ID = client.api_call("auth.test")['user_id']
message_counts = {}
welcome_messages = {}
BAD_WORDS = ['hmm', 'no', 'tim']
SCHEDULED_MESSAGES = [
{'text': 'First message', 'post_at': (
datetime.now() + timedelta(seconds=20)).timestamp(), 'channel': 'C01BXQNT598'},
{'text': 'Second Message!', 'post_at': (
datetime.now() + timedelta(seconds=30)).timestamp(), 'channel': 'C01BXQNT598'}
]
class WelcomeMessage:
START_TEXT = {
'type': 'section',
'text': {
'type': 'mrkdwn',
'text': (
'Welcome to this awesome channel! \n\n'
'*Get started by completing the tasks!*'
)
}
}
DIVIDER = {'type': 'divider'}
def __init__(self, channel):
self.channel = channel
self.icon_emoji = ':robot_face:'
self.timestamp = ''
self.completed = False
def get_message(self):
return {
'ts': self.timestamp,
'channel': self.channel,
'username': 'Welcome Robot!',
'icon_emoji': self.icon_emoji,
'blocks': [
self.START_TEXT,
self.DIVIDER,
self._get_reaction_task()
]
}
def _get_reaction_task(self):
checkmark = ':white_check_mark:'
if not self.completed:
checkmark = ':white_large_square:'
text = f'{checkmark} *React to this message!*'
return {'type': 'section', 'text': {'type': 'mrkdwn', 'text': text}}
def send_welcome_message(channel, user):
if channel not in welcome_messages:
welcome_messages[channel] = {}
if user in welcome_messages[channel]:
return
welcome = WelcomeMessage(channel)
message = welcome.get_message()
response = client.chat_postMessage(**message)
welcome.timestamp = response['ts']
welcome_messages[channel][user] = welcome
def list_scheduled_messages(channel):
response = client.chat_scheduledMessages_list(channel=channel)
messages = response.data.get('scheduled_messages')
ids = []
for msg in messages:
ids.append(msg.get('id'))
return ids
def schedule_messages(messages):
ids = []
for msg in messages:
response = client.chat_scheduleMessage(
channel=msg['channel'], text=msg['text'], post_at=msg['post_at']).data
id_ = response.get('scheduled_message_id')
ids.append(id_)
return ids
def delete_scheduled_messages(ids, channel):
for _id in ids:
try:
client.chat_deleteScheduledMessage(
channel=channel, scheduled_message_id=_id)
except Exception as e:
print(e)
def check_if_bad_words(message):
msg = message.lower()
msg = msg.translate(str.maketrans('', '', string.punctuation))
return any(word in msg for word in BAD_WORDS)
@ slack_event_adapter.on('message')
def message(payload):
event = payload.get('event', {})
channel_id = event.get('channel')
user_id = event.get('user')
text = event.get('text')
if user_id != None and BOT_ID != user_id:
if user_id in message_counts:
message_counts[user_id] += 1
else:
message_counts[user_id] = 1
if text.lower() == 'start':
send_welcome_message(f'@{user_id}', user_id)
elif check_if_bad_words(text):
ts = event.get('ts')
client.chat_postMessage(
channel=channel_id, thread_ts=ts, text="THAT IS A BAD WORD!")
@ slack_event_adapter.on('reaction_added')
def reaction(payload):
event = payload.get('event', {})
channel_id = event.get('item', {}).get('channel')
user_id = event.get('user')
if f'@{user_id}' not in welcome_messages:
return
welcome = welcome_messages[f'@{user_id}'][user_id]
welcome.completed = True
welcome.channel = channel_id
message = welcome.get_message()
updated_message = client.chat_update(**message)
welcome.timestamp = updated_message['ts']
@ app.route('/message-count', methods=['POST'])
def message_count():
data = request.form
user_id = data.get('user_id')
channel_id = data.get('channel_id')
message_count = message_counts.get(user_id, 0)
client.chat_postMessage(
channel=channel_id, text=f"Message: {message_count}")
return Response(), 200
if __name__ == "__main__":
schedule_messages(SCHEDULED_MESSAGES)
ids = list_scheduled_messages('C01BXQNT598')
delete_scheduled_messages(ids, 'C01BXQNT598')
app.run(debug=True)