-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
505 lines (382 loc) · 17.2 KB
/
Copy pathapi.py
File metadata and controls
505 lines (382 loc) · 17.2 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
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
import os
from dotenv import load_dotenv, set_key
import requests
import json
from langchain_core.tools import tool
from codespaces_secrets import update_secret
load_dotenv()
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
REFRESH_TOKEN = os.getenv("REFRESH_TOKEN")
CLIENT_ID = os.getenv("CLIENT_ID")
CLIENT_SECRET = os.getenv("CLIENT_SECRET")
@tool
def refresh_access_token(a: str) -> str:
'''
Refreshes the access token for MyAnimeList. Use this if you get an invalid token error when using the API, then retry the previous API call.
'''
load_dotenv(override=True)
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
api_url = "https://myanimelist.net/v1/oauth2/token"
params = {
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"grant_type": "refresh_token",
"refresh_token": REFRESH_TOKEN
}
response = requests.post(api_url, data=params).json()
os.environ["ACCESS_TOKEN"] = response['access_token']
os.environ["REFRESH_TOKEN"] = response['refresh_token']
if os.path.exists(".env"):
set_key(".env", "ACCESS_TOKEN", response['access_token'])
set_key(".env", "REFRESH_TOKEN", response['refresh_token'])
if os.getenv("GH_TOKEN"):
update_secret("ACCESS_TOKEN", response['access_token'])
update_secret("REFRESH_TOKEN", response['refresh_token'])
return "Successfully refreshed the access token"
@tool
def search_anime(anime_name: str) -> str:
'''
Takes a string and searches MyAnimeList for the anime.
The result will be a JSON table of titles and IDs.
All titles will be in the original language (Japanese, Chinese, or Korean). anime_details's alternative_titles section might have other titles.
Use this when you know the name of an anime but not the ID, or searching for an anime by name.
If the search returns 'invalid q', try using simpler search terms to widen the search.
'''
load_dotenv(override=True)
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
api_url = "https://api.myanimelist.net/v2/anime"
headers = {
"Authorization": f"Bearer {ACCESS_TOKEN}"
}
params = {
"q": anime_name
}
return json.dumps(requests.get(api_url, headers=headers, params=params).json())
@tool
def anime_details(id: int, fields: str) -> str:
'''
Provides details on the anime from MyAnimeList using an integer ID.
PRIMARY AUTHENTICATED USER ONLY (@me)!!!: my_list_status field, if and only if it is on the user's list, contains watching status, individual score, episodes watched, if they're rewatching, and time updated. All values required. This field will only ever get you MY details, so never ever use it to find anyone else's information.
Use search_anime to find the ID.
English titles are located in the alternative_titled field.
fields: comma separated list of fields to return, without spaces between commas.
Possible fields are: id,title,main_picture,alternative_titles,start_date,end_date,synopsis,mean,rank,popularity,num_list_users,num_scoring_users,nsfw,created_at,updated_at,media_type,status,genres,my_list_status,num_episodes,start_season,broadcast,source,average_episode_duration,rating,pictures,background,related_anime,related_manga,recommendations,studios,statistics
'''
load_dotenv(override=True)
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
api_url = f"https://api.myanimelist.net/v2/anime/{id}"
headers = {
"Authorization": f"Bearer {ACCESS_TOKEN}"
}
params = {
"fields": fields
}
return json.dumps(requests.get(api_url, headers=headers, params=params).json())
@tool
def ranked_anime(limit: int, offset: int, field: str) -> str:
'''
Searches anime by ranking.
limit: Number of results to return. Make this as small as possible to get the necessary information.
offset: Number to offset search by.
field: The ranking type of anime to list
All possible ranking types are: all, airing, upcoming, tv, ova, movie, special, bypopularity, favorite
Example: limit=1 offset=4 field=all will get the 5th top anime series.
'''
load_dotenv(override=True)
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
api_url = f"https://api.myanimelist.net/v2/anime/ranking"
headers = {
"Authorization": f"Bearer {ACCESS_TOKEN}"
}
params = {
"ranking_type": field,
"limit": limit,
"offset": offset
}
return json.dumps(requests.get(api_url, headers=headers, params=params).json())
@tool
def seasonal_anime(year: int, season: str, sort: str, limit: int, offset: int) -> str:
'''
Gets seasonal anime from MyAnimelist.
year: example: 2025
season: winter, spring, summer, or fall
sort: anime_score or anime_num_list_users
limit: number of anime to return. Keep as low as possible.
offset: number away from the top. 0 will be the top rated or top users.
'''
load_dotenv(override=True)
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
api_url = f"https://api.myanimelist.net/v2/anime/season/{year}/{season}"
headers = {
"Authorization": f"Bearer {ACCESS_TOKEN}"
}
params = {
"ranking_type": sort,
"limit": limit,
"offset": offset
}
return json.dumps(requests.get(api_url, headers=headers, params=params).json())
@tool
def get_user_anime_list(user: str, status: str | None, sort: str, limit: int, offset: int) -> str:
'''
Gets a user's anime list from MyAnimelist, which includes information about what the user has seen. Does not include scores, but can be sorted by score. The top result by score should be considered the favorite. No need to verify scores. Do not use to look for individual entries. Values should be given separated by a |.
user: Use @me for the main user's list
status: None for all, or watching, completed, on_hold, dropped, plan_to_watch
sort: list_score (descending), list_updated_at (descending), anime_title (ascending), anime_start_date (descending)
limit: Number of results to return. Keep this as low as possible.
offset: number away from the top. 0 will be the top of the list.
'''
load_dotenv(override=True)
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
api_url = f"https://api.myanimelist.net/v2/users/{user}/animelist"
headers = {
"Authorization": f"Bearer {ACCESS_TOKEN}"
}
params = {
"status": status,
"sort": sort,
"limit": limit,
"offset": offset
}
return json.dumps(requests.get(api_url, headers=headers, params=params).json())
@tool
def update_anime_list(id: int, status: str, score: int, is_rewatching: str, num_watched_episodes: int, num_times_rewatched: int) -> str:
'''
Updates a user's anime list from MyAnimelist. Make sure the fields not asked to be updated remain the same. Current status can be found using the anime_details tool.
status: watching, completed, on_hold, dropped, plan_to_watch
score: 0-10
is_rewatching: true or false. lowercase.
'''
load_dotenv(override=True)
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
api_url = f"https://api.myanimelist.net/v2/anime/{id}/my_list_status"
headers = {
"Authorization": f"Bearer {ACCESS_TOKEN}"
}
params = {
"status": status,
"score": score,
"is_rewatching": is_rewatching,
"num_watched_episodes": num_watched_episodes,
"num_times_rewatched": num_times_rewatched
}
return json.dumps(requests.put(api_url, headers=headers, data=params).json())
@tool
def delete_anime_from_list(id: int) -> str:
'''
Deletes an entry from the user's anime list. The only parameter is the anime id. The response will either be 200 or 404 indicating whether or not the item was on the list before deletion. 404 means it was never on the user's list.
'''
load_dotenv(override=True)
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
api_url = f"https://api.myanimelist.net/v2/anime/{id}/my_list_status"
headers = {
"Authorization": f"Bearer {ACCESS_TOKEN}"
}
params = {
"anime_id": id
}
return json.dumps(requests.delete(api_url, headers=headers, data=params).json())
@tool
def user_details(fields):
'''
Returns information about the user, as well as statistics such as counts of certain lists. The id should always be @me. It is not possible to get this information about other users.
fields should be a comma separated list with no spaces. Valid fields are: id, name, picture, gender, birthday, location, joined_at, anime_statistics, time_zone, is_supporter
'''
load_dotenv(override=True)
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
api_url = f"https://api.myanimelist.net/v2/users/@me"
headers = {
"Authorization": f"Bearer {ACCESS_TOKEN}"
}
params = {
"fields": fields
}
return json.dumps(requests.get(api_url, headers=headers, params=params).json())
@tool
def search_manga(manga_name):
'''
Takes a string and searches MyAnimeList for the manga.
The result will be a JSON table of titles and IDs.
All titles will be in the original language (Japanese, Chinese, or Korean). manga_details's alternative_titles section might have other titles.
Use this when you know the name of a manga but not the ID, or searching for a manga by name.
If the search returns 'invalid q', try using simpler search terms to widen the search.
'''
load_dotenv(override=True)
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
api_url = "https://api.myanimelist.net/v2/manga"
headers = {
"Authorization": f"Bearer {ACCESS_TOKEN}"
}
params = {
"q": manga_name
}
return json.dumps(requests.get(api_url, headers=headers, params=params).json())
@tool
def manga_details(values):
'''
Provides details on the manga from MyAnimeList using an integer ID. FOR THE AUTHENTICATED USER ONLY!!!!: my_list_status field, if and only if it is on the user's list, contains reading status, individual score, chapters read, if they're rereading, and time updated. This field will only ever get you MY details, so never ever use it to find anyone else's information.
Use search_manga to find this ID.
There should be 2 inputs separated by a |. One is the id in numerical form. This is followed by a comma separated list of fields to return, without spaces between commas.
Possible fields are: id,title,main_picture,alternative_titles,start_date,end_date,synopsis,mean,rank,popularity,num_list_users,num_scoring_users,nsfw,genres,created_at,updated_at,media_type,status,genres,my_list_status,num_chapters,authors,pictures,background,related_anime,related_manga,related_manga,recommendations,serialization
'''
load_dotenv(override=True)
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
id, fields = values.split('|')
api_url = f"https://api.myanimelist.net/v2/manga/{id}"
headers = {
"Authorization": f"Bearer {ACCESS_TOKEN}"
}
params = {
"fields": fields
}
return json.dumps(requests.get(api_url, headers=headers, params=params).json())
@tool
def ranked_manga(values):
'''
Searches manga by ranking. There should be 3 inputs separated by a |.
Number of results to return. Make this as small as possible to get the necessary information.
Number to offset search by.
One of the following fields:
all, manga, novels, oneshots, doujin, manhwa, manhua, bypopularity, favorite
Example: 1|4|all will get the 5th top manga.
'''
load_dotenv(override=True)
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
limit, offset, field = values.split('|')
api_url = f"https://api.myanimelist.net/v2/manga/ranking"
headers = {
"Authorization": f"Bearer {ACCESS_TOKEN}"
}
params = {
"ranking_type": field,
"limit": limit,
"offset": offset
}
return json.dumps(requests.get(api_url, headers=headers, params=params).json())
@tool
def get_user_manga_list(values):
'''
Gets a user's manga list from MyAnimelist, which includes information about what the user has read. Does not include scores, but can be sorted by score. The top result by score should be considered the favorite. You do not need to verify. Do not use to look for individual entries. Values should be given separated by a |. All values required. IT IS ABSOLUTELY IMPOSSIBLE TO FIND THE SCORES OF SPECIFIC USERS BY USERNAME!! NEVER UNDER ANY CIRCUMSTANCES SHOULD YOU TRY AND FIND THEM.
Username: Use @me for the main user's list
Status: all, reading, completed, on_hold, dropped, plan_to_read
Sort: list_score (descending), list_updated_at (descending), manga_title (ascending), manga_start_date (descending)
Limit: Number of results to return. Keep this as low as possible.
Offset: integer representing the number away from the top. 0 will be the top of the list.
'''
load_dotenv(override=True)
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
user, status, sort, limit, offset = values.split("|")
if status == "all":
status = None
api_url = f"https://api.myanimelist.net/v2/users/{user}/mangalist"
headers = {
"Authorization": f"Bearer {ACCESS_TOKEN}"
}
params = {
"status": status,
"sort": sort,
"limit": limit,
"offset": offset
}
return json.dumps(requests.get(api_url, headers=headers, params=params).json())
@tool
def update_manga_list(values):
'''
Updates a user's manga list from MyAnimelist. Make sure the fields not asked to be updated remain the same. Current status can be found using the manga_details tool. Values should be given separated by a |. All values required.
manga_id
Status: reading, completed, on_hold, dropped, plan_to_read
is_rereading: True, False
score: integer 0-10
num_volumes_read: integer number of volumes completed.
num_chapters_read: integer number of chapters read.
num_times_reread: integer number of times the entry has been reread
'''
load_dotenv(override=True)
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
id, status, is_rereading, score, num_volumes_read, num_chapters_read, num_times_reread = values.split("|")
api_url = f"https://api.myanimelist.net/v2/manga/{id}/my_list_status"
headers = {
"Authorization": f"Bearer {ACCESS_TOKEN}"
}
params = {
"status": status,
"score": score,
"is_rereading": is_rereading,
"num_volumes_read": num_volumes_read,
"num_chapters_read": num_chapters_read,
"num_times_reread": num_times_reread
}
return json.dumps(requests.put(api_url, headers=headers, data=params).json())
@tool
def delete_manga_from_list(id):
'''
Deletes an entry from the user's manga list. The only parameter is the manga id. The response will either be 200 or 404 indicating whether or not the item was on the list before deletion. 404 means it was never on the user's list.
'''
load_dotenv(override=True)
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
api_url = f"https://api.myanimelist.net/v2/manga/{id}/my_list_status"
headers = {
"Authorization": f"Bearer {ACCESS_TOKEN}"
}
params = {
"manga_id": id
}
return json.dumps(requests.delete(api_url, headers=headers, data=params).json())
@tool
def get_forum_boards(values):
'''
Gets the available forum boards and subboards from MyAnimeList. Action Input should be None.
'''
load_dotenv(override=True)
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
api_url = f"https://api.myanimelist.net/v2/forum/boards"
values = None
headers = {
"Authorization": f"Bearer {ACCESS_TOKEN}"
}
return json.dumps(requests.get(api_url, headers=headers).json())
@tool
def get_forum_topics(values):
'''
Gets the topics within a forum board and/or subboard. All values are required and should be separated by a |.
board_id: Optional, recommended. acquired from get_forum_boards. None if none.
subboard_id: Optional, recommended if available. None if none.
query: Optional, recommended search query. None if none.
'''
load_dotenv(override=True)
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
api_url = f"https://api.myanimelist.net/v2/forum/topics"
board_id, subboard_id, q = values.split('|')
if board_id == "None":
board_id = None
if subboard_id == "None":
subboard_id = None
if q == "None":
q = None
headers = {
"Authorization": f"Bearer {ACCESS_TOKEN}"
}
params = {
"board_id": board_id,
"subboard_id": subboard_id,
"q": q,
"limit": 10
}
return json.dumps(requests.get(api_url, headers=headers, params=params).json())
@tool
def read_forum_topic(id):
'''
Reads the forum topic from the given topic id, acquired from get_forum_topics.
'''
load_dotenv(override=True)
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
api_url = f"https://api.myanimelist.net/v2/forum/topic/{id}"
headers = {
"Authorization": f"Bearer {ACCESS_TOKEN}"
}
params = {
"limit": 10
}
return json.dumps(requests.get(api_url, headers=headers, params=params).json())
system_tools = [refresh_access_token, user_details]
anime_tools = [search_anime, anime_details, ranked_anime, seasonal_anime, get_user_anime_list, update_anime_list, delete_anime_from_list]