__main__.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. """Main app"""
  2. from datetime import datetime, timedelta
  3. import random
  4. import time
  5. # libraries and data
  6. import matplotlib.pyplot as plt
  7. import matplotlib.dates as mdates
  8. import pandas as pd
  9. from pandas.plotting import register_matplotlib_converters
  10. from telegram import ParseMode
  11. from app import SCHEDULER, LOGGER, TELEGRAM_BOT
  12. from app.api import download_resources, refill
  13. from app.database import save_resources, get_resources, get_work_percentage
  14. from app.app import need_refill, max_refill_seconds, print_resources
  15. register_matplotlib_converters()
  16. def job_check_resources(state_id, capital_id, resource_id, do_refill):
  17. """Check resources and refill if necessary"""
  18. regions = download_resources(state_id, resource_id)
  19. print_resources(regions)
  20. save_resources(state_id, regions, resource_id)
  21. if do_refill and need_refill(regions, 25):
  22. max_seconds = max_refill_seconds(regions, 25, 900)
  23. random_seconds = random.randint(0, max_seconds)
  24. random_time_delta = timedelta(seconds=random_seconds)
  25. scheduled_date = datetime.now() + random_time_delta
  26. job_id = 'refill_{}_{}'.format(capital_id, resource_id)
  27. LOGGER.info(
  28. 'Refil resource %s at %s (%s minutes)',
  29. resource_id,
  30. scheduled_date,
  31. round(random_time_delta.seconds / 60)
  32. )
  33. job = SCHEDULER.get_job(job_id)
  34. if not job:
  35. SCHEDULER.add_job(
  36. job_refill_resource,
  37. 'date',
  38. args=[state_id, capital_id, resource_id],
  39. id=job_id,
  40. run_date=scheduled_date
  41. )
  42. def job_refill_resource(state_id, capital_id, resource_id):
  43. """Execute refill job"""
  44. refill(state_id, capital_id, resource_id)
  45. def add_check_resources(state_id, capital_id, resource_id, do_refill, minute):
  46. """Add check resources job"""
  47. SCHEDULER.add_job(
  48. job_check_resources,
  49. 'cron',
  50. args=[state_id, capital_id, resource_id, do_refill],
  51. id='{}_check_{}'.format(state_id, resource_id),
  52. replace_existing=True,
  53. minute=minute
  54. )
  55. def job_send_telegram_update(state_id, group_id, resource_type):
  56. """Send telegram update"""
  57. message = get_work_percentage(state_id, resource_type, datetime.utcnow(), 1, 1)
  58. print(message)
  59. TELEGRAM_BOT.sendMessage(
  60. chat_id=group_id,
  61. text='```\n{}```'.format(message),
  62. parse_mode=ParseMode.MARKDOWN
  63. )
  64. def graph():
  65. """make graph"""
  66. date = datetime.now()# - timedelta(1)
  67. region_4001 = get_resources(4001, date, 0)
  68. region_4002 = get_resources(4002, date, 0)
  69. region_4003 = get_resources(4003, date, 0)
  70. region_4004 = get_resources(4004, date, 0)
  71. region_4008 = get_resources(4008, date, 0)
  72. # resource_tmp = np.random.randn(2499)+range(2500, 1, -1)
  73. # Make a data frame
  74. data_frame = pd.DataFrame({
  75. # 'x': range(1, 2500),
  76. # '4001': resource_tmp,
  77. 'x': list(region_4001.keys()),
  78. 'Northern Netherlands': list(region_4001.values()),
  79. 'Eastern Netherlands': list(region_4002.values()),
  80. 'Western Netherlands': list(region_4003.values()),
  81. 'Southern Netherlands': list(region_4004.values()),
  82. 'Amsterdam': list(region_4008.values()),
  83. })
  84. major_fmt = mdates.DateFormatter('%m-%d %H:%M')
  85. fig, ax = plt.subplots()
  86. ax.xaxis.set_major_formatter(major_fmt)
  87. fig.autofmt_xdate()
  88. end_date_time = date.replace(hour=19, minute=0, second=0, microsecond=0)
  89. start_date_time = end_date_time - timedelta(hours=24)
  90. ax.set_xlim([start_date_time, end_date_time])
  91. ax.set_ylim([0, 2700])
  92. # style
  93. plt.style.use('seaborn-darkgrid')
  94. # create a color palette
  95. palette = plt.get_cmap('Set1')
  96. # multiple line plot
  97. num = 0
  98. for column in data_frame.drop('x', axis=1):
  99. num += 1
  100. plt.plot(
  101. data_frame['x'],
  102. data_frame[column],
  103. marker='',
  104. color=palette(num),
  105. linewidth=1,
  106. alpha=0.9,
  107. label=column
  108. )
  109. # Add legend
  110. plt.legend(loc=3, ncol=1)
  111. # plt.setp(plt.xticks()[1], rotation=30, ha='right')
  112. # Add titles
  113. plt.title(
  114. 'Resource limit left | {}'.format(date.strftime('%Y-%m-%d')),
  115. loc='left',
  116. fontsize=12,
  117. fontweight=1
  118. )
  119. plt.xlabel("Time")
  120. plt.ylabel("Resources")
  121. plt.savefig('foo.png')
  122. if __name__ == '__main__':
  123. # job_refill_resource(2788, 4002, 0)
  124. # job_check_resources(2788, 4002, 0, False) # VN
  125. # job_check_resources(2620, 4002, 0, False) # Zeelandiae
  126. # get_resources(4001, datetime.now(), 0)
  127. graph()
  128. exit()
  129. # VN
  130. add_check_resources(2788, 4008, 0, True, '0,15,30,45')
  131. add_check_resources(2788, 4008, 11, True, '0')
  132. # Zeelandiae
  133. add_check_resources(2620, 0, 0, False, '50')
  134. # Belgium
  135. add_check_resources(2604, 0, 0, False, '40')
  136. SCHEDULER.add_job(
  137. job_send_telegram_update,
  138. 'cron',
  139. args=[2788, '@vn_resources', 0],
  140. id='job_send_telegram_update',
  141. replace_existing=True,
  142. minute='5'
  143. )
  144. try:
  145. while True:
  146. time.sleep(100)
  147. except KeyboardInterrupt:
  148. LOGGER.info('Exiting application')
  149. SCHEDULER.shutdown()
  150. exit()