· 6 years ago · Apr 03, 2020, 05:50 PM
1import vk_api, requests, time
2from telebot import types
3import os
4from flask import Flask, request
5from telebot import apihelper
6import telebot
7import re, csv, random
8import threading
9from datetime import datetime,timedelta
10import apiai, json
11import lastdaymonthmodul
12from emoji import emojize
13from dbmbot import init_db, add_user_id_and_message_id, verify_user, get_summ, add_autor_id,\
14 get_autor_id, get_great_foto,delete_from_date, add_user_chat_id,get_user_chat_id
15
16
17server = Flask(__name__)
18URL = os.getenv("URL")
19vk = vk_api.VkApi(token='f5b07c111......................')
20bot = telebot.TeleBot('101763313...............',threaded=False)
21print(bot.get_me())
22
23
24def check_id_post(text_autor=''):
25 with open('id_post_text.txt', 'r',encoding='UTF-8') as text:
26 post_id=text.readlines()
27 print(post_id)
28 if text_autor!=post_id[0]:
29 return True
30 else:
31 return False
32
33
34def check_pinned(): # проверить запись
35 time.sleep(0.35)
36 is_pinned=vk.method('wall.get', {'owner_id': -78985442, 'count': 1, 'filter':'owner', 'offset':0})['items'][0]['is_pinned']
37 if is_pinned==1: return 1
38 return 0
39
40
41def get_wall_post(): # получить пост из ВК
42 offset=check_pinned()
43 info_wall = vk.method('wall.get', {'owner_id': -78985442, 'count': 1, 'filter':'owner', 'offset':offset})['items'][0]
44 time.sleep(0.35)
45 info_autor=info_wall['text']
46 id_post_text = str(info_wall['id'])
47 info_attachments=info_wall["attachments"][0]['photo']['sizes'][-1]['url']
48 if check_id_post(id_post_text):
49 save_photo(info_attachments)
50 save_post_id_vk(id_post_text=id_post_text)
51 save_text(info_autor)
52 print(info_autor)
53 return info_autor
54 else:
55 return False
56
57
58def save_photo(info_attachments): # запись фотографии со стены группы в ВК
59 img_data = requests.get(str(info_attachments))
60 with open('file_place_name.jpg', 'wb') as photo:
61 photo.write(img_data.content)
62
63
64def save_text(info_autor=''): # запись текста в файл с поста ВК
65 autor_link=re.findall(r'htt(.+)', info_autor)
66 autor_link[0]='htt'+autor_link[0]
67 info_autor=info_autor.replace(autor_link[0],'')
68 autor_link.append(info_autor)
69 with open('post_m_text.txt', 'w', encoding='UTF-8') as text:
70 for element in autor_link:
71 text.write(element)
72 text.write('\n')
73
74
75def save_post_id_vk(id_post_text=''): # запись id в файл с поста ВК
76 with open('id_post_text.txt', 'w', encoding='UTF-8') as text:
77 text.write(id_post_text)
78
79
80def send_new_posts(): # отправка сообщение в канала телеграмма
81 autor=get_wall_post()
82 if autor!=False:
83 with open('post_m_text.txt', 'r',encoding='UTF-8') as text:
84 mes=text.readlines()
85 with open('file_place_name.jpg', 'rb') as photo:
86 count=[0,0]
87 keyboard=create_new_keyboard(autor_id=str(mes[0]))
88 res=bot.send_photo(-1001238583708, photo, caption=mes[1], reply_markup=keyboard)
89 add_autor_id(autor_id=str(mes[0]), message_id=res.message_id, data_time=datetime.now().date())
90 print('сообщение отправил')
91 else:
92 pass
93
94
95def create_new_keyboard(count=[0,0], autor_id=''):
96 keyboard = types.InlineKeyboardMarkup(row_width=2)
97 like_button = types.InlineKeyboardButton(text=f"? +{str(count[0])}", callback_data='like')
98 dislike_button = types.InlineKeyboardButton(text=f"?? -{str(count[1])}", callback_data='dislike')
99 keyboard.add(like_button, dislike_button)
100 to_tell = types.InlineKeyboardButton(text='Рассказать друзьям',
101 url='https://telegram.me/share/url?url=https://t.me/magellando')
102 to_autor = types.InlineKeyboardButton(text='Связаться с автором', url=autor_id)
103 to_link_a = types.InlineKeyboardButton(text='Подобрать Авиабилет', url='http://www.aviasales.ru/?marker=276711')
104 keyboard.add(to_tell)
105 keyboard.add(to_autor)
106 keyboard.add(to_link_a)
107 return keyboard
108
109
110@bot.callback_query_handler(func=lambda call: call.data and call.data in ['like', 'dislike'])
111def query_handler(call):
112 if call.data == 'like':
113 user_id = call.from_user.id
114 message_id=call.message.message_id
115 like=True
116 if verify_user(user_id=user_id, message_id=message_id):
117 bot.answer_callback_query(callback_query_id=call.id, text='Вы уже голосовали за эту фотографию!', show_alert=False)
118 else:
119 add_user_id_and_message_id(user_id=user_id, message_id=message_id, like=like, data_time=datetime.now().date())
120 count=get_summ(message_id=message_id)
121 autor_id=get_autor_id(message_id=message_id)
122 bot.edit_message_reply_markup(chat_id=call.message.chat.id, message_id=call.message.message_id,
123 reply_markup=create_new_keyboard(count=count, autor_id=autor_id[0]))
124 bot.answer_callback_query(callback_query_id=call.id, text='Вы поставили лайк!', show_alert=False)
125 elif call.data == 'dislike':
126 user_id = call.from_user.id
127 message_id = call.message.message_id
128 like = False
129 if verify_user(user_id=user_id, message_id=message_id):
130 bot.answer_callback_query(callback_query_id=call.id, text='Вы уже голосовали за эту фотографию!', show_alert=False)
131 else:
132 add_user_id_and_message_id(user_id=user_id, message_id=message_id, like=like, data_time=datetime.now().date())
133 count = get_summ(message_id=message_id)
134 autor_id = get_autor_id(message_id=message_id)
135 bot.edit_message_reply_markup(chat_id=call.message.chat.id, message_id=call.message.message_id,
136 reply_markup=create_new_keyboard(count=count, autor_id=autor_id[0]))
137 bot.answer_callback_query(callback_query_id=call.id, text='Вы поставили дизлайк!', show_alert=False)
138
139
140@bot.message_handler(commands=['start'])
141def start(message):
142 bot.send_message(message.from_user.id, 'Салют. Географ Фернан Магеллан с поддержкой ИИ к вашим услугам.'
143 '\nУ меня вы можете узнать: '
144 '\n1. Как делать фотографии уникальных природных объектов.'
145 '\n2. Куда лучше отправиться в путешествие в текущем сезоне.'
146 '\n3. Найти недорогие билеты для путешествий.'
147 '\n Я умею работать в режиме искусственного интеллекта, с его помощью '
148 '\n вы можете поговорить со мной в свободной форме обмениваясь сообщениями.'
149 '\n Первые три пункта при этом можно выбрать из стандартного меню.'
150 '\n Введите для продолжения /help.')
151 add_user_chat_id(user_id=message.from_user.id, chat_id=message.chat.id)
152
153
154@bot.message_handler(commands=['help'])
155def help_msg(message):
156 request = apiai.ApiAI('a6526b4fdc..............').text_request() # Токен API к Dialogflow
157 request.lang = 'ru' # На каком языке будет послан запрос
158 request.session_id = 'Mogellanbot' # ID Сессии диалога (нужно, чтобы потом учить бота)
159 request.query = 'хей' # Посылаем запрос к ИИ с сообщением от юзера
160 responseJson = json.loads(request.getresponse().read().decode('utf-8'))
161 response = responseJson['result']['fulfillment']['speech'] # Разбираем JSON и вытаскиваем ответ
162 bot.send_message(message.chat.id, response)
163 keyboardmain = types.InlineKeyboardMarkup(row_width=2)
164 foto_info_button = types.InlineKeyboardButton(text="Съемка пейзажей", callback_data="foto_info")
165 observation_button = types.InlineKeyboardButton(text="Интересные места", callback_data="geo")
166 calendar_button = types.InlineKeyboardButton(text="Недорогие билеты", callback_data="astrocalendar")
167 keyboardmain.add(foto_info_button, observation_button)
168 keyboardmain.add(calendar_button)
169 bot.send_message(message.chat.id, "Выбери, что интересно узнать из стандартного меню.", reply_markup=keyboardmain)
170
171
172@bot.message_handler(commands=['greatphoto'])
173def get_interval_date(message):
174 dt=datetime.now().date()
175 if dt.month==1:
176 year_past = dt.year - 1
177 dt = str(dt.replace(month=12,year=year_past))
178 else:
179 pastmonth = dt.month - 1
180 dt = str(dt.replace(month=pastmonth))
181 star_dt=lastdaymonthmodul.get_first_day_of_month( dt )
182 end_dt=lastdaymonthmodul.get_last_day_of_month( dt )
183 bot.send_message(message.chat.id, 'Лучшие фотографы за месяц')
184 links=get_great_foto(start_dt=star_dt, end_dt=end_dt)
185 for i in range(len(links)):
186 bot.send_message(message.chat.id, links[i][1])
187
188
189@bot.message_handler(commands=['deletebd'])
190def delete_bd(message):
191 dt=datetime.now().date()
192 if dt.month==1:
193 year_past = dt.year-1
194 dt = str(dt.replace(month=10, year=year_past))
195 elif dt.month==2:
196 year_past = dt.year - 1
197 dt = str(dt.replace(month=11, year=year_past))
198 elif dt.month==3:
199 year_past = dt.year - 1
200 dt = str(dt.replace(month=12, year=year_past))
201 else:
202 pastmonth = dt.month - 3
203 dt = str(dt.replace(month=pastmonth))
204 star_dt=lastdaymonthmodul.get_first_day_of_month( dt )
205 end_dt=lastdaymonthmodul.get_last_day_of_month( dt )
206 bot.send_message(message.chat.id, 'Записи удалил')
207 links=delete_from_date(start_dt=star_dt, end_dt=end_dt)
208
209
210@bot.message_handler(commands=["newsletter"])
211def answer(message):
212 if (message.from_user.id == 479715437):
213 newsletter = message.text.split(maxsplit=1)[1]
214 allusers=get_user_chat_id()
215 for i in range(len(allusers)):
216 try:
217 if i % 10 == 0:
218 time.sleep(1)
219 bot.send_message(allusers[i][0], newsletter)
220 except:
221 continue
222
223
224def get_text_travel():
225 columns_dict = dict()
226 with open('maginfo.csv', 'r', encoding='utf-8') as resultFile:
227 reader = csv.DictReader(resultFile, delimiter=';')
228 for col_name in reader.fieldnames:
229 columns_dict[col_name] = []
230 for row in reader:
231 for col_name in reader.fieldnames:
232 columns_dict[col_name].append(row[col_name])
233 columns_dict['европа'] = columns_dict.pop('\ufeffeвропа')
234 for key in columns_dict.keys():
235 columns_dict[key] = [i.rstrip() for i in columns_dict[key] if i != '']
236 return columns_dict
237
238
239def get_text_foto():
240 columns_dict = dict()
241 with open('foto_view.csv', 'r', encoding='utf-8') as resultFile:
242 reader = csv.DictReader(resultFile, delimiter=';')
243 for col_name in reader.fieldnames:
244 columns_dict[col_name] = []
245 for row in reader:
246 for col_name in reader.fieldnames:
247 columns_dict[col_name].append(row[col_name])
248 return columns_dict
249
250
251def get_foto(key=''):
252 return random.SystemRandom().choice(get_text_foto()[key])
253
254
255def get_place(key=''):
256 return random.SystemRandom().choice(get_text_travel()[key])
257
258
259@bot.message_handler(content_types=['text'])
260def reply_massage(message):
261 request = apiai.ApiAI('a6526b4fdcff433499a0940e756e24bc').text_request() # Токен API к Dialogflow
262 request.lang = 'ru' # На каком языке будет послан запрос
263 request.session_id = 'Mogellanbot' # ID Сессии диалога (нужно, чтобы потом учить бота)
264 request.query = message.text # Посылаем запрос к ИИ с сообщением от юзера
265 responseJson = json.loads(request.getresponse().read().decode('utf-8'))
266 response = responseJson['result']['fulfillment']['speech'] # Разбираем JSON и вытаскиваем ответ
267 bot.send_message(message.chat.id, response)
268
269
270@bot.callback_query_handler(func=lambda call:call.data and call.data in
271 ['mainmenu', 'foto_info', 'geo','astrocalendar', 'europe',
272 'nordAm','southAm', 'australia','asia','africa','foto_nature','foto_night'])
273def callback_inline(call):
274 if call.data == "mainmenu":
275 keyboardmain = types.InlineKeyboardMarkup(row_width=2)
276 foto_info_button = types.InlineKeyboardButton(text="Съемка пейзажей", callback_data="foto_info")
277 observation_button = types.InlineKeyboardButton(text="Интересные места", callback_data="geo")
278 calendar_button = types.InlineKeyboardButton(text="Недорогие билеты", callback_data="hostel_info")
279 keyboardmain.add(foto_info_button, observation_button)
280 keyboardmain.add(calendar_button)
281 bot.edit_message_text(chat_id=call.message.chat.id,message_id=call.message.message_id, text="Главное меню",reply_markup=keyboardmain)
282
283
284 if call.data == "foto_info":
285 bot.send_message(chat_id=call.message.chat.id, text='Выберите тип объекта съемки')
286 keyboard = types.InlineKeyboardMarkup(row_width=2)
287 foto_info_nature = types.InlineKeyboardButton(text="Съемка дневного пейзажа", callback_data="foto_nature")
288 foto_info_night = types.InlineKeyboardButton(text="Съемка ночного пейзажа", callback_data="foto_night")
289 backbutton = types.InlineKeyboardButton(text="Назад", callback_data="mainmenu")
290 keyboard.add(foto_info_nature)
291 keyboard.add(foto_info_night)
292 keyboard.add(backbutton)
293 bot.send_message(chat_id=call.message.chat.id, text="Объект съемки:",reply_markup=keyboard)
294
295
296 elif call.data == "geo":
297 bot.send_message(chat_id=call.message.chat.id,text='Выберите материк')
298 keyboard = types.InlineKeyboardMarkup(row_width=2)
299 europe_button = types.InlineKeyboardButton(text="Европа",callback_data="europe")
300 asia_button = types.InlineKeyboardButton(text="Азия", callback_data="asia")
301 africa_button = types.InlineKeyboardButton(text="Африка", callback_data="africa")
302 nordAm_button = types.InlineKeyboardButton(text="Северная Америка", callback_data="nordAm")
303 southAm_button = types.InlineKeyboardButton(text="Южная Америка", callback_data="southAm")
304 australia_button = types.InlineKeyboardButton(text="Австралия", callback_data="australia")
305 backbutton = types.InlineKeyboardButton(text="Назад", callback_data="mainmenu")
306 keyboard.add(asia_button, europe_button)
307 keyboard.add(southAm_button)
308 keyboard.add(nordAm_button)
309 keyboard.add(africa_button)
310 keyboard.add(australia_button)
311 keyboard.add(backbutton)
312 bot.send_message(chat_id=call.message.chat.id, text="Объект съемки: ", reply_markup=keyboard)
313
314
315 elif call.data == "foto_night":
316 keyboard = types.InlineKeyboardMarkup()
317 backbutton = types.InlineKeyboardButton(text="Назад", callback_data="mainmenu")
318 yet_place = types.InlineKeyboardButton(text="Узнать еще", callback_data="foto_info")
319 keyboard.add(backbutton)
320 keyboard.add(yet_place)
321 key='Съемка ночного пейзажа'
322 bot.send_message(chat_id=call.message.chat.id, text=get_foto(key=key), reply_markup=keyboard)
323
324
325 elif call.data == "foto_nature":
326 keyboard = types.InlineKeyboardMarkup()
327 backbutton = types.InlineKeyboardButton(text="Назад", callback_data="mainmenu")
328 yet_place = types.InlineKeyboardButton(text="Узнать еще", callback_data="foto_info")
329 keyboard.add(backbutton)
330 keyboard.add(yet_place)
331 key='Съемка дневного пейзажа'
332 bot.send_message(chat_id=call.message.chat.id, text=get_foto(key=key), reply_markup=keyboard)
333
334
335 elif call.data == "europe":
336 keyboard = types.InlineKeyboardMarkup()
337 backbutton = types.InlineKeyboardButton(text="Назад", callback_data="mainmenu")
338 yet_place = types.InlineKeyboardButton(text="Еще место", callback_data="geo")
339 keyboard.add(backbutton)
340 keyboard.add(yet_place)
341 key='европа'
342 bot.send_message(chat_id=call.message.chat.id, text=get_place(key=key), reply_markup=keyboard)
343
344
345 elif call.data == "asia":
346 keyboard = types.InlineKeyboardMarkup()
347 backbutton = types.InlineKeyboardButton(text="Назад", callback_data="mainmenu")
348 yet_place = types.InlineKeyboardButton(text="Еще место", callback_data="geo")
349 keyboard.add(backbutton)
350 keyboard.add(yet_place)
351 key='азия'
352 bot.send_message(chat_id=call.message.chat.id, text=get_place(key=key), reply_markup=keyboard)
353
354
355 elif call.data == "southAm":
356 keyboard = types.InlineKeyboardMarkup()
357 backbutton = types.InlineKeyboardButton(text="Назад", callback_data="mainmenu")
358 yet_place = types.InlineKeyboardButton(text="Еще место", callback_data="geo")
359 keyboard.add(backbutton)
360 keyboard.add(yet_place)
361 key='южная америка'
362 bot.send_message(chat_id=call.message.chat.id, text=get_place(key=key), reply_markup=keyboard)
363
364
365 elif call.data == "nordAm":
366 keyboard = types.InlineKeyboardMarkup()
367 backbutton = types.InlineKeyboardButton(text="Назад", callback_data="mainmenu")
368 yet_place = types.InlineKeyboardButton(text="Еще место", callback_data="geo")
369 keyboard.add(backbutton)
370 keyboard.add(yet_place)
371 key='северная америка'
372 bot.send_message(chat_id=call.message.chat.id, text=get_place(key=key), reply_markup=keyboard)
373
374
375 elif call.data == "africa":
376 keyboard = types.InlineKeyboardMarkup()
377 backbutton = types.InlineKeyboardButton(text="Назад", callback_data="mainmenu")
378 yet_place = types.InlineKeyboardButton(text="Еще место", callback_data="geo")
379 keyboard.add(backbutton)
380 keyboard.add(yet_place)
381 key='африка'
382 bot.send_message(chat_id=call.message.chat.id, text=get_place(key=key), reply_markup=keyboard)
383
384
385 elif call.data == "australia":
386 keyboard = types.InlineKeyboardMarkup()
387 backbutton = types.InlineKeyboardButton(text="Назад", callback_data="mainmenu")
388 yet_place = types.InlineKeyboardButton(text="Еще место", callback_data="geo")
389 keyboard.add(backbutton)
390 keyboard.add(yet_place)
391 key='австралия'
392 bot.send_message(chat_id=call.message.chat.id, text=get_place(key=key), reply_markup=keyboard)
393
394
395def run_post():
396 threading.Timer(300.0, run_post).start()
397 send_new_posts()
398
399
400@server.route('/' + '101763313.................', methods=['POST'])
401def getMessage():
402 bot.process_new_updates([telebot.types.Update.de_json(request.stream.read().decode("utf-8"))])
403 return "!", 200
404
405
406@server.route("/")
407def webhook():
408 bot.remove_webhook()
409 bot.set_webhook(url=URL + '10176331...................')
410 return "!", 200
411
412init_db()
413run_post()
414
415if __name__=='__main__':
416 server.run(host="0.0.0.0", port=int(os.environ.get('PORT', 5000)))