-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_task.py
More file actions
178 lines (145 loc) · 5.96 KB
/
Copy pathcreate_task.py
File metadata and controls
178 lines (145 loc) · 5.96 KB
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
#!/usr/bin/env python3
"""
ManageBac Task Creation Automation
Automates the creation of tasks for IGCSE Music classes
"""
from playwright.sync_api import sync_playwright
import json
import os
from datetime import datetime
# Configuration
CONFIG = {
"url": "https://wids.managebac.cn",
"username": "antony.leedale@suis.com.cn",
"classes": {
"g9": {
"id": "11417810",
"name": "CAIE IGCSE MusicB - Grade 9",
"url": "https://wids.managebac.cn/teacher/classes/11417810"
},
"g10": {
"id": "11338714",
"name": "Grade 10 Music",
"url": "https://wids.managebac.cn/teacher/classes/11338714"
}
}
}
def load_task_config(config_file="task_config.json"):
"""Load task configuration from JSON file"""
if os.path.exists(config_file):
with open(config_file, 'r') as f:
return json.load(f)
else:
print(f"❌ Config file not found: {config_file}")
print("Please create a task_config.json file with your task details")
return None
def create_task(page, task_data, class_info):
"""Create a single task on ManageBac"""
print(f"\n📝 Creating task: {task_data['title']}")
print(f" Class: {class_info['name']}")
# Navigate to the class
page.goto(class_info['url'])
page.wait_for_load_state('networkidle')
# Click on Tasks & Units tab
page.click('text=Tasks & Units')
page.wait_for_load_state('networkidle')
# Click "Add Task" button
page.click('button:has-text("Add Task"), a:has-text("Add Task")')
page.wait_for_load_state('networkidle')
# Fill in task details
print(" ✏️ Filling in task details...")
# Title
page.fill('input[name="title"], input[placeholder*="Title"]', task_data['title'])
# Category (if specified)
if 'category' in task_data:
page.click('select[name="category"]')
page.select_option('select[name="category"]', label=task_data['category'])
# Type (if specified)
if 'type' in task_data:
page.click('select[name="type"]')
page.select_option('select[name="type"]', label=task_data['type'])
# Due date
if 'due_date' in task_data:
page.fill('input[name="due_date"], input[type="date"]', task_data['due_date'])
# Description
if 'description' in task_data:
# Try to find the description field (might be a textarea or rich text editor)
try:
page.fill('textarea[name="description"]', task_data['description'])
except:
# If it's a rich text editor, try alternative selectors
page.click('.rich-text-editor, .description-field')
page.keyboard.type(task_data['description'])
# Save as draft option
if task_data.get('save_as_draft', False):
print(" 💾 Saving as draft...")
draft_checkbox = page.locator('input[type="checkbox"][name*="draft"], label:has-text("Save as draft")')
if draft_checkbox.count() > 0:
draft_checkbox.check()
# Submit the form
print(" 📤 Submitting task...")
submit_button = page.locator('button[type="submit"]:has-text("Save"), button:has-text("Create Task")')
submit_button.click()
# Wait for confirmation
page.wait_for_load_state('networkidle')
print(" ✅ Task created successfully!")
def main():
"""Main execution function"""
print("🎵 ManageBac Task Creation Automation")
print("=" * 50)
# Load task configuration
task_config = load_task_config()
if not task_config:
return
# Get password from environment or prompt
password = os.environ.get('MANAGEBAC_PASSWORD')
if not password:
import getpass
password = getpass.getpass("Enter your ManageBac password: ")
# Determine which class to use
class_key = task_config.get('class', 'g9') # default to g9
if class_key not in CONFIG['classes']:
print(f"❌ Unknown class: {class_key}")
print(f"Available classes: {', '.join(CONFIG['classes'].keys())}")
return
class_info = CONFIG['classes'][class_key]
with sync_playwright() as p:
# Launch browser
print("\n🌐 Launching browser...")
browser = p.chromium.launch(headless=False) # Set to True for headless mode
context = browser.new_context()
page = context.new_page()
try:
# Login
print(f"🔐 Logging in to {CONFIG['url']}...")
page.goto(CONFIG['url'])
page.wait_for_load_state('networkidle')
# Fill in login credentials
page.fill('input[type="email"], input[name="username"]', CONFIG['username'])
page.fill('input[type="password"], input[name="password"]', password)
page.click('button[type="submit"], input[type="submit"]')
page.wait_for_load_state('networkidle')
print("✅ Login successful!")
# Create tasks
tasks = task_config.get('tasks', [])
if not tasks:
print("⚠️ No tasks found in configuration")
return
print(f"\n📋 Found {len(tasks)} task(s) to create")
for i, task_data in enumerate(tasks, 1):
print(f"\n--- Task {i}/{len(tasks)} ---")
create_task(page, task_data, class_info)
print("\n" + "=" * 50)
print("🎉 All tasks created successfully!")
print("=" * 50)
# Keep browser open for a moment to verify
input("\nPress Enter to close the browser...")
except Exception as e:
print(f"\n❌ Error: {str(e)}")
import traceback
traceback.print_exc()
input("\nPress Enter to close the browser...")
finally:
browser.close()
if __name__ == "__main__":
main()