Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

bot.py 7.3 KB

You have to be logged in to leave a comment. Sign In
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
  1. import telegram
  2. from telegram.ext import Updater, InlineQueryHandler, CommandHandler, Defaults, Job, MessageHandler, Filters
  3. import requests # to make requests to external api
  4. import re # regex for pictures of doggos
  5. import logging
  6. from datetime import datetime # use to restart everyday
  7. import sys
  8. from consts import *
  9. reports = []
  10. shags_situation = {
  11. 'גדול': {
  12. 'isRasar':0 # is rasar is a number between 0 and 1, 1- rasar, 0 clean
  13. },
  14. 'קטן':{
  15. 'isRasar':0
  16. }
  17. }
  18. logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  19. level=logging.INFO)
  20. logger = logging.getLogger()
  21. logger.setLevel(logging.INFO)
  22. if MODE == "dev":
  23. def run(updater):
  24. updater.start_polling()
  25. elif MODE == "prod":
  26. def run(updater):
  27. PORT = int(os.environ.get("PORT", "8443"))
  28. HEROKU_APP_NAME = os.environ.get("HEROKU_APP_NAME")
  29. updater.start_webhook(listen="0.0.0.0",
  30. port=PORT,
  31. url_path=BOT_TOKEN)
  32. updater.bot.set_webhook("https://{}.herokuapp.com/{}".format(HEROKU_APP_NAME, BOT_TOKEN))
  33. else:
  34. logger.error("No MODE specified!")
  35. sys.exit(1)
  36. # Get random dog image for the memes
  37. def get_url():
  38. contents = requests.get('https://random.dog/woof.json').json()
  39. image_url = contents['url']
  40. return image_url
  41. def get_image_url():
  42. allowed_extention = ['jpg', 'jpeg', 'png']
  43. file_extention = ''
  44. while file_extention not in allowed_extention:
  45. url = get_url()
  46. file_extention = re.search("([^.]*)$",url).group(1)
  47. logger.info('Sent image url: ' + url)
  48. return url
  49. def bop(bot, update):
  50. chat_id = update.message.chat_id
  51. url = get_image_url()
  52. bot.send_photo(chat_id=chat_id, photo=url)
  53. # Helper functions
  54. def reset_shags():
  55. global shags_situation
  56. shags_situation['גדול']['isRasar'] = 0
  57. shags_situation['קטן']['isRasar'] = 0
  58. def count_reports_in_shag(shag):
  59. global reports
  60. return len(list(filter(lambda report: report['shag']==shag, reports)))
  61. def get_last_report(shag):
  62. global reports
  63. for report in reversed(reports):
  64. if report['shag']==shag:
  65. return report
  66. def message_admin(bot, update, text):
  67. bot.forward_message(chat_id=ADMIN_ID,
  68. from_chat_id=update.message.chat_id,
  69. message_id=update.message.message_id)
  70. def log_admin(bot, info):
  71. logger.info(info)
  72. bot.send_message(chat_id=ADMIN_ID, text="LOG: %s"%info)
  73. # Get update of the rasar situation
  74. def update(bot, update):
  75. global reports
  76. chat_id = update.message.chat_id
  77. for shag in shags_situation:
  78. isRasar = shags_situation[shag]['isRasar']
  79. if isRasar>= 0.5:
  80. situation = 'רס"ר'
  81. chance = isRasar*100
  82. else:
  83. situation = 'נקי'
  84. chance = (1-isRasar)*100
  85. reports_count = count_reports_in_shag(shag)
  86. if reports_count >= MIN_REPORTS:
  87. last_report = get_last_report(shag)
  88. bot.send_message(chat_id=chat_id, text = 'שג ' + shag +' '+ situation
  89. + ' בטוח ב- ' + str(chance) +'%\n'
  90. + "התקבלו " + str(reports_count) + " דיווחים\n" +
  91. "דיווח אחרון (" +
  92. last_report['state'] +
  93. ") התקבל ב: " + last_report['time'].strftime("%H:%M:%S") )
  94. else:
  95. bot.send_message(chat_id=chat_id, text = "לא התקבלו דיווחים בשג " + shag)
  96. def cancel_report(bot, update):
  97. global reports
  98. chat_id = update.message.chat_id
  99. report = next((report for report in reports if report["chat_id"] == chat_id), None)
  100. if report:
  101. reports.remove(report)
  102. calculate_prob()
  103. bot.send_message(chat_id=chat_id, text='דיווח בוטל')
  104. user_name = str(update.effective_user.full_name)
  105. log_admin(bot, "Cancel report by user: %s" % user_name)
  106. else:
  107. bot.send_message(chat_id=chat_id, text='הדיווח כבר בוטל או שלא נשלח מעולם')
  108. reply_markup = telegram.ReplyKeyboardMarkup(KEYBOARD)
  109. bot.send_message(chat_id=chat_id,
  110. text="בחרו מהאפשרויות לדיווח",
  111. reply_markup=reply_markup)
  112. def calculate_prob():
  113. global reports, shags_situation
  114. reset_shags()
  115. for report in reports:
  116. shag = report['shag']
  117. state = report['state']
  118. if state=='רס"ר':
  119. shags_situation[shag]['isRasar'] +=RASAR_FACTOR*(1-shags_situation[shag]['isRasar'])
  120. else:
  121. shags_situation[shag]['isRasar'] *=CLEAN_FACTOR
  122. def report(bot, update):
  123. global reports
  124. chat_id = update.message.chat_id
  125. shag = update.message.text.split()[1]
  126. state = update.message.text.split()[2]
  127. old_report = next((report for report in reports if report["chat_id"] == chat_id), None)
  128. if old_report:
  129. reports.remove(old_report)
  130. reports.append({
  131. 'shag': shag,
  132. 'state': state,
  133. 'chat_id': chat_id,
  134. 'time': datetime.now()
  135. })
  136. calculate_prob()
  137. custom_keyboard = [['/cancel_report', '/new_report'],
  138. ['מה המצב?']]
  139. reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard)
  140. bot.send_message(chat_id=chat_id, text='תודה שדיווחת!', reply_markup=reply_markup)
  141. user_name = str(update.effective_user.full_name)
  142. log_admin(bot, "Recived report: %s %s by user: %s" % (shag, state, user_name))
  143. def send_feedback(bot, update):
  144. global feedback_message
  145. chat_id = update.message.chat_id
  146. message = update.message.text
  147. if len(message.split()) == 1:
  148. feedback_message = bot.send_message(chat_id=chat_id, text='דברו אני מקשיב')
  149. else:
  150. bot.send_message(chat_id=chat_id, text='תודה רבה :)')
  151. message_admin(bot, update, message.split(' ', 1)[1])
  152. def message_handler(bot, update):
  153. global feedback_message
  154. chat_id = update.message.chat_id
  155. message = update.message.text
  156. if 'feedback_message' in globals() and feedback_message.message_id + 1 == update.message.message_id:
  157. bot.send_message(chat_id=chat_id, text='תודה רבה :)')
  158. message_admin(bot, update, message)
  159. elif chat_id == int(ADMIN_ID) and update.message.reply_to_message:
  160. user_id = update.message.reply_to_message.forward_from.id
  161. bot.send_message(chat_id=user_id, text=message)
  162. else:
  163. bot.send_message(chat_id=chat_id, text='אם אתם רוצים לספר לי משהו השתמשו בפקודה /send_feedback')
  164. def new_report(bot, update):
  165. bot.send_message(chat_id=update.message.chat_id,
  166. text="בחרו מהאפשרויות לדיווח",
  167. reply_markup=telegram.ReplyKeyboardMarkup(KEYBOARD))
  168. def main():
  169. updater = Updater(BOT_TOKEN)
  170. dp = updater.dispatcher
  171. dp.add_handler(CommandHandler('cancel_report',cancel_report))
  172. dp.add_handler(CommandHandler('bop',bop))
  173. dp.add_handler(CommandHandler('send_feedback', send_feedback))
  174. dp.add_handler(CommandHandler('report',report))
  175. dp.add_handler(CommandHandler('new_report',new_report))
  176. dp.add_handler(MessageHandler(Filters.text("מה המצב?"), update))
  177. dp.add_handler(MessageHandler(Filters.all, message_handler))
  178. run(updater)
  179. updater.idle()
  180. if __name__ == '__main__':
  181. main()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...