forked from vibhor98/Slack_bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvibhor_bot.py
206 lines (151 loc) · 6.54 KB
/
vibhor_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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import bs4
import json
from lang_translator import translate
import os
import random
import requests
from scrabble import scrabble
import slackclient
import sys
import time
import urllib2
# delay in secs
SOCKET_DELAY = 1
# slackbot environment variables
VIBHOR_SLACK_TOKEN = os.environ.get('VIBHOR_SLACK_TOKEN')
VIBHOR_SLACK_NAME = os.environ.get('VIBHOR_SLACK_NAME')
VIBHOR_SLACK_ID = os.environ.get('VIBHOR_SLACK_ID')
# VIBHOR_SLACK_TOKEN='xoxb-207770090644-nuaIgpyyG8eX48voyZAb5Mgd'
# VIBHOR_SLACK_NAME='vibhor_bot'
# VIBHOR_SLACK_ID='U63NN2NJY'
# initialise the slack client
vibhor_slack_client = slackclient.SlackClient(VIBHOR_SLACK_TOKEN)
# checks if message is privately for the user or mentioned for the user in public chat
def is_for_me(event):
msg_type = event.get('type')
if msg_type and msg_type=='message' and not(event.get('user') == VIBHOR_SLACK_ID):
if is_private(event):
return True
text = event.get('text')
if vibhor_slack_mention in text.strip().split():
return True
return False
# checks if Slack channel is private
def is_private( event):
return event.get('channel').startswith('D') # As private channel startswith 'D'
def get_mention(user):
return '<@{user}>'.format( user=user)
vibhor_slack_mention = get_mention( VIBHOR_SLACK_ID) # Way the bot is mentioned in the chats
def is_hi(message):
tokens = [word.lower() for word in message.strip().split()]
return any( word in tokens for word in ['hello', 'hi', 'hey', 'hola', 'sup', 'yo', 'ohai', 'morning', 'bonjour'])
def is_bye(message):
tokens = [word.lower() for word in message.strip().split()]
return any( word in tokens for word in ['bye', 'cya', 'goodbye', 'later'])
def is_time( message):
message.replace('?', '')
return any( st in message.strip().lower() for st in ['time', 'what is the hour of the day', 'tell me the date today',
"what's the day today", 'date', "what's the date today"])
def say_hi(user_mention):
response = random.choice(['Hello {mention}...', 'Hi {mention}!', 'Hola!'])
return response.format( mention=user_mention)
def say_bye(user_mention):
response = random.choice(['Bye {mention}', 'See you Later', 'See you soon!'])
return response.format( mention=user_mention)
def is_how_r_u( message):
message.replace('?', '')
return any( st in message.strip().lower() for st in ['how are you', "what's up", 'tell me about you', "what's going on", "how it's going",
"how have you been", "are you well", 'how are you keeping',
'what have you been up to', "what's happening"])
def say_about_u (user_mention):
response = random.choice(["I'm fine {mention}", 'Nice', 'Fit and Healthy', 'Awesome! {mention}',
'Fine, thanks', 'Great! How are you doing?',"I've been better"])
return response.format( mention=user_mention)
def tell_time(user_mention):
return str(time.ctime()) + str(user_mention)
def is_weather( message):
return any( message.strip().lower().startswith(st) for st in ['weather', 'tell me weather'])
def weather_forecast(place):
base_url = 'http://api.openweathermap.org/data/2.5/forecast?q='
url = base_url + place + 'india&APPID=041d68834f4ca8f569d71cd6df88ae61'
data = json.load(urllib2.urlopen(url))
return data
def tell_weather( message, channel):
place = message.split()[-1]
data2 = weather_forecast(place)
post_message('Condition: ' + data2['list'][0]['weather'][0]['main'] + ' (' + data2['list'][0]['weather'][0]['description']
+ ')', channel)
post_message('Temperature: ' + str(float(data2['list'][0]['main']['temp']) - 273.15) + ' Celsius', channel)
def is_translate( message):
if message == None:
return False
if message.lower().startswith('translate'):
return True
else:
return False
def tell_translation( message, channel):
msg = translate(message)
post_message(msg, channel)
def is_scrabble(message):
if message == None:
return False
if message.lower().startswith('scrabble') or message.lower().startswith('jumble'):
return True
else:
return False
def scrabble_cheat(message, channel):
rack = message.split()[1]
words = scrabble( rack)
result = "Bingo!! Here's the cheat ... \
\n Use the word with max. score and WIN your Scrabble game in minutes\n\n"
for word in words:
result += 'score: ' + str(word[0]) + ' ' + word[1] + '\n'
post_message(result, channel)
# posts a response to the channel on behalf of the user
def post_message( message, channel):
vibhor_slack_client.api_call( 'chat.postMessage', text=message,
channel=channel, as_user=True)
def handle_message(message, user, channel):
if is_translate( message):
tell_translation(message, channel)
elif is_hi( message):
mention = get_mention(user)
post_message( say_hi(mention), channel)
elif is_bye( message):
mention = get_mention(user)
post_message( say_bye(mention), channel)
elif is_how_r_u( message):
mention = get_mention( user)
post_message( say_about_u(mention), channel)
elif is_time( message):
mention = get_mention( user)
post_message( tell_time(mention), channel)
elif is_weather( message):
tell_weather(message, channel)
elif is_scrabble(message):
scrabble_cheat(message, channel)
elif is_movie(message) :
movie(message, channel)
elif is_hotel(message) :
hotel(message, channel)
else:
post_message("Not sure what you have just said!", channel)
# main()
def run():
if vibhor_slack_client.rtm_connect():
print '[.] Slack bot is ONN'
while True:
event_list = vibhor_slack_client.rtm_read()
if len( event_list)>0:
for event in event_list:
print event
if is_for_me( event):
handle_message( message=event.get('text'),
user=event.get('user'), channel=event.get('channel'))
if str(datetime.now()).split()[1] == '00:00:00':
post_message(message="It's midnight of %s" % (str(datetime.now()).split()[0]), channel=event.get('channel'))
time.sleep( SOCKET_DELAY)
else:
print '[!] Connection to the Slack failed'
if __name__ == '__main__':
run()