-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathfarmer.py
1581 lines (1438 loc) · 61.1 KB
/
farmer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
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
#!/usr/bin/python3
import random
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import WebDriverException
import tenacity
from tenacity import stop_after_attempt, wait_fixed, retry_if_exception_type, RetryCallState
import logging
import requests
from requests.exceptions import RequestException
import functools
from decimal import Decimal
from typing import List, Dict
import base64
from pprint import pprint
import logger
import utils
from utils import plat
from settings import user_param
import res
from res import Building, Resoure, Animal, Asset, Farming, Crop, NFT, Axe, Tool, Token, Chicken, FishingRod, MBS
from res import BabyCalf, Calf, FeMaleCalf, MaleCalf, Bull, DairyCow, MbsSavedClaims
from datetime import datetime, timedelta
from settings import cfg
import os
from logger import log
class FarmerException(Exception):
pass
class CookieExpireException(FarmerException):
pass
# 调用智能合约出错,此时应停止并检查日志,不宜反复重试
class TransactException(FarmerException):
# 有的智能合约错误可以重试,-1为无限重试
def __init__(self, msg, retry=True, max_retry_times: int = -1):
super().__init__(msg)
self.retry = retry
self.max_retry_times = max_retry_times
# 遇到不可恢复的错误 ,终止程序
class StopException(FarmerException):
pass
class Status:
Continue = 1
Stop = 2
class Farmer:
# wax rpc
# url_rpc = "https://api.wax.alohaeos.com/v1/chain/"
# url_rpc = "https://wax.dapplica.io/v1/chain/"
# url_table_row = url_rpc + "get_table_rows"
# 资产API
# url_assets = "https://wax.api.atomicassets.io/atomicassets/v1/assets"
# url_assets = "https://atomic.wax.eosrio.io/atomicassets/v1/assets"
waxjs: str = None
myjs: str = None
chrome_data_dir = os.path.abspath(cfg.chrome_data_dir)
def __init__(self):
self.url_rpc: str = None
self.url_table_row: str = None
self.url_assets: str = None
self.wax_account: str = None
self.login_name: str = None
self.password: str = None
self.driver: webdriver.Chrome = None
self.proxy: str = None
self.http: requests.Session = None
self.cookies: List[dict] = None
self.log: logging.LoggerAdapter = log
# 下一次可以操作东西的时间
self.next_operate_time: datetime = datetime.max
# 下一次扫描时间
self.next_scan_time: datetime = datetime.min
# 本轮扫描中暂不可操作的东西
self.not_operational: List[Farming] = []
# 智能合约连续出错次数
self.count_error_transact = 0
# 本轮扫描中作物操作成功个数
self.count_success_claim = 0
# 本轮扫描中作物操作失败个数
self.count_error_claim = 0
# 本轮开始时的资源数量
self.resoure: Resoure = None
self.token: Token = None
self.mbs_saved_claims: MbsSavedClaims = None
def close(self):
if self.driver:
self.log.info("稍等,程序正在退出")
self.driver.quit()
def init(self):
self.url_rpc = user_param.rpc_domain + '/v1/chain/'
self.url_table_row = user_param.rpc_domain + '/v1/chain/get_table_rows'
self.url_assets = user_param.assets_domain + '/atomicassets/v1/assets'
self.log.extra["tag"] = self.wax_account
options = webdriver.ChromeOptions()
# options.add_argument("--headless")
# options.add_argument("--no-sandbox")
options.add_argument("--disable-extensions")
options.add_argument("--log-level=3")
options.add_argument("--disable-logging")
options.add_experimental_option('useAutomationExtension', False)
options.add_experimental_option('excludeSwitches', ['enable-automation'])
data_dir = os.path.join(Farmer.chrome_data_dir, self.wax_account)
options.add_argument("--user-data-dir={0}".format(data_dir))
if self.proxy:
options.add_argument("--proxy-server={0}".format(self.proxy))
self.driver = webdriver.Chrome(plat.driver_path, options=options)
self.driver.implicitly_wait(60)
self.driver.set_script_timeout(60)
self.http = requests.Session()
self.http.trust_env = False
self.http.request = functools.partial(self.http.request, timeout=30)
if self.proxy:
self.http.proxies = {
"http": "http://{0}".format(self.proxy),
"https": "http://{0}".format(self.proxy),
}
http_retry_wrapper = tenacity.retry(wait=wait_fixed(cfg.req_interval), stop=stop_after_attempt(5),
retry=retry_if_exception_type(RequestException),
before_sleep=self.log_retry, reraise=True)
self.http.get = http_retry_wrapper(self.http.get)
self.http.post = http_retry_wrapper(self.http.post)
def inject_waxjs(self):
# 如果已经注入过就不再注入了
if self.driver.execute_script("return window.mywax != undefined;"):
return True
if not Farmer.waxjs:
with open("waxjs.js", "r") as file:
Farmer.waxjs = file.read()
file.close()
Farmer.waxjs = base64.b64encode(Farmer.waxjs.encode()).decode()
if not Farmer.myjs:
with open("inject.js", "r") as file:
inject_rpc = "window.mywax = new waxjs.WaxJS({rpcEndpoint: '" + user_param.rpc_domain + "'});"
Farmer.myjs = inject_rpc + file.read()
file.close()
code = "var s = document.createElement('script');"
code += "s.type = 'text/javascript';"
code += "s.text = atob('{0}');".format(Farmer.waxjs)
code += "document.head.appendChild(s);"
self.driver.execute_script(code)
self.driver.execute_script(Farmer.myjs)
return True
def start(self):
self.log.info("启动浏览器")
self.log.info("wax节点: {0}".format(user_param.rpc_domain))
self.log.info("原子市场节点: {0}".format(user_param.assets_domain))
if self.cookies:
self.log.info("使用预设的cookie自动登录")
cookies = self.cookies["cookies"]
key_cookie = {}
for item in cookies:
if item.get("domain") == "all-access.wax.io":
key_cookie = item
break
if not key_cookie:
raise CookieExpireException("not find cookie domain as all-access.wax.io")
ret = self.driver.execute_cdp_cmd("Network.setCookie", key_cookie)
self.log.info("Network.setCookie: {0}".format(ret))
if not ret["success"]:
raise CookieExpireException("Network.setCookie error")
self.driver.get("https://play.farmersworld.io/")
# 等待页面加载完毕
elem = self.driver.find_element(By.ID, "RPC-Endpoint")
elem.find_element(By.XPATH, "option[contains(@name, 'https')]")
wait_seconds = 60
if self.may_cache_login():
self.log.info("使用Cache自动登录")
else:
wait_seconds = 600
self.log.info("请在弹出的窗口中手动登录账号")
# 点击登录按钮,点击WAX云钱包方式登录
elem = self.driver.find_element(By.CLASS_NAME, "login-button")
elem.click()
elem = self.driver.find_element(By.CLASS_NAME, "login-button--text")
elem.click()
# 等待登录成功
self.log.info("等待登录")
WebDriverWait(self.driver, wait_seconds, 1).until(
EC.presence_of_element_located((By.XPATH, "//img[@class='navbar-group--icon' and @alt='Map']")))
# self.driver.find_element(By.XPATH, "//img[@class='navbar-group--icon' and @alt='Map']")
self.log.info("登录成功,稍等...")
time.sleep(cfg.req_interval)
self.inject_waxjs()
ret = self.driver.execute_script("return window.wax_login();")
self.log.info("window.wax_login(): {0}".format(ret))
if not ret[0]:
raise CookieExpireException("cookie失效")
# 从服务器获取游戏参数
self.log.info("正在加载游戏配置")
self.init_farming_config()
time.sleep(cfg.req_interval)
def may_cache_login(self):
cookies = self.driver.execute_cdp_cmd("Network.getCookies", {"urls": ["https://all-access.wax.io"]})
for item in cookies["cookies"]:
if item.get("name") == "token_id":
return True
return False
def log_retry(self, state: RetryCallState):
exp = state.outcome.exception()
if isinstance(exp, RequestException):
self.log.info("网络错误: {0}".format(exp))
self.log.info("正在重试: [{0}]".format(state.attempt_number))
def http_post(self, post_data):
# rpc_domain = random.choice(user_param.rpc_domain_list)
url_table_row = user_param.rpc_domain + '/v1/chain/get_table_rows'
return self.http.post(url_table_row, json=post_data)
def table_row_template(self) -> dict:
post_data = {
"json": True,
"code": "farmersworld",
"scope": "farmersworld",
"table": None, # 覆写
"lower_bound": self.wax_account,
"upper_bound": self.wax_account,
"index_position": None, # 覆写
"key_type": "i64",
"limit": 100,
"reverse": False,
"show_payer": False
}
return post_data
# 从服务器获取各种工具和作物的参数
def init_farming_config(self):
# 工具
post_data = {
"json": True,
"code": "farmersworld",
"scope": "farmersworld",
"table": "toolconfs",
"lower_bound": "",
"upper_bound": "",
"index_position": 1,
"key_type": "",
"limit": 100,
"reverse": False,
"show_payer": False
}
resp = self.http_post(post_data)
self.log.debug("get tools config:{0}".format(resp.text))
resp = resp.json()
res.init_tool_config(resp["rows"])
time.sleep(cfg.req_interval)
# 农作物
post_data["table"] = "cropconf"
resp = self.http_post(post_data)
self.log.debug("get crop config:{0}".format(resp.text))
resp = resp.json()
res.init_crop_config(resp["rows"])
# 动物
post_data["table"] = "anmconf"
resp = self.http_post(post_data)
self.log.debug("get animal conf:{0}".format(resp.text))
resp = resp.json()
res.init_animal_config(resp["rows"])
# 会员卡
post_data["table"] = "mbsconf"
resp = self.http_post(post_data)
self.log.debug("get mbs config:{0}".format(resp.text))
resp = resp.json()
res.init_mbs_config(resp["rows"])
# 从服务器获取配置
def get_farming_config(self):
post_data = {
"json": True,
"code": "farmersworld",
"scope": "farmersworld",
"table": "config",
"lower_bound": "",
"upper_bound": "",
"index_position": 1,
"key_type": "",
"limit": 1,
"reverse": False,
"show_payer": False
}
resp = self.http_post(post_data)
self.log.debug("get farming config:{0}".format(resp.text))
resp = resp.json()
return resp["rows"][0]
# 获取游戏中的三种资源数量和能量值
def get_resource(self) -> Resoure:
post_data = self.table_row_template()
post_data["table"] = "accounts"
post_data["index_position"] = 1
resp = self.http_post(post_data)
self.log.debug("get_table_rows:{0}".format(resp.text))
resp = resp.json()
if len(resp["rows"]) == 0:
self.log.info("===============================")
self.log.info("获取不到账号数据,请检查账号名是否有误")
self.log.info("===============================")
resource = Resoure()
resource.energy = Decimal(resp["rows"][0]["energy"])
resource.max_energy = Decimal(resp["rows"][0]["max_energy"])
resource.gold = Decimal(0)
resource.wood = Decimal(0)
resource.food = Decimal(0)
balances: List[str] = resp["rows"][0]["balances"]
for item in balances:
sp = item.split(" ")
if sp[1].upper() == "GOLD":
resource.gold = Decimal(sp[0])
elif sp[1].upper() == "WOOD":
resource.wood = Decimal(sp[0])
elif sp[1].upper() == "FOOD":
resource.food = Decimal(sp[0])
self.log.debug("resource: {0}".format(resource))
return resource
# 获取建造信息
def get_buildings(self) -> List[Building]:
post_data = self.table_row_template()
post_data["table"] = "buildings"
post_data["index_position"] = 2
resp = self.http_post(post_data)
self.log.debug("get_buildings_info:{0}".format(resp.text))
resp = resp.json()
buildings = []
for item in resp["rows"]:
build = Building()
build.asset_id = item["asset_id"]
build.name = item["name"]
build.is_ready = item["is_ready"]
build.next_availability = datetime.fromtimestamp(item["next_availability"])
build.template_id = item["template_id"]
build.times_claimed = item.get("times_claimed", None)
build.slots_used = item.get("slots_used", None)
if build.is_ready == 1:
continue
buildings.append(build)
return buildings
# 获取农作物信息
def get_crops(self) -> List[Crop]:
post_data = self.table_row_template()
post_data["table"] = "crops"
post_data["index_position"] = 2
resp = self.http_post(post_data)
self.log.debug("get_crops_info:{0}".format(resp.text))
resp = resp.json()
crops = []
for item in resp["rows"]:
crop = res.create_crop(item)
if crop:
crops.append(crop)
else:
self.log.warning("尚未支持的农作物类型:{0}".format(item))
return crops
# claim 建筑
def claim_building(self, item: Building):
self.consume_energy(Decimal(item.energy_consumed))
transaction = {
"actions": [{
"account": "farmersworld",
"name": "bldclaim",
"authorization": [{
"actor": self.wax_account,
"permission": "active",
}],
"data": {
"asset_id": item.asset_id,
"owner": self.wax_account,
},
}],
}
return self.wax_transact(transaction)
# 耕种农作物
def claim_crop(self, crop: Crop):
energy_consumed = crop.energy_consumed
fake_consumed = Decimal(0)
if crop.times_claimed == crop.required_claims - 1:
# 收获前的最后一次耕作,多需要200点能量,游戏合约BUG(玉米需要245)
fake_consumed = Decimal(250)
self.consume_energy(Decimal(energy_consumed), fake_consumed)
transaction = {
"actions": [{
"account": "farmersworld",
"name": "cropclaim",
"authorization": [{
"actor": self.wax_account,
"permission": "active",
}],
"data": {
"crop_id": crop.asset_id,
"owner": self.wax_account,
},
}],
}
return self.wax_transact(transaction)
def claim_buildings(self, blds: List[Building]):
for item in blds:
self.log.info("正在建造: {0}".format(item.show()))
if self.claim_building(item):
self.log.info("建造成功: {0}".format(item.show(more=False)))
else:
self.log.info("建造失败: {0}".format(item.show(more=False)))
self.count_error_claim += 1
time.sleep(cfg.req_interval)
def claim_crops(self, crops: List[Crop]):
for item in crops:
self.log.info("正在耕作: {0}".format(item.show()))
if self.claim_crop(item):
self.log.info("耕作成功: {0}".format(item.show(more=False)))
else:
self.log.info("耕作失败: {0}".format(item.show(more=False)))
self.count_error_claim += 1
time.sleep(cfg.req_interval)
# 获取箱子里的NTF
def get_chest(self) -> dict:
payload = {
"limit": 1000,
"collection_name": "farmersworld",
"owner": self.wax_account,
"template_blacklist": "260676",
}
resp = self.http.get(self.url_assets, params=payload)
self.log.debug("get_chest:{0}".format(resp.text))
resp = resp.json()
assert resp["success"]
return resp
# schema: [foods]
def get_chest_by_schema_name(self, schema_name: str):
payload = {
"limit": 1000,
"collection_name": "farmersworld",
"owner": self.wax_account,
"schema_name": schema_name,
}
resp = self.http.get(self.url_assets, params=payload)
self.log.debug("get_chest_by_schema_name:{0}".format(resp.text))
resp = resp.json()
assert resp["success"]
return resp
# template_id: [大麦 318606] [玉米 318607]
def get_chest_by_template_id(self, template_id: int):
payload = {
"limit": 1000,
"collection_name": "farmersworld",
"owner": self.wax_account,
"template_id": template_id,
}
resp = self.http.get(self.url_assets, params=payload)
self.log.debug("get_chest_by_template_id:{0}".format(resp.text))
resp = resp.json()
assert resp["success"]
return resp
# 获取大麦
def get_barley(self) -> List[Asset]:
barley_list = self.get_asset(NFT.Barley, 'Barley')
return barley_list
# 获取牛奶
def get_milk(self) -> List[Asset]:
milk_list = self.get_asset(NFT.Milk, 'Milk')
return milk_list
# 获取鸡蛋
def get_egg(self) -> List[Asset]:
egg_list = self.get_asset(NFT.ChickenEgg, 'ChickenEgg')
return egg_list
# 获取玉米
def get_corn(self) -> List[Asset]:
corn_list = self.get_asset(NFT.Corn, 'Corn')
return corn_list
# 获取NFT资产,可以是小麦,小麦种子,牛奶等
def get_asset(self, template_id, name) -> List[Asset]:
asset_list = []
chest = self.get_chest_by_template_id(template_id)
if len(chest["data"]) <= 0:
return asset_list
for item in chest["data"]:
asset = Asset()
asset.asset_id = item["asset_id"]
asset.name = item["name"]
asset.is_transferable = item["is_transferable"]
asset.is_burnable = item["is_transferable"]
asset.schema_name = item["schema"]["schema_name"]
asset.template_id = item["template"]["template_id"]
asset_list.append(asset)
self.log.debug("[{0}]_get_asset_list: [{1}]".format(name, format(asset_list)))
return asset_list
# 获取动物的信息
def get_breedings(self) -> List[Animal]:
post_data = self.table_row_template()
post_data["table"] = "breedings"
post_data["index_position"] = 2
resp = self.http_post(post_data)
self.log.debug("get_breedings:{0}".format(resp.text))
resp = resp.json()
if len(resp["rows"]) == 0:
self.log.warning("没有正在繁殖的动物,请先手动开启繁殖")
animals = []
for item in resp["rows"]:
anim = res.create_animal(item, True)
if anim:
animals.append(anim)
else:
self.log.info("尚未支持繁殖的动物")
return animals
def get_animals(self) -> List[Animal]:
post_data = self.table_row_template()
post_data["table"] = "animals"
post_data["index_position"] = 2
resp = self.http_post(post_data)
self.log.debug("get_animal_info:{0}".format(resp.text))
resp = resp.json()
if len(resp["rows"]) == 0:
self.log.warning("账户中没有动物")
animals = []
for item in resp["rows"]:
anim = res.create_animal(item)
if anim:
if anim.required_building == 298590 and user_param.cow:
# 牛棚
animals.append(anim)
elif anim.required_building == 298591 and user_param.chicken:
# 鸡舍
animals.append(anim)
else:
self.log.info("尚未支持的动物:{0}".format(item["name"]))
return animals
# 喂动物
def feed_animal(self, asset_id_food: str, animal: Animal, breeding=False) -> bool:
fake_consumed = Decimal(0)
if animal.times_claimed == animal.required_claims - 1:
# 收获前的最后一次喂养,多需要200点能量,游戏合约BUG
fake_consumed = Decimal(200)
self.consume_energy(Decimal(animal.energy_consumed), fake_consumed)
if not breeding:
self.log.info("feed [{0}] to [{1}]".format(asset_id_food, animal.asset_id))
memo = "feed_animal:{0}".format(animal.asset_id)
else:
self.log.info("feed [{0}] to [{1}]".format(asset_id_food, animal.bearer_id))
memo = "breed_animal:{0},{1}".format(animal.bearer_id, animal.partner_id)
transaction = {
"actions": [{
"account": "atomicassets",
"name": "transfer",
"authorization": [{
"actor": self.wax_account,
"permission": "active",
}],
"data": {
"asset_ids": [asset_id_food],
"from": self.wax_account,
"memo": memo,
"to": "farmersworld"
},
}],
}
return self.wax_transact(transaction)
# 获取动物需要的食物
def get_animal_food(self, animal: Animal):
food_class = res.farming_table.get(animal.consumed_card)
list_food = self.get_asset(animal.consumed_card, food_class.name)
self.log.info("剩余[{0}]数量: [{1}]".format(food_class.name, len(list_food)))
if len(list_food) <= 0:
rs = self.buy_corps(animal.consumed_card, user_param.buy_food_num)
if not rs:
self.log.warning("{0}数量不足,请及时补充".format(food_class.name))
return False
else:
list_food = self.get_asset(animal.consumed_card, food_class.name)
asset = list_food.pop()
return asset.asset_id
# 饲养动物
def claim_animal(self, animals: List[Animal]):
for item in animals:
self.log.info("正在喂[{0}]: [{1}]".format(item.name, item.show()))
if 'Egg' in item.name:
success = self.care_animal(item)
else:
feed_asset_id = self.get_animal_food(item)
if not feed_asset_id:
return False
success = self.feed_animal(feed_asset_id, item)
if success:
self.log.info("喂养成功: {0}".format(item.show(more=False)))
else:
self.log.info("喂养失败: {0}".format(item.show(more=False)))
self.count_error_claim += 1
time.sleep(cfg.req_interval)
return True
# 饲养繁殖的动物
def breeding_claim(self, animals: List[Animal]):
for item in animals:
self.log.info("【繁殖】正在喂[{0}]: [{1}]".format(item.name, item.show(False, True)))
feed_asset_id = self.get_animal_food(item)
if not feed_asset_id:
return False
success = self.feed_animal(feed_asset_id, item, True)
if success:
self.log.info("【繁殖】喂养成功: {0}".format(item.show(more=False, breeding=True)))
else:
self.log.info("【繁殖】喂养失败: {0}".format(item.show(more=False, breeding=True)))
self.count_error_claim += 1
time.sleep(cfg.req_interval)
return True
def care_animal(self, animal: Animal):
self.log.info("care_animal {0}".format(animal.asset_id))
fake_consumed = Decimal(0)
if animal.times_claimed == animal.required_claims - 1:
# 收获前的最后一次喂养,多需要200点能量,游戏合约BUG
fake_consumed = Decimal(200)
self.consume_energy(Decimal(animal.energy_consumed), fake_consumed)
transaction = {
"actions": [{
"account": "farmersworld",
"name": "anmclaim",
"authorization": [{
"actor": self.wax_account,
"permission": "active",
}],
"data": {
"animal_id": animal.asset_id,
"owner": self.wax_account,
},
}],
}
return self.wax_transact(transaction)
# 获取wax账户信息
def wax_get_account(self):
url = self.url_rpc + "get_account"
post_data = {"account_name": self.wax_account}
resp = self.http.post(url, json=post_data)
self.log.debug("get_account:{0}".format(resp.text))
resp = resp.json()
return resp
# 获取三种资源的代币余额 FWF FWG FWW
def get_fw_balance(self) -> Token:
url = self.url_rpc + "get_currency_balance"
post_data = {
"code": "farmerstoken",
"account": self.wax_account,
"symbol": None
}
resp = self.http.post(url, json=post_data)
self.log.debug("get_fw_balance:{0}".format(resp.text))
resp = resp.json()
balance = Token()
balance.fwf = 0
balance.fwg = 0
balance.fww = 0
for item in resp:
sp = item.split(" ")
if sp[1].upper() == "FWF":
balance.fwf = Decimal(sp[0])
elif sp[1].upper() == "FWG":
balance.fwg = Decimal(sp[0])
elif sp[1].upper() == "FWW":
balance.fww = Decimal(sp[0])
self.log.debug("fw_balance: {0}".format(balance))
return balance
# 签署交易(只许成功,否则抛异常)
def wax_transact(self, transaction: dict):
self.inject_waxjs()
self.log.info("begin transact: {0}".format(transaction))
try:
success, result = self.driver.execute_script("return window.wax_transact(arguments[0]);", transaction)
if success:
self.log.info("transact ok, transaction_id: [{0}]".format(result["transaction_id"]))
self.log.debug("transact result: {0}".format(result))
time.sleep(cfg.transact_interval)
return result
else:
if "is greater than the maximum billable" in result:
self.log.error("CPU资源不足,可能需要质押更多WAX,一般为误报,稍后重试 maximum")
elif "estimated CPU time (0 us) is not less than the maximum billable CPU time for the transaction (0 us)" in result:
self.log.error("CPU资源不足,可能需要质押更多WAX,一般为误报,稍后重试 estimated")
else:
self.log.error("transact error: {0}".format(result))
raise TransactException(result)
except WebDriverException as e:
self.log.error("transact error: {0}".format(e))
self.log.exception(str(e))
raise TransactException(result)
# 过滤可操作的作物
def filter_operable(self, items: List[Farming]) -> Farming:
now = datetime.now()
op = []
for item in items:
if isinstance(item, Building):
if item.is_ready == 1:
continue
# daily_claim_limit 鸡24小时内最多喂4次 ,奶牛24小时内最多喂6次,小牛犊24小时内最多喂2次
if isinstance(item, Animal):
if len(item.day_claims_at) >= item.daily_claim_limit:
next_op_time = item.day_claims_at[0] + timedelta(hours=24)
item.next_availability = max(item.next_availability, next_op_time)
self.log.info("[{0}]24小时内最多喂[{1}]次 ".format(item.name, item.daily_claim_limit))
if now < item.next_availability:
self.not_operational.append(item)
continue
op.append(item)
return op
def scan_buildings(self):
self.log.info("检查建筑物")
buildings = self.get_buildings()
if not buildings:
self.log.info("没有未完成的建筑物")
return True
self.log.info("未完成的建筑物:")
for item in buildings:
self.log.info(item.show())
buildings = self.filter_operable(buildings)
if not buildings:
self.log.info("没有可操作的建筑物")
return True
self.log.info("可操作的建筑物:")
for item in buildings:
self.log.info(item.show())
self.claim_buildings(buildings)
return True
def scan_plants(self):
self.log.info("自动种地")
post_data = self.table_row_template()
post_data["table"] = "buildings"
post_data["index_position"] = 2
resp = self.http_post(post_data)
self.log.debug("get_buildings_info:{0}".format(resp.text))
resp = resp.json()
for item in resp["rows"]:
if item["template_id"] == 298592 and item["is_ready"] == 1:
slots_num = 8 - item["slots_used"]
if slots_num > 0:
self.plant_corps(slots_num)
else:
self.log.info("没有未使用的地块")
return True
# 购买作物
def buy_corps(self, template_id: int, buy_num: int):
if buy_num <= 0:
self.log.info("购买数量为0")
return False
item_class = res.farming_table.get(template_id)
total_golds = item_class.golds_cost * buy_num
if total_golds > self.resoure.gold:
new_buy_num = int(self.resoure.gold / item_class.golds_cost)
if new_buy_num <= 0:
self.log.info("金币不足,无法购买,请先补充金币")
return False
else:
self.log.info("金币不足,需要购买[{0}]个,实际购买[{1}]个".format(buy_num, new_buy_num))
buy_num = new_buy_num
if user_param.buy_barley_seed and template_id == 298595:
self.log.info("开始购买大麦种子,数量:{0}".format(buy_num))
self.market_buy(template_id, buy_num)
elif user_param.buy_corn_seed and template_id == 298596:
self.log.info("开始购买玉米种子,数量:{0}".format(buy_num))
self.market_buy(template_id, buy_num)
elif user_param.buy_food and template_id == 318606:
self.log.info("开始购买大麦,数量:{0}".format(buy_num))
self.market_buy(template_id, buy_num)
elif user_param.buy_food and template_id == 318607:
self.log.info("开始购买玉米,数量:{0}".format(buy_num))
self.market_buy(template_id, buy_num)
else:
self.log.info("配置不执行购买,请检查")
time.sleep(2)
return True
# 市场购买
def market_buy(self, template_id: int, buy_num: int):
transaction = {
"actions": [{
"account": "farmersworld",
"name": "mktbuy",
"authorization": [{
"actor": self.wax_account,
"permission": "active",
}],
"data": {
"owner": self.wax_account,
"quantity": buy_num,
"template_id": template_id,
},
}],
}
self.wax_transact(transaction)
self.log.info("购买完成")
return True
# 种植
def plant_corps(self, slots_num):
self.log.info("获取大麦或玉米种子")
if user_param.barleyseed_num > 0:
barleyseed_list = self.get_asset(298595, 'Barley Seed')
plant_times = min(slots_num, user_param.barleyseed_num)
if len(barleyseed_list) < plant_times and user_param.buy_barley_seed:
self.log.warning("大麦种子数量不足,开始市场购买")
buy_barleyseed_num = plant_times - len(barleyseed_list)
rs = self.buy_corps(298595, buy_barleyseed_num)
if not rs:
return False
else:
barleyseed_list = self.get_asset(298595, 'Barley Seed')
if len(barleyseed_list) > 0:
for i in range(plant_times):
asset = barleyseed_list.pop()
self.wear_assets([asset.asset_id])
else:
self.log.info("大麦种子数量不足,请及时补充")
else:
self.log.info("设置的大麦种子数量为0")
if user_param.cornseed_num > 0:
cornseed_list = self.get_asset(298596, 'Corn Seed')
plant_times2 = min(slots_num, user_param.cornseed_num)
if len(cornseed_list) < plant_times2 and user_param.buy_corn_seed:
self.log.warning("玉米种子数量不足,开始市场购买")
buy_cornseed_num = plant_times2 - len(cornseed_list)
rs = self.buy_corps(298596, buy_cornseed_num)
if not rs:
return False
else:
cornseed_list = self.get_asset(298596, 'Corn Seed')
if len(cornseed_list) > 0:
for i in range(plant_times2):
asset = cornseed_list.pop()
self.wear_assets([asset.asset_id])
else:
self.log.info("玉米种子数量不足,请及时补充")
else:
self.log.info("设置的玉米种子数量为0")
return True
# 穿戴工具,种地-(种地:玉米、小麦)
def wear_assets(self, asset_ids):
self.log.info("正在种地【玉米种子|小麦种子】")
transaction = {
"actions": [{
"account": "atomicassets",
"name": "transfer",
"authorization": [{
"actor": self.wax_account,
"permission": "active",
}],
"data": {
"from": self.wax_account,
"to": "farmersworld",
"asset_ids": asset_ids,
"memo": "stake",
},
}],
}
self.wax_transact(transaction)
self.log.info("种地完成")
time.sleep(cfg.req_interval)
def scan_crops(self):
self.log.info("检查农田")
crops = self.get_crops()
if not crops:
self.log.info("没有农作物")
return True
self.log.info("种植的农作物:")
for item in crops:
self.log.info(item.show())
crops = self.filter_operable(crops)
if not crops:
self.log.info("没有可操作的农作物")
return True
self.log.info("可操作的农作物:")
for item in crops:
self.log.info(item.show())
self.claim_crops(crops)
return True
# 售卖玉米和大麦
def scan_nft_assets(self):
asset_ids = []
sell_barley_num = 0
sell_corn_num = 0
sell_milk_num = 0
sell_egg_num = 0
if user_param.sell_corn:
self.log.info("检查玉米NFT")
list_corn = self.get_corn()
self.log.info("剩余玉米数量: {0}".format(len(list_corn)))
if len(list_corn) > 0:
for item in list_corn:
if len(list_corn) - sell_corn_num <= user_param.remaining_corn_num:
break
asset_ids.append(item.asset_id)
sell_corn_num = sell_corn_num + 1
if user_param.sell_barley:
self.log.info("检查大麦")
list_barley = self.get_barley()
self.log.info("剩余大麦数量: {0}".format(len(list_barley)))
if len(list_barley) > 0:
for item in list_barley:
if len(list_barley) - sell_barley_num <= user_param.remaining_barley_num:
break
asset_ids.append(item.asset_id)
sell_barley_num = sell_barley_num + 1
if user_param.sell_milk:
self.log.info("检查牛奶")
list_milk = self.get_milk()
self.log.info("剩余牛奶数量: {0}".format(len(list_milk)))
if len(list_milk) > 0:
for item in list_milk:
if len(list_milk) - sell_milk_num <= user_param.remaining_milk_num:
break
asset_ids.append(item.asset_id)
sell_milk_num = sell_milk_num + 1
if user_param.sell_egg:
self.log.info("检查鸡蛋")
list_egg = self.get_egg()
self.log.info("剩余鸡蛋数量: {0}".format(len(list_egg)))
if len(list_egg) > 0:
for item in list_egg:
if len(list_egg) - sell_egg_num <= user_param.remaining_egg_num:
break
asset_ids.append(item.asset_id)
sell_egg_num = sell_egg_num + 1
if len(asset_ids) <= 0: