Home Automate Teams creation on MS Teams using Graph API
Post
Cancel

Automate Teams creation on MS Teams using Graph API

If you have tried it once you know how cumbersome it is to create and customize teams via GUI.

…but if you have the right level of access to the Azure tenancy and you have privileges to create apps, you could automate the whole stuff and all you need is to keep a template (as a JSON, etc) which you can give to the code to do the heavy work for you while you sip your cup of coffee!

Pre-requisites

  • Azure AD App with the relevant permissions.

    I have given Directory.ReadWrite.All but there may be a better one specific for Teams

  • python msal (or any client library for that matter)

Code in detail

Save the config as a json. A sample config.json is as follows:

1
2
3
4
5
6
7
{
    "authority": "https://login.microsoftonline.com/<tenant name>",
    "client_id": "<Azure AD App client id here>",
    "scope": ["https://graph.microsoft.com/.default"],
    "secret": "<Azure AD App client secret value here>",
    "endpoint": "https://graph.microsoft.com/v1.0/teams/"
}

Create the template of the Team(s) that you would like to create. A sample payload.json is as follows:

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
{
   "[email protected]":"https://graph.microsoft.com/v1.0/teamsTemplates('educationStaff')",
   "visibility":"Private",
   "displayName":"Teacher Template",
   "description":"This is a sample teacher team using teamsTemplates('educationStaff')",
   "members":[
      {
         "@odata.type":"#microsoft.graph.aadUserConversationMember",
         "roles":[
            "owner"
         ],
         "[email protected]":"https://graph.microsoft.com/v1.0/users('<user Object ID here>')"
      }
   ],
   "channels":[
      {
         "displayName":"Announcements",
         "isFavoriteByDefault":"true",
         "description":"....."
      },
      {
         "displayName":"Training",
         "isFavoriteByDefault":"true",
         "description":"This is a sample training channel, that is favorited by default, and contains an example of pinned website and YouTube tabs.",
         "tabs":[
            {
     "[email protected]":"https://graph.microsoft.com/v1.0/appCatalogs/teamsApps('com.microsoft.teamspace.tab.web')",
               "displayName":"A Pinned Website",
               "configuration":{
                  "contentUrl":"https://docs.microsoft.com/microsoftteams/microsoft-teams"
               }
            },
            {
               "[email protected]":"https://graph.microsoft.com/v1.0/appCatalogs/teamsApps('com.microsoft.teamspace.tab.youtube')",
               "displayName":"A Pinned YouTube Video",
               "configuration":{
                  "contentUrl":"https://tabs.teams.microsoft.com/Youtube/Home/YoutubeTab?videoId=X8krAMdGvCQ",
                  "websiteUrl":"https://www.youtube.com/watch?v=X8krAMdGvCQ"
               }
            }
         ]
      },

   "memberSettings": {
        "allowCreateUpdateChannels": "true",
        "allowDeleteChannels": "true",
        "allowAddRemoveApps": "true",
        "allowCreateUpdateRemoveTabs": "true",
        "allowCreateUpdateRemoveConnectors": "true"
    },
    "guestSettings": {
        "allowCreateUpdateChannels": "false",
        "allowDeleteChannels": "false"
    },
    "funSettings": {
        "allowGiphy": true,
        "giphyContentRating": "Moderate",
        "allowStickersAndMemes": "true",
        "allowCustomMemes": "true"
    },
    "messagingSettings": {
        "allowUserEditMessages": "true",
        "allowUserDeleteMessages": "true",
        "allowOwnerDeleteMessages": "true",
        "allowTeamMentions": "true",
        "allowChannelMentions": "true"
    },
    "discoverySettings": {
        "showInTeamsSearchAndSuggestions": "true"
    },
   ],
   "installedApps":[
      {
         "[email protected]":"https://graph.microsoft.com/v1.0/appCatalogs/teamsApps('com.microsoft.teamspace.tab.vsts')"
      },
      {
         "[email protected]":"https://graph.microsoft.com/v1.0/appCatalogs/teamsApps('1542629c-01b3-4a6d-8f76-1938b779e48d')"
      }
   ]
}

A basic teams.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
import json
import requests
import msal
import time
config = json.load(open(sys.argv[1]))
result = None

def auth():
    global result
    app = msal.ConfidentialClientApplication(
        config["client_id"], authority=config["authority"],
        client_credential=config["secret"]
        )
    result = app.acquire_token_silent(config["scope"], account=None)
    if not result:
        result = app.acquire_token_for_client(scopes=config["scope"])


def create_team():
    if 'access_token' in result:
        http_headers = {'Authorization': 'Bearer ' + result['access_token'], 'Accept': 'application/json', 'Content-Type': 'application/json'}
        with open('payload.json') as f:
           payload = json.load(f)

        url = "https://graph.microsoft.com/v1.0/teams"
        status_endpoint = "https://graph.microsoft.com/v1.0"

        try:
            data = requests.post(url, headers=http_headers, json=payload, stream=False)
            print (data.status_code)
            print (data.headers)
            print (data.reason)
            if data.status_code == 202:
                url = f"{status_endpoint}{data.headers['Location']}"
                print (url)
                check_status = True
                timeout = -1
                while check_status:
                    timeout += 1
                    print ("waiting for 30 seconds to check status of team creation.")
                    time.sleep(30)
                    if timeout < 15:
                        status_json = requests.get(url, headers=http_headers).json()
                        print (status_json['status'])
                        if status_json['status'] == 'succeeded':
                            print (status_json)
                            check_status = False
                    else:
                        print ("time out reached for status check, the team may have created, check later.")
                        break

        except Exception as e:
            //handle the exceptions well by modifying the code.
            print (str(e))
    else:
        print ("issue with auth, no token was found.")



if __name__=="__main__":
    auth()
    create_team()

Advanced teams.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
import msal
import json
import requests
import os
import time
import re
import sys
import pandas
import logging

team_ids_file_location = "Teams.csv" #file that have groupIds for the teams that require private channels_for_members
create_team_ids_file_location = "createTeams.csv" #file that have displayName for the new teams to be created using create_team()
teacher_email = "[email protected]"
config = json.load(open(sys.argv[1]))

def auth_then_proceed():
    global result, config
    app = msal.ConfidentialClientApplication(
        config["client_id"], authority=config["authority"],
        client_credential=config["secret"],
    )
    result = app.acquire_token_silent(config["scope"], account=None)
    if not result:
        result = app.acquire_token_for_client(scopes=config["scope"])

    if "access_token" in result:
        #Comment any function that is not required.
        #1. delete_all_teams() deletes all the teams in the tenancy.
        #2. teams_and_channels() creates private channels for the groupIds supplied by team_ids_file_location
        #3. create_teams() creates teams supplied by create_team_ids_file_location
        #I do not have the interest and time to create a menu based system to handle this in a better way.
        #Edit below according to your choice of operation:

        #delete_all_teams()
        #create_teams()
        teams_and_channels()

    else:
        print(result.get("error"))
        print(result.get("error_description"))
        print(result.get("correlation_id"))

def get_existing_priv_channels(groupId):
    global result, config
    channels = []
    http_headers = {'Authorization': 'Bearer ' + result['access_token'],
                        'Accept': 'application/json',
                        'Content-Type': 'application/json'}
    url = f"{config['endpoint']}/{groupId}/channels?$filter=membershipType eq 'private'"
    try:
        data = requests.get(url, headers=http_headers, timeout=10, stream=False).json()
        if 'value' in data:
            for channel in data['value']:
                channels.append(channel['displayName'])
            return channels

    except Exception as e:
        logging.warning(str(e))
    return channels

def create_priv_channel(groupId, displayName, memberEmail):
    http_headers = {'Authorization': 'Bearer ' + result['access_token'],'Accept': 'application/json','Content-Type': 'application/json'}
    payload = {"@odata.type":"#Microsoft.Graph.channel", "membershipType": "private", "displayName": displayName, "members":
       [
          {
             "@odata.type":"#microsoft.graph.aadUserConversationMember",
             "[email protected]":f"https://graph.microsoft.com/v1.0/users('{teacher_email}')",
             "roles":["owner"]
          },
          {
             "@odata.type":"#microsoft.graph.aadUserConversationMember",
             "[email protected]":f"https://graph.microsoft.com/v1.0/users('{memberEmail}')",
             "roles":["owner"]
          }
       ]}
    url = f"{config['endpoint']}/{groupId}/channels"
    try:
        data = requests.post(url, headers=http_headers, json=payload, stream=False)
        if data.status_code == 201:
            data = data.json()
            print (f"Channel created {data['displayName']}")
        else:
            logging.error(f"Could not create the channel {displayName}.\nMore Details:\n{data}")
    except Exception as e:
        logging.warning(str(e))

def channels_for_members(groupId):
    global result, config
    http_headers = {'Authorization': 'Bearer ' + result['access_token'], 'Accept': 'application/json', 'Content-Type': 'application/json'}
    url = f"{config['endpoint']}/{groupId}/members"
    try:
        #get members of the team and loop through each member
        data = requests.get(url, headers=http_headers, timeout=10, stream=False).json()
        if 'value' in data:
            channels = get_existing_priv_channels(groupId)
            for member in data['value']:
                if "owner" not in member["roles"]:
                    clean_member_name = re.sub(r"[#%&*{}/\\:<>?+|']", '', member["displayName"])
                    if clean_member_name not in channels:
                        create_priv_channel(groupId, clean_member_name, member["email"])
                    else:
                        print (f"The channel {clean_member_name} exists.")
        else:
            logging.error(f"There may be some issue with the teamId {groupId}\nMore Details:\n{data}")

    except Exception as e:
        logging.error(str(e))

def teams_and_channels():
    groups = pandas.read_csv(team_ids_file_location)
    for i, group in groups.iterrows():
        print(f"Processing {group['groupId']}")
        channels_for_members(group['groupId'])

def delete_all_teams():
    #Requires Group.ReadWrite.All permissions on Azure App API permissions
    global result, config
    confirm = input ("This will delete all teams in the tenancy. Proceed?\n")
    if confirm == 'yes':
        http_headers = {'Authorization': 'Bearer ' + result['access_token'], 'Accept': 'application/json', 'Content-Type': 'application/json'}
        url = "https://graph.microsoft.com/v1.0/groups?$select=id,resourceProvisioningOptions"
        try:
            data = requests.get(url, headers=http_headers).json()
            if 'value' in data:
                for group in data['value']:
                    if 'Team' in group['resourceProvisioningOptions']:
                        print (group['id'])
                        url = f"https://graph.microsoft.com/v1.0/groups/{group['id']}"
                        data = requests.delete(url, headers=http_headers)
                        if data.status_code == 204:
                            print (f"Deleted {group['id']}")
                        else:
                            print (f"groupd id is {group['id']}")
                            logging.error(f"Could not delete {group['id']} because:\n{data}")

        except Exception as e:
            logging.error("Can't proceed with deletion of teams")

def create_teams():
    #Requires Team.Create permissions on Azure App API permissions
    global result, config
    url = "https://graph.microsoft.com/v1.0/teams"
    status_endpoint = "https://graph.microsoft.com/v1.0"
    http_headers = {'Authorization': 'Bearer ' + result['access_token'], 'Accept': 'application/json', 'Content-Type': 'application/json'}
    displayNames = pandas.read_csv(create_team_ids_file_location)
    status_urls = []
    for i, displayName in displayNames.iterrows():
        print (f"Processing {displayName['Display Name']}...")
        payload = {"[email protected]": "https://graph.microsoft.com/v1.0/teamsTemplates('standard')","displayName": displayName['Display Name'],         "description": displayName['Display Name'],"members":[
            {
             "@odata.type":"#microsoft.graph.aadUserConversationMember",
             "roles":[
                "owner"
             ],
             "[email protected]":f"https://graph.microsoft.com/v1.0/users('{teacher_email}')"
             }
         ]}
        try:
            data = requests.post(url, headers=http_headers, json=payload, stream=False)
            if data.status_code == 202:
                print ("Submitted to the backend.")
                status_urls.append(data.headers['Location'])

        except Exception as e:
            #handle the exceptions, well, by modifying the code.
            print (str(e))

    if len(status_urls) > 0:
        print (f"{len(status_urls)} statuses to process...")
        groups_created = []
        for status_url in status_urls:
            url = f"{status_endpoint}{status_url}"
            check_status = True
            timeout = -1
            while check_status:
                timeout += 1
                print ("Waiting for 2 seconds...")
                time.sleep(2)
                if timeout < 15:
                    status_json = requests.get(url, headers=http_headers).json()
                    print (status_json['status'])
                    if status_json['status'] == 'succeeded':
                        groups_created.append(status_json['targetResourceId'])
                        check_status = False
                else:
                    print ("time out reached for status check, the team may have created, check later.")
                    break
        if (len(status_urls) == len(groups_created)):
            print (f"Detected the status of {len(groups_created)}. Team IDs are as follows:")
        else:
            print (f"Confirmed that {len(groups_created)} teams were created but there may be more. The confirmed Team IDs are as follows:")
        for confirmed_group in groups_created:
            print (confirmed_group)

        #Rest of the code only if you want to add 'member's. Since I am dealing with test users, I hardcoded it here.
        for confirmed_group in groups_created:
            print (f"Trying to add the users as members to {confirmed_group}")
            url = f"https://graph.microsoft.com/v1.0/teams/{confirmed_group}/members/add"
            payload = {
                "values": [
                    {
                        "@odata.type": "microsoft.graph.aadUserConversationMember",
                        "roles":[],
                        "[email protected]": "https://graph.microsoft.com/v1.0/users('[email protected]')"
                    },
                    {
                        "@odata.type": "microsoft.graph.aadUserConversationMember",
                        "roles":[],
                        "[email protected]": "https://graph.microsoft.com/v1.0/users('[email protected]')"
                    },
                    {
                        "@odata.type": "microsoft.graph.aadUserConversationMember",
                        "roles":[],
                        "[email protected]": "https://graph.microsoft.com/v1.0/users('[email protected]')"
                    },
                    {
                        "@odata.type": "microsoft.graph.aadUserConversationMember",
                        "roles":[],
                        "[email protected]": "https://graph.microsoft.com/v1.0/users('[email protected]')"
                    }
                ]
            }
            try:
                data = requests.post(url, headers=http_headers, json=payload, stream=False)
                if data.status_code == 200:
                    data = data.json()
                    print (f"Users added!")
                else:
                    logging.error(f"Could not add the users as member to {confirmed_group}.\nMore Details:\n{data.text}")
            except Exception as e:
                logging.warning(str(e))


if __name__ == "__main__":
    auth_then_proceed()

Execute

1
$ python3 teams.py config.json
This post is licensed under CC BY 4.0 by the author.