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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
|
%global _empty_manifest_terminate_build 0
Name: python-genshinstats
Version: 1.4.11.3
Release: 1
Summary: A python library that can get the stats of Genshin Impact players using Mihoyo's API.
License: MIT
URL: https://github.com/thesadru/genshinstats
Source0: https://mirrors.nju.edu.cn/pypi/web/packages/62/3e/731d6117d863f92756425083abccc455be989e46703e57a0f666ccfabcb6/genshinstats-1.4.11.3.tar.gz
BuildArch: noarch
%description
# genshinstats
[](https://pepy.tech/project/genshinstats)
[](https://pepy.tech/project/genshinstats)
[](https://pypi.org/project/genshinstats/)
[](https://github.com/thesadru/genshinstats/commits/master)
[](https://github.com/thesadru/genshinstats/graphs/code-frequency)
[](https://github.com/thesadru/genshinstats/blob/master/LICENSE)
[](https://discord.gg/sMkSKRPuCR)
Genshinstats is an unofficial wrapper for the Genshin Impact api. It supports getting user stats, wish history and automatic claiming of daily check-in rewards.
**If you want to use this library asynchronously or are simply looking for a better experience check out [`genshin.py`](https://thesadru.github.io/genshin.py/)**
## how to install
using [pip](https://pypi.org/project/genshinstats/)
```
pip install genshinstats
```
### Alternatives:
using pip from git
```
pip install git+https://github.com/thesadru/genshinstats
```
clone and install manually
```
git clone https://github.com/thesadru/genshinstats.git
cd genshinstats
python setup.py install
```
# how to use
You simply need to import the module and use the `set_cookie` function to login.
Since all mihoyo's apis are private there's no kind of api token or authentication header, instead you are required to use your own account cookies. ([how can I get my cookies?](#how-can-I-get-my-cookies))
The best way to learn is with examples so I have provided a usage example for every function.
You may also use the [documentation](https://thesadru.github.io/pdoc/genshinstats/)
# examples
Simple examples of usage:
```py
import genshinstats as gs
gs.set_cookie(ltuid=119480035, ltoken="cnF7TiZqHAAvYqgCBoSPx5EjwezOh1ZHoqSHf7dT")
uid = 710785423
data = gs.get_user_stats(uid)
total_characters = len(data['characters'])
print('user "sadru" has a total of', total_characters, 'characters')
```
> Cookies should be your own. These are just some example cookies of an account that can be deleted at any time.
> Note that `set_cookie` and `set_cookies` are different functions! The latter should only be used when getting data for other users (for example social media bots)
```py
stats = gs.get_user_stats(uid)['stats']
for field, value in stats.items():
print(f"{field}: {value}")
# achievements: 210
# active_days: 121
# characters: 19
# ...
```
```py
characters = gs.get_characters(uid)
for char in characters:
print(f"{char['rarity']}* {char['name']:10} | lvl {char['level']:2} C{char['constellation']}")
# 5* Xiao | lvl 90 C0
# 4* Beidou | lvl 80 C1
# 4* Fischl | lvl 80 C1
# ...
```
```py
spiral_abyss = gs.get_spiral_abyss(uid, previous=True)
stats = spiral_abyss['stats']
for field, value in stats.items():
print(f"{field}: {value}")
# total_battles: 14
# total_wins: 9
# max_floor: 11-3
# total_stars: 19
```
```py
notes = gs.get_notes(uid)
print(f"Current resin: {notes['resin']}/{notes['max_resin']}")
print(f"Current realm currency: {notes['realm_currency']}/{notes['max_realm_currency']}")
print(f"Expeditions: {len(notes['expeditions'])}/{notes['max_expeditions']}")
```
It's possible to set the cookies with a header
```py
gs.set_cookie("ltoken=cnF7TiZqHAAvYqgCBoSPx5EjwezOh1ZHoqSHf7dT; ltuid=119480035")
```
Or set them automatically by getting them from a browser
```py
gs.set_cookie_auto() # search all browsers
gs.set_cookie_auto('chrome') # search specific browser
```
> requires `cookie-browser3`, can take up to 10s
## submodules
### wishes
Gets your wish history.
For this you must first open the history/details page in genshin impact,
you can find the page in the wish menu on the bottom left.
The script is then able to get your authkey by itself and fetch the data with it.
```py
for i in gs.get_wish_history():
print(f"{i['time']} - {i['name']} ({i['rarity']}* {i['type']})")
# 2021-03-22 09:50:12 - Razor (4* Character)
# 2021-03-22 09:50:12 - Harbinger of Dawn (3* Weapon)
# 2021-03-22 09:50:12 - Cool Steel (3* Weapon)
# 2021-03-22 09:50:12 - Emerald Orb (3* Weapon)
# ...
```
```py
types = gs.get_banner_types() # get all possible types
print(types)
# {100: 'Novice Wishes',
# 200: 'Permanent Wish',
# 301: 'Character Event Wish',
# 302: 'Weapon Event Wish'}
# get pulls only from a specific banner
for i in gs.get_wish_history(301):
print(f"{i['time']} - {i['name']} ({i['rarity']}* {i['type']})")
```
```py
banner_ids = gs.get_banner_ids()
for i in banner_ids:
details = gs.get_banner_details(i)
print(f"{details['banner_type_name']} - {details['banner']}")
print('5 stars:', ', '.join(i['name'] for i in details['r5_up_items']))
print('4 stars:', ', '.join(i['name'] for i in details['r4_up_items']))
print()
# Weapon Event Wish - Event Wish "Epitome Invocation"
# 5 stars: Elegy for the End, Skyward Blade
# 4 stars: The Alley Flash, Wine and Song, Favonius Greatsword, Favonius Warbow, Dragon's Bane
```
> `get_banner_ids()` gets a list of all banners whose details page has been opened in the game.
>
> Basically uses the same approach as `get_authkey`
View other's history by passing in an authkey:
```py
authkey = "t5QMiyrenV50CFbqnB4Z+aG4ltprY1JxM5YoaChr9QH0Lp6rK5855xxa1P55..."
gs.get_wish_history(size=20, authkey=authkey)
```
Or by directly setting the authkey:
```py
# directly with the token:
gs.set_authkey("D3ZYe49SUzpDgzrt/l00n2673Zg8N/Yd9OSc7NulRHhp8EhzlEnz2ISBtKBR0fZ/DGs8...")
# get from a url:
gs.set_authkey("https://webstatic-sea.mihoyo.com/ys/event/im-service/index.html?...")
# read from a custom file:
gs.set_authkey('other_output_log.txt')
```
> Since the authkey lasts only a day this is more like for exporting than for actual use.
>
> When importing from platforms like android you must use the authkey manually. ([how can I get my authkey?](#how-can-I-get-my-authkey))
### daily rewards
Automatically get daily sign in rewards for the currently logged-in user.
```py
reward = gs.claim_daily_reward()
if reward is not None:
print(f"Claimed daily reward - {reward['cnt']}x {reward['name']}")
else:
print("Could not claim daily reward")
```
You can also get a list of all rewards you have claimed so far
```py
for i in gs.get_claimed_rewards():
print(i['cnt'], i['name'])
# 20 Primogem
# 5000 Mora
# 3 Fine Enhancement Ore
# 3 Adventurer's Experience
# 8000 Mora
```
### transaction logs
Logs for artifact, weapon, resin, genesis crystol and primogem "transactions".
You may view a history of everything you have gained in the last 3 months however you may not get the exact amount of any of these so it's generally meant for statistics of gain/loss.
> These functions require the same authkey as wish history.
All of these functions work the same:
```
get_primogem_log
get_resin_log
get_crystal_log
get_artifact_log
get_weapon_log
```
```py
for i in gs.get_primogem_log(size=40):
print(f"{i['time']} - {i['reason']}: {i['amount']} primogems")
# 2021-08-14 19:43:12 - Achievement reward: 5 primogems
# 2021-08-13 18:32:58 - Daily Commission reward: 20 primogems
# 2021-08-13 18:22:00 - Daily Commission reward: 10 primogems
# 2021-08-13 18:19:05 - Daily Commission reward: 10 primogems
# 2021-08-13 17:48:09 - Shop purchase: -1600 primogems
```
```py
total = 0
for i in gs.get_primogem_log():
total += i['amount']
print(f"Since {i['time']} you have gained {total} primogems ", end='\r')
# Since 2021-01-02 20:35:16 you have gained 5197 primogems
```
Since you the api itself doesn't provide the current amount of resin genshinstats provides a way to calculate it yourself.
First it requires a reference to how much primogems you had at a specific time and then it calculates how much you should have currently.
```py
from datetime import datetime
# calculating the current amount of resin based on the fact you had 60 resin on the September 28th 2021 12:00 UTC
print(gs.current_resin(datetime(2021, 9, 28, 12, 00), 60))
```
> Since mihoyo can take up to an hour to update their public database of logs this will only work as long as you haven't used any resin in the last hour
> If you do not know how much resin you had at any point you can very roughly approximate it with `gs.approximate_current_resin()`
### hoyolab
Miscalenious stuff for mihoyo's hoyolab. Has searching, auto check-in and code redemption.
```py
# search all users and get their nickname and uid
for user in gs.search('sadru'):
print(f"{user['nickname']} ({user['uid']}) - \"{user['introduce']}\"")
# check in to hoyolab
gs.hoyolab_check_in()
# get a record card; has user nickname and game uid
card = gs.get_record_card(8366222)
print(f"{card['nickname']} ({card['game_role_id']}) - AR {card['level']}")
# get an in-game uid from a hoyolab uid directly
uid = 8366222
# if it's an actual hoyolab uid
if not gs.is_game_uid(uid):
uid = gs.get_uid_from_hoyolab_uid(uid)
```
You can also redeem gift codes mihoyo gives out during events such as livestreams
```py
gs.redeem_code('GENSHINGIFT')
```
> `redeem_code()` requires a special form of authentication: an `account_id` and `cookie_token` cookies.
> You can get these by grabbing cookies from [the official genshin site](https://genshin.mihoyo.com/en/gift) instead of hoyolabs.
### caching
Caching is currently not native to genshinstats however there's a builtin way to install a cache into every function.
This will cache everything install a cache into every* function in genshinstats.
```py
cache = {}
gs.install_cache(cache)
```
The same cache reference is used accross all functions allowing you to see the entire cache and possibly even clear it.
```py
cache = {}
gs.install_cache(cache)
gs.get_characters(710785423)
print(cache.keys())
# dict_keys([('get_user_stats', 710785423), ('get_characters', 710785423, None, 'en-us')])
```
You're highly encouraged to use preexisting cache objects from libraries such as `cachetools` to allow for more functionality
```py
from cachetools import Cache
cache = Cache(100) # only store maximum of 100 objects in the cache
gs.install_cache(cache)
```
However the majority of these approaches have a fatal flaw: if they are not periodically cleared then old data might get stuck in them. It's therefore recommended to keep a ttl cache or automatically clear the cache yourself.
```py
from cachetools import TTLCache
cache = TTLCache(1024, 3600) # max 1024 objects with max livespan of 1 hour
gs.install_cache(cache)
```
> \*Not every function *can* be cached, some are dependent on cookies and some do not cleanly integrate with preexisting caches.
> The `install_cache` function requires a `MutableMapping[Tuple[Any, ...], Any]` and only uses `__geitem__`, `__setitem__` and `__contains__`. You may and are encouraged to create your own cache objects.
> In case you're considering storing your data in json files or similar it's encouraged to hash your keys before storing them as tuples as keys are generally not supported in other formats.
## change language
Some api endpoints support changing languages, you can see them listed here:
```py
get_characters
get_banner_types
get_wish_history
get_gacha_items
get_banner_details
claim_daily_reward
```
You can get a all language codes and their names with `get_langs()`
```py
{'de-de': 'Deutsch',
'en-us': 'English',
'es-es': 'Español',
'fr-fr': 'Français',
'id-id': 'Indonesia',
'ja-jp': '日本語',
'ko-kr': '한국어',
'pt-pt': 'Português',
'ru-ru': 'Pусский',
'th-th': 'ภาษาไทย',
'vi-vn': 'Tiếng Việt',
'zh-cn': '简体中文',
'zh-tw': '繁體中文'}
```
Any of these codes can then be passed as the `lang` parameter
```py
characters = gs.get_characters(710785423, lang='zh-cn')
print(characters)
# {'name': '莫娜',
# 'rarity': 5,
# 'element': 'Hydro',
# ...
# 'weapon': {'name': '万国诸海图谱',
# 'rarity': 4,
# 'type': '法器',
# 'description': '详尽记载了大陆周边海流气候的海图,是从异国经由商路流落到璃月的奇异典籍。',
# ...},
# ...
```
## using genshinstats asynchronously (for example with a discord bot)
You have probably noticed that while you're fetching data with genshinstats or any other sync library for that matter that other async functions never run.
To solve this issue you must turn the synchronous function into an asynchronous one.
To use any function asynchronously you can use the `asyncio.to_thread(func, *args, **kwargs)` function.
If you're using python 3.8 or less you can use `loop.run_in_executor(None, func, *args)`. Check out the [`asyncio`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_in_executor) docs for more info.
```py
import asyncio
import genshinstats as gs
gs.set_cookie_auto()
async def main():
characters = await asyncio.to_thread(gs.get_characters, 710785423)
print(characters)
asyncio.run(main())
```
# faq
## How can I get my cookies?
1. go to [hoyolab.com](https://www.hoyolab.com/genshin/)
2. login to your account
3. press `F12` to open inspect mode (aka Developer Tools)
4. go to `Application`, `Cookies`, `https://www.hoyolab.com`.
5. copy `ltuid` and `ltoken`
6. use `set_cookie(ltuid=..., ltoken=...)` in your code
> It is possible that ltuid or ltoken are for some reason not avalible in your cookies (blame it on mihoyo).
> In this case there are probably the old `account_id` and `cookie_token` cookies, so use those with `set_cookie(account_id=..., cookie_token=...)`.
>
> If not even those are avalible go to https://account.mihoyo.com/#/login and use the `login_ticket` cookie in `https://webapi-os.account.mihoyo.com/Api/cookie_accountinfo_by_loginticket?login_ticket=<...>`
### automatic alternative
You can call `get_browser_cookies` to get a dictionary of cookies that are needed for authentication.
```py
import genshinstats as gs
cookies = gs.get_browser_cookies()
print(cookies)
# {'ltuid': '93827185', 'ltoken': 'aH0cEGX458eJjGoC2z0iiDHL7UGMz09ad0a9udwh'}
```
You can then use these cookies in your actual code or save them as enviroment variables
```py
gs.set_cookie(ltuid=93827185, ltoken='aH0cEGX458eJjGoC2z0iiDHL7UGMz09ad0a9udwh')
```
You can also just set the cookies using `set_cookie_auto` which calls `get_browser_cookies` every time you run the script
```py
gs.set_cookie_auto()
```
### setting multiple cookies at once
Mihoyo allows users to get data for only up to 30 other users per day, to circumvent this limitation you can set multiple cookies at once with `set_cookies()`
```py
gs.set_cookies({'ltuid': 1, 'ltoken': 'token...'}, {'ltuid': 2, 'ltoken': 'other token...'})
```
> Creating alt accounts by hand is a lengthy and painful process so you can use one of the countless automated account creators like [genshin account creator](https://github.com/thesadru/genshin-account-creator)
## How can I get my authkey?
To get your authkey manually from other platforms you can use any of these approaches:
- PC
1. Open Paimon menu [ESC]
2. Click Feedback
3. Wait for it to load and a browser page should open
4. Copy the link
- Android
1. Open Paimon menu
2. Click Feedback
3. Wait for it to load and a feedback page should open
4. Turn off your Wi-Fi and data connection
5. Press refresh on top right corner
6. The page should display an error and show you some text with black font
7. Hold the text and press select all, then copy that text (don't copy only some portion of the text)
- IOS
1. Open Paimon menu
2. Click Feedback
3. Wait for it to load and a feedback page should open
4. Press In-game issue
5. Press Co-Op Mode
6. There is a link on the bottom of the reply; press that
7. A browser should open up
8. Copy the link
- PS
1. Open Genshin Impact on your PlayStation
2. Open the event mail that contains the QR Code
3. Scan the QR Code with your phone
4. Copy the link
> You can only use this if you have an in-game mail with QR Code to open the web event
> this is largerly copied from [paimon.moe](https://paimon.moe/wish)
## Why do I keep getting `DataNotPublic` errors even though I'm trying to view my own account stats and didn't set anything to private?
The `DataNotPublic` is raised when a user has not made their data public, because the account visibility is set to private by default.
To solve this error You must go to [hoyolab.com](https://www.hoyolab.com/genshin/accountCenter/gameRecord) and make your account public by clicking [the toogle next to "public"](https://cdn.discordapp.com/attachments/529573765743509504/817509874417008759/make_account_public.png).
## How do the cookie and authkey work?
Every endpoint in mihoyo's api requires authentication, this is in the form of a cookie and an authkey.
User stats use a cookie and wish history uses an authkey.
The cookie is bound to the user and as far as I know can only be reset by changing your password, so remember to never give your cookie to anyone. For extra safety you may want to create an alt account, so your real account is never in any danger. This token will allow you to view public stats of all users and private stats of yourself.
The authkey is a temporary token to access your wish history. It's unique for every user and is reset after 24 hours. It cannot be used to view the history of anyone else. It is fine to share this key with anyone you want, the only "private" data they will have access to is the wish history.
Tip for developers: the first 682 characters (85 bytes) of the authkey are always the same for each user. You can use this to easily indentify if an authkey belongs to the same user as another authkey.
## How can I claim daily rewards for other users.
When making projects that claim daily rewards for other users you can pass in a `cookie` parameter - `claim_daily_rewards(cookie={'ltuid': ..., 'ltoken': ...})`.
This will avoid having to set global cookies so you can use it with threading.
This cookie parameter is avalible for the majority of other accounts.
## Is it possible that my account can be stolen when I login with the cookie?
I would like to be completely clear in this aspect, I do no have any way to access the cookies you use to login. If you give your cookie to someone it is indeed possible to get into your account but that doesn't yet mean they can do anything with it. The most probable thing a hacker would do is just do a password request, but since version `1.3` they will need to confirm this request with an email. That means they would need to know what your email is and have a way to get into it, which I doubt they can. Since version `1.5` there is also 2FA which will make it completely impossible to steal your account.
They can of course access your data like email, phone number and real name, however those are censored so unless they already have an idea what those could be that data is useless to them. (For example the email may be `thesadru@gmail.com` but it'll only show up as `th****ru@gmail.com`)
TL;DR unless you have also given your password away your account cannnot be stolen.
## How do I get the wish history of other players?
To get the wish history of other players you must get their authkey and pass it as a keyword into `get_wish_history`. That will make the function return their wish history instead of yours, it will also avoid the error when you try to run your project on a machine that doesn't have genshin installed.
To get the autkey you ask the player to press `ESC` while in the game and click the feedback button on the bottom left, then get them to send the url they get redirected to. You can then extract the authkey with `extract_authkey(url)` which you can then pass into the functions.
## Why doesn't `get_wish_history()` return a normal list?
When you do `print(gs.get_wish_history())` you get an output that looks something like `<generator object get_wish_history at 0x000001DA6A128580>`
This is because the wish history is split into pages which must be requested one at a time, that means trying to return all the pulls at once would take way too long. The wokaround around this is to use a "generator" - a special list that generates values on the fly.
If you absolutely need a list you can just explicitely cast the generator to a list with `list(get_wish_history())` however that might take a few seconds fetch.
## How does `set_cookie_auto()` work? Can my data be stolen with it?
`set_cookie_auto()` searches your browsers for possible cookies used to login into your genshin accounts and then uses those, so there's no need to use `set_cookies()`.
When getting said cookies, they are filtered so only ones for mihoyo are ever pulled out. They will only ever be used as authentication and will never be sent anywhere else.
## What's the ratelimit?
You may only fetch data for 30 users per day per cookie.
That means that when making projects that fetches data for other users it's recommended to use multiple cookies.
You can set a bunch of cookies at once with `set_cookies(cookie1, cookie2, ...)`.
## How can I get an in-game uid from a hoyolab uid?
`get_uid_from_hoyolab(hoyolab_uid)` can do that for you. It will return None if the user's data is private. To check whether a given uid is a game or a hoyolab one use `is_game_uid(uid)`.
## How can I get a user's username?
Getting the user's username and adventure rank is possible only with their hoyolab uid. You can get them with `get_record_card(hoyolab_uid)` along with a bunch of other data.
## How do I get one type of uid from another?
- uids of currently logged in user: `gs.get_game_accounts()`
- from hoyolab uid to game uid: `gs.get_uid_from_hoyolab(hoyolab_uid)`
- from authkey to uid: `gs.get_uid_from_authkey(authkey)`
- from uid to hoyolab uid: `currently impossible`
# project layout
```
caching.py caching utilities
daily.py automatic daily reward claiming
errors.py errors used by genshinstats
genshinstats.py user stats and characters
hoyolab.py user hoyolab community info
map.py genshin webstatic map
pretty.py formatting of api responses
transactions.py transaction logs
utils.py various utility functions
wishes.py wish history
```
# CHANGELOG
## 1.4.11.3
- Added support for realm currency counter in `get_notes`
## 1.4.11.2
- Make the record card return proper values for new accounts
## 1.4.11.1
- Fix various chinese endpoints
- Update domain to account for hoyolab server migration
## 1.4.11
- Added `get_notes`
## 1.4.10
- Added an `equipment` kwarg to `get_user_stats`
- Added support for activities
## 1.4.9.4
- Made Ei and Sara have correct names in the abyss
## 1.4.9.3
- Teapot now prettifies data properly
- Aloy no longer has 105 stars
## 1.4.9.2
- Made sure that None returns do not get cached
## 1.4.9.1
- Minor mypy fixes
## 1.4.9
- Added support for the genshin map
- Made `daily_reward_info` return a namedtuple
## 1.4.8
- Fixed support for chinese accounts
## 1.4.7
- Added `install_cache` for installing a cache into the entire library
## 1.4.6.1
- Added an error for when you don't have a hoyolab account created
## 1.4.6
- Added several new log related endpoints
- get_primogem_log, get_resin_log, get_crystal_log
- get_artifact_log, get_weapon_log
- Made tests cleaner (now requires pytest)
- Added an explanation how to get your authkey on other platforms
## 1.4.5.1
- Made yanfei have the correct name in spiral abyss
## 1.4.5
- Added support for the serenita teapot
- This is not yet an official endpoint, therefore there's a large number of bugs. For example the comfort level is shared across all styles.
- Made `get_game_accounts` be prettified
- This will most likely break a lot of scripts, I'm sorry in advance.
- Added a `retry` decorator
## 1.4.4.4
- Added support for electroculi and outfits
- Annotated all unsubscripted lists in the library as `List[Dict[str, Any]]`
## 1.4.4.3
- Added electro traveler's element to the character prettifier
- Annotated all unsubscripted dicts in the library as `Dict[str, Any]`
- Fixed bug where getting banner types with different authkeys would not get the cached result
## 1.4.4.2
- Added a custom error message for set_cookie_auto
## 1.4.4.1
- Added `validate_authkey`
- Made `claim_daily_reward` no longer require a uid.
- Renamed `GachaLogException` to `AuthkeyError`
- Removed `genshinstats.asyncify()` in favor of `asyncio.to_thread()`
## 1.4.4
- Added a cookie parameter to all functions that use cookies
- Added `set_visibility`
- Made `claim_daily_reward` send an email in the correct language
- Improved `setup.py`
- Updated to the new wish history domain
## 1.4.3
- Added a cookie parameter to `claim_daily_reward`
## 1.4.2
- Made several improvements to the claiming of daily rewards
## 1.4.1
- Added `get_recommended_users`
- Added `get_hot_posts`
## 1.4
- Renamed majority of functions
- `get_user_data` -> `get_user_stats`
- `get_gacha_history` -> `get_wish_history`
- the before ambigious `gacha` was renamed to `wish` or `bannner`
- `sign_in` -> `claim_daily_reward`
- ...
- Removed `get_all_*` style functions - functions are overloaded to get all by default
- Made it possible to use multiple cookies to overcome ratelimits
- `set_cookie` keeps its behaviour but is now overloaded to work with headers
- `set_cookies` sets multiple cookies which will be silently rotated as needed
- Removed the need for short lang codes, they are now parsed internally
- `get_langs` and `get_banner_types` now return a dict instead of a list of dicts
- Gift codes can now be redeemed for all game accounts instead of just a single one.
- Added `__all__` to not spam the namespace with unexpected variables
- Reduced the amount of errors
%package -n python3-genshinstats
Summary: A python library that can get the stats of Genshin Impact players using Mihoyo's API.
Provides: python-genshinstats
BuildRequires: python3-devel
BuildRequires: python3-setuptools
BuildRequires: python3-pip
%description -n python3-genshinstats
# genshinstats
[](https://pepy.tech/project/genshinstats)
[](https://pepy.tech/project/genshinstats)
[](https://pypi.org/project/genshinstats/)
[](https://github.com/thesadru/genshinstats/commits/master)
[](https://github.com/thesadru/genshinstats/graphs/code-frequency)
[](https://github.com/thesadru/genshinstats/blob/master/LICENSE)
[](https://discord.gg/sMkSKRPuCR)
Genshinstats is an unofficial wrapper for the Genshin Impact api. It supports getting user stats, wish history and automatic claiming of daily check-in rewards.
**If you want to use this library asynchronously or are simply looking for a better experience check out [`genshin.py`](https://thesadru.github.io/genshin.py/)**
## how to install
using [pip](https://pypi.org/project/genshinstats/)
```
pip install genshinstats
```
### Alternatives:
using pip from git
```
pip install git+https://github.com/thesadru/genshinstats
```
clone and install manually
```
git clone https://github.com/thesadru/genshinstats.git
cd genshinstats
python setup.py install
```
# how to use
You simply need to import the module and use the `set_cookie` function to login.
Since all mihoyo's apis are private there's no kind of api token or authentication header, instead you are required to use your own account cookies. ([how can I get my cookies?](#how-can-I-get-my-cookies))
The best way to learn is with examples so I have provided a usage example for every function.
You may also use the [documentation](https://thesadru.github.io/pdoc/genshinstats/)
# examples
Simple examples of usage:
```py
import genshinstats as gs
gs.set_cookie(ltuid=119480035, ltoken="cnF7TiZqHAAvYqgCBoSPx5EjwezOh1ZHoqSHf7dT")
uid = 710785423
data = gs.get_user_stats(uid)
total_characters = len(data['characters'])
print('user "sadru" has a total of', total_characters, 'characters')
```
> Cookies should be your own. These are just some example cookies of an account that can be deleted at any time.
> Note that `set_cookie` and `set_cookies` are different functions! The latter should only be used when getting data for other users (for example social media bots)
```py
stats = gs.get_user_stats(uid)['stats']
for field, value in stats.items():
print(f"{field}: {value}")
# achievements: 210
# active_days: 121
# characters: 19
# ...
```
```py
characters = gs.get_characters(uid)
for char in characters:
print(f"{char['rarity']}* {char['name']:10} | lvl {char['level']:2} C{char['constellation']}")
# 5* Xiao | lvl 90 C0
# 4* Beidou | lvl 80 C1
# 4* Fischl | lvl 80 C1
# ...
```
```py
spiral_abyss = gs.get_spiral_abyss(uid, previous=True)
stats = spiral_abyss['stats']
for field, value in stats.items():
print(f"{field}: {value}")
# total_battles: 14
# total_wins: 9
# max_floor: 11-3
# total_stars: 19
```
```py
notes = gs.get_notes(uid)
print(f"Current resin: {notes['resin']}/{notes['max_resin']}")
print(f"Current realm currency: {notes['realm_currency']}/{notes['max_realm_currency']}")
print(f"Expeditions: {len(notes['expeditions'])}/{notes['max_expeditions']}")
```
It's possible to set the cookies with a header
```py
gs.set_cookie("ltoken=cnF7TiZqHAAvYqgCBoSPx5EjwezOh1ZHoqSHf7dT; ltuid=119480035")
```
Or set them automatically by getting them from a browser
```py
gs.set_cookie_auto() # search all browsers
gs.set_cookie_auto('chrome') # search specific browser
```
> requires `cookie-browser3`, can take up to 10s
## submodules
### wishes
Gets your wish history.
For this you must first open the history/details page in genshin impact,
you can find the page in the wish menu on the bottom left.
The script is then able to get your authkey by itself and fetch the data with it.
```py
for i in gs.get_wish_history():
print(f"{i['time']} - {i['name']} ({i['rarity']}* {i['type']})")
# 2021-03-22 09:50:12 - Razor (4* Character)
# 2021-03-22 09:50:12 - Harbinger of Dawn (3* Weapon)
# 2021-03-22 09:50:12 - Cool Steel (3* Weapon)
# 2021-03-22 09:50:12 - Emerald Orb (3* Weapon)
# ...
```
```py
types = gs.get_banner_types() # get all possible types
print(types)
# {100: 'Novice Wishes',
# 200: 'Permanent Wish',
# 301: 'Character Event Wish',
# 302: 'Weapon Event Wish'}
# get pulls only from a specific banner
for i in gs.get_wish_history(301):
print(f"{i['time']} - {i['name']} ({i['rarity']}* {i['type']})")
```
```py
banner_ids = gs.get_banner_ids()
for i in banner_ids:
details = gs.get_banner_details(i)
print(f"{details['banner_type_name']} - {details['banner']}")
print('5 stars:', ', '.join(i['name'] for i in details['r5_up_items']))
print('4 stars:', ', '.join(i['name'] for i in details['r4_up_items']))
print()
# Weapon Event Wish - Event Wish "Epitome Invocation"
# 5 stars: Elegy for the End, Skyward Blade
# 4 stars: The Alley Flash, Wine and Song, Favonius Greatsword, Favonius Warbow, Dragon's Bane
```
> `get_banner_ids()` gets a list of all banners whose details page has been opened in the game.
>
> Basically uses the same approach as `get_authkey`
View other's history by passing in an authkey:
```py
authkey = "t5QMiyrenV50CFbqnB4Z+aG4ltprY1JxM5YoaChr9QH0Lp6rK5855xxa1P55..."
gs.get_wish_history(size=20, authkey=authkey)
```
Or by directly setting the authkey:
```py
# directly with the token:
gs.set_authkey("D3ZYe49SUzpDgzrt/l00n2673Zg8N/Yd9OSc7NulRHhp8EhzlEnz2ISBtKBR0fZ/DGs8...")
# get from a url:
gs.set_authkey("https://webstatic-sea.mihoyo.com/ys/event/im-service/index.html?...")
# read from a custom file:
gs.set_authkey('other_output_log.txt')
```
> Since the authkey lasts only a day this is more like for exporting than for actual use.
>
> When importing from platforms like android you must use the authkey manually. ([how can I get my authkey?](#how-can-I-get-my-authkey))
### daily rewards
Automatically get daily sign in rewards for the currently logged-in user.
```py
reward = gs.claim_daily_reward()
if reward is not None:
print(f"Claimed daily reward - {reward['cnt']}x {reward['name']}")
else:
print("Could not claim daily reward")
```
You can also get a list of all rewards you have claimed so far
```py
for i in gs.get_claimed_rewards():
print(i['cnt'], i['name'])
# 20 Primogem
# 5000 Mora
# 3 Fine Enhancement Ore
# 3 Adventurer's Experience
# 8000 Mora
```
### transaction logs
Logs for artifact, weapon, resin, genesis crystol and primogem "transactions".
You may view a history of everything you have gained in the last 3 months however you may not get the exact amount of any of these so it's generally meant for statistics of gain/loss.
> These functions require the same authkey as wish history.
All of these functions work the same:
```
get_primogem_log
get_resin_log
get_crystal_log
get_artifact_log
get_weapon_log
```
```py
for i in gs.get_primogem_log(size=40):
print(f"{i['time']} - {i['reason']}: {i['amount']} primogems")
# 2021-08-14 19:43:12 - Achievement reward: 5 primogems
# 2021-08-13 18:32:58 - Daily Commission reward: 20 primogems
# 2021-08-13 18:22:00 - Daily Commission reward: 10 primogems
# 2021-08-13 18:19:05 - Daily Commission reward: 10 primogems
# 2021-08-13 17:48:09 - Shop purchase: -1600 primogems
```
```py
total = 0
for i in gs.get_primogem_log():
total += i['amount']
print(f"Since {i['time']} you have gained {total} primogems ", end='\r')
# Since 2021-01-02 20:35:16 you have gained 5197 primogems
```
Since you the api itself doesn't provide the current amount of resin genshinstats provides a way to calculate it yourself.
First it requires a reference to how much primogems you had at a specific time and then it calculates how much you should have currently.
```py
from datetime import datetime
# calculating the current amount of resin based on the fact you had 60 resin on the September 28th 2021 12:00 UTC
print(gs.current_resin(datetime(2021, 9, 28, 12, 00), 60))
```
> Since mihoyo can take up to an hour to update their public database of logs this will only work as long as you haven't used any resin in the last hour
> If you do not know how much resin you had at any point you can very roughly approximate it with `gs.approximate_current_resin()`
### hoyolab
Miscalenious stuff for mihoyo's hoyolab. Has searching, auto check-in and code redemption.
```py
# search all users and get their nickname and uid
for user in gs.search('sadru'):
print(f"{user['nickname']} ({user['uid']}) - \"{user['introduce']}\"")
# check in to hoyolab
gs.hoyolab_check_in()
# get a record card; has user nickname and game uid
card = gs.get_record_card(8366222)
print(f"{card['nickname']} ({card['game_role_id']}) - AR {card['level']}")
# get an in-game uid from a hoyolab uid directly
uid = 8366222
# if it's an actual hoyolab uid
if not gs.is_game_uid(uid):
uid = gs.get_uid_from_hoyolab_uid(uid)
```
You can also redeem gift codes mihoyo gives out during events such as livestreams
```py
gs.redeem_code('GENSHINGIFT')
```
> `redeem_code()` requires a special form of authentication: an `account_id` and `cookie_token` cookies.
> You can get these by grabbing cookies from [the official genshin site](https://genshin.mihoyo.com/en/gift) instead of hoyolabs.
### caching
Caching is currently not native to genshinstats however there's a builtin way to install a cache into every function.
This will cache everything install a cache into every* function in genshinstats.
```py
cache = {}
gs.install_cache(cache)
```
The same cache reference is used accross all functions allowing you to see the entire cache and possibly even clear it.
```py
cache = {}
gs.install_cache(cache)
gs.get_characters(710785423)
print(cache.keys())
# dict_keys([('get_user_stats', 710785423), ('get_characters', 710785423, None, 'en-us')])
```
You're highly encouraged to use preexisting cache objects from libraries such as `cachetools` to allow for more functionality
```py
from cachetools import Cache
cache = Cache(100) # only store maximum of 100 objects in the cache
gs.install_cache(cache)
```
However the majority of these approaches have a fatal flaw: if they are not periodically cleared then old data might get stuck in them. It's therefore recommended to keep a ttl cache or automatically clear the cache yourself.
```py
from cachetools import TTLCache
cache = TTLCache(1024, 3600) # max 1024 objects with max livespan of 1 hour
gs.install_cache(cache)
```
> \*Not every function *can* be cached, some are dependent on cookies and some do not cleanly integrate with preexisting caches.
> The `install_cache` function requires a `MutableMapping[Tuple[Any, ...], Any]` and only uses `__geitem__`, `__setitem__` and `__contains__`. You may and are encouraged to create your own cache objects.
> In case you're considering storing your data in json files or similar it's encouraged to hash your keys before storing them as tuples as keys are generally not supported in other formats.
## change language
Some api endpoints support changing languages, you can see them listed here:
```py
get_characters
get_banner_types
get_wish_history
get_gacha_items
get_banner_details
claim_daily_reward
```
You can get a all language codes and their names with `get_langs()`
```py
{'de-de': 'Deutsch',
'en-us': 'English',
'es-es': 'Español',
'fr-fr': 'Français',
'id-id': 'Indonesia',
'ja-jp': '日本語',
'ko-kr': '한국어',
'pt-pt': 'Português',
'ru-ru': 'Pусский',
'th-th': 'ภาษาไทย',
'vi-vn': 'Tiếng Việt',
'zh-cn': '简体中文',
'zh-tw': '繁體中文'}
```
Any of these codes can then be passed as the `lang` parameter
```py
characters = gs.get_characters(710785423, lang='zh-cn')
print(characters)
# {'name': '莫娜',
# 'rarity': 5,
# 'element': 'Hydro',
# ...
# 'weapon': {'name': '万国诸海图谱',
# 'rarity': 4,
# 'type': '法器',
# 'description': '详尽记载了大陆周边海流气候的海图,是从异国经由商路流落到璃月的奇异典籍。',
# ...},
# ...
```
## using genshinstats asynchronously (for example with a discord bot)
You have probably noticed that while you're fetching data with genshinstats or any other sync library for that matter that other async functions never run.
To solve this issue you must turn the synchronous function into an asynchronous one.
To use any function asynchronously you can use the `asyncio.to_thread(func, *args, **kwargs)` function.
If you're using python 3.8 or less you can use `loop.run_in_executor(None, func, *args)`. Check out the [`asyncio`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_in_executor) docs for more info.
```py
import asyncio
import genshinstats as gs
gs.set_cookie_auto()
async def main():
characters = await asyncio.to_thread(gs.get_characters, 710785423)
print(characters)
asyncio.run(main())
```
# faq
## How can I get my cookies?
1. go to [hoyolab.com](https://www.hoyolab.com/genshin/)
2. login to your account
3. press `F12` to open inspect mode (aka Developer Tools)
4. go to `Application`, `Cookies`, `https://www.hoyolab.com`.
5. copy `ltuid` and `ltoken`
6. use `set_cookie(ltuid=..., ltoken=...)` in your code
> It is possible that ltuid or ltoken are for some reason not avalible in your cookies (blame it on mihoyo).
> In this case there are probably the old `account_id` and `cookie_token` cookies, so use those with `set_cookie(account_id=..., cookie_token=...)`.
>
> If not even those are avalible go to https://account.mihoyo.com/#/login and use the `login_ticket` cookie in `https://webapi-os.account.mihoyo.com/Api/cookie_accountinfo_by_loginticket?login_ticket=<...>`
### automatic alternative
You can call `get_browser_cookies` to get a dictionary of cookies that are needed for authentication.
```py
import genshinstats as gs
cookies = gs.get_browser_cookies()
print(cookies)
# {'ltuid': '93827185', 'ltoken': 'aH0cEGX458eJjGoC2z0iiDHL7UGMz09ad0a9udwh'}
```
You can then use these cookies in your actual code or save them as enviroment variables
```py
gs.set_cookie(ltuid=93827185, ltoken='aH0cEGX458eJjGoC2z0iiDHL7UGMz09ad0a9udwh')
```
You can also just set the cookies using `set_cookie_auto` which calls `get_browser_cookies` every time you run the script
```py
gs.set_cookie_auto()
```
### setting multiple cookies at once
Mihoyo allows users to get data for only up to 30 other users per day, to circumvent this limitation you can set multiple cookies at once with `set_cookies()`
```py
gs.set_cookies({'ltuid': 1, 'ltoken': 'token...'}, {'ltuid': 2, 'ltoken': 'other token...'})
```
> Creating alt accounts by hand is a lengthy and painful process so you can use one of the countless automated account creators like [genshin account creator](https://github.com/thesadru/genshin-account-creator)
## How can I get my authkey?
To get your authkey manually from other platforms you can use any of these approaches:
- PC
1. Open Paimon menu [ESC]
2. Click Feedback
3. Wait for it to load and a browser page should open
4. Copy the link
- Android
1. Open Paimon menu
2. Click Feedback
3. Wait for it to load and a feedback page should open
4. Turn off your Wi-Fi and data connection
5. Press refresh on top right corner
6. The page should display an error and show you some text with black font
7. Hold the text and press select all, then copy that text (don't copy only some portion of the text)
- IOS
1. Open Paimon menu
2. Click Feedback
3. Wait for it to load and a feedback page should open
4. Press In-game issue
5. Press Co-Op Mode
6. There is a link on the bottom of the reply; press that
7. A browser should open up
8. Copy the link
- PS
1. Open Genshin Impact on your PlayStation
2. Open the event mail that contains the QR Code
3. Scan the QR Code with your phone
4. Copy the link
> You can only use this if you have an in-game mail with QR Code to open the web event
> this is largerly copied from [paimon.moe](https://paimon.moe/wish)
## Why do I keep getting `DataNotPublic` errors even though I'm trying to view my own account stats and didn't set anything to private?
The `DataNotPublic` is raised when a user has not made their data public, because the account visibility is set to private by default.
To solve this error You must go to [hoyolab.com](https://www.hoyolab.com/genshin/accountCenter/gameRecord) and make your account public by clicking [the toogle next to "public"](https://cdn.discordapp.com/attachments/529573765743509504/817509874417008759/make_account_public.png).
## How do the cookie and authkey work?
Every endpoint in mihoyo's api requires authentication, this is in the form of a cookie and an authkey.
User stats use a cookie and wish history uses an authkey.
The cookie is bound to the user and as far as I know can only be reset by changing your password, so remember to never give your cookie to anyone. For extra safety you may want to create an alt account, so your real account is never in any danger. This token will allow you to view public stats of all users and private stats of yourself.
The authkey is a temporary token to access your wish history. It's unique for every user and is reset after 24 hours. It cannot be used to view the history of anyone else. It is fine to share this key with anyone you want, the only "private" data they will have access to is the wish history.
Tip for developers: the first 682 characters (85 bytes) of the authkey are always the same for each user. You can use this to easily indentify if an authkey belongs to the same user as another authkey.
## How can I claim daily rewards for other users.
When making projects that claim daily rewards for other users you can pass in a `cookie` parameter - `claim_daily_rewards(cookie={'ltuid': ..., 'ltoken': ...})`.
This will avoid having to set global cookies so you can use it with threading.
This cookie parameter is avalible for the majority of other accounts.
## Is it possible that my account can be stolen when I login with the cookie?
I would like to be completely clear in this aspect, I do no have any way to access the cookies you use to login. If you give your cookie to someone it is indeed possible to get into your account but that doesn't yet mean they can do anything with it. The most probable thing a hacker would do is just do a password request, but since version `1.3` they will need to confirm this request with an email. That means they would need to know what your email is and have a way to get into it, which I doubt they can. Since version `1.5` there is also 2FA which will make it completely impossible to steal your account.
They can of course access your data like email, phone number and real name, however those are censored so unless they already have an idea what those could be that data is useless to them. (For example the email may be `thesadru@gmail.com` but it'll only show up as `th****ru@gmail.com`)
TL;DR unless you have also given your password away your account cannnot be stolen.
## How do I get the wish history of other players?
To get the wish history of other players you must get their authkey and pass it as a keyword into `get_wish_history`. That will make the function return their wish history instead of yours, it will also avoid the error when you try to run your project on a machine that doesn't have genshin installed.
To get the autkey you ask the player to press `ESC` while in the game and click the feedback button on the bottom left, then get them to send the url they get redirected to. You can then extract the authkey with `extract_authkey(url)` which you can then pass into the functions.
## Why doesn't `get_wish_history()` return a normal list?
When you do `print(gs.get_wish_history())` you get an output that looks something like `<generator object get_wish_history at 0x000001DA6A128580>`
This is because the wish history is split into pages which must be requested one at a time, that means trying to return all the pulls at once would take way too long. The wokaround around this is to use a "generator" - a special list that generates values on the fly.
If you absolutely need a list you can just explicitely cast the generator to a list with `list(get_wish_history())` however that might take a few seconds fetch.
## How does `set_cookie_auto()` work? Can my data be stolen with it?
`set_cookie_auto()` searches your browsers for possible cookies used to login into your genshin accounts and then uses those, so there's no need to use `set_cookies()`.
When getting said cookies, they are filtered so only ones for mihoyo are ever pulled out. They will only ever be used as authentication and will never be sent anywhere else.
## What's the ratelimit?
You may only fetch data for 30 users per day per cookie.
That means that when making projects that fetches data for other users it's recommended to use multiple cookies.
You can set a bunch of cookies at once with `set_cookies(cookie1, cookie2, ...)`.
## How can I get an in-game uid from a hoyolab uid?
`get_uid_from_hoyolab(hoyolab_uid)` can do that for you. It will return None if the user's data is private. To check whether a given uid is a game or a hoyolab one use `is_game_uid(uid)`.
## How can I get a user's username?
Getting the user's username and adventure rank is possible only with their hoyolab uid. You can get them with `get_record_card(hoyolab_uid)` along with a bunch of other data.
## How do I get one type of uid from another?
- uids of currently logged in user: `gs.get_game_accounts()`
- from hoyolab uid to game uid: `gs.get_uid_from_hoyolab(hoyolab_uid)`
- from authkey to uid: `gs.get_uid_from_authkey(authkey)`
- from uid to hoyolab uid: `currently impossible`
# project layout
```
caching.py caching utilities
daily.py automatic daily reward claiming
errors.py errors used by genshinstats
genshinstats.py user stats and characters
hoyolab.py user hoyolab community info
map.py genshin webstatic map
pretty.py formatting of api responses
transactions.py transaction logs
utils.py various utility functions
wishes.py wish history
```
# CHANGELOG
## 1.4.11.3
- Added support for realm currency counter in `get_notes`
## 1.4.11.2
- Make the record card return proper values for new accounts
## 1.4.11.1
- Fix various chinese endpoints
- Update domain to account for hoyolab server migration
## 1.4.11
- Added `get_notes`
## 1.4.10
- Added an `equipment` kwarg to `get_user_stats`
- Added support for activities
## 1.4.9.4
- Made Ei and Sara have correct names in the abyss
## 1.4.9.3
- Teapot now prettifies data properly
- Aloy no longer has 105 stars
## 1.4.9.2
- Made sure that None returns do not get cached
## 1.4.9.1
- Minor mypy fixes
## 1.4.9
- Added support for the genshin map
- Made `daily_reward_info` return a namedtuple
## 1.4.8
- Fixed support for chinese accounts
## 1.4.7
- Added `install_cache` for installing a cache into the entire library
## 1.4.6.1
- Added an error for when you don't have a hoyolab account created
## 1.4.6
- Added several new log related endpoints
- get_primogem_log, get_resin_log, get_crystal_log
- get_artifact_log, get_weapon_log
- Made tests cleaner (now requires pytest)
- Added an explanation how to get your authkey on other platforms
## 1.4.5.1
- Made yanfei have the correct name in spiral abyss
## 1.4.5
- Added support for the serenita teapot
- This is not yet an official endpoint, therefore there's a large number of bugs. For example the comfort level is shared across all styles.
- Made `get_game_accounts` be prettified
- This will most likely break a lot of scripts, I'm sorry in advance.
- Added a `retry` decorator
## 1.4.4.4
- Added support for electroculi and outfits
- Annotated all unsubscripted lists in the library as `List[Dict[str, Any]]`
## 1.4.4.3
- Added electro traveler's element to the character prettifier
- Annotated all unsubscripted dicts in the library as `Dict[str, Any]`
- Fixed bug where getting banner types with different authkeys would not get the cached result
## 1.4.4.2
- Added a custom error message for set_cookie_auto
## 1.4.4.1
- Added `validate_authkey`
- Made `claim_daily_reward` no longer require a uid.
- Renamed `GachaLogException` to `AuthkeyError`
- Removed `genshinstats.asyncify()` in favor of `asyncio.to_thread()`
## 1.4.4
- Added a cookie parameter to all functions that use cookies
- Added `set_visibility`
- Made `claim_daily_reward` send an email in the correct language
- Improved `setup.py`
- Updated to the new wish history domain
## 1.4.3
- Added a cookie parameter to `claim_daily_reward`
## 1.4.2
- Made several improvements to the claiming of daily rewards
## 1.4.1
- Added `get_recommended_users`
- Added `get_hot_posts`
## 1.4
- Renamed majority of functions
- `get_user_data` -> `get_user_stats`
- `get_gacha_history` -> `get_wish_history`
- the before ambigious `gacha` was renamed to `wish` or `bannner`
- `sign_in` -> `claim_daily_reward`
- ...
- Removed `get_all_*` style functions - functions are overloaded to get all by default
- Made it possible to use multiple cookies to overcome ratelimits
- `set_cookie` keeps its behaviour but is now overloaded to work with headers
- `set_cookies` sets multiple cookies which will be silently rotated as needed
- Removed the need for short lang codes, they are now parsed internally
- `get_langs` and `get_banner_types` now return a dict instead of a list of dicts
- Gift codes can now be redeemed for all game accounts instead of just a single one.
- Added `__all__` to not spam the namespace with unexpected variables
- Reduced the amount of errors
%package help
Summary: Development documents and examples for genshinstats
Provides: python3-genshinstats-doc
%description help
# genshinstats
[](https://pepy.tech/project/genshinstats)
[](https://pepy.tech/project/genshinstats)
[](https://pypi.org/project/genshinstats/)
[](https://github.com/thesadru/genshinstats/commits/master)
[](https://github.com/thesadru/genshinstats/graphs/code-frequency)
[](https://github.com/thesadru/genshinstats/blob/master/LICENSE)
[](https://discord.gg/sMkSKRPuCR)
Genshinstats is an unofficial wrapper for the Genshin Impact api. It supports getting user stats, wish history and automatic claiming of daily check-in rewards.
**If you want to use this library asynchronously or are simply looking for a better experience check out [`genshin.py`](https://thesadru.github.io/genshin.py/)**
## how to install
using [pip](https://pypi.org/project/genshinstats/)
```
pip install genshinstats
```
### Alternatives:
using pip from git
```
pip install git+https://github.com/thesadru/genshinstats
```
clone and install manually
```
git clone https://github.com/thesadru/genshinstats.git
cd genshinstats
python setup.py install
```
# how to use
You simply need to import the module and use the `set_cookie` function to login.
Since all mihoyo's apis are private there's no kind of api token or authentication header, instead you are required to use your own account cookies. ([how can I get my cookies?](#how-can-I-get-my-cookies))
The best way to learn is with examples so I have provided a usage example for every function.
You may also use the [documentation](https://thesadru.github.io/pdoc/genshinstats/)
# examples
Simple examples of usage:
```py
import genshinstats as gs
gs.set_cookie(ltuid=119480035, ltoken="cnF7TiZqHAAvYqgCBoSPx5EjwezOh1ZHoqSHf7dT")
uid = 710785423
data = gs.get_user_stats(uid)
total_characters = len(data['characters'])
print('user "sadru" has a total of', total_characters, 'characters')
```
> Cookies should be your own. These are just some example cookies of an account that can be deleted at any time.
> Note that `set_cookie` and `set_cookies` are different functions! The latter should only be used when getting data for other users (for example social media bots)
```py
stats = gs.get_user_stats(uid)['stats']
for field, value in stats.items():
print(f"{field}: {value}")
# achievements: 210
# active_days: 121
# characters: 19
# ...
```
```py
characters = gs.get_characters(uid)
for char in characters:
print(f"{char['rarity']}* {char['name']:10} | lvl {char['level']:2} C{char['constellation']}")
# 5* Xiao | lvl 90 C0
# 4* Beidou | lvl 80 C1
# 4* Fischl | lvl 80 C1
# ...
```
```py
spiral_abyss = gs.get_spiral_abyss(uid, previous=True)
stats = spiral_abyss['stats']
for field, value in stats.items():
print(f"{field}: {value}")
# total_battles: 14
# total_wins: 9
# max_floor: 11-3
# total_stars: 19
```
```py
notes = gs.get_notes(uid)
print(f"Current resin: {notes['resin']}/{notes['max_resin']}")
print(f"Current realm currency: {notes['realm_currency']}/{notes['max_realm_currency']}")
print(f"Expeditions: {len(notes['expeditions'])}/{notes['max_expeditions']}")
```
It's possible to set the cookies with a header
```py
gs.set_cookie("ltoken=cnF7TiZqHAAvYqgCBoSPx5EjwezOh1ZHoqSHf7dT; ltuid=119480035")
```
Or set them automatically by getting them from a browser
```py
gs.set_cookie_auto() # search all browsers
gs.set_cookie_auto('chrome') # search specific browser
```
> requires `cookie-browser3`, can take up to 10s
## submodules
### wishes
Gets your wish history.
For this you must first open the history/details page in genshin impact,
you can find the page in the wish menu on the bottom left.
The script is then able to get your authkey by itself and fetch the data with it.
```py
for i in gs.get_wish_history():
print(f"{i['time']} - {i['name']} ({i['rarity']}* {i['type']})")
# 2021-03-22 09:50:12 - Razor (4* Character)
# 2021-03-22 09:50:12 - Harbinger of Dawn (3* Weapon)
# 2021-03-22 09:50:12 - Cool Steel (3* Weapon)
# 2021-03-22 09:50:12 - Emerald Orb (3* Weapon)
# ...
```
```py
types = gs.get_banner_types() # get all possible types
print(types)
# {100: 'Novice Wishes',
# 200: 'Permanent Wish',
# 301: 'Character Event Wish',
# 302: 'Weapon Event Wish'}
# get pulls only from a specific banner
for i in gs.get_wish_history(301):
print(f"{i['time']} - {i['name']} ({i['rarity']}* {i['type']})")
```
```py
banner_ids = gs.get_banner_ids()
for i in banner_ids:
details = gs.get_banner_details(i)
print(f"{details['banner_type_name']} - {details['banner']}")
print('5 stars:', ', '.join(i['name'] for i in details['r5_up_items']))
print('4 stars:', ', '.join(i['name'] for i in details['r4_up_items']))
print()
# Weapon Event Wish - Event Wish "Epitome Invocation"
# 5 stars: Elegy for the End, Skyward Blade
# 4 stars: The Alley Flash, Wine and Song, Favonius Greatsword, Favonius Warbow, Dragon's Bane
```
> `get_banner_ids()` gets a list of all banners whose details page has been opened in the game.
>
> Basically uses the same approach as `get_authkey`
View other's history by passing in an authkey:
```py
authkey = "t5QMiyrenV50CFbqnB4Z+aG4ltprY1JxM5YoaChr9QH0Lp6rK5855xxa1P55..."
gs.get_wish_history(size=20, authkey=authkey)
```
Or by directly setting the authkey:
```py
# directly with the token:
gs.set_authkey("D3ZYe49SUzpDgzrt/l00n2673Zg8N/Yd9OSc7NulRHhp8EhzlEnz2ISBtKBR0fZ/DGs8...")
# get from a url:
gs.set_authkey("https://webstatic-sea.mihoyo.com/ys/event/im-service/index.html?...")
# read from a custom file:
gs.set_authkey('other_output_log.txt')
```
> Since the authkey lasts only a day this is more like for exporting than for actual use.
>
> When importing from platforms like android you must use the authkey manually. ([how can I get my authkey?](#how-can-I-get-my-authkey))
### daily rewards
Automatically get daily sign in rewards for the currently logged-in user.
```py
reward = gs.claim_daily_reward()
if reward is not None:
print(f"Claimed daily reward - {reward['cnt']}x {reward['name']}")
else:
print("Could not claim daily reward")
```
You can also get a list of all rewards you have claimed so far
```py
for i in gs.get_claimed_rewards():
print(i['cnt'], i['name'])
# 20 Primogem
# 5000 Mora
# 3 Fine Enhancement Ore
# 3 Adventurer's Experience
# 8000 Mora
```
### transaction logs
Logs for artifact, weapon, resin, genesis crystol and primogem "transactions".
You may view a history of everything you have gained in the last 3 months however you may not get the exact amount of any of these so it's generally meant for statistics of gain/loss.
> These functions require the same authkey as wish history.
All of these functions work the same:
```
get_primogem_log
get_resin_log
get_crystal_log
get_artifact_log
get_weapon_log
```
```py
for i in gs.get_primogem_log(size=40):
print(f"{i['time']} - {i['reason']}: {i['amount']} primogems")
# 2021-08-14 19:43:12 - Achievement reward: 5 primogems
# 2021-08-13 18:32:58 - Daily Commission reward: 20 primogems
# 2021-08-13 18:22:00 - Daily Commission reward: 10 primogems
# 2021-08-13 18:19:05 - Daily Commission reward: 10 primogems
# 2021-08-13 17:48:09 - Shop purchase: -1600 primogems
```
```py
total = 0
for i in gs.get_primogem_log():
total += i['amount']
print(f"Since {i['time']} you have gained {total} primogems ", end='\r')
# Since 2021-01-02 20:35:16 you have gained 5197 primogems
```
Since you the api itself doesn't provide the current amount of resin genshinstats provides a way to calculate it yourself.
First it requires a reference to how much primogems you had at a specific time and then it calculates how much you should have currently.
```py
from datetime import datetime
# calculating the current amount of resin based on the fact you had 60 resin on the September 28th 2021 12:00 UTC
print(gs.current_resin(datetime(2021, 9, 28, 12, 00), 60))
```
> Since mihoyo can take up to an hour to update their public database of logs this will only work as long as you haven't used any resin in the last hour
> If you do not know how much resin you had at any point you can very roughly approximate it with `gs.approximate_current_resin()`
### hoyolab
Miscalenious stuff for mihoyo's hoyolab. Has searching, auto check-in and code redemption.
```py
# search all users and get their nickname and uid
for user in gs.search('sadru'):
print(f"{user['nickname']} ({user['uid']}) - \"{user['introduce']}\"")
# check in to hoyolab
gs.hoyolab_check_in()
# get a record card; has user nickname and game uid
card = gs.get_record_card(8366222)
print(f"{card['nickname']} ({card['game_role_id']}) - AR {card['level']}")
# get an in-game uid from a hoyolab uid directly
uid = 8366222
# if it's an actual hoyolab uid
if not gs.is_game_uid(uid):
uid = gs.get_uid_from_hoyolab_uid(uid)
```
You can also redeem gift codes mihoyo gives out during events such as livestreams
```py
gs.redeem_code('GENSHINGIFT')
```
> `redeem_code()` requires a special form of authentication: an `account_id` and `cookie_token` cookies.
> You can get these by grabbing cookies from [the official genshin site](https://genshin.mihoyo.com/en/gift) instead of hoyolabs.
### caching
Caching is currently not native to genshinstats however there's a builtin way to install a cache into every function.
This will cache everything install a cache into every* function in genshinstats.
```py
cache = {}
gs.install_cache(cache)
```
The same cache reference is used accross all functions allowing you to see the entire cache and possibly even clear it.
```py
cache = {}
gs.install_cache(cache)
gs.get_characters(710785423)
print(cache.keys())
# dict_keys([('get_user_stats', 710785423), ('get_characters', 710785423, None, 'en-us')])
```
You're highly encouraged to use preexisting cache objects from libraries such as `cachetools` to allow for more functionality
```py
from cachetools import Cache
cache = Cache(100) # only store maximum of 100 objects in the cache
gs.install_cache(cache)
```
However the majority of these approaches have a fatal flaw: if they are not periodically cleared then old data might get stuck in them. It's therefore recommended to keep a ttl cache or automatically clear the cache yourself.
```py
from cachetools import TTLCache
cache = TTLCache(1024, 3600) # max 1024 objects with max livespan of 1 hour
gs.install_cache(cache)
```
> \*Not every function *can* be cached, some are dependent on cookies and some do not cleanly integrate with preexisting caches.
> The `install_cache` function requires a `MutableMapping[Tuple[Any, ...], Any]` and only uses `__geitem__`, `__setitem__` and `__contains__`. You may and are encouraged to create your own cache objects.
> In case you're considering storing your data in json files or similar it's encouraged to hash your keys before storing them as tuples as keys are generally not supported in other formats.
## change language
Some api endpoints support changing languages, you can see them listed here:
```py
get_characters
get_banner_types
get_wish_history
get_gacha_items
get_banner_details
claim_daily_reward
```
You can get a all language codes and their names with `get_langs()`
```py
{'de-de': 'Deutsch',
'en-us': 'English',
'es-es': 'Español',
'fr-fr': 'Français',
'id-id': 'Indonesia',
'ja-jp': '日本語',
'ko-kr': '한국어',
'pt-pt': 'Português',
'ru-ru': 'Pусский',
'th-th': 'ภาษาไทย',
'vi-vn': 'Tiếng Việt',
'zh-cn': '简体中文',
'zh-tw': '繁體中文'}
```
Any of these codes can then be passed as the `lang` parameter
```py
characters = gs.get_characters(710785423, lang='zh-cn')
print(characters)
# {'name': '莫娜',
# 'rarity': 5,
# 'element': 'Hydro',
# ...
# 'weapon': {'name': '万国诸海图谱',
# 'rarity': 4,
# 'type': '法器',
# 'description': '详尽记载了大陆周边海流气候的海图,是从异国经由商路流落到璃月的奇异典籍。',
# ...},
# ...
```
## using genshinstats asynchronously (for example with a discord bot)
You have probably noticed that while you're fetching data with genshinstats or any other sync library for that matter that other async functions never run.
To solve this issue you must turn the synchronous function into an asynchronous one.
To use any function asynchronously you can use the `asyncio.to_thread(func, *args, **kwargs)` function.
If you're using python 3.8 or less you can use `loop.run_in_executor(None, func, *args)`. Check out the [`asyncio`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_in_executor) docs for more info.
```py
import asyncio
import genshinstats as gs
gs.set_cookie_auto()
async def main():
characters = await asyncio.to_thread(gs.get_characters, 710785423)
print(characters)
asyncio.run(main())
```
# faq
## How can I get my cookies?
1. go to [hoyolab.com](https://www.hoyolab.com/genshin/)
2. login to your account
3. press `F12` to open inspect mode (aka Developer Tools)
4. go to `Application`, `Cookies`, `https://www.hoyolab.com`.
5. copy `ltuid` and `ltoken`
6. use `set_cookie(ltuid=..., ltoken=...)` in your code
> It is possible that ltuid or ltoken are for some reason not avalible in your cookies (blame it on mihoyo).
> In this case there are probably the old `account_id` and `cookie_token` cookies, so use those with `set_cookie(account_id=..., cookie_token=...)`.
>
> If not even those are avalible go to https://account.mihoyo.com/#/login and use the `login_ticket` cookie in `https://webapi-os.account.mihoyo.com/Api/cookie_accountinfo_by_loginticket?login_ticket=<...>`
### automatic alternative
You can call `get_browser_cookies` to get a dictionary of cookies that are needed for authentication.
```py
import genshinstats as gs
cookies = gs.get_browser_cookies()
print(cookies)
# {'ltuid': '93827185', 'ltoken': 'aH0cEGX458eJjGoC2z0iiDHL7UGMz09ad0a9udwh'}
```
You can then use these cookies in your actual code or save them as enviroment variables
```py
gs.set_cookie(ltuid=93827185, ltoken='aH0cEGX458eJjGoC2z0iiDHL7UGMz09ad0a9udwh')
```
You can also just set the cookies using `set_cookie_auto` which calls `get_browser_cookies` every time you run the script
```py
gs.set_cookie_auto()
```
### setting multiple cookies at once
Mihoyo allows users to get data for only up to 30 other users per day, to circumvent this limitation you can set multiple cookies at once with `set_cookies()`
```py
gs.set_cookies({'ltuid': 1, 'ltoken': 'token...'}, {'ltuid': 2, 'ltoken': 'other token...'})
```
> Creating alt accounts by hand is a lengthy and painful process so you can use one of the countless automated account creators like [genshin account creator](https://github.com/thesadru/genshin-account-creator)
## How can I get my authkey?
To get your authkey manually from other platforms you can use any of these approaches:
- PC
1. Open Paimon menu [ESC]
2. Click Feedback
3. Wait for it to load and a browser page should open
4. Copy the link
- Android
1. Open Paimon menu
2. Click Feedback
3. Wait for it to load and a feedback page should open
4. Turn off your Wi-Fi and data connection
5. Press refresh on top right corner
6. The page should display an error and show you some text with black font
7. Hold the text and press select all, then copy that text (don't copy only some portion of the text)
- IOS
1. Open Paimon menu
2. Click Feedback
3. Wait for it to load and a feedback page should open
4. Press In-game issue
5. Press Co-Op Mode
6. There is a link on the bottom of the reply; press that
7. A browser should open up
8. Copy the link
- PS
1. Open Genshin Impact on your PlayStation
2. Open the event mail that contains the QR Code
3. Scan the QR Code with your phone
4. Copy the link
> You can only use this if you have an in-game mail with QR Code to open the web event
> this is largerly copied from [paimon.moe](https://paimon.moe/wish)
## Why do I keep getting `DataNotPublic` errors even though I'm trying to view my own account stats and didn't set anything to private?
The `DataNotPublic` is raised when a user has not made their data public, because the account visibility is set to private by default.
To solve this error You must go to [hoyolab.com](https://www.hoyolab.com/genshin/accountCenter/gameRecord) and make your account public by clicking [the toogle next to "public"](https://cdn.discordapp.com/attachments/529573765743509504/817509874417008759/make_account_public.png).
## How do the cookie and authkey work?
Every endpoint in mihoyo's api requires authentication, this is in the form of a cookie and an authkey.
User stats use a cookie and wish history uses an authkey.
The cookie is bound to the user and as far as I know can only be reset by changing your password, so remember to never give your cookie to anyone. For extra safety you may want to create an alt account, so your real account is never in any danger. This token will allow you to view public stats of all users and private stats of yourself.
The authkey is a temporary token to access your wish history. It's unique for every user and is reset after 24 hours. It cannot be used to view the history of anyone else. It is fine to share this key with anyone you want, the only "private" data they will have access to is the wish history.
Tip for developers: the first 682 characters (85 bytes) of the authkey are always the same for each user. You can use this to easily indentify if an authkey belongs to the same user as another authkey.
## How can I claim daily rewards for other users.
When making projects that claim daily rewards for other users you can pass in a `cookie` parameter - `claim_daily_rewards(cookie={'ltuid': ..., 'ltoken': ...})`.
This will avoid having to set global cookies so you can use it with threading.
This cookie parameter is avalible for the majority of other accounts.
## Is it possible that my account can be stolen when I login with the cookie?
I would like to be completely clear in this aspect, I do no have any way to access the cookies you use to login. If you give your cookie to someone it is indeed possible to get into your account but that doesn't yet mean they can do anything with it. The most probable thing a hacker would do is just do a password request, but since version `1.3` they will need to confirm this request with an email. That means they would need to know what your email is and have a way to get into it, which I doubt they can. Since version `1.5` there is also 2FA which will make it completely impossible to steal your account.
They can of course access your data like email, phone number and real name, however those are censored so unless they already have an idea what those could be that data is useless to them. (For example the email may be `thesadru@gmail.com` but it'll only show up as `th****ru@gmail.com`)
TL;DR unless you have also given your password away your account cannnot be stolen.
## How do I get the wish history of other players?
To get the wish history of other players you must get their authkey and pass it as a keyword into `get_wish_history`. That will make the function return their wish history instead of yours, it will also avoid the error when you try to run your project on a machine that doesn't have genshin installed.
To get the autkey you ask the player to press `ESC` while in the game and click the feedback button on the bottom left, then get them to send the url they get redirected to. You can then extract the authkey with `extract_authkey(url)` which you can then pass into the functions.
## Why doesn't `get_wish_history()` return a normal list?
When you do `print(gs.get_wish_history())` you get an output that looks something like `<generator object get_wish_history at 0x000001DA6A128580>`
This is because the wish history is split into pages which must be requested one at a time, that means trying to return all the pulls at once would take way too long. The wokaround around this is to use a "generator" - a special list that generates values on the fly.
If you absolutely need a list you can just explicitely cast the generator to a list with `list(get_wish_history())` however that might take a few seconds fetch.
## How does `set_cookie_auto()` work? Can my data be stolen with it?
`set_cookie_auto()` searches your browsers for possible cookies used to login into your genshin accounts and then uses those, so there's no need to use `set_cookies()`.
When getting said cookies, they are filtered so only ones for mihoyo are ever pulled out. They will only ever be used as authentication and will never be sent anywhere else.
## What's the ratelimit?
You may only fetch data for 30 users per day per cookie.
That means that when making projects that fetches data for other users it's recommended to use multiple cookies.
You can set a bunch of cookies at once with `set_cookies(cookie1, cookie2, ...)`.
## How can I get an in-game uid from a hoyolab uid?
`get_uid_from_hoyolab(hoyolab_uid)` can do that for you. It will return None if the user's data is private. To check whether a given uid is a game or a hoyolab one use `is_game_uid(uid)`.
## How can I get a user's username?
Getting the user's username and adventure rank is possible only with their hoyolab uid. You can get them with `get_record_card(hoyolab_uid)` along with a bunch of other data.
## How do I get one type of uid from another?
- uids of currently logged in user: `gs.get_game_accounts()`
- from hoyolab uid to game uid: `gs.get_uid_from_hoyolab(hoyolab_uid)`
- from authkey to uid: `gs.get_uid_from_authkey(authkey)`
- from uid to hoyolab uid: `currently impossible`
# project layout
```
caching.py caching utilities
daily.py automatic daily reward claiming
errors.py errors used by genshinstats
genshinstats.py user stats and characters
hoyolab.py user hoyolab community info
map.py genshin webstatic map
pretty.py formatting of api responses
transactions.py transaction logs
utils.py various utility functions
wishes.py wish history
```
# CHANGELOG
## 1.4.11.3
- Added support for realm currency counter in `get_notes`
## 1.4.11.2
- Make the record card return proper values for new accounts
## 1.4.11.1
- Fix various chinese endpoints
- Update domain to account for hoyolab server migration
## 1.4.11
- Added `get_notes`
## 1.4.10
- Added an `equipment` kwarg to `get_user_stats`
- Added support for activities
## 1.4.9.4
- Made Ei and Sara have correct names in the abyss
## 1.4.9.3
- Teapot now prettifies data properly
- Aloy no longer has 105 stars
## 1.4.9.2
- Made sure that None returns do not get cached
## 1.4.9.1
- Minor mypy fixes
## 1.4.9
- Added support for the genshin map
- Made `daily_reward_info` return a namedtuple
## 1.4.8
- Fixed support for chinese accounts
## 1.4.7
- Added `install_cache` for installing a cache into the entire library
## 1.4.6.1
- Added an error for when you don't have a hoyolab account created
## 1.4.6
- Added several new log related endpoints
- get_primogem_log, get_resin_log, get_crystal_log
- get_artifact_log, get_weapon_log
- Made tests cleaner (now requires pytest)
- Added an explanation how to get your authkey on other platforms
## 1.4.5.1
- Made yanfei have the correct name in spiral abyss
## 1.4.5
- Added support for the serenita teapot
- This is not yet an official endpoint, therefore there's a large number of bugs. For example the comfort level is shared across all styles.
- Made `get_game_accounts` be prettified
- This will most likely break a lot of scripts, I'm sorry in advance.
- Added a `retry` decorator
## 1.4.4.4
- Added support for electroculi and outfits
- Annotated all unsubscripted lists in the library as `List[Dict[str, Any]]`
## 1.4.4.3
- Added electro traveler's element to the character prettifier
- Annotated all unsubscripted dicts in the library as `Dict[str, Any]`
- Fixed bug where getting banner types with different authkeys would not get the cached result
## 1.4.4.2
- Added a custom error message for set_cookie_auto
## 1.4.4.1
- Added `validate_authkey`
- Made `claim_daily_reward` no longer require a uid.
- Renamed `GachaLogException` to `AuthkeyError`
- Removed `genshinstats.asyncify()` in favor of `asyncio.to_thread()`
## 1.4.4
- Added a cookie parameter to all functions that use cookies
- Added `set_visibility`
- Made `claim_daily_reward` send an email in the correct language
- Improved `setup.py`
- Updated to the new wish history domain
## 1.4.3
- Added a cookie parameter to `claim_daily_reward`
## 1.4.2
- Made several improvements to the claiming of daily rewards
## 1.4.1
- Added `get_recommended_users`
- Added `get_hot_posts`
## 1.4
- Renamed majority of functions
- `get_user_data` -> `get_user_stats`
- `get_gacha_history` -> `get_wish_history`
- the before ambigious `gacha` was renamed to `wish` or `bannner`
- `sign_in` -> `claim_daily_reward`
- ...
- Removed `get_all_*` style functions - functions are overloaded to get all by default
- Made it possible to use multiple cookies to overcome ratelimits
- `set_cookie` keeps its behaviour but is now overloaded to work with headers
- `set_cookies` sets multiple cookies which will be silently rotated as needed
- Removed the need for short lang codes, they are now parsed internally
- `get_langs` and `get_banner_types` now return a dict instead of a list of dicts
- Gift codes can now be redeemed for all game accounts instead of just a single one.
- Added `__all__` to not spam the namespace with unexpected variables
- Reduced the amount of errors
%prep
%autosetup -n genshinstats-1.4.11.3
%build
%py3_build
%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
find usr/lib -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
find usr/lib64 -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
find usr/bin -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
find usr/sbin -type f -printf "/%h/%f\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
find usr/share/man -type f -printf "/%h/%f.gz\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .
%files -n python3-genshinstats -f filelist.lst
%dir %{python3_sitelib}/*
%files help -f doclist.lst
%{_docdir}/*
%changelog
* Fri May 05 2023 Python_Bot <Python_Bot@openeuler.org> - 1.4.11.3-1
- Package Spec generated
|