import os
import json

import asyncio
import websockets

import slacker


################################
# IMPORTANT: just for testing! #
################################
slack = slacker.Slacker('xoxb-24649221783-q40uS6HJkH7D6TMhykeyaH7h')
# Use this for production:
#
#     slack = slacker.Slacker(os.environ["SLACKAPIKEY"])
#


def open_im_channel(user):
    try:
        response = slack.im.open(user)
    except slacker.Error as e:
        print(e)
        return None

    # https://api.slack.com/methods/im.open
    return response.body.get('channel', {}).get('id')


async def read_loop(uri):
    ws = await websockets.connect(uri)
    while True:
        json_data = await ws.recv()
        data = json.loads(json_data)
        print(data)

        if data.get('type') == 'team_join':
            user_id = data.get('user').get('id')
            user_name = data.get('user').get('name')

            im_channel_id = open_im_channel(user_id)
            if im_channel_id is not None:
                slack.chat.post_message(user_id, "Test message, sent when you message")
                slack.chat.post_message(user_id, "Hey " + user_name + ", welcome to the Devolio Slack group!")
                slack.chat.post_message(user_id, "We'd love to hear a little about you - feel free to drop" \
                                        "in on <#intro> and let everyone know what you're about.")
                slack.chat.post_message(user_id, "You can add your interests to your profile by clicking on your name, " \
                                        "and then you can join different channels for your various interests " \
                                        "by clicking on that \"Channels\" link up near the top left.")


def get_rtm_uri():
    rtm = slack.rtm.start()
    print(rtm)

    try:
        body = rtm.body
    except slacker.Error as e:
        print(e)
        return None
    return body.get('url')

if __name__ == '__main__':
    ws_url = get_rtm_uri()

    if ws_url is not None:
        asyncio.get_event_loop().run_until_complete(
            read_loop(ws_url)
        )

# Send a message to #general channel
# slack.chat.post_message('#general', 'Hello fellow slackers!')

# while True:
    
    # Get users list
    # response = slack.users.list()
    # users = response.body['members']

    # print(users)

    # for x in users:
        # print(user_id)
        # slack.chat.post_message(user_id, 'Hey ' + x['name'] + ', welcome to the Devolio Slack group!')
        # slack.chat.post_message(user_id, 'We\'d love to hear a little about you - feel free to drop in on #intro and let everyone know what you\'re about.')
        # slack.chat.post_message(user_id, 'You can add your interests to your profile by [fill this out - I don\'t know what the easiest way to describe this is], and then you can join different channels for your various interests by clicking on that "Channels" link up near the top left [image of Channels link].')

    # time.sleep(500)

@@ -646,24 +646,74 @@
 while True:%0A
+        #wait for the data from slack to come in.%0A
         json
@@ -802,18 +802,25 @@
         
-if
+user_id =
  data.ge
@@ -826,42 +826,33 @@
 et('
-type') == 'team_join':%0A   
+user').get('id')%0A
         
  use
@@ -843,32 +843,33 @@
 d')%0A        
- 
 user_
-id
+name
  = data.get(
@@ -873,34 +873,36 @@
 et('user').get('
-id
+name
 ')%0A            u
@@ -900,53 +900,134 @@
     
-    user_name = data.get('user').get('name')%0A
+im_channel_id = open_im_channel(user_id)%0A        #if a user joins the devolio team%0A        if data.get('type') == 'team_join':
 %0A   
@@ -1027,32 +1027,35 @@
 n':%0A            
+if 
 im_channel_id = 
@@ -1056,177 +1056,824 @@
 _id 
-= op
+is not None:%0A                s
 en
+d
 _i
-m_channel(user_id)%0A            if im_channel_id is not None:%0A                slack.chat.post_message(user_id, %22Test message, sent when you message%22)%0A            
+ntroduction_message()%0A                slack.channels.join(%22intro%22)%0A        if data.get('type') == %22pref_change%22:%0A            if im_channel_id is not None:%0A                slack.chat.post_message(user_id, %22I see you changed your preferences, that's great!%22)%0A                slack.chat.post_message(user_id, %22I will now put you in some channels that I think might be relevant to you.%22)%0A                slack.chat.post_message(user_id, %22Feel free to join other channels as well!%22)%0A%0A%0Adef get_rtm_uri():%0A    rtm = slack.rtm.start()%0A    print(rtm)%0A%0A    try:%0A        body = rtm.body%0A    except slacker.Error as e:%0A        print(e)%0A        return None%0A    return body.get('url')%0A%0Adef send_introduction_message():%0A    slack.chat.post_message(user_id, %22Test message, sent when you message%22)%0A
     
@@ -1963,36 +1963,24 @@
 ck group!%22)%0A
-            
     slack.ch
@@ -2105,16 +2105,20 @@
         
+    
 %22in on %3C
@@ -2164,36 +2164,24 @@
 re about.%22)%0A
-            
     slack.ch
@@ -2319,16 +2319,20 @@
         
+  
+  
 %22and the
@@ -2436,16 +2436,20 @@
         
+    
 %22by clic
@@ -2507,201 +2507,69 @@
 .%22)%0A
-%0A%0Adef get_rtm_uri():%0A    rtm = slack.rtm.start()%0A    print(rtm)%0A%0A    try:%0A        body = rtm.body%0A    except slacker.Error as e:%0A        print(e)%0A        return None%0A    return body.get('url')%0A
+#check if this is the main application running (not imported)
 %0Aif 

Add check if user changed his pref