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 8.8 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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
  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 show time of last report
  7. import pytz # handles timezone difference with remote server
  8. import sys
  9. from consts import *
  10. reports = []
  11. report_chat_ids = set()
  12. shags_situation = {
  13. 'גדול': {
  14. 'isDirty':0 # is dirty is a number between 0 and 1, 1- dirty, 0 clean
  15. },
  16. 'קטן':{
  17. 'isDirty':0
  18. }
  19. }
  20. logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  21. level=logging.INFO)
  22. logger = logging.getLogger()
  23. logger.setLevel(logging.INFO)
  24. if MODE == "dev":
  25. def run(updater):
  26. updater.start_polling()
  27. elif MODE == "prod":
  28. def run(updater):
  29. PORT = int(os.environ.get("PORT", "8443"))
  30. HEROKU_APP_NAME = os.environ.get("HEROKU_APP_NAME")
  31. updater.start_webhook(listen="0.0.0.0",
  32. port=PORT,
  33. url_path=BOT_TOKEN)
  34. updater.bot.set_webhook("https://{}.herokuapp.com/{}".format(HEROKU_APP_NAME, BOT_TOKEN))
  35. else:
  36. logger.error("No MODE specified!")
  37. sys.exit(1)
  38. # Get random dog image for the memes
  39. def get_url():
  40. contents = requests.get('https://random.dog/woof.json').json()
  41. image_url = contents['url']
  42. return image_url
  43. def get_image_url():
  44. allowed_extention = ['jpg', 'jpeg', 'png']
  45. file_extention = ''
  46. while file_extention not in allowed_extention:
  47. url = get_url()
  48. file_extention = re.search("([^.]*)$",url).group(1)
  49. logger.info('Sent image url: ' + url)
  50. return url
  51. def bop(bot, update):
  52. chat_id = update.message.chat_id
  53. url = get_image_url()
  54. bot.send_photo(chat_id=chat_id, photo=url)
  55. # Helper functions
  56. def reset_shags():
  57. global shags_situation
  58. shags_situation['גדול']['isDirty'] = 0
  59. shags_situation['קטן']['isDirty'] = 0
  60. def count_reports_in_shag(shag):
  61. global reports
  62. return len(list(filter(lambda report: report['shag']==shag, reports)))
  63. def get_last_report(shag):
  64. global reports
  65. for report in reversed(reports):
  66. if report['shag']==shag:
  67. return report
  68. def message_admin(bot, update, text):
  69. bot.forward_message(chat_id=ADMIN_ID,
  70. from_chat_id=update.message.chat_id,
  71. message_id=update.message.message_id)
  72. def log_admin(bot, info):
  73. logger.info(info)
  74. bot.send_message(chat_id=ADMIN_ID, text="LOG: %s"%info)
  75. def auto_reply_markup(chat_id):
  76. if next((report for report in reports if report["chat_id"] == chat_id), None):
  77. return telegram.ReplyKeyboardMarkup(SECOND_KEYBOARD, one_time_keyboard=True)
  78. else:
  79. return telegram.ReplyKeyboardMarkup(BASE_KEYBOARD, one_time_keyboard=True)
  80. # Get update of the rasar situation
  81. def update(bot, update):
  82. global reports
  83. chat_id = update.message.chat_id
  84. reply_markup = auto_reply_markup(chat_id)
  85. for shag in shags_situation:
  86. isDirty = shags_situation[shag]['isDirty']
  87. if isDirty>= 0.5:
  88. situation = 'מלוכלך'
  89. chance = isDirty*100
  90. else:
  91. situation = 'נקי'
  92. chance = (1-isDirty)*100
  93. reports_count = count_reports_in_shag(shag)
  94. if reports_count >= MIN_REPORTS:
  95. last_report = get_last_report(shag)
  96. bot.send_message(chat_id=chat_id, text = 'שג ' + shag +' '+ situation
  97. + '\n'
  98. + "התקבלו " + str(reports_count) + " דיווחים\n" +
  99. "דיווח אחרון (" +
  100. last_report['state'] +
  101. ") התקבל ב: " +
  102. last_report['time'].strftime("%H:%M:%S"), reply_markup=reply_markup)
  103. else:
  104. bot.send_message(chat_id=chat_id, text = "לא התקבלו דיווחים בשג " + shag, reply_markup=reply_markup)
  105. def cancel_report(bot, update):
  106. global reports
  107. chat_id = update.message.chat_id
  108. report = next((report for report in reversed(reports) if report["chat_id"] == chat_id), None)
  109. if report:
  110. reports.remove(report)
  111. calculate_prob()
  112. bot.send_message(chat_id=chat_id, text='דיווח בוטל')
  113. user_name = str(update.effective_user.full_name)
  114. log_admin(bot, "Cancel report by user: %s" % user_name)
  115. else:
  116. bot.send_message(chat_id=chat_id, text='הדיווח כבר בוטל או שלא נשלח מעולם')
  117. reply_markup = telegram.ReplyKeyboardMarkup(BASE_KEYBOARD, one_time_keyboard=True)
  118. bot.send_message(chat_id=chat_id,
  119. text="בחרו מהאפשרויות לדיווח",
  120. reply_markup=reply_markup)
  121. def calculate_prob():
  122. global reports, shags_situation
  123. reset_shags()
  124. for report in reports:
  125. shag = report['shag']
  126. state = report['state']
  127. if state=='נקי':
  128. shags_situation[shag]['isDirty'] *=CLEAN_FACTOR
  129. else:
  130. shags_situation[shag]['isDirty'] +=DIRTY_FACTOR*(1-shags_situation[shag]['isDirty'])
  131. def report(bot, update):
  132. global reports
  133. chat_id = update.message.chat_id
  134. shag = update.message.text.split()[1]
  135. state = update.message.text.split()[2]
  136. old_report = next((report for report in reports if report["chat_id"] == chat_id and report["shag"] == shag), None)
  137. if old_report:
  138. reports.remove(old_report)
  139. reports.append({
  140. 'shag': shag,
  141. 'state': state,
  142. 'chat_id': chat_id,
  143. 'time': pytz.utc.localize(datetime.utcnow()).astimezone(pytz.timezone("Israel"))
  144. })
  145. calculate_prob()
  146. if state == 'מלוכלך':
  147. global report_chat_ids
  148. reply_markup = telegram.ReplyKeyboardMarkup(STATE_KEYBOARD)
  149. report_chat_ids.add(chat_id)
  150. bot.send_message(chat_id=chat_id, text=('מה סוג האיום בשג ה'+shag+'? (אם האיום לא נמצא ברשימה, כתבו במקלדת בשפה חופשית)'), reply_markup=reply_markup)
  151. else:
  152. reply_markup = telegram.ReplyKeyboardMarkup(SECOND_KEYBOARD, one_time_keyboard=True)
  153. bot.send_message(chat_id=chat_id, text='תודה שדיווחת!', reply_markup=reply_markup)
  154. user_name = str(update.effective_user.full_name)
  155. log_admin(bot, "Recived report: %s %s by user: %s" % (shag, state, user_name))
  156. def send_feedback(bot, update):
  157. global feedback_message
  158. chat_id = update.message.chat_id
  159. message = update.message.text
  160. if len(message.split()) == 1:
  161. feedback_message = bot.send_message(chat_id=chat_id, text='דברו אני מקשיב')
  162. else:
  163. message_admin(bot, update, message.split(' ', 1)[1])
  164. bot.send_message(chat_id=chat_id, text='תודה רבה :)', reply_markup=auto_reply_markup(chat_id))
  165. def message_handler(bot, update):
  166. global feedback_message, state_kind, report_chat_ids, reports
  167. chat_id = update.message.chat_id
  168. message = update.message.text
  169. if chat_id in report_chat_ids:
  170. for report in reports:
  171. if report['chat_id'] == chat_id:
  172. report['state'] = message
  173. reply_markup = telegram.ReplyKeyboardMarkup(SECOND_KEYBOARD, one_time_keyboard=True)
  174. bot.send_message(chat_id=chat_id, text='תודה שדיווחת!', reply_markup=reply_markup)
  175. report_chat_ids.discard(chat_id)
  176. elif 'feedback_message' in globals():
  177. bot.send_message(chat_id=chat_id, text='תודה רבה :)', reply_markup=auto_reply_markup(chat_id))
  178. message_admin(bot, update, message)
  179. del feedback_message
  180. elif chat_id == int(ADMIN_ID) and update.message.reply_to_message:
  181. user_id = update.message.reply_to_message.forward_from.id
  182. bot.send_message(chat_id=user_id, text=message)
  183. else:
  184. bot.send_message(chat_id=chat_id, text='אם אתם רוצים לספר לי משהו השתמשו בפקודה /send_feedback או שלחו דיווח חדש עם /new_report')
  185. def new_report(bot, update):
  186. bot.send_message(chat_id=update.message.chat_id,
  187. text="בחרו מהאפשרויות לדיווח",
  188. reply_markup=telegram.ReplyKeyboardMarkup(BASE_KEYBOARD, one_time_keyboard=True))
  189. def main():
  190. updater = Updater(BOT_TOKEN)
  191. dp = updater.dispatcher
  192. dp.add_handler(CommandHandler('cancel_report',cancel_report))
  193. dp.add_handler(CommandHandler('bop',bop))
  194. dp.add_handler(CommandHandler('send_feedback', send_feedback))
  195. dp.add_handler(CommandHandler('report',report))
  196. dp.add_handler(CommandHandler('new_report',new_report))
  197. dp.add_handler(MessageHandler(Filters.text("מה המצב?"), update))
  198. dp.add_handler(MessageHandler(Filters.all, message_handler))
  199. run(updater)
  200. updater.idle()
  201. if __name__ == '__main__':
  202. main()
Tip!

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

Comments

Loading...