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

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

Comments

Loading...